Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1141
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1141 ! raeburn 4: # $Id: lonnet.pm,v 1.1140 2011/10/24 12:05:58 www Exp $
1.178 www 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: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1117 foxr 99:
1.1090 raeburn 100: use File::Copy;
1.676 albertel 101:
1.195 www 102: my $readit;
1.550 foxr 103: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 104:
1.619 albertel 105: require Exporter;
106:
107: our @ISA = qw (Exporter);
108: our @EXPORT = qw(%env);
109:
1.449 matthew 110:
1.1 albertel 111: # --------------------------------------------------------------------- Logging
1.729 www 112: {
113: my $logid;
114: sub instructor_log {
1.957 raeburn 115: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
116: if (($cnum eq '') || ($cdom eq '')) {
117: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
118: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
119: }
1.729 www 120: $logid++;
1.957 raeburn 121: my $now = time();
122: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 123: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 124: { $id => {
125: 'exe_uname' => $env{'user.name'},
126: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 127: 'exe_time' => $now,
1.730 www 128: 'exe_ip' => $ENV{'REMOTE_ADDR'},
129: 'delflag' => $delflag,
130: 'logentry' => $storehash,
131: 'uname' => $uname,
132: 'udom' => $udom,
133: }
1.957 raeburn 134: },$cdom,$cnum);
1.729 www 135: }
136: }
1.1 albertel 137:
1.163 harris41 138: sub logtouch {
139: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 140: unless (-e "$execdir/logs/lonnet.log") {
141: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 142: close $fh;
143: }
144: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
145: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
146: }
147:
1.1 albertel 148: sub logthis {
149: my $message=shift;
150: my $execdir=$perlvar{'lonDaemons'};
151: my $now=time;
152: my $local=localtime($now);
1.448 albertel 153: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 154: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
155: print $fh $logstring;
1.448 albertel 156: close($fh);
157: }
1.1 albertel 158: return 1;
159: }
160:
161: sub logperm {
162: my $message=shift;
163: my $execdir=$perlvar{'lonDaemons'};
164: my $now=time;
165: my $local=localtime($now);
1.448 albertel 166: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
167: print $fh "$now:$message:$local\n";
168: close($fh);
169: }
1.1 albertel 170: return 1;
171: }
172:
1.850 albertel 173: sub create_connection {
1.853 albertel 174: my ($hostname,$lonid) = @_;
1.851 albertel 175: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 176: Type => SOCK_STREAM,
177: Timeout => 10);
178: return 0 if (!$client);
1.890 albertel 179: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 180: my $result = <$client>;
181: chomp($result);
182: return 1 if ($result eq 'done');
183: return 0;
184: }
185:
1.983 raeburn 186: sub get_server_timezone {
187: my ($cnum,$cdom) = @_;
188: my $home=&homeserver($cnum,$cdom);
189: if ($home ne 'no_host') {
190: my $cachetime = 24*3600;
191: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
192: if (defined($cached)) {
193: return $timezone;
194: } else {
195: my $timezone = &reply('servertimezone',$home);
196: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
197: }
198: }
199: }
1.850 albertel 200:
1.1106 raeburn 201: sub get_server_distarch {
202: my ($lonhost,$ignore_cache) = @_;
203: if (defined($lonhost)) {
204: if (!defined(&hostname($lonhost))) {
205: return;
206: }
207: my $cachetime = 12*3600;
208: if (!$ignore_cache) {
209: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
210: if (defined($cached)) {
211: return $distarch;
212: }
213: }
214: my $rep = &reply('serverdistarch',$lonhost);
215: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
216: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
217: $rep eq '') {
218: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
219: }
220: }
221: return;
222: }
223:
1.993 raeburn 224: sub get_server_loncaparev {
1.1073 raeburn 225: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 226: if (defined($lonhost)) {
227: if (!defined(&hostname($lonhost))) {
228: undef($lonhost);
229: }
230: }
231: if (!defined($lonhost)) {
232: if (defined(&domain($dom,'primary'))) {
233: $lonhost=&domain($dom,'primary');
234: if ($lonhost eq 'no_host') {
235: undef($lonhost);
236: }
237: }
238: }
239: if (defined($lonhost)) {
1.1073 raeburn 240: my $cachetime = 12*3600;
241: if (!$ignore_cache) {
242: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
243: if (defined($cached)) {
244: return $loncaparev;
245: }
246: }
247: my ($answer,$loncaparev);
248: my @ids=¤t_machine_ids();
249: if (grep(/^\Q$lonhost\E$/,@ids)) {
250: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 251: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 252: $loncaparev = $1;
253: }
254: } else {
255: $answer = &reply('serverloncaparev',$lonhost);
256: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
257: if ($caller eq 'loncron') {
258: my $ua=new LWP::UserAgent;
1.1082 raeburn 259: $ua->timeout(4);
1.1073 raeburn 260: my $protocol = $protocol{$lonhost};
261: $protocol = 'http' if ($protocol ne 'https');
262: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
263: my $request=new HTTP::Request('GET',$url);
264: my $response=$ua->request($request);
265: unless ($response->is_error()) {
266: my $content = $response->content;
1.1081 raeburn 267: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 268: $loncaparev = $1;
269: }
270: }
271: } else {
272: $loncaparev = $loncaparevs{$lonhost};
273: }
1.1081 raeburn 274: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 275: $loncaparev = $1;
276: }
1.993 raeburn 277: }
1.1073 raeburn 278: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 279: }
280: }
281:
1.1074 raeburn 282: sub get_server_homeID {
283: my ($hostname,$ignore_cache,$caller) = @_;
284: unless ($ignore_cache) {
285: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
286: if (defined($cached)) {
287: return $serverhomeID;
288: }
289: }
290: my $cachetime = 12*3600;
291: my $serverhomeID;
292: if ($caller eq 'loncron') {
293: my @machine_ids = &machine_ids($hostname);
294: foreach my $id (@machine_ids) {
295: my $response = &reply('serverhomeID',$id);
296: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
297: $serverhomeID = $response;
298: last;
299: }
300: }
301: if ($serverhomeID eq '') {
302: $serverhomeID = $machine_ids[-1];
303: }
304: } else {
305: $serverhomeID = $serverhomeIDs{$hostname};
306: }
307: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
308: }
309:
1.1121 raeburn 310: sub get_remote_globals {
311: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 312: my ($result,%returnhash,%whatneeded);
313: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 314: foreach my $what (sort(keys(%{$whathash}))) {
315: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 316: my ($response,$cached);
1.1121 raeburn 317: unless ($ignore_cache) {
1.1125 raeburn 318: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 319: }
320: if (defined($cached)) {
1.1125 raeburn 321: $returnhash{$what} = $response;
1.1121 raeburn 322: } else {
1.1125 raeburn 323: $whatneeded{$what} = 1;
1.1121 raeburn 324: }
325: }
1.1125 raeburn 326: if (keys(%whatneeded) == 0) {
327: $result = 'ok';
328: } else {
1.1121 raeburn 329: my $requested = &freeze_escape(\%whatneeded);
330: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 331: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
332: ($rep eq 'unknown_cmd')) {
333: $result = $rep;
334: } else {
335: $result = 'ok';
1.1121 raeburn 336: my @pairs=split(/\&/,$rep);
1.1125 raeburn 337: foreach my $item (@pairs) {
338: my ($key,$value)=split(/=/,$item,2);
339: my $what = &unescape($key);
340: my $hashid = $lonhost.'-'.$what;
341: $returnhash{$what}=&thaw_unescape($value);
342: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 343: }
344: }
345: }
346: }
1.1125 raeburn 347: return ($result,\%returnhash);
1.1121 raeburn 348: }
349:
1.1124 raeburn 350: sub remote_devalidate_cache {
351: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 352: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 353: return $response;
354: }
355:
1.1 albertel 356: # -------------------------------------------------- Non-critical communication
357: sub subreply {
358: my ($cmd,$server)=@_;
1.838 albertel 359: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 360: #
361: # With loncnew process trimming, there's a timing hole between lonc server
362: # process exit and the master server picking up the listen on the AF_UNIX
363: # socket. In that time interval, a lock file will exist:
364:
365: my $lockfile=$peerfile.".lock";
366: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
367: sleep(1);
368: }
369: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 370: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 371: #
1.550 foxr 372: # We'll give the connection a few tries before abandoning it. If
373: # connection is not possible, we'll con_lost back to the client.
374: #
375: my $client;
376: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
377: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
378: Type => SOCK_STREAM,
379: Timeout => 10);
1.869 albertel 380: if ($client) {
1.550 foxr 381: last; # Connected!
1.850 albertel 382: } else {
1.853 albertel 383: &create_connection(&hostname($server),$server);
1.550 foxr 384: }
1.850 albertel 385: sleep(1); # Try again later if failed connection.
1.550 foxr 386: }
387: my $answer;
388: if ($client) {
1.704 albertel 389: print $client "sethost:$server:$cmd\n";
1.550 foxr 390: $answer=<$client>;
391: if (!$answer) { $answer="con_lost"; }
392: chomp($answer);
393: } else {
394: $answer = 'con_lost'; # Failed connection.
395: }
1.1 albertel 396: return $answer;
397: }
398:
399: sub reply {
400: my ($cmd,$server)=@_;
1.838 albertel 401: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 402: my $answer=subreply($cmd,$server);
1.65 www 403: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 404: &logthis("<font color=\"blue\">WARNING:".
1.12 www 405: " $cmd to $server returned $answer</font>");
406: }
1.1 albertel 407: return $answer;
408: }
409:
410: # ----------------------------------------------------------- Send USR1 to lonc
411:
412: sub reconlonc {
1.891 albertel 413: my ($lonid) = @_;
414: my $hostname = &hostname($lonid);
415: if ($lonid) {
416: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
417: if ($hostname && -e $peerfile) {
418: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
419: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
420: Type => SOCK_STREAM,
421: Timeout => 10);
422: if ($client) {
423: print $client ("reset_retries\n");
424: my $answer=<$client>;
425: #reset just this one.
426: }
427: }
428: return;
429: }
430:
1.836 www 431: &logthis("Trying to reconnect lonc");
1.1 albertel 432: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 433: if (open(my $fh,"<$loncfile")) {
1.1 albertel 434: my $loncpid=<$fh>;
435: chomp($loncpid);
436: if (kill 0 => $loncpid) {
437: &logthis("lonc at pid $loncpid responding, sending USR1");
438: kill USR1 => $loncpid;
439: sleep 1;
1.836 www 440: } else {
1.12 www 441: &logthis(
1.672 albertel 442: "<font color=\"blue\">WARNING:".
1.12 www 443: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 444: }
445: } else {
1.836 www 446: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 447: }
448: }
449:
450: # ------------------------------------------------------ Critical communication
1.12 www 451:
1.1 albertel 452: sub critical {
453: my ($cmd,$server)=@_;
1.838 albertel 454: unless (&hostname($server)) {
1.672 albertel 455: &logthis("<font color=\"blue\">WARNING:".
1.89 www 456: " Critical message to unknown server ($server)</font>");
457: return 'no_such_host';
458: }
1.1 albertel 459: my $answer=reply($cmd,$server);
460: if ($answer eq 'con_lost') {
461: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 462: my $answer=reply($cmd,$server);
1.1 albertel 463: if ($answer eq 'con_lost') {
464: my $now=time;
465: my $middlename=$cmd;
1.5 www 466: $middlename=substr($middlename,0,16);
1.1 albertel 467: $middlename=~s/\W//g;
468: my $dfilename=
1.305 www 469: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
470: $dumpcount++;
1.1 albertel 471: {
1.448 albertel 472: my $dfh;
473: if (open($dfh,">$dfilename")) {
474: print $dfh "$cmd\n";
475: close($dfh);
476: }
1.1 albertel 477: }
478: sleep 2;
479: my $wcmd='';
480: {
1.448 albertel 481: my $dfh;
482: if (open($dfh,"<$dfilename")) {
483: $wcmd=<$dfh>;
484: close($dfh);
485: }
1.1 albertel 486: }
487: chomp($wcmd);
1.7 www 488: if ($wcmd eq $cmd) {
1.672 albertel 489: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 490: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 491: &logperm("D:$server:$cmd");
492: return 'con_delayed';
493: } else {
1.672 albertel 494: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 495: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 496: &logperm("F:$server:$cmd");
497: return 'con_failed';
498: }
499: }
500: }
501: return $answer;
1.405 albertel 502: }
503:
1.755 albertel 504: # ------------------------------------------- check if return value is an error
505:
506: sub error {
507: my ($result) = @_;
1.756 albertel 508: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 509: if ($2 == 2) { return undef; }
510: return $1;
511: }
512: return undef;
513: }
514:
1.783 albertel 515: sub convert_and_load_session_env {
516: my ($lonidsdir,$handle)=@_;
517: my @profile;
518: {
1.917 albertel 519: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
520: if (!$opened) {
1.915 albertel 521: return 0;
522: }
1.783 albertel 523: flock($idf,LOCK_SH);
524: @profile=<$idf>;
525: close($idf);
526: }
527: my %temp_env;
528: foreach my $line (@profile) {
1.786 albertel 529: if ($line !~ m/=/) {
530: return 0;
531: }
1.783 albertel 532: chomp($line);
533: my ($envname,$envvalue)=split(/=/,$line,2);
534: $temp_env{&unescape($envname)} = &unescape($envvalue);
535: }
536: unlink("$lonidsdir/$handle.id");
537: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
538: 0640)) {
539: %disk_env = %temp_env;
540: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
541: untie(%disk_env);
542: }
1.786 albertel 543: return 1;
1.783 albertel 544: }
545:
1.374 www 546: # ------------------------------------------- Transfer profile into environment
1.780 albertel 547: my $env_loaded;
548: sub transfer_profile_to_env {
1.788 albertel 549: my ($lonidsdir,$handle,$force_transfer) = @_;
550: if (!$force_transfer && $env_loaded) { return; }
1.374 www 551:
1.720 albertel 552: if (!defined($lonidsdir)) {
553: $lonidsdir = $perlvar{'lonIDsDir'};
554: }
555: if (!defined($handle)) {
556: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
557: }
558:
1.786 albertel 559: my $convert;
560: {
1.917 albertel 561: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
562: if (!$opened) {
1.915 albertel 563: return;
564: }
1.786 albertel 565: flock($idf,LOCK_SH);
566: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
567: &GDBM_READER(),0640)) {
568: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
569: untie(%disk_env);
570: } else {
571: $convert = 1;
572: }
573: }
574: if ($convert) {
575: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
576: &logthis("Failed to load session, or convert session.");
577: }
1.374 www 578: }
1.783 albertel 579:
1.786 albertel 580: my %remove;
1.783 albertel 581: while ( my $envname = each(%env) ) {
1.433 matthew 582: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
583: if ($time < time-300) {
1.783 albertel 584: $remove{$key}++;
1.433 matthew 585: }
586: }
587: }
1.783 albertel 588:
1.619 albertel 589: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 590: $env_loaded=1;
1.783 albertel 591: foreach my $expired_key (keys(%remove)) {
1.433 matthew 592: &delenv($expired_key);
1.374 www 593: }
1.1 albertel 594: }
595:
1.916 albertel 596: # ---------------------------------------------------- Check for valid session
597: sub check_for_valid_session {
598: my ($r) = @_;
599: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
600: my $lonid=$cookies{'lonID'};
601: return undef if (!$lonid);
602:
603: my $handle=&LONCAPA::clean_handle($lonid->value);
604: my $lonidsdir=$r->dir_config('lonIDsDir');
605: return undef if (!-e "$lonidsdir/$handle.id");
606:
1.917 albertel 607: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
608: return undef if (!$opened);
1.916 albertel 609:
610: flock($idf,LOCK_SH);
611: my %disk_env;
612: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
613: &GDBM_READER(),0640)) {
614: return undef;
615: }
616:
617: if (!defined($disk_env{'user.name'})
618: || !defined($disk_env{'user.domain'})) {
619: return undef;
620: }
621: return $handle;
622: }
623:
1.830 albertel 624: sub timed_flock {
625: my ($file,$lock_type) = @_;
626: my $failed=0;
627: eval {
628: local $SIG{__DIE__}='DEFAULT';
629: local $SIG{ALRM}=sub {
630: $failed=1;
631: die("failed lock");
632: };
633: alarm(13);
634: flock($file,$lock_type);
635: alarm(0);
636: };
637: if ($failed) {
638: return undef;
639: } else {
640: return 1;
641: }
642: }
643:
1.5 www 644: # ---------------------------------------------------------- Append Environment
645:
646: sub appenv {
1.949 raeburn 647: my ($newenv,$roles) = @_;
648: if (ref($newenv) eq 'HASH') {
649: foreach my $key (keys(%{$newenv})) {
650: my $refused = 0;
651: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
652: $refused = 1;
653: if (ref($roles) eq 'ARRAY') {
654: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
655: if (grep(/^\Q$role\E$/,@{$roles})) {
656: $refused = 0;
657: }
658: }
659: }
660: if ($refused) {
661: &logthis("<font color=\"blue\">WARNING: ".
662: "Attempt to modify environment ".$key." to ".$newenv->{$key}
663: .'</font>');
664: delete($newenv->{$key});
665: } else {
666: $env{$key}=$newenv->{$key};
667: }
668: }
669: my $opened = open(my $env_file,'+<',$env{'user.environment'});
670: if ($opened
671: && &timed_flock($env_file,LOCK_EX)
672: &&
673: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
674: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
675: while (my ($key,$value) = each(%{$newenv})) {
676: $disk_env{$key} = $value;
677: }
678: untie(%disk_env);
1.35 www 679: }
1.191 harris41 680: }
1.56 www 681: return 'ok';
682: }
683: # ----------------------------------------------------- Delete from Environment
684:
685: sub delenv {
1.1104 raeburn 686: my ($delthis,$regexp,$roles) = @_;
687: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
688: my $refused = 1;
689: if (ref($roles) eq 'ARRAY') {
690: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
691: if (grep(/^\Q$role\E$/,@{$roles})) {
692: $refused = 0;
693: }
694: }
695: if ($refused) {
696: &logthis("<font color=\"blue\">WARNING: ".
697: "Attempt to delete from environment ".$delthis);
698: return 'error';
699: }
1.56 www 700: }
1.917 albertel 701: my $opened = open(my $env_file,'+<',$env{'user.environment'});
702: if ($opened
1.915 albertel 703: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 704: &&
705: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
706: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 707: foreach my $key (keys(%disk_env)) {
1.987 raeburn 708: if ($regexp) {
709: if ($key=~/^$delthis/) {
710: delete($env{$key});
711: delete($disk_env{$key});
712: }
713: } else {
714: if ($key=~/^\Q$delthis\E/) {
715: delete($env{$key});
716: delete($disk_env{$key});
717: }
718: }
1.448 albertel 719: }
1.783 albertel 720: untie(%disk_env);
1.5 www 721: }
722: return 'ok';
1.369 albertel 723: }
724:
1.790 albertel 725: sub get_env_multiple {
726: my ($name) = @_;
727: my @values;
728: if (defined($env{$name})) {
729: # exists is it an array
730: if (ref($env{$name})) {
731: @values=@{ $env{$name} };
732: } else {
733: $values[0]=$env{$name};
734: }
735: }
736: return(@values);
737: }
738:
1.958 www 739: # ------------------------------------------------------------------- Locking
740:
741: sub set_lock {
742: my ($text)=@_;
743: $locknum++;
744: my $id=$$.'-'.$locknum;
745: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
746: 'session.lock.'.$id => $text});
747: return $id;
748: }
749:
750: sub get_locks {
751: my $num=0;
752: my %texts=();
753: foreach my $lock (split(/\,/,$env{'session.locks'})) {
754: if ($lock=~/\w/) {
755: $num++;
756: $texts{$lock}=$env{'session.lock.'.$lock};
757: }
758: }
759: return ($num,%texts);
760: }
761:
762: sub remove_lock {
763: my ($id)=@_;
764: my $newlocks='';
765: foreach my $lock (split(/\,/,$env{'session.locks'})) {
766: if (($lock=~/\w/) && ($lock ne $id)) {
767: $newlocks.=','.$lock;
768: }
769: }
770: &appenv({'session.locks' => $newlocks});
771: &delenv('session.lock.'.$id);
772: }
773:
774: sub remove_all_locks {
775: my $activelocks=$env{'session.locks'};
776: foreach my $lock (split(/\,/,$env{'session.locks'})) {
777: if ($lock=~/\w/) {
778: &remove_lock($lock);
779: }
780: }
781: }
782:
783:
1.369 albertel 784: # ------------------------------------------ Find out current server userload
785: sub userload {
786: my $numusers=0;
787: {
788: opendir(LONIDS,$perlvar{'lonIDsDir'});
789: my $filename;
790: my $curtime=time;
791: while ($filename=readdir(LONIDS)) {
1.925 albertel 792: next if ($filename eq '.' || $filename eq '..');
793: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 794: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 795: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 796: }
797: closedir(LONIDS);
798: }
799: my $userloadpercent=0;
800: my $maxuserload=$perlvar{'lonUserLoadLim'};
801: if ($maxuserload) {
1.371 albertel 802: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 803: }
1.372 albertel 804: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 805: return $userloadpercent;
1.283 www 806: }
807:
1.1 albertel 808: # ------------------------------ Find server with least workload from spare.tab
1.11 www 809:
1.1 albertel 810: sub spareserver {
1.1083 raeburn 811: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 812: my $spare_server;
1.370 albertel 813: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 814: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
815: : $userloadpercent;
1.1083 raeburn 816: my ($uint_dom,$remotesessions);
817: if (($udom ne '') && (&domain($udom) ne '')) {
818: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
819: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
820: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
821: $remotesessions = $udomdefaults{'remotesessions'};
822: }
1.1123 raeburn 823: my $spareshash = &this_host_spares($udom);
824: if (ref($spareshash) eq 'HASH') {
825: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
826: foreach my $try_server (@{ $spareshash->{'primary'} }) {
827: if ($uint_dom) {
828: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
829: $try_server));
830: }
831: ($spare_server, $lowest_load) =
832: &compare_server_load($try_server, $spare_server, $lowest_load);
833: }
1.1083 raeburn 834: }
1.784 albertel 835:
1.1123 raeburn 836: my $found_server = ($spare_server ne '' && $lowest_load < 100);
837:
838: if (!$found_server) {
839: if (ref($spareshash->{'default'}) eq 'ARRAY') {
840: foreach my $try_server (@{ $spareshash->{'default'} }) {
841: if ($uint_dom) {
842: next unless (&spare_can_host($udom,$uint_dom,
843: $remotesessions,$try_server));
844: }
845: ($spare_server, $lowest_load) =
846: &compare_server_load($try_server, $spare_server, $lowest_load);
847: }
848: }
849: }
1.784 albertel 850: }
851:
852: if (!$want_server_name) {
1.968 raeburn 853: my $protocol = 'http';
854: if ($protocol{$spare_server} eq 'https') {
855: $protocol = $protocol{$spare_server};
856: }
1.1001 raeburn 857: if (defined($spare_server)) {
858: my $hostname = &hostname($spare_server);
1.1083 raeburn 859: if (defined($hostname)) {
1.1001 raeburn 860: $spare_server = $protocol.'://'.$hostname;
861: }
862: }
1.784 albertel 863: }
864: return $spare_server;
865: }
866:
867: sub compare_server_load {
868: my ($try_server, $spare_server, $lowest_load) = @_;
869:
870: my $loadans = &reply('load', $try_server);
871: my $userloadans = &reply('userload',$try_server);
872:
873: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 874: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 875: }
876:
877: my $load;
878: if ($loadans =~ /\d/) {
879: if ($userloadans =~ /\d/) {
880: #both are numbers, pick the bigger one
881: $load = ($loadans > $userloadans) ? $loadans
882: : $userloadans;
1.411 albertel 883: } else {
1.784 albertel 884: $load = $loadans;
1.411 albertel 885: }
1.784 albertel 886: } else {
887: $load = $userloadans;
888: }
889:
890: if (($load =~ /\d/) && ($load < $lowest_load)) {
891: $spare_server = $try_server;
892: $lowest_load = $load;
1.370 albertel 893: }
1.784 albertel 894: return ($spare_server,$lowest_load);
1.202 matthew 895: }
1.914 albertel 896:
897: # --------------------------- ask offload servers if user already has a session
898: sub find_existing_session {
899: my ($udom,$uname) = @_;
1.1123 raeburn 900: my $spareshash = &this_host_spares($udom);
901: if (ref($spareshash) eq 'HASH') {
902: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
903: foreach my $try_server (@{ $spareshash->{'primary'} }) {
904: return $try_server if (&has_user_session($try_server, $udom, $uname));
905: }
906: }
907: if (ref($spareshash->{'default'}) eq 'ARRAY') {
908: foreach my $try_server (@{ $spareshash->{'default'} }) {
909: return $try_server if (&has_user_session($try_server, $udom, $uname));
910: }
911: }
1.914 albertel 912: }
913: return;
914: }
915:
916: # -------------------------------- ask if server already has a session for user
917: sub has_user_session {
918: my ($lonid,$udom,$uname) = @_;
919: my $result = &reply(join(':','userhassession',
920: map {&escape($_)} ($udom,$uname)),$lonid);
921: return 1 if ($result eq 'ok');
922:
923: return 0;
924: }
925:
1.1076 raeburn 926: # --------- determine least loaded server in a user's domain which allows login
927:
928: sub choose_server {
1.1115 raeburn 929: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 930: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 931: my %servers = &get_servers($udom);
1.1076 raeburn 932: my $lowest_load = 30000;
1.1116 raeburn 933: my ($login_host,$hostname,$portal_path);
1.1076 raeburn 934: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 935: my $loginvia;
936: if ($checkloginvia) {
937: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 938: if ($loginvia) {
939: my ($server,$path) = split(/:/,$loginvia);
940: ($login_host, $lowest_load) =
941: &compare_server_load($server, $login_host, $lowest_load);
942: if ($login_host eq $server) {
943: $portal_path = $path;
944: }
945: } else {
946: ($login_host, $lowest_load) =
947: &compare_server_load($lonhost, $login_host, $lowest_load);
948: if ($login_host eq $lonhost) {
949: $portal_path = '';
950: }
951: }
952: } else {
1.1076 raeburn 953: ($login_host, $lowest_load) =
1.1116 raeburn 954: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 955: }
956: }
957: if ($login_host ne '') {
1.1116 raeburn 958: $hostname = &hostname($login_host);
1.1076 raeburn 959: }
1.1116 raeburn 960: return ($login_host,$hostname,$portal_path);
1.1076 raeburn 961: }
962:
1.202 matthew 963: # --------------------------------------------- Try to change a user's password
964:
965: sub changepass {
1.799 raeburn 966: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 967: $currentpass = &escape($currentpass);
968: $newpass = &escape($newpass);
1.1030 raeburn 969: my $lonhost = $perlvar{'lonHostID'};
970: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 971: $server);
972: if (! $answer) {
973: &logthis("No reply on password change request to $server ".
974: "by $uname in domain $udom.");
975: } elsif ($answer =~ "^ok") {
976: &logthis("$uname in $udom successfully changed their password ".
977: "on $server.");
978: } elsif ($answer =~ "^pwchange_failure") {
979: &logthis("$uname in $udom was unable to change their password ".
980: "on $server. The action was blocked by either lcpasswd ".
981: "or pwchange");
982: } elsif ($answer =~ "^non_authorized") {
983: &logthis("$uname in $udom did not get their password correct when ".
984: "attempting to change it on $server.");
985: } elsif ($answer =~ "^auth_mode_error") {
986: &logthis("$uname in $udom attempted to change their password despite ".
987: "not being locally or internally authenticated on $server.");
988: } elsif ($answer =~ "^unknown_user") {
989: &logthis("$uname in $udom attempted to change their password ".
990: "on $server but were unable to because $server is not ".
991: "their home server.");
992: } elsif ($answer =~ "^refused") {
993: &logthis("$server refused to change $uname in $udom password because ".
994: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 995: } elsif ($answer =~ "invalid_client") {
996: &logthis("$server refused to change $uname in $udom password because ".
997: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 998: }
999: return $answer;
1.1 albertel 1000: }
1001:
1.169 harris41 1002: # ----------------------- Try to determine user's current authentication scheme
1003:
1004: sub queryauthenticate {
1005: my ($uname,$udom)=@_;
1.456 albertel 1006: my $uhome=&homeserver($uname,$udom);
1007: if (!$uhome) {
1008: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1009: return 'no_host';
1010: }
1011: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1012: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1013: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1014: }
1.456 albertel 1015: return $answer;
1.169 harris41 1016: }
1017:
1.1 albertel 1018: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1019:
1.1 albertel 1020: sub authenticate {
1.1073 raeburn 1021: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1022: $upass=&escape($upass);
1023: $uname= &LONCAPA::clean_username($uname);
1.836 www 1024: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1025: my $newhome;
1.836 www 1026: if ((!$uhome) || ($uhome eq 'no_host')) {
1027: # Maybe the machine was offline and only re-appeared again recently?
1028: &reconlonc();
1029: # One more
1.952 raeburn 1030: $uhome=&homeserver($uname,$udom,1);
1031: if (($uhome eq 'no_host') && $checkdefauth) {
1032: if (defined(&domain($udom,'primary'))) {
1033: $newhome=&domain($udom,'primary');
1034: }
1035: if ($newhome ne '') {
1036: $uhome = $newhome;
1037: }
1038: }
1.836 www 1039: if ((!$uhome) || ($uhome eq 'no_host')) {
1040: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1041: return 'no_host';
1042: }
1.1 albertel 1043: }
1.1073 raeburn 1044: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1045: if ($answer eq 'authorized') {
1.952 raeburn 1046: if ($newhome) {
1047: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1048: return 'no_account_on_host';
1049: } else {
1050: &logthis("User $uname at $udom authorized by $uhome");
1051: return $uhome;
1052: }
1.471 albertel 1053: }
1054: if ($answer eq 'non_authorized') {
1055: &logthis("User $uname at $udom rejected by $uhome");
1056: return 'no_host';
1.9 www 1057: }
1.471 albertel 1058: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1059: return 'no_host';
1060: }
1061:
1.1073 raeburn 1062: sub can_host_session {
1.1074 raeburn 1063: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1064: my $canhost = 1;
1.1074 raeburn 1065: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1066: if (ref($remotesessions) eq 'HASH') {
1067: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1068: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1069: $canhost = 0;
1070: } else {
1071: $canhost = 1;
1072: }
1073: }
1074: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1075: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1076: $canhost = 1;
1077: } else {
1078: $canhost = 0;
1079: }
1080: }
1081: if ($canhost) {
1082: if ($remotesessions->{'version'} ne '') {
1083: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1084: if ($reqmajor ne '' && $reqminor ne '') {
1085: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1086: my $major = $1;
1087: my $minor = $2;
1088: if (($major < $reqmajor ) ||
1089: (($major == $reqmajor) && ($minor < $reqminor))) {
1090: $canhost = 0;
1091: }
1092: } else {
1093: $canhost = 0;
1094: }
1095: }
1096: }
1097: }
1098: }
1099: if ($canhost) {
1100: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1101: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1102: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1103: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1104: if (($uint_dom ne '') &&
1105: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1106: $canhost = 0;
1107: } else {
1108: $canhost = 1;
1109: }
1110: }
1111: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1112: if (($uint_dom ne '') &&
1113: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1114: $canhost = 1;
1115: } else {
1116: $canhost = 0;
1117: }
1118: }
1119: }
1120: }
1121: return $canhost;
1122: }
1123:
1.1083 raeburn 1124: sub spare_can_host {
1125: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1126: my $canhost=1;
1127: my @intdoms;
1128: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1129: if (ref($internet_names) eq 'ARRAY') {
1130: @intdoms = @{$internet_names};
1131: }
1132: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1133: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1134: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1135: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1136: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1137: $canhost = &can_host_session($udom,$try_server,$remoterev,
1138: $remotesessions,
1139: $defdomdefaults{'hostedsessions'});
1140: }
1141: return $canhost;
1142: }
1143:
1.1123 raeburn 1144: sub this_host_spares {
1145: my ($dom) = @_;
1.1126 raeburn 1146: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1147: my @hosts = ¤t_machine_ids();
1148: foreach my $lonhost (@hosts) {
1149: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1150: $dom_in_use = $dom;
1151: $lonhost_in_use = $lonhost;
1.1123 raeburn 1152: last;
1153: }
1154: }
1.1126 raeburn 1155: if ($dom_in_use ne '') {
1156: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1157: }
1158: if (ref($result) ne 'HASH') {
1159: $lonhost_in_use = $perlvar{'lonHostID'};
1160: $dom_in_use = &host_domain($lonhost_in_use);
1161: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1162: if (ref($result) ne 'HASH') {
1163: $result = \%spareid;
1164: }
1165: }
1166: return $result;
1167: }
1168:
1169: sub spares_for_offload {
1170: my ($dom_in_use,$lonhost_in_use) = @_;
1171: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1172: if (defined($cached)) {
1173: return $result;
1174: } else {
1.1126 raeburn 1175: my $cachetime = 60*60*24;
1176: my %domconfig =
1177: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1178: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1179: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1180: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1181: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1182: }
1183: }
1184: }
1185: }
1.1126 raeburn 1186: return;
1.1123 raeburn 1187: }
1188:
1.1129 raeburn 1189: sub get_lonbalancer_config {
1190: my ($servers) = @_;
1191: my ($currbalancer,$currtargets);
1192: if (ref($servers) eq 'HASH') {
1193: foreach my $server (keys(%{$servers})) {
1194: my %what = (
1195: spareid => 1,
1196: perlvar => 1,
1197: );
1198: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1199: if ($result eq 'ok') {
1200: if (ref($returnhash) eq 'HASH') {
1201: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1202: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1203: $currbalancer = $server;
1204: $currtargets = {};
1205: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1206: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1207: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1208: }
1209: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1210: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1211: }
1212: }
1213: last;
1214: }
1215: }
1216: }
1217: }
1218: }
1219: }
1220: return ($currbalancer,$currtargets);
1221: }
1222:
1223: sub check_loadbalancing {
1224: my ($uname,$udom) = @_;
1225: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1226: $offloadto,$otherserver);
1227: my $lonhost = $perlvar{'lonHostID'};
1228: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1229: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1230: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1231: my $serverhomedom = &host_domain($lonhost);
1232:
1233: my $cachetime = 60*60*24;
1234:
1235: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1236: $dom_in_use = $udom;
1237: $homeintdom = 1;
1238: } else {
1239: $dom_in_use = $serverhomedom;
1240: }
1241: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1242: unless (defined($cached)) {
1243: my %domconfig =
1244: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1245: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1246: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1247: }
1248: }
1249: if (ref($result) eq 'HASH') {
1250: my $currbalancer = $result->{'lonhost'};
1251: my $currtargets = $result->{'targets'};
1252: my $currrules = $result->{'rules'};
1253: if ($currbalancer ne '') {
1254: my @hosts = ¤t_machine_ids();
1255: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1256: $is_balancer = 1;
1257: }
1258: }
1259: if ($is_balancer) {
1260: if (ref($currrules) eq 'HASH') {
1261: if ($homeintdom) {
1262: if ($uname ne '') {
1263: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1264: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1265: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1266: $rule_in_effect = $currrules->{'_LC_author'};
1267: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1268: $rule_in_effect = $currrules->{'_LC_adv'}
1269: }
1270: }
1271: if ($rule_in_effect eq '') {
1272: my %userenv = &userenvironment($udom,$uname,'inststatus');
1273: if ($userenv{'inststatus'} ne '') {
1274: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1275: my ($othertitle,$usertypes,$types) =
1276: &Apache::loncommon::sorted_inst_types($udom);
1277: if (ref($types) eq 'ARRAY') {
1278: foreach my $type (@{$types}) {
1279: if (grep(/^\Q$type\E$/,@statuses)) {
1280: if (exists($currrules->{$type})) {
1281: $rule_in_effect = $currrules->{$type};
1282: }
1283: }
1284: }
1285: }
1286: } else {
1287: if (exists($currrules->{'default'})) {
1288: $rule_in_effect = $currrules->{'default'};
1289: }
1290: }
1291: }
1292: } else {
1293: if (exists($currrules->{'default'})) {
1294: $rule_in_effect = $currrules->{'default'};
1295: }
1296: }
1297: } else {
1298: if ($currrules->{'_LC_external'} ne '') {
1299: $rule_in_effect = $currrules->{'_LC_external'};
1300: }
1301: }
1302: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1303: $uname,$udom);
1304: }
1305: }
1306: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1307: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1308: unless (defined($cached)) {
1309: my %domconfig =
1310: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1311: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1312: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1313: }
1314: }
1315: if (ref($result) eq 'HASH') {
1316: my $currbalancer = $result->{'lonhost'};
1317: my $currtargets = $result->{'targets'};
1318: my $currrules = $result->{'rules'};
1319:
1320: if ($currbalancer eq $lonhost) {
1321: $is_balancer = 1;
1322: if (ref($currrules) eq 'HASH') {
1323: if ($currrules->{'_LC_internetdom'} ne '') {
1324: $rule_in_effect = $currrules->{'_LC_internetdom'};
1325: }
1326: }
1327: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1328: $uname,$udom);
1329: }
1330: } else {
1331: if ($perlvar{'lonBalancer'} eq 'yes') {
1332: $is_balancer = 1;
1333: $offloadto = &this_host_spares($dom_in_use);
1334: }
1335: }
1336: } else {
1337: if ($perlvar{'lonBalancer'} eq 'yes') {
1338: $is_balancer = 1;
1339: $offloadto = &this_host_spares($dom_in_use);
1340: }
1341: }
1342: my $lowest_load = 30000;
1343: if (ref($offloadto) eq 'HASH') {
1344: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1345: foreach my $try_server (@{$offloadto->{'primary'}}) {
1346: ($otherserver,$lowest_load) =
1347: &compare_server_load($try_server,$otherserver,$lowest_load);
1348: }
1349: }
1350: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1351:
1352: if (!$found_server) {
1353: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1354: foreach my $try_server (@{$offloadto->{'default'}}) {
1355: ($otherserver,$lowest_load) =
1356: &compare_server_load($try_server,$otherserver,$lowest_load);
1357: }
1358: }
1359: }
1360: } elsif (ref($offloadto) eq 'ARRAY') {
1361: if (@{$offloadto} == 1) {
1362: $otherserver = $offloadto->[0];
1363: } elsif (@{$offloadto} > 1) {
1364: foreach my $try_server (@{$offloadto}) {
1365: ($otherserver,$lowest_load) =
1366: &compare_server_load($try_server,$otherserver,$lowest_load);
1367: }
1368: }
1369: }
1370: return ($is_balancer,$otherserver);
1371: }
1372:
1373: sub get_loadbalancer_targets {
1374: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1375: my $offloadto;
1376: if ($rule_in_effect eq '') {
1377: $offloadto = $currtargets;
1378: } else {
1379: if ($rule_in_effect eq 'homeserver') {
1380: my $homeserver = &homeserver($uname,$udom);
1381: if ($homeserver ne 'no_host') {
1382: $offloadto = [$homeserver];
1383: }
1384: } elsif ($rule_in_effect eq 'externalbalancer') {
1385: my %domconfig =
1386: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1387: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1388: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1389: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1390: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1391: }
1392: }
1393: } else {
1394: my %servers = &dom_servers($udom);
1395: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1396: if (&hostname($remotebalancer) ne '') {
1397: $offloadto = [$remotebalancer];
1398: }
1399: }
1400: } elsif (&hostname($rule_in_effect) ne '') {
1401: $offloadto = [$rule_in_effect];
1402: }
1403: }
1404: return $offloadto;
1405: }
1406:
1.1127 raeburn 1407: sub internet_dom_servers {
1408: my ($dom) = @_;
1409: my (%uniqservers,%servers);
1410: my $primaryserver = &hostname(&domain($dom,'primary'));
1411: my @machinedoms = &machine_domains($primaryserver);
1412: foreach my $mdom (@machinedoms) {
1413: my %currservers = %servers;
1414: my %server = &get_servers($mdom);
1415: %servers = (%currservers,%server);
1416: }
1417: my %by_hostname;
1418: foreach my $id (keys(%servers)) {
1419: push(@{$by_hostname{$servers{$id}}},$id);
1420: }
1421: foreach my $hostname (sort(keys(%by_hostname))) {
1422: if (@{$by_hostname{$hostname}} > 1) {
1423: my $match = 0;
1424: foreach my $id (@{$by_hostname{$hostname}}) {
1425: if (&host_domain($id) eq $dom) {
1426: $uniqservers{$id} = $hostname;
1427: $match = 1;
1428: }
1429: }
1430: unless ($match) {
1431: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1432: }
1433: } else {
1434: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1435: }
1436: }
1437: return %uniqservers;
1438: }
1439:
1.1 albertel 1440: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1441:
1.599 albertel 1442: my %homecache;
1.1 albertel 1443: sub homeserver {
1.230 stredwic 1444: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1445: my $index="$uname:$udom";
1.426 albertel 1446:
1.599 albertel 1447: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1448:
1449: my %servers = &get_servers($udom,'library');
1450: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1451: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1452: exists($badServerCache{$tryserver}));
1.841 albertel 1453:
1454: my $answer=reply("home:$udom:$uname",$tryserver);
1455: if ($answer eq 'found') {
1456: delete($badServerCache{$tryserver});
1457: return $homecache{$index}=$tryserver;
1458: } elsif ($answer eq 'no_host') {
1459: $badServerCache{$tryserver}=1;
1460: }
1.1 albertel 1461: }
1462: return 'no_host';
1.70 www 1463: }
1464:
1465: # ------------------------------------- Find the usernames behind a list of IDs
1466:
1467: sub idget {
1468: my ($udom,@ids)=@_;
1469: my %returnhash=();
1470:
1.841 albertel 1471: my %servers = &get_servers($udom,'library');
1472: foreach my $tryserver (keys(%servers)) {
1473: my $idlist=join('&',@ids);
1474: $idlist=~tr/A-Z/a-z/;
1475: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1476: my @answer=();
1477: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1478: @answer=split(/\&/,$reply);
1479: } ;
1480: my $i;
1481: for ($i=0;$i<=$#ids;$i++) {
1482: if ($answer[$i]) {
1483: $returnhash{$ids[$i]}=$answer[$i];
1484: }
1485: }
1486: }
1.70 www 1487: return %returnhash;
1488: }
1489:
1490: # ------------------------------------- Find the IDs behind a list of usernames
1491:
1492: sub idrget {
1493: my ($udom,@unames)=@_;
1494: my %returnhash=();
1.800 albertel 1495: foreach my $uname (@unames) {
1496: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1497: }
1.70 www 1498: return %returnhash;
1499: }
1500:
1501: # ------------------------------- Store away a list of names and associated IDs
1502:
1503: sub idput {
1504: my ($udom,%ids)=@_;
1505: my %servers=();
1.800 albertel 1506: foreach my $uname (keys(%ids)) {
1507: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1508: my $uhom=&homeserver($uname,$udom);
1.70 www 1509: if ($uhom ne 'no_host') {
1.800 albertel 1510: my $id=&escape($ids{$uname});
1.70 www 1511: $id=~tr/A-Z/a-z/;
1.800 albertel 1512: my $esc_unam=&escape($uname);
1.70 www 1513: if ($servers{$uhom}) {
1.800 albertel 1514: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1515: } else {
1.800 albertel 1516: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1517: }
1518: }
1.191 harris41 1519: }
1.800 albertel 1520: foreach my $server (keys(%servers)) {
1521: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1522: }
1.344 www 1523: }
1524:
1.1023 raeburn 1525: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1526: sub dump_dom {
1.1023 raeburn 1527: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1528: if (!$udom) {
1529: $udom=$env{'user.domain'};
1530: }
1531: my %returnhash;
1.1023 raeburn 1532: if ($udom) {
1533: my $uname = &get_domainconfiguser($udom);
1534: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1535: }
1536: return %returnhash;
1537: }
1538:
1.1023 raeburn 1539: # ------------------------------------------ get items from domain db files
1.806 raeburn 1540:
1541: sub get_dom {
1.860 raeburn 1542: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1543: my $items='';
1544: foreach my $item (@$storearr) {
1545: $items.=&escape($item).'&';
1546: }
1547: $items=~s/\&$//;
1.860 raeburn 1548: if (!$udom) {
1549: $udom=$env{'user.domain'};
1550: if (defined(&domain($udom,'primary'))) {
1551: $uhome=&domain($udom,'primary');
1552: } else {
1.874 albertel 1553: undef($uhome);
1.860 raeburn 1554: }
1555: } else {
1556: if (!$uhome) {
1557: if (defined(&domain($udom,'primary'))) {
1558: $uhome=&domain($udom,'primary');
1559: }
1560: }
1561: }
1562: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1563: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1564: my %returnhash;
1.875 albertel 1565: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1566: return %returnhash;
1567: }
1.806 raeburn 1568: my @pairs=split(/\&/,$rep);
1569: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1570: return @pairs;
1571: }
1572: my $i=0;
1573: foreach my $item (@$storearr) {
1574: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1575: $i++;
1576: }
1577: return %returnhash;
1578: } else {
1.880 banghart 1579: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1580: }
1581: }
1582:
1583: # -------------------------------------------- put items in domain db files
1584:
1585: sub put_dom {
1.860 raeburn 1586: my ($namespace,$storehash,$udom,$uhome)=@_;
1587: if (!$udom) {
1588: $udom=$env{'user.domain'};
1589: if (defined(&domain($udom,'primary'))) {
1590: $uhome=&domain($udom,'primary');
1591: } else {
1.874 albertel 1592: undef($uhome);
1.860 raeburn 1593: }
1594: } else {
1595: if (!$uhome) {
1596: if (defined(&domain($udom,'primary'))) {
1597: $uhome=&domain($udom,'primary');
1598: }
1599: }
1600: }
1601: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1602: my $items='';
1603: foreach my $item (keys(%$storehash)) {
1604: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1605: }
1606: $items=~s/\&$//;
1607: return &reply("putdom:$udom:$namespace:$items",$uhome);
1608: } else {
1.860 raeburn 1609: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1610: }
1611: }
1612:
1.1023 raeburn 1613: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1614: sub newput_dom {
1.1023 raeburn 1615: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1616: my $result;
1617: if (!$udom) {
1618: $udom=$env{'user.domain'};
1619: }
1.1023 raeburn 1620: if ($udom) {
1621: my $uname = &get_domainconfiguser($udom);
1622: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1623: }
1624: return $result;
1625: }
1626:
1.1023 raeburn 1627: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1628: sub del_dom {
1.1023 raeburn 1629: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1630: if (ref($storearr) eq 'ARRAY') {
1631: if (!$udom) {
1632: $udom=$env{'user.domain'};
1633: }
1.1023 raeburn 1634: if ($udom) {
1635: my $uname = &get_domainconfiguser($udom);
1636: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1637: }
1638: }
1639: }
1640:
1.1023 raeburn 1641: # ----------------------------------construct domainconfig user for a domain
1642: sub get_domainconfiguser {
1643: my ($udom) = @_;
1644: return $udom.'-domainconfig';
1645: }
1646:
1.837 raeburn 1647: sub retrieve_inst_usertypes {
1648: my ($udom) = @_;
1649: my (%returnhash,@order);
1.989 raeburn 1650: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1651: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1652: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1653: %returnhash = %{$domdefs{'inststatustypes'}};
1654: @order = @{$domdefs{'inststatusorder'}};
1655: } else {
1656: if (defined(&domain($udom,'primary'))) {
1657: my $uhome=&domain($udom,'primary');
1658: my $rep=&reply("inst_usertypes:$udom",$uhome);
1659: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1660: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1661: return (\%returnhash,\@order);
1662: }
1663: my ($hashitems,$orderitems) = split(/:/,$rep);
1664: my @pairs=split(/\&/,$hashitems);
1665: foreach my $item (@pairs) {
1666: my ($key,$value)=split(/=/,$item,2);
1667: $key = &unescape($key);
1668: next if ($key =~ /^error: 2 /);
1669: $returnhash{$key}=&thaw_unescape($value);
1670: }
1671: my @esc_order = split(/\&/,$orderitems);
1672: foreach my $item (@esc_order) {
1673: push(@order,&unescape($item));
1674: }
1675: } else {
1676: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1677: }
1678: }
1679: return (\%returnhash,\@order);
1680: }
1681:
1.868 raeburn 1682: sub is_domainimage {
1683: my ($url) = @_;
1684: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1685: if (&domain($1) ne '') {
1686: return '1';
1687: }
1688: }
1689: return;
1690: }
1691:
1.899 raeburn 1692: sub inst_directory_query {
1693: my ($srch) = @_;
1694: my $udom = $srch->{'srchdomain'};
1695: my %results;
1696: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1697: my $outcome;
1.899 raeburn 1698: if ($homeserver ne '') {
1.904 albertel 1699: my $queryid=&reply("querysend:instdirsearch:".
1700: &escape($srch->{'srchby'}).':'.
1701: &escape($srch->{'srchterm'}).':'.
1702: &escape($srch->{'srchtype'}),$homeserver);
1703: my $host=&hostname($homeserver);
1704: if ($queryid !~/^\Q$host\E\_/) {
1705: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1706: return;
1707: }
1708: my $response = &get_query_reply($queryid);
1709: my $maxtries = 5;
1710: my $tries = 1;
1711: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1712: $response = &get_query_reply($queryid);
1713: $tries ++;
1714: }
1715:
1716: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1717: if ($response eq 'unavailable') {
1718: $outcome = $response;
1719: } else {
1720: $outcome = 'ok';
1721: my @matches = split(/\n/,$response);
1722: foreach my $match (@matches) {
1723: my ($key,$value) = split(/=/,$match);
1724: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1725: }
1.899 raeburn 1726: }
1727: }
1728: }
1.909 raeburn 1729: return ($outcome,%results);
1.899 raeburn 1730: }
1731:
1732: sub usersearch {
1733: my ($srch) = @_;
1734: my $dom = $srch->{'srchdomain'};
1735: my %results;
1736: my %libserv = &all_library();
1737: my $query = 'usersearch';
1738: foreach my $tryserver (keys(%libserv)) {
1739: if (&host_domain($tryserver) eq $dom) {
1740: my $host=&hostname($tryserver);
1741: my $queryid=
1.911 raeburn 1742: &reply("querysend:".&escape($query).':'.
1743: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1744: &escape($srch->{'srchtype'}).':'.
1745: &escape($srch->{'srchterm'}),$tryserver);
1746: if ($queryid !~/^\Q$host\E\_/) {
1747: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1748: next;
1.899 raeburn 1749: }
1750: my $reply = &get_query_reply($queryid);
1751: my $maxtries = 1;
1752: my $tries = 1;
1753: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1754: $reply = &get_query_reply($queryid);
1755: $tries ++;
1756: }
1757: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1758: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1759: } else {
1.911 raeburn 1760: my @matches;
1761: if ($reply =~ /\n/) {
1762: @matches = split(/\n/,$reply);
1763: } else {
1764: @matches = split(/\&/,$reply);
1765: }
1.899 raeburn 1766: foreach my $match (@matches) {
1767: my ($uname,$udom,%userhash);
1.911 raeburn 1768: foreach my $entry (split(/:/,$match)) {
1769: my ($key,$value) =
1770: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1771: $userhash{$key} = $value;
1772: if ($key eq 'username') {
1773: $uname = $value;
1774: } elsif ($key eq 'domain') {
1775: $udom = $value;
1.911 raeburn 1776: }
1.899 raeburn 1777: }
1778: $results{$uname.':'.$udom} = \%userhash;
1779: }
1780: }
1781: }
1782: }
1783: return %results;
1784: }
1785:
1.912 raeburn 1786: sub get_instuser {
1787: my ($udom,$uname,$id) = @_;
1788: my $homeserver = &domain($udom,'primary');
1789: my ($outcome,%results);
1790: if ($homeserver ne '') {
1791: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1792: &escape($id).':'.&escape($udom),$homeserver);
1793: my $host=&hostname($homeserver);
1794: if ($queryid !~/^\Q$host\E\_/) {
1795: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1796: return;
1797: }
1798: my $response = &get_query_reply($queryid);
1799: my $maxtries = 5;
1800: my $tries = 1;
1801: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1802: $response = &get_query_reply($queryid);
1803: $tries ++;
1804: }
1805: if (!&error($response) && $response ne 'refused') {
1806: if ($response eq 'unavailable') {
1807: $outcome = $response;
1808: } else {
1809: $outcome = 'ok';
1810: my @matches = split(/\n/,$response);
1811: foreach my $match (@matches) {
1812: my ($key,$value) = split(/=/,$match);
1813: $results{&unescape($key)} = &thaw_unescape($value);
1814: }
1815: }
1816: }
1817: }
1818: my %userinfo;
1819: if (ref($results{$uname}) eq 'HASH') {
1820: %userinfo = %{$results{$uname}};
1821: }
1822: return ($outcome,%userinfo);
1823: }
1824:
1825: sub inst_rulecheck {
1.923 raeburn 1826: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1827: my %returnhash;
1828: if ($udom ne '') {
1829: if (ref($rules) eq 'ARRAY') {
1830: @{$rules} = map {&escape($_);} (@{$rules});
1831: my $rulestr = join(':',@{$rules});
1832: my $homeserver=&domain($udom,'primary');
1833: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1834: my $response;
1835: if ($item eq 'username') {
1836: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1837: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1838: $homeserver));
1.923 raeburn 1839: } elsif ($item eq 'id') {
1840: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1841: ':'.&escape($id).':'.$rulestr,
1842: $homeserver));
1.945 raeburn 1843: } elsif ($item eq 'selfcreate') {
1844: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1845: &escape($udom).':'.&escape($uname).
1846: ':'.$rulestr,$homeserver));
1.923 raeburn 1847: }
1.912 raeburn 1848: if ($response ne 'refused') {
1849: my @pairs=split(/\&/,$response);
1850: foreach my $item (@pairs) {
1851: my ($key,$value)=split(/=/,$item,2);
1852: $key = &unescape($key);
1853: next if ($key =~ /^error: 2 /);
1854: $returnhash{$key}=&thaw_unescape($value);
1855: }
1856: }
1857: }
1858: }
1859: }
1860: return %returnhash;
1861: }
1862:
1863: sub inst_userrules {
1.923 raeburn 1864: my ($udom,$check) = @_;
1.912 raeburn 1865: my (%ruleshash,@ruleorder);
1866: if ($udom ne '') {
1867: my $homeserver=&domain($udom,'primary');
1868: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1869: my $response;
1870: if ($check eq 'id') {
1871: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1872: $homeserver);
1.943 raeburn 1873: } elsif ($check eq 'email') {
1874: $response=&reply('instemailrules:'.&escape($udom),
1875: $homeserver);
1.923 raeburn 1876: } else {
1877: $response=&reply('instuserrules:'.&escape($udom),
1878: $homeserver);
1879: }
1.912 raeburn 1880: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1881: ($response ne 'unknown_cmd') &&
1.912 raeburn 1882: ($response ne 'no_such_host')) {
1883: my ($hashitems,$orderitems) = split(/:/,$response);
1884: my @pairs=split(/\&/,$hashitems);
1885: foreach my $item (@pairs) {
1886: my ($key,$value)=split(/=/,$item,2);
1887: $key = &unescape($key);
1888: next if ($key =~ /^error: 2 /);
1889: $ruleshash{$key}=&thaw_unescape($value);
1890: }
1891: my @esc_order = split(/\&/,$orderitems);
1892: foreach my $item (@esc_order) {
1893: push(@ruleorder,&unescape($item));
1894: }
1895: }
1896: }
1897: }
1898: return (\%ruleshash,\@ruleorder);
1899: }
1900:
1.976 raeburn 1901: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1902:
1903: sub get_domain_defaults {
1904: my ($domain) = @_;
1905: my $cachetime = 60*60*24;
1906: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1907: if (defined($cached)) {
1908: if (ref($result) eq 'HASH') {
1909: return %{$result};
1910: }
1911: }
1912: my %domdefaults;
1913: my %domconfig =
1.989 raeburn 1914: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1915: 'requestcourses','inststatus',
1.1073 raeburn 1916: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1917: if (ref($domconfig{'defaults'}) eq 'HASH') {
1918: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1919: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1920: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1921: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1922: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1923: } else {
1924: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1925: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1926: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1927: }
1.976 raeburn 1928: if (ref($domconfig{'quotas'}) eq 'HASH') {
1929: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1930: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1931: } else {
1932: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1933: }
1934: my @usertools = ('aboutme','blog','portfolio');
1935: foreach my $item (@usertools) {
1936: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1937: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1938: }
1939: }
1940: }
1.985 raeburn 1941: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1942: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1943: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1944: }
1945: }
1.989 raeburn 1946: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1947: foreach my $item ('inststatustypes','inststatusorder') {
1948: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1949: }
1950: }
1.1047 raeburn 1951: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1952: foreach my $item ('canuse_pdfforms') {
1953: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1954: }
1955: }
1.1073 raeburn 1956: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1957: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1958: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1959: }
1960: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1961: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1962: }
1963: }
1.943 raeburn 1964: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1965: $cachetime);
1966: return %domdefaults;
1967: }
1968:
1.344 www 1969: # --------------------------------------------------- Assign a key to a student
1970:
1971: sub assign_access_key {
1.364 www 1972: #
1973: # a valid key looks like uname:udom#comments
1974: # comments are being appended
1975: #
1.498 www 1976: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1977: $kdom=
1.620 albertel 1978: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1979: $knum=
1.620 albertel 1980: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1981: $cdom=
1.620 albertel 1982: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1983: $cnum=
1.620 albertel 1984: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1985: $udom=$env{'user.name'} unless (defined($udom));
1986: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1987: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1988: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1989: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1990: # assigned to this person
1991: # - this should not happen,
1.345 www 1992: # unless something went wrong
1993: # the first time around
1994: # ready to assign
1.364 www 1995: $logentry=$1.'; '.$logentry;
1.496 www 1996: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1997: $kdom,$knum) eq 'ok') {
1.345 www 1998: # key now belongs to user
1.346 www 1999: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2000: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2001: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2002: return 'ok';
2003: } else {
2004: return
2005: 'error: Count not permanently assign key, will need to be re-entered later.';
2006: }
2007: } else {
2008: return 'error: Could not assign key, try again later.';
2009: }
1.364 www 2010: } elsif (!$existing{$ckey}) {
1.345 www 2011: # the key does not exist
2012: return 'error: The key does not exist';
2013: } else {
2014: # the key is somebody else's
2015: return 'error: The key is already in use';
2016: }
1.344 www 2017: }
2018:
1.364 www 2019: # ------------------------------------------ put an additional comment on a key
2020:
2021: sub comment_access_key {
2022: #
2023: # a valid key looks like uname:udom#comments
2024: # comments are being appended
2025: #
2026: my ($ckey,$cdom,$cnum,$logentry)=@_;
2027: $cdom=
1.620 albertel 2028: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2029: $cnum=
1.620 albertel 2030: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2031: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2032: if ($existing{$ckey}) {
2033: $existing{$ckey}.='; '.$logentry;
2034: # ready to assign
1.367 www 2035: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2036: $cdom,$cnum) eq 'ok') {
2037: return 'ok';
2038: } else {
2039: return 'error: Count not store comment.';
2040: }
2041: } else {
2042: # the key does not exist
2043: return 'error: The key does not exist';
2044: }
2045: }
2046:
1.344 www 2047: # ------------------------------------------------------ Generate a set of keys
2048:
2049: sub generate_access_keys {
1.364 www 2050: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2051: $cdom=
1.620 albertel 2052: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2053: $cnum=
1.620 albertel 2054: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2055: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2056: unless (($cdom) && ($cnum)) { return 0; }
2057: if ($number>10000) { return 0; }
2058: sleep(2); # make sure don't get same seed twice
2059: srand(time()^($$+($$<<15))); # from "Programming Perl"
2060: my $total=0;
2061: for (my $i=1;$i<=$number;$i++) {
2062: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2063: sprintf("%lx",int(100000*rand)).'-'.
2064: sprintf("%lx",int(100000*rand));
2065: $newkey=~s/1/g/g; # folks mix up 1 and l
2066: $newkey=~s/0/h/g; # and also 0 and O
2067: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2068: if ($existing{$newkey}) {
2069: $i--;
2070: } else {
1.364 www 2071: if (&put('accesskeys',
2072: { $newkey => '# generated '.localtime().
1.620 albertel 2073: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2074: '; '.$logentry },
2075: $cdom,$cnum) eq 'ok') {
1.344 www 2076: $total++;
2077: }
2078: }
2079: }
1.620 albertel 2080: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2081: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2082: return $total;
2083: }
2084:
2085: # ------------------------------------------------------- Validate an accesskey
2086:
2087: sub validate_access_key {
2088: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2089: $cdom=
1.620 albertel 2090: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2091: $cnum=
1.620 albertel 2092: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2093: $udom=$env{'user.domain'} unless (defined($udom));
2094: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2095: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2096: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2097: }
2098:
2099: # ------------------------------------- Find the section of student in a course
1.652 albertel 2100: sub devalidate_getsection_cache {
2101: my ($udom,$unam,$courseid)=@_;
2102: my $hashid="$udom:$unam:$courseid";
2103: &devalidate_cache_new('getsection',$hashid);
2104: }
1.298 matthew 2105:
1.815 albertel 2106: sub courseid_to_courseurl {
2107: my ($courseid) = @_;
2108: #already url style courseid
2109: return $courseid if ($courseid =~ m{^/});
2110:
2111: if (exists($env{'course.'.$courseid.'.num'})) {
2112: my $cnum = $env{'course.'.$courseid.'.num'};
2113: my $cdom = $env{'course.'.$courseid.'.domain'};
2114: return "/$cdom/$cnum";
2115: }
2116:
2117: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2118: if (exists($courseinfo{'num'})) {
2119: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2120: }
2121:
2122: return undef;
2123: }
2124:
1.298 matthew 2125: sub getsection {
2126: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2127: my $cachetime=1800;
1.551 albertel 2128:
2129: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2130: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2131: if (defined($cached)) { return $result; }
2132:
1.298 matthew 2133: my %Pending;
2134: my %Expired;
2135: #
2136: # Each role can either have not started yet (pending), be active,
2137: # or have expired.
2138: #
2139: # If there is an active role, we are done.
2140: #
2141: # If there is more than one role which has not started yet,
2142: # choose the one which will start sooner
2143: # If there is one role which has not started yet, return it.
2144: #
2145: # If there is more than one expired role, choose the one which ended last.
2146: # If there is a role which has expired, return it.
2147: #
1.815 albertel 2148: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 2149: my $extra = &freeze_escape({'skipcheck' => 1});
2150: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 2151: foreach my $key (keys(%roleshash)) {
1.479 albertel 2152: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2153: my $section=$1;
2154: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2155: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2156: my $now=time;
1.548 albertel 2157: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2158: $Expired{$end}=$section;
2159: next;
2160: }
1.548 albertel 2161: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2162: $Pending{$start}=$section;
2163: next;
2164: }
1.599 albertel 2165: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2166: }
2167: #
2168: # Presumedly there will be few matching roles from the above
2169: # loop and the sorting time will be negligible.
2170: if (scalar(keys(%Pending))) {
2171: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2172: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2173: }
2174: if (scalar(keys(%Expired))) {
2175: my @sorted = sort {$a <=> $b} keys(%Expired);
2176: my $time = pop(@sorted);
1.599 albertel 2177: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2178: }
1.599 albertel 2179: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2180: }
1.70 www 2181:
1.599 albertel 2182: sub save_cache {
2183: &purge_remembered();
1.722 albertel 2184: #&Apache::loncommon::validate_page();
1.620 albertel 2185: undef(%env);
1.780 albertel 2186: undef($env_loaded);
1.599 albertel 2187: }
1.452 albertel 2188:
1.599 albertel 2189: my $to_remember=-1;
2190: my %remembered;
2191: my %accessed;
2192: my $kicks=0;
2193: my $hits=0;
1.849 albertel 2194: sub make_key {
2195: my ($name,$id) = @_;
1.872 albertel 2196: if (length($id) > 65
2197: && length(&escape($id)) > 200) {
2198: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2199: }
1.849 albertel 2200: return &escape($name.':'.$id);
2201: }
2202:
1.599 albertel 2203: sub devalidate_cache_new {
2204: my ($name,$id,$debug) = @_;
2205: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2206: $id=&make_key($name,$id);
1.599 albertel 2207: $memcache->delete($id);
2208: delete($remembered{$id});
2209: delete($accessed{$id});
2210: }
2211:
2212: sub is_cached_new {
2213: my ($name,$id,$debug) = @_;
1.849 albertel 2214: $id=&make_key($name,$id);
1.599 albertel 2215: if (exists($remembered{$id})) {
1.1133 foxr 2216: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2217: $accessed{$id}=[&gettimeofday()];
2218: $hits++;
2219: return ($remembered{$id},1);
2220: }
2221: my $value = $memcache->get($id);
2222: if (!(defined($value))) {
2223: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2224: return (undef,undef);
1.416 albertel 2225: }
1.599 albertel 2226: if ($value eq '__undef__') {
2227: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2228: $value=undef;
2229: }
2230: &make_room($id,$value,$debug);
2231: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2232: return ($value,1);
2233: }
2234:
2235: sub do_cache_new {
2236: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2237: $id=&make_key($name,$id);
1.599 albertel 2238: my $setvalue=$value;
2239: if (!defined($setvalue)) {
2240: $setvalue='__undef__';
2241: }
1.623 albertel 2242: if (!defined($time) ) {
2243: $time=600;
2244: }
1.599 albertel 2245: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2246: my $result = $memcache->set($id,$setvalue,$time);
2247: if (! $result) {
1.872 albertel 2248: &logthis("caching of id -> $id failed");
1.910 albertel 2249: $memcache->disconnect_all();
1.872 albertel 2250: }
1.600 albertel 2251: # need to make a copy of $value
1.919 albertel 2252: &make_room($id,$value,$debug);
1.599 albertel 2253: return $value;
2254: }
2255:
2256: sub make_room {
2257: my ($id,$value,$debug)=@_;
1.919 albertel 2258:
2259: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2260: : $value;
1.599 albertel 2261: if ($to_remember<0) { return; }
2262: $accessed{$id}=[&gettimeofday()];
2263: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2264: my $to_kick;
2265: my $max_time=0;
2266: foreach my $other (keys(%accessed)) {
2267: if (&tv_interval($accessed{$other}) > $max_time) {
2268: $to_kick=$other;
2269: $max_time=&tv_interval($accessed{$other});
2270: }
2271: }
2272: delete($remembered{$to_kick});
2273: delete($accessed{$to_kick});
2274: $kicks++;
2275: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2276: return;
2277: }
2278:
1.599 albertel 2279: sub purge_remembered {
1.604 albertel 2280: #&logthis("Tossing ".scalar(keys(%remembered)));
2281: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2282: undef(%remembered);
2283: undef(%accessed);
1.428 albertel 2284: }
1.70 www 2285: # ------------------------------------- Read an entry from a user's environment
2286:
2287: sub userenvironment {
2288: my ($udom,$unam,@what)=@_;
1.976 raeburn 2289: my $items;
2290: foreach my $item (@what) {
2291: $items.=&escape($item).'&';
2292: }
2293: $items=~s/\&$//;
1.70 www 2294: my %returnhash=();
1.1009 raeburn 2295: my $uhome = &homeserver($unam,$udom);
2296: unless ($uhome eq 'no_host') {
2297: my @answer=split(/\&/,
2298: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2299: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2300: return %returnhash;
2301: }
1.1009 raeburn 2302: my $i;
2303: for ($i=0;$i<=$#what;$i++) {
2304: $returnhash{$what[$i]}=&unescape($answer[$i]);
2305: }
1.70 www 2306: }
2307: return %returnhash;
1.1 albertel 2308: }
2309:
1.617 albertel 2310: # ---------------------------------------------------------- Get a studentphoto
2311: sub studentphoto {
2312: my ($udom,$unam,$ext) = @_;
2313: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2314: if (defined($env{'request.course.id'})) {
1.708 raeburn 2315: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2316: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2317: return(&retrievestudentphoto($udom,$unam,$ext));
2318: } else {
2319: my ($result,$perm_reqd)=
1.707 albertel 2320: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2321: if ($result eq 'ok') {
2322: if (!($perm_reqd eq 'yes')) {
2323: return(&retrievestudentphoto($udom,$unam,$ext));
2324: }
2325: }
2326: }
2327: }
2328: } else {
2329: my ($result,$perm_reqd) =
1.707 albertel 2330: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2331: if ($result eq 'ok') {
2332: if (!($perm_reqd eq 'yes')) {
2333: return(&retrievestudentphoto($udom,$unam,$ext));
2334: }
2335: }
2336: }
2337: return '/adm/lonKaputt/lonlogo_broken.gif';
2338: }
2339:
2340: sub retrievestudentphoto {
2341: my ($udom,$unam,$ext,$type) = @_;
2342: my $home=&Apache::lonnet::homeserver($unam,$udom);
2343: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2344: if ($ret eq 'ok') {
2345: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2346: if ($type eq 'thumbnail') {
2347: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2348: }
2349: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2350: return $tokenurl;
2351: } else {
2352: if ($type eq 'thumbnail') {
2353: return '/adm/lonKaputt/genericstudent_tn.gif';
2354: } else {
2355: return '/adm/lonKaputt/lonlogo_broken.gif';
2356: }
1.617 albertel 2357: }
2358: }
2359:
1.263 www 2360: # -------------------------------------------------------------------- New chat
2361:
2362: sub chatsend {
1.724 raeburn 2363: my ($newentry,$anon,$group)=@_;
1.620 albertel 2364: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2365: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2366: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2367: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2368: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2369: &escape($newentry)).':'.$group,$chome);
1.292 www 2370: }
2371:
2372: # ------------------------------------------ Find current version of a resource
2373:
2374: sub getversion {
2375: my $fname=&clutter(shift);
2376: unless ($fname=~/^\/res\//) { return -1; }
2377: return ¤tversion(&filelocation('',$fname));
2378: }
2379:
2380: sub currentversion {
2381: my $fname=shift;
2382: my $author=$fname;
2383: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2384: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2385: my $home=&homeserver($uname,$udom);
1.292 www 2386: if ($home eq 'no_host') {
2387: return -1;
2388: }
1.1112 www 2389: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2390: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2391: return -1;
2392: }
1.1112 www 2393: return $answer;
1.263 www 2394: }
2395:
1.1111 www 2396: #
2397: # Return special version number of resource if set by override, empty otherwise
2398: #
2399: sub usedversion {
2400: my $fname=shift;
2401: unless ($fname) { $fname=$env{'request.uri'}; }
2402: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2403: if ($urlversion) { return $urlversion; }
2404: return '';
2405: }
2406:
1.1 albertel 2407: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2408:
1.1 albertel 2409: sub subscribe {
2410: my $fname=shift;
1.761 raeburn 2411: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2412: $fname=~s/[\n\r]//g;
1.1 albertel 2413: my $author=$fname;
2414: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2415: my ($udom,$uname)=split(/\//,$author);
2416: my $home=homeserver($uname,$udom);
1.335 albertel 2417: if ($home eq 'no_host') {
2418: return 'not_found';
1.1 albertel 2419: }
2420: my $answer=reply("sub:$fname",$home);
1.64 www 2421: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2422: $answer.=' by '.$home;
2423: }
1.1 albertel 2424: return $answer;
2425: }
2426:
1.8 www 2427: # -------------------------------------------------------------- Replicate file
2428:
2429: sub repcopy {
2430: my $filename=shift;
1.23 www 2431: $filename=~s/\/+/\//g;
1.607 raeburn 2432: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2433: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2434: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2435: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2436: return &repcopy_userfile($filename);
2437: }
1.532 albertel 2438: $filename=~s/[\n\r]//g;
1.8 www 2439: my $transname="$filename.in.transfer";
1.828 www 2440: # FIXME: this should flock
1.607 raeburn 2441: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2442: my $remoteurl=subscribe($filename);
1.64 www 2443: if ($remoteurl =~ /^con_lost by/) {
2444: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2445: return 'unavailable';
1.8 www 2446: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2447: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2448: return 'not_found';
1.64 www 2449: } elsif ($remoteurl =~ /^rejected by/) {
2450: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2451: return 'forbidden';
1.20 www 2452: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2453: return 'ok';
1.8 www 2454: } else {
1.290 www 2455: my $author=$filename;
2456: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2457: my ($udom,$uname)=split(/\//,$author);
2458: my $home=homeserver($uname,$udom);
2459: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2460: my @parts=split(/\//,$filename);
2461: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2462: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2463: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2464: return 'bad_request';
1.8 www 2465: }
2466: my $count;
2467: for ($count=5;$count<$#parts;$count++) {
2468: $path.="/$parts[$count]";
2469: if ((-e $path)!=1) {
2470: mkdir($path,0777);
2471: }
2472: }
2473: my $ua=new LWP::UserAgent;
2474: my $request=new HTTP::Request('GET',"$remoteurl");
2475: my $response=$ua->request($request,$transname);
2476: if ($response->is_error()) {
2477: unlink($transname);
2478: my $message=$response->status_line;
1.672 albertel 2479: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2480: ." LWP get: $message: $filename</font>");
1.607 raeburn 2481: return 'unavailable';
1.8 www 2482: } else {
1.16 www 2483: if ($remoteurl!~/\.meta$/) {
2484: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2485: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2486: if ($mresponse->is_error()) {
2487: unlink($filename.'.meta');
2488: &logthis(
1.672 albertel 2489: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2490: }
2491: }
1.8 www 2492: rename($transname,$filename);
1.607 raeburn 2493: return 'ok';
1.8 www 2494: }
1.290 www 2495: }
1.8 www 2496: }
1.330 www 2497: }
2498:
2499: # ------------------------------------------------ Get server side include body
2500: sub ssi_body {
1.381 albertel 2501: my ($filelink,%form)=@_;
1.606 matthew 2502: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2503: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2504: }
1.953 www 2505: my $output='';
2506: my $response;
1.980 raeburn 2507: if ($filelink=~/^https?\:/) {
1.954 raeburn 2508: ($output,$response)=&externalssi($filelink);
1.953 www 2509: } else {
1.1004 droeschl 2510: $filelink .= $filelink=~/\?/ ? '&' : '?';
2511: $filelink .= 'inhibitmenu=yes';
1.953 www 2512: ($output,$response)=&ssi($filelink,%form);
2513: }
1.778 albertel 2514: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2515: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2516: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2517: if (wantarray) {
2518: return ($output, $response);
2519: } else {
2520: return $output;
2521: }
1.8 www 2522: }
2523:
1.15 www 2524: # --------------------------------------------------------- Server Side Include
2525:
1.782 albertel 2526: sub absolute_url {
2527: my ($host_name) = @_;
2528: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2529: if ($host_name eq '') {
2530: $host_name = $ENV{'SERVER_NAME'};
2531: }
2532: return $protocol.$host_name;
2533: }
2534:
1.942 foxr 2535: #
2536: # Server side include.
2537: # Parameters:
2538: # fn Possibly encrypted resource name/id.
2539: # form Hash that describes how the rendering should be done
2540: # and other things.
1.944 foxr 2541: # Returns:
1.950 raeburn 2542: # Scalar context: The content of the response.
2543: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2544: #
1.15 www 2545: sub ssi {
2546:
1.944 foxr 2547: my ($fn,%form)=@_;
1.15 www 2548: my $ua=new LWP::UserAgent;
1.23 www 2549: my $request;
1.711 albertel 2550:
2551: $form{'no_update_last_known'}=1;
1.895 albertel 2552: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2553: if (%form) {
1.782 albertel 2554: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2555: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2556: } else {
1.782 albertel 2557: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2558: }
2559:
1.15 www 2560: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2561: my $response=$ua->request($request);
2562:
1.944 foxr 2563: if (wantarray) {
2564: return ($response->content, $response);
2565: } else {
2566: return $response->content;
1.942 foxr 2567: }
1.324 www 2568: }
2569:
2570: sub externalssi {
2571: my ($url)=@_;
2572: my $ua=new LWP::UserAgent;
2573: my $request=new HTTP::Request('GET',$url);
2574: my $response=$ua->request($request);
1.954 raeburn 2575: if (wantarray) {
2576: return ($response->content, $response);
2577: } else {
2578: return $response->content;
2579: }
1.15 www 2580: }
1.254 www 2581:
1.492 albertel 2582: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2583:
2584: sub allowuploaded {
2585: my ($srcurl,$url)=@_;
2586: $url=&clutter(&declutter($url));
2587: my $dir=$url;
2588: $dir=~s/\/[^\/]+$//;
2589: my %httpref=();
2590: my $httpurl=&hreflocation('',$url);
2591: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2592: &Apache::lonnet::appenv(\%httpref);
1.254 www 2593: }
1.477 raeburn 2594:
1.478 albertel 2595: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2596: # input: action, courseID, current domain, intended
1.637 raeburn 2597: # path to file, source of file, instruction to parse file for objects,
2598: # ref to hash for embedded objects,
2599: # ref to hash for codebase of java objects.
1.1095 raeburn 2600: # reference to scalar to accommodate mime type determined
2601: # from File::MMagic if $parser = parse.
1.637 raeburn 2602: #
1.485 raeburn 2603: # output: url to file (if action was uploaddoc),
2604: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2605: #
1.478 albertel 2606: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2607: # course.
1.477 raeburn 2608: #
1.478 albertel 2609: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2610: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2611: # course's home server.
1.477 raeburn 2612: #
1.478 albertel 2613: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2614: # be copied from $source (current location) to
2615: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2616: # and will then be copied to
2617: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2618: # course's home server.
1.485 raeburn 2619: #
1.481 raeburn 2620: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2621: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2622: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2623: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2624: # in course's home server.
1.637 raeburn 2625: #
1.477 raeburn 2626:
2627: sub process_coursefile {
1.1095 raeburn 2628: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2629: $mimetype)=@_;
1.477 raeburn 2630: my $fetchresult;
1.638 albertel 2631: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2632: if ($action eq 'propagate') {
1.638 albertel 2633: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2634: $home);
1.481 raeburn 2635: } else {
1.477 raeburn 2636: my $fpath = '';
2637: my $fname = $file;
1.478 albertel 2638: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2639: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2640: my $filepath = &build_filepath($fpath);
1.481 raeburn 2641: if ($action eq 'copy') {
2642: if ($source eq '') {
2643: $fetchresult = 'no source file';
2644: return $fetchresult;
2645: } else {
2646: my $destination = $filepath.'/'.$fname;
2647: rename($source,$destination);
2648: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2649: $home);
1.481 raeburn 2650: }
2651: } elsif ($action eq 'uploaddoc') {
2652: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2653: print $fh $env{'form.'.$source};
1.481 raeburn 2654: close($fh);
1.637 raeburn 2655: if ($parser eq 'parse') {
1.1024 raeburn 2656: my $mm = new File::MMagic;
1.1095 raeburn 2657: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2658: if ($type eq 'text/html') {
1.1024 raeburn 2659: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2660: unless ($parse_result eq 'ok') {
2661: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2662: }
1.637 raeburn 2663: }
1.1095 raeburn 2664: if (ref($mimetype)) {
2665: $$mimetype = $type;
2666: }
1.637 raeburn 2667: }
1.477 raeburn 2668: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2669: $home);
1.481 raeburn 2670: if ($fetchresult eq 'ok') {
2671: return '/uploaded/'.$fpath.'/'.$fname;
2672: } else {
2673: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2674: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2675: return '/adm/notfound.html';
2676: }
1.477 raeburn 2677: }
2678: }
1.485 raeburn 2679: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2680: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2681: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2682: }
2683: return $fetchresult;
2684: }
2685:
1.637 raeburn 2686: sub build_filepath {
2687: my ($fpath) = @_;
2688: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2689: unless ($fpath eq '') {
2690: my @parts=split('/',$fpath);
2691: foreach my $part (@parts) {
2692: $filepath.= '/'.$part;
2693: if ((-e $filepath)!=1) {
2694: mkdir($filepath,0777);
2695: }
2696: }
2697: }
2698: return $filepath;
2699: }
2700:
2701: sub store_edited_file {
1.638 albertel 2702: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2703: my $file = $primary_url;
2704: $file =~ s#^/uploaded/$docudom/$docuname/##;
2705: my $fpath = '';
2706: my $fname = $file;
2707: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2708: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2709: my $filepath = &build_filepath($fpath);
2710: open(my $fh,'>'.$filepath.'/'.$fname);
2711: print $fh $content;
2712: close($fh);
1.638 albertel 2713: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2714: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2715: $home);
1.637 raeburn 2716: if ($$fetchresult eq 'ok') {
2717: return '/uploaded/'.$fpath.'/'.$fname;
2718: } else {
1.638 albertel 2719: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2720: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2721: return '/adm/notfound.html';
2722: }
2723: }
2724:
1.531 albertel 2725: sub clean_filename {
1.831 albertel 2726: my ($fname,$args)=@_;
1.315 www 2727: # Replace Windows backslashes by forward slashes
1.257 www 2728: $fname=~s/\\/\//g;
1.831 albertel 2729: if (!$args->{'keep_path'}) {
2730: # Get rid of everything but the actual filename
2731: $fname=~s/^.*\/([^\/]+)$/$1/;
2732: }
1.315 www 2733: # Replace spaces by underscores
2734: $fname=~s/\s+/\_/g;
2735: # Replace all other weird characters by nothing
1.831 albertel 2736: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2737: # Replace all .\d. sequences with _\d. so they no longer look like version
2738: # numbers
2739: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2740: return $fname;
2741: }
1.1051 raeburn 2742: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2743: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2744: # image with the same aspect ratio as the original, but with dimensions which do
2745: # not exceed $resizewidth and $resizeheight.
2746:
1.984 neumanie 2747: sub resizeImage {
1.1051 raeburn 2748: my ($img_path,$resizewidth,$resizeheight) = @_;
2749: my $ima = Image::Magick->new;
2750: my $resized;
2751: if (-e $img_path) {
2752: $ima->Read($img_path);
2753: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2754: my $width = $ima->Get('width');
2755: my $height = $ima->Get('height');
2756: if ($width > $resizewidth) {
2757: my $factor = $width/$resizewidth;
2758: my $newheight = $height/$factor;
2759: $ima->Scale(width=>$resizewidth,height=>$newheight);
2760: $resized = 1;
2761: }
2762: }
2763: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2764: my $width = $ima->Get('width');
2765: my $height = $ima->Get('height');
2766: if ($height > $resizeheight) {
2767: my $factor = $height/$resizeheight;
2768: my $newwidth = $width/$factor;
2769: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2770: $resized = 1;
2771: }
2772: }
2773: if ($resized) {
2774: $ima->Write($img_path);
2775: }
2776: }
2777: return;
1.977 amueller 2778: }
2779:
1.608 albertel 2780: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2781: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2782: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2783: # $context - possible values: coursedoc, existingfile, overwrite,
2784: # canceloverwrite, or ''.
2785: # if 'coursedoc': upload to the current course
2786: # if 'existingfile': write file to tmp/overwrites directory
2787: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2788: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2789: # $subdir - directory in userfile to store the file into
1.858 raeburn 2790: # $parser - instruction to parse file for objects ($parser = parse)
2791: # $allfiles - reference to hash for embedded objects
2792: # $codebase - reference to hash for codebase of java objects
2793: # $desuname - username for permanent storage of uploaded file
2794: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2795: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2796: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2797: # $resizewidth - width (pixels) to which to resize uploaded image
2798: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2799: # $mimetype - reference to scalar to accommodate mime type determined
2800: # from File::MMagic if $parser = parse.
1.858 raeburn 2801: #
1.686 albertel 2802: # output: url of file in userspace, or error: <message>
2803: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2804:
1.531 albertel 2805: sub userfileupload {
1.1090 raeburn 2806: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2807: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2808: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2809: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2810: $fname=&clean_filename($fname);
1.1090 raeburn 2811: # See if there is anything left
1.257 www 2812: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2813: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2814: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2815: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2816: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2817: my $now = time;
1.1090 raeburn 2818: my $filepath;
1.1095 raeburn 2819: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2820: $filepath = 'tmp/helprequests/'.$now;
2821: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2822: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2823: '_'.$env{'user.domain'}.'/pending';
2824: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2825: my ($docuname,$docudom);
2826: if ($destudom) {
2827: $docudom = $destudom;
2828: } else {
2829: $docudom = $env{'user.domain'};
2830: }
2831: if ($destuname) {
2832: $docuname = $destuname;
2833: } else {
2834: $docuname = $env{'user.name'};
2835: }
2836: if (exists($env{'form.group'})) {
2837: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2838: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2839: }
2840: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2841: if ($context eq 'canceloverwrite') {
2842: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2843: if (-e $tempfile) {
2844: my @info = stat($tempfile);
2845: if ($info[9] eq $env{'form.timestamp'}) {
2846: unlink($tempfile);
2847: }
2848: }
2849: return;
1.523 raeburn 2850: }
2851: }
1.1090 raeburn 2852: # Create the directory if not present
1.741 raeburn 2853: my @parts=split(/\//,$filepath);
2854: my $fullpath = $perlvar{'lonDaemons'};
2855: for (my $i=0;$i<@parts;$i++) {
2856: $fullpath .= '/'.$parts[$i];
2857: if ((-e $fullpath)!=1) {
2858: mkdir($fullpath,0777);
2859: }
2860: }
2861: open(my $fh,'>'.$fullpath.'/'.$fname);
2862: print $fh $env{'form.'.$formname};
2863: close($fh);
1.1090 raeburn 2864: if ($context eq 'existingfile') {
2865: my @info = stat($fullpath.'/'.$fname);
2866: return ($fullpath.'/'.$fname,$info[9]);
2867: } else {
2868: return $fullpath.'/'.$fname;
2869: }
1.523 raeburn 2870: }
1.995 raeburn 2871: if ($subdir eq 'scantron') {
2872: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2873: } else {
1.995 raeburn 2874: $fname="$subdir/$fname";
2875: }
1.1090 raeburn 2876: if ($context eq 'coursedoc') {
1.638 albertel 2877: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2878: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2879: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2880: return &finishuserfileupload($docuname,$docudom,
2881: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2882: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2883: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2884: } else {
1.620 albertel 2885: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2886: return &process_coursefile('uploaddoc',$docuname,$docudom,
2887: $fname,$formname,$parser,
1.1095 raeburn 2888: $allfiles,$codebase,$mimetype);
1.481 raeburn 2889: }
1.719 banghart 2890: } elsif (defined($destuname)) {
2891: my $docuname=$destuname;
2892: my $docudom=$destudom;
1.860 raeburn 2893: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2894: $parser,$allfiles,$codebase,
1.1051 raeburn 2895: $thumbwidth,$thumbheight,
1.1095 raeburn 2896: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2897: } else {
1.638 albertel 2898: my $docuname=$env{'user.name'};
2899: my $docudom=$env{'user.domain'};
1.714 raeburn 2900: if (exists($env{'form.group'})) {
2901: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2902: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2903: }
1.860 raeburn 2904: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2905: $parser,$allfiles,$codebase,
1.1051 raeburn 2906: $thumbwidth,$thumbheight,
1.1095 raeburn 2907: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2908: }
1.271 www 2909: }
2910:
2911: sub finishuserfileupload {
1.860 raeburn 2912: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2913: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2914: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2915: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2916:
1.860 raeburn 2917: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2918: $file=$fname;
2919: if ($fname=~m|/|) {
2920: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2921: $path.=$fnamepath.'/';
2922: }
1.259 www 2923: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2924: my $count;
2925: for ($count=4;$count<=$#parts;$count++) {
2926: $filepath.="/$parts[$count]";
2927: if ((-e $filepath)!=1) {
2928: mkdir($filepath,0777);
2929: }
2930: }
1.984 neumanie 2931:
1.258 www 2932: # Save the file
2933: {
1.701 albertel 2934: if (!open(FH,'>'.$filepath.'/'.$file)) {
2935: &logthis('Failed to create '.$filepath.'/'.$file);
2936: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2937: return '/adm/notfound.html';
2938: }
1.1090 raeburn 2939: if ($context eq 'overwrite') {
1.1117 foxr 2940: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2941: my $target = $filepath.'/'.$file;
2942: if (-e $source) {
2943: my @info = stat($source);
2944: if ($info[9] eq $env{'form.timestamp'}) {
2945: unless (&File::Copy::move($source,$target)) {
2946: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2947: return "Moving from $source failed";
2948: }
2949: } else {
2950: return "Temporary file: $source had unexpected date/time for last modification";
2951: }
2952: } else {
2953: return "Temporary file: $source missing";
2954: }
2955: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2956: &logthis('Failed to write to '.$filepath.'/'.$file);
2957: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2958: return '/adm/notfound.html';
2959: }
1.570 albertel 2960: close(FH);
1.1051 raeburn 2961: if ($resizewidth && $resizeheight) {
2962: my $mm = new File::MMagic;
2963: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2964: if ($mime_type =~ m{^image/}) {
2965: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2966: }
1.977 amueller 2967: }
1.258 www 2968: }
1.637 raeburn 2969: if ($parser eq 'parse') {
1.1024 raeburn 2970: my $mm = new File::MMagic;
1.1095 raeburn 2971: my $type = $mm->checktype_filename($filepath.'/'.$file);
2972: if ($type eq 'text/html') {
1.1024 raeburn 2973: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2974: $allfiles,$codebase);
2975: unless ($parse_result eq 'ok') {
2976: &logthis('Failed to parse '.$filepath.$file.
2977: ' for embedded media: '.$parse_result);
2978: }
1.637 raeburn 2979: }
1.1095 raeburn 2980: if (ref($mimetype)) {
2981: $$mimetype = $type;
2982: }
1.637 raeburn 2983: }
1.860 raeburn 2984: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2985: my $input = $filepath.'/'.$file;
2986: my $output = $filepath.'/'.'tn-'.$file;
2987: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2988: system("convert -sample $thumbsize $input $output");
2989: if (-e $filepath.'/'.'tn-'.$file) {
2990: $fetchthumb = 1;
2991: }
2992: }
1.858 raeburn 2993:
1.259 www 2994: # Notify homeserver to grep it
2995: #
1.984 neumanie 2996: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2997: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2998: if ($fetchresult eq 'ok') {
1.860 raeburn 2999: if ($fetchthumb) {
3000: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3001: if ($thumbresult ne 'ok') {
3002: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3003: $docuhome.': '.$thumbresult);
3004: }
3005: }
1.259 www 3006: #
1.258 www 3007: # Return the URL to it
1.494 albertel 3008: return '/uploaded/'.$path.$file;
1.263 www 3009: } else {
1.494 albertel 3010: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3011: ': '.$fetchresult);
1.263 www 3012: return '/adm/notfound.html';
1.858 raeburn 3013: }
1.493 albertel 3014: }
3015:
1.637 raeburn 3016: sub extract_embedded_items {
1.961 raeburn 3017: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3018: my @state = ();
3019: my %javafiles = (
3020: codebase => '',
3021: code => '',
3022: archive => ''
3023: );
3024: my %mediafiles = (
3025: src => '',
3026: movie => '',
3027: );
1.648 raeburn 3028: my $p;
3029: if ($content) {
3030: $p = HTML::LCParser->new($content);
3031: } else {
1.961 raeburn 3032: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3033: }
1.641 albertel 3034: while (my $t=$p->get_token()) {
1.640 albertel 3035: if ($t->[0] eq 'S') {
3036: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3037: push(@state, $tagname);
1.648 raeburn 3038: if (lc($tagname) eq 'allow') {
3039: &add_filetype($allfiles,$attr->{'src'},'src');
3040: }
1.640 albertel 3041: if (lc($tagname) eq 'img') {
3042: &add_filetype($allfiles,$attr->{'src'},'src');
3043: }
1.886 albertel 3044: if (lc($tagname) eq 'a') {
3045: &add_filetype($allfiles,$attr->{'href'},'href');
3046: }
1.645 raeburn 3047: if (lc($tagname) eq 'script') {
3048: if ($attr->{'archive'} =~ /\.jar$/i) {
3049: &add_filetype($allfiles,$attr->{'archive'},'archive');
3050: } else {
3051: &add_filetype($allfiles,$attr->{'src'},'src');
3052: }
3053: }
3054: if (lc($tagname) eq 'link') {
3055: if (lc($attr->{'rel'}) eq 'stylesheet') {
3056: &add_filetype($allfiles,$attr->{'href'},'href');
3057: }
3058: }
1.640 albertel 3059: if (lc($tagname) eq 'object' ||
3060: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3061: foreach my $item (keys(%javafiles)) {
3062: $javafiles{$item} = '';
3063: }
3064: }
3065: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3066: my $name = lc($attr->{'name'});
3067: foreach my $item (keys(%javafiles)) {
3068: if ($name eq $item) {
3069: $javafiles{$item} = $attr->{'value'};
3070: last;
3071: }
3072: }
3073: foreach my $item (keys(%mediafiles)) {
3074: if ($name eq $item) {
3075: &add_filetype($allfiles, $attr->{'value'}, 'value');
3076: last;
3077: }
3078: }
3079: }
3080: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3081: foreach my $item (keys(%javafiles)) {
3082: if ($attr->{$item}) {
3083: $javafiles{$item} = $attr->{$item};
3084: last;
3085: }
3086: }
3087: foreach my $item (keys(%mediafiles)) {
3088: if ($attr->{$item}) {
3089: &add_filetype($allfiles,$attr->{$item},$item);
3090: last;
3091: }
3092: }
3093: }
3094: } elsif ($t->[0] eq 'E') {
3095: my ($tagname) = ($t->[1]);
3096: if ($javafiles{'codebase'} ne '') {
3097: $javafiles{'codebase'} .= '/';
3098: }
3099: if (lc($tagname) eq 'applet' ||
3100: lc($tagname) eq 'object' ||
3101: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3102: ) {
3103: foreach my $item (keys(%javafiles)) {
3104: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3105: my $file=$javafiles{'codebase'}.$javafiles{$item};
3106: &add_filetype($allfiles,$file,$item);
3107: }
3108: }
3109: }
3110: pop @state;
3111: }
3112: }
1.637 raeburn 3113: return 'ok';
3114: }
3115:
1.639 albertel 3116: sub add_filetype {
3117: my ($allfiles,$file,$type)=@_;
3118: if (exists($allfiles->{$file})) {
3119: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3120: push(@{$allfiles->{$file}}, &escape($type));
3121: }
3122: } else {
3123: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3124: }
3125: }
3126:
1.493 albertel 3127: sub removeuploadedurl {
1.984 neumanie 3128: my ($url)=@_;
3129: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3130: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3131: }
3132:
3133: sub removeuserfile {
3134: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3135: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3136: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3137: if ($result eq 'ok') {
1.798 raeburn 3138: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3139: my $metafile = $fname.'.meta';
3140: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3141: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3142: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3143: my $sqlresult =
1.823 albertel 3144: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3145: 'portfolio_metadata',$group,
3146: 'delete');
1.798 raeburn 3147: }
3148: }
3149: return $result;
1.257 www 3150: }
1.15 www 3151:
1.530 albertel 3152: sub mkdiruserfile {
3153: my ($docuname,$docudom,$dir)=@_;
3154: my $home=&homeserver($docuname,$docudom);
3155: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3156: }
3157:
1.531 albertel 3158: sub renameuserfile {
3159: my ($docuname,$docudom,$old,$new)=@_;
3160: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3161: my $result = &reply("renameuserfile:$docudom:$docuname:".
3162: &escape("$old").':'.&escape("$new"),$home);
3163: if ($result eq 'ok') {
3164: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3165: my $oldmeta = $old.'.meta';
3166: my $newmeta = $new.'.meta';
3167: my $metaresult =
3168: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3169: my $url = "/uploaded/$docudom/$docuname/$old";
3170: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3171: my $sqlresult =
1.823 albertel 3172: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3173: 'portfolio_metadata',$group,
3174: 'delete');
1.798 raeburn 3175: }
3176: }
3177: return $result;
1.531 albertel 3178: }
3179:
1.14 www 3180: # ------------------------------------------------------------------------- Log
3181:
3182: sub log {
3183: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3184: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3185: }
3186:
3187: # ------------------------------------------------------------------ Course Log
1.352 www 3188: #
3189: # This routine flushes several buffers of non-mission-critical nature
3190: #
1.157 www 3191:
3192: sub flushcourselogs {
1.352 www 3193: &logthis('Flushing log buffers');
3194: #
3195: # course logs
3196: # This is a log of all transactions in a course, which can be used
3197: # for data mining purposes
3198: #
3199: # It also collects the courseid database, which lists last transaction
3200: # times and course titles for all courseids
3201: #
3202: my %courseidbuffer=();
1.921 raeburn 3203: foreach my $crsid (keys(%courselogs)) {
1.352 www 3204: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3205: &escape($courselogs{$crsid}),
3206: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3207: delete $courselogs{$crsid};
3208: } else {
3209: &logthis('Failed to flush log buffer for '.$crsid);
3210: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3211: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3212: " exceeded maximum size, deleting.</font>");
3213: delete $courselogs{$crsid};
3214: }
1.352 www 3215: }
1.920 raeburn 3216: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3217: 'description' => $coursedescrbuf{$crsid},
3218: 'inst_code' => $courseinstcodebuf{$crsid},
3219: 'type' => $coursetypebuf{$crsid},
3220: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3221: };
1.191 harris41 3222: }
1.352 www 3223: #
3224: # Write course id database (reverse lookup) to homeserver of courses
3225: # Is used in pickcourse
3226: #
1.840 albertel 3227: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3228: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3229: $courseidbuffer{$crs_home},
3230: $crs_home,'timeonly');
1.352 www 3231: }
3232: #
3233: # File accesses
3234: # Writes to the dynamic metadata of resources to get hit counts, etc.
3235: #
1.449 matthew 3236: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3237: if ($entry =~ /___count$/) {
3238: my ($dom,$name);
1.807 albertel 3239: ($dom,$name,undef)=
1.811 albertel 3240: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3241: if (! defined($dom) || $dom eq '' ||
3242: ! defined($name) || $name eq '') {
1.620 albertel 3243: my $cid = $env{'request.course.id'};
3244: $dom = $env{'request.'.$cid.'.domain'};
3245: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3246: }
1.450 matthew 3247: my $value = $accesshash{$entry};
3248: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3249: my %temphash=($url => $value);
1.449 matthew 3250: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3251: if ($result eq 'ok') {
3252: delete $accesshash{$entry};
3253: } elsif ($result eq 'unknown_cmd') {
3254: # Target server has old code running on it.
1.450 matthew 3255: my %temphash=($entry => $value);
1.449 matthew 3256: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3257: delete $accesshash{$entry};
3258: }
3259: }
3260: } else {
1.811 albertel 3261: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 3262: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3263: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3264: delete $accesshash{$entry};
3265: }
1.185 www 3266: }
1.191 harris41 3267: }
1.352 www 3268: #
3269: # Roles
3270: # Reverse lookup of user roles for course faculty/staff and co-authorship
3271: #
1.800 albertel 3272: foreach my $entry (keys(%userrolehash)) {
1.351 www 3273: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3274: split(/\:/,$entry);
3275: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3276: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3277: $rudom,$runame) eq 'ok') {
3278: delete $userrolehash{$entry};
3279: }
3280: }
1.662 raeburn 3281: #
3282: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3283: #
3284: my %domrolebuffer = ();
1.1000 raeburn 3285: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3286: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3287: if ($domrolebuffer{$rudom}) {
3288: $domrolebuffer{$rudom}.='&'.&escape($entry).
3289: '='.&escape($domainrolehash{$entry});
3290: } else {
3291: $domrolebuffer{$rudom}.=&escape($entry).
3292: '='.&escape($domainrolehash{$entry});
3293: }
3294: delete $domainrolehash{$entry};
3295: }
3296: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3297: my %servers = &get_servers($dom,'library');
3298: foreach my $tryserver (keys(%servers)) {
3299: unless (&reply('domroleput:'.$dom.':'.
3300: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3301: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3302: }
1.662 raeburn 3303: }
3304: }
1.186 www 3305: $dumpcount++;
1.157 www 3306: }
3307:
3308: sub courselog {
3309: my $what=shift;
1.158 www 3310: $what=time.':'.$what;
1.620 albertel 3311: unless ($env{'request.course.id'}) { return ''; }
3312: $coursedombuf{$env{'request.course.id'}}=
3313: $env{'course.'.$env{'request.course.id'}.'.domain'};
3314: $coursenumbuf{$env{'request.course.id'}}=
3315: $env{'course.'.$env{'request.course.id'}.'.num'};
3316: $coursehombuf{$env{'request.course.id'}}=
3317: $env{'course.'.$env{'request.course.id'}.'.home'};
3318: $coursedescrbuf{$env{'request.course.id'}}=
3319: $env{'course.'.$env{'request.course.id'}.'.description'};
3320: $courseinstcodebuf{$env{'request.course.id'}}=
3321: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3322: $courseownerbuf{$env{'request.course.id'}}=
3323: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3324: $coursetypebuf{$env{'request.course.id'}}=
3325: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3326: if (defined $courselogs{$env{'request.course.id'}}) {
3327: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3328: } else {
1.620 albertel 3329: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3330: }
1.620 albertel 3331: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3332: &flushcourselogs();
3333: }
1.158 www 3334: }
3335:
3336: sub courseacclog {
3337: my $fnsymb=shift;
1.620 albertel 3338: unless ($env{'request.course.id'}) { return ''; }
3339: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 3340: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 3341: $what.=':POST';
1.583 matthew 3342: # FIXME: Probably ought to escape things....
1.800 albertel 3343: foreach my $key (keys(%env)) {
3344: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3345: my $formitem = $1;
3346: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3347: $what.=':'.$formitem.'='.$env{$key};
3348: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3349: $what.=':'.$formitem.'='.$env{$key};
3350: }
1.158 www 3351: }
1.191 harris41 3352: }
1.583 matthew 3353: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3354: # FIXME: We should not be depending on a form parameter that someone
3355: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3356: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3357: $what.= ':POST';
3358: # FIXME: Probably ought to escape things....
3359: foreach my $element ('courseexp','crsfulltext','crsrelated',
3360: 'crsdiscuss') {
1.620 albertel 3361: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3362: }
3363: }
1.158 www 3364: }
3365: &courselog($what);
1.149 www 3366: }
3367:
1.185 www 3368: sub countacc {
3369: my $url=&declutter(shift);
1.458 matthew 3370: return if (! defined($url) || $url eq '');
1.620 albertel 3371: unless ($env{'request.course.id'}) { return ''; }
3372: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 3373: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3374: $accesshash{$key}++;
1.185 www 3375: }
1.349 www 3376:
1.361 www 3377: sub linklog {
3378: my ($from,$to)=@_;
3379: $from=&declutter($from);
3380: $to=&declutter($to);
3381: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3382: $accesshash{$to.'___'.$from.'___goto'}=1;
3383: }
3384:
1.349 www 3385: sub userrolelog {
3386: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3387: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3388: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3389: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3390: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3391: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3392: $userrolehash
3393: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3394: =$tend.':'.$tstart;
1.662 raeburn 3395: }
1.898 albertel 3396: if (($env{'request.role'} =~ /dc\./) &&
3397: (($trole=~/^au/) || ($trole=~/^in/) ||
3398: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3399: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3400: ($trole=~/^co/))) {
1.898 albertel 3401: $userrolehash
3402: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3403: =$tend.':'.$tstart;
3404: }
1.662 raeburn 3405: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3406: ($trole=~/^li/) || ($trole=~/^li/) ||
3407: ($trole=~/^au/) || ($trole=~/^dg/) ||
3408: ($trole=~/^sc/)) {
3409: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3410: $domainrolehash
3411: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3412: = $tend.':'.$tstart;
3413: }
1.351 www 3414: }
3415:
1.957 raeburn 3416: sub courserolelog {
3417: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3418: if (($trole eq 'cc') || ($trole eq 'in') ||
3419: ($trole eq 'ep') || ($trole eq 'ad') ||
3420: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3421: ($trole=~/^cr/) || ($trole eq 'gr') ||
3422: ($trole eq 'co')) {
1.957 raeburn 3423: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3424: my $cdom = $1;
3425: my $cnum = $2;
3426: my $sec = $3;
3427: my $namespace = 'rolelog';
3428: my %storehash = (
3429: role => $trole,
3430: start => $tstart,
3431: end => $tend,
3432: selfenroll => $selfenroll,
3433: context => $context,
3434: );
3435: if ($trole eq 'gr') {
3436: $namespace = 'groupslog';
3437: $storehash{'group'} = $sec;
3438: } else {
3439: $storehash{'section'} = $sec;
3440: }
3441: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3442: if (($trole ne 'st') || ($sec ne '')) {
3443: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3444: }
1.957 raeburn 3445: }
3446: }
3447: return;
3448: }
3449:
1.351 www 3450: sub get_course_adv_roles {
1.948 raeburn 3451: my ($cid,$codes) = @_;
1.620 albertel 3452: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3453: my %coursehash=&coursedescription($cid);
1.988 raeburn 3454: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3455: my %nothide=();
1.800 albertel 3456: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3457: if ($user !~ /:/) {
3458: $nothide{join(':',split(/[\@]/,$user))}=1;
3459: } else {
3460: $nothide{$user}=1;
3461: }
1.470 www 3462: }
1.351 www 3463: my %returnhash=();
3464: my %dumphash=
3465: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3466: my $now=time;
1.997 raeburn 3467: my %privileged;
1.1000 raeburn 3468: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3469: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3470: if (($tstart) && ($tstart<0)) { next; }
3471: if (($tend) && ($tend<$now)) { next; }
3472: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3473: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3474: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3475: unless (ref($privileged{$domain}) eq 'HASH') {
3476: my %dompersonnel =
1.998 raeburn 3477: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3478: $privileged{$domain} = {};
3479: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3480: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3481: foreach my $user (keys(%{$dompersonnel{$server}})) {
3482: my ($trole,$uname,$udom) = split(/:/,$user);
3483: $privileged{$udom}{$uname} = 1;
3484: }
3485: }
3486: }
3487: }
3488: if ((exists($privileged{$domain}{$username})) &&
3489: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3490: if ($role eq 'cr') { next; }
1.948 raeburn 3491: if ($codes) {
3492: if ($section) { $role .= ':'.$section; }
3493: if ($returnhash{$role}) {
3494: $returnhash{$role}.=','.$username.':'.$domain;
3495: } else {
3496: $returnhash{$role}=$username.':'.$domain;
3497: }
1.351 www 3498: } else {
1.988 raeburn 3499: my $key=&plaintext($role,$crstype);
1.973 bisitz 3500: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3501: if ($returnhash{$key}) {
3502: $returnhash{$key}.=','.$username.':'.$domain;
3503: } else {
3504: $returnhash{$key}=$username.':'.$domain;
3505: }
1.351 www 3506: }
1.948 raeburn 3507: }
1.400 www 3508: return %returnhash;
3509: }
3510:
3511: sub get_my_roles {
1.937 raeburn 3512: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3513: unless (defined($uname)) { $uname=$env{'user.name'}; }
3514: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3515: my (%dumphash,%nothide);
1.1086 raeburn 3516: if ($context eq 'userroles') {
3517: my $extra = &freeze_escape({'skipcheck' => 1});
3518: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3519: } else {
3520: %dumphash=
1.400 www 3521: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3522: if ($hidepriv) {
3523: my %coursehash=&coursedescription($udom.'_'.$uname);
3524: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3525: if ($user !~ /:/) {
3526: $nothide{join(':',split(/[\@]/,$user))} = 1;
3527: } else {
3528: $nothide{$user} = 1;
3529: }
3530: }
3531: }
1.858 raeburn 3532: }
1.400 www 3533: my %returnhash=();
3534: my $now=time;
1.999 raeburn 3535: my %privileged;
1.800 albertel 3536: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3537: my ($role,$tend,$tstart);
3538: if ($context eq 'userroles') {
3539: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3540: } else {
3541: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3542: }
1.400 www 3543: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3544: my $status = 'active';
1.939 raeburn 3545: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3546: $status = 'previous';
3547: }
3548: if (($tstart) && ($now<$tstart)) {
3549: $status = 'future';
3550: }
3551: if (ref($types) eq 'ARRAY') {
3552: if (!grep(/^\Q$status\E$/,@{$types})) {
3553: next;
3554: }
3555: } else {
3556: if ($status ne 'active') {
3557: next;
3558: }
3559: }
1.867 raeburn 3560: my ($rolecode,$username,$domain,$section,$area);
3561: if ($context eq 'userroles') {
3562: ($area,$rolecode) = split(/_/,$entry);
3563: (undef,$domain,$username,$section) = split(/\//,$area);
3564: } else {
3565: ($role,$username,$domain,$section) = split(/\:/,$entry);
3566: }
1.832 raeburn 3567: if (ref($roledoms) eq 'ARRAY') {
3568: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3569: next;
3570: }
3571: }
3572: if (ref($roles) eq 'ARRAY') {
3573: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3574: if ($role =~ /^cr\//) {
3575: if (!grep(/^cr$/,@{$roles})) {
3576: next;
3577: }
1.1104 raeburn 3578: } elsif ($role =~ /^gr\//) {
3579: if (!grep(/^gr$/,@{$roles})) {
3580: next;
3581: }
1.922 raeburn 3582: } else {
3583: next;
3584: }
1.832 raeburn 3585: }
1.867 raeburn 3586: }
1.937 raeburn 3587: if ($hidepriv) {
1.999 raeburn 3588: if ($context eq 'userroles') {
3589: if ((&privileged($username,$domain)) &&
3590: (!$nothide{$username.':'.$domain})) {
3591: next;
3592: }
3593: } else {
3594: unless (ref($privileged{$domain}) eq 'HASH') {
3595: my %dompersonnel =
3596: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3597: $privileged{$domain} = {};
3598: if (keys(%dompersonnel)) {
3599: foreach my $server (keys(%dompersonnel)) {
3600: if (ref($dompersonnel{$server}) eq 'HASH') {
3601: foreach my $user (keys(%{$dompersonnel{$server}})) {
3602: my ($trole,$uname,$udom) = split(/:/,$user);
3603: $privileged{$udom}{$uname} = $trole;
3604: }
3605: }
3606: }
3607: }
3608: }
3609: if (exists($privileged{$domain}{$username})) {
3610: if (!$nothide{$username.':'.$domain}) {
3611: next;
3612: }
3613: }
1.937 raeburn 3614: }
3615: }
1.933 raeburn 3616: if ($withsec) {
3617: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3618: $tstart.':'.$tend;
3619: } else {
3620: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3621: }
1.832 raeburn 3622: }
1.373 www 3623: return %returnhash;
1.399 www 3624: }
3625:
3626: # ----------------------------------------------------- Frontpage Announcements
3627: #
3628: #
3629:
3630: sub postannounce {
3631: my ($server,$text)=@_;
1.844 albertel 3632: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3633: unless ($text=~/\w/) { $text=''; }
3634: return &reply('setannounce:'.&escape($text),$server);
3635: }
3636:
3637: sub getannounce {
1.448 albertel 3638:
3639: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3640: my $announcement='';
1.800 albertel 3641: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3642: close($fh);
1.399 www 3643: if ($announcement=~/\w/) {
3644: return
3645: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3646: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3647: } else {
3648: return '';
3649: }
3650: } else {
3651: return '';
3652: }
1.351 www 3653: }
1.353 www 3654:
3655: # ---------------------------------------------------------- Course ID routines
3656: # Deal with domain's nohist_courseid.db files
3657: #
3658:
3659: sub courseidput {
1.921 raeburn 3660: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3661: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3662: my $outcome;
3663: if ($caller eq 'timeonly') {
3664: my $cids = '';
3665: foreach my $item (keys(%$storehash)) {
3666: $cids.=&escape($item).'&';
3667: }
3668: $cids=~s/\&$//;
3669: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3670: $coursehome);
3671: } else {
3672: my $items = '';
3673: foreach my $item (keys(%$storehash)) {
3674: $items.= &escape($item).'='.
3675: &freeze_escape($$storehash{$item}).'&';
3676: }
3677: $items=~s/\&$//;
3678: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3679: $coursehome);
1.918 raeburn 3680: }
3681: if ($outcome eq 'unknown_cmd') {
3682: my $what;
3683: foreach my $cid (keys(%$storehash)) {
3684: $what .= &escape($cid).'=';
1.921 raeburn 3685: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3686: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3687: }
3688: $what =~ s/\:$/&/;
3689: }
3690: $what =~ s/\&$//;
3691: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3692: } else {
3693: return $outcome;
3694: }
1.353 www 3695: }
3696:
3697: sub courseiddump {
1.921 raeburn 3698: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3699: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3700: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3701: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3702: my $as_hash = 1;
3703: my %returnhash;
3704: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3705: my %libserv = &all_library();
3706: foreach my $tryserver (keys(%libserv)) {
3707: if ( ( $hostidflag == 1
3708: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3709: || (!defined($hostidflag)) ) {
3710:
1.918 raeburn 3711: if (($domfilter eq '') ||
3712: (&host_domain($tryserver) eq $domfilter)) {
3713: my $rep =
3714: &reply('courseiddump:'.&host_domain($tryserver).':'.
3715: $sincefilter.':'.&escape($descfilter).':'.
3716: &escape($instcodefilter).':'.&escape($ownerfilter).
3717: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3718: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3719: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3720: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3721: &escape($cc_clone).':'.$cloneonly.':'.
3722: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3723: &escape($creationcontext).':'.$domcloner,
3724: $tryserver);
1.918 raeburn 3725: my @pairs=split(/\&/,$rep);
3726: foreach my $item (@pairs) {
3727: my ($key,$value)=split(/\=/,$item,2);
3728: $key = &unescape($key);
3729: next if ($key =~ /^error: 2 /);
3730: my $result = &thaw_unescape($value);
3731: if (ref($result) eq 'HASH') {
3732: $returnhash{$key}=$result;
3733: } else {
1.921 raeburn 3734: my @responses = split(/:/,$value);
3735: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3736: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3737: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3738: }
1.1008 raeburn 3739: }
1.353 www 3740: }
3741: }
3742: }
3743: }
3744: return %returnhash;
3745: }
3746:
1.1055 raeburn 3747: sub courselastaccess {
3748: my ($cdom,$cnum,$hostidref) = @_;
3749: my %returnhash;
3750: if ($cdom && $cnum) {
3751: my $chome = &homeserver($cnum,$cdom);
3752: if ($chome ne 'no_host') {
3753: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3754: &extract_lastaccess(\%returnhash,$rep);
3755: }
3756: } else {
3757: if (!$cdom) { $cdom=''; }
3758: my %libserv = &all_library();
3759: foreach my $tryserver (keys(%libserv)) {
3760: if (ref($hostidref) eq 'ARRAY') {
3761: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3762: }
3763: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3764: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3765: &extract_lastaccess(\%returnhash,$rep);
3766: }
3767: }
3768: }
3769: return %returnhash;
3770: }
3771:
3772: sub extract_lastaccess {
3773: my ($returnhash,$rep) = @_;
3774: if (ref($returnhash) eq 'HASH') {
3775: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3776: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3777: $rep eq '') {
3778: my @pairs=split(/\&/,$rep);
3779: foreach my $item (@pairs) {
3780: my ($key,$value)=split(/\=/,$item,2);
3781: $key = &unescape($key);
3782: next if ($key =~ /^error: 2 /);
3783: $returnhash->{$key} = &thaw_unescape($value);
3784: }
3785: }
3786: }
3787: return;
3788: }
3789:
1.658 raeburn 3790: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3791:
3792: sub dcmailput {
1.685 raeburn 3793: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3794: my $status = &Apache::lonnet::critical(
1.740 www 3795: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3796: &escape($message),$server);
1.662 raeburn 3797: return $status;
3798: }
3799:
1.658 raeburn 3800: sub dcmaildump {
3801: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3802: my %returnhash=();
1.846 albertel 3803:
3804: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3805: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3806: &escape($enddate).':';
3807: my @esc_senders=map { &escape($_)} @$senders;
3808: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3809: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3810: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3811: if (($key) && ($value)) {
3812: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3813: }
3814: }
3815: }
3816: return %returnhash;
3817: }
1.662 raeburn 3818: # ---------------------------------------------------------- Domain roles
3819:
3820: sub get_domain_roles {
3821: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3822: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3823: $startdate = '.';
3824: }
1.1018 raeburn 3825: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3826: $enddate = '.';
3827: }
1.922 raeburn 3828: my $rolelist;
3829: if (ref($roles) eq 'ARRAY') {
3830: $rolelist = join(':',@{$roles});
3831: }
1.662 raeburn 3832: my %personnel = ();
1.841 albertel 3833:
3834: my %servers = &get_servers($dom,'library');
3835: foreach my $tryserver (keys(%servers)) {
3836: %{$personnel{$tryserver}}=();
3837: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3838: &escape($startdate).':'.
3839: &escape($enddate).':'.
3840: &escape($rolelist), $tryserver))) {
3841: my ($key,$value) = split(/\=/,$line,2);
3842: if (($key) && ($value)) {
3843: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3844: }
3845: }
1.662 raeburn 3846: }
3847: return %personnel;
3848: }
1.658 raeburn 3849:
1.1057 www 3850: # ----------------------------------------------------------- Interval timing
1.149 www 3851:
1.504 albertel 3852: sub get_first_access {
3853: my ($type,$argsymb)=@_;
1.790 albertel 3854: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3855: if ($argsymb) { $symb=$argsymb; }
3856: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3857: if ($type eq 'course') {
3858: $res='course';
3859: } elsif ($type eq 'map') {
1.588 albertel 3860: $res=&symbread($map);
3861: } else {
3862: $res=$symb;
3863: }
3864: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3865: return $times{"$courseid\0$res"};
1.504 albertel 3866: }
3867:
3868: sub set_first_access {
3869: my ($type)=@_;
1.790 albertel 3870: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3871: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3872: if ($type eq 'course') {
3873: $res='course';
3874: } elsif ($type eq 'map') {
1.588 albertel 3875: $res=&symbread($map);
3876: } else {
3877: $res=$symb;
3878: }
3879: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3880: if (!$firstaccess) {
1.588 albertel 3881: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3882: }
3883: return 'already_set';
1.504 albertel 3884: }
3885:
1.110 www 3886: # --------------------------------------------- Set Expire Date for Spreadsheet
3887:
3888: sub expirespread {
3889: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3890: my $cid=$env{'request.course.id'};
1.110 www 3891: if ($cid) {
3892: my $now=time;
3893: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3894: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3895: $env{'course.'.$cid.'.num'}.
1.110 www 3896: ':nohist_expirationdates:'.
3897: &escape($key).'='.$now,
1.620 albertel 3898: $env{'course.'.$cid.'.home'})
1.110 www 3899: }
3900: return 'ok';
1.14 www 3901: }
3902:
1.109 www 3903: # ----------------------------------------------------- Devalidate Spreadsheets
3904:
3905: sub devalidate {
1.325 www 3906: my ($symb,$uname,$udom)=@_;
1.620 albertel 3907: my $cid=$env{'request.course.id'};
1.109 www 3908: if ($cid) {
1.391 matthew 3909: # delete the stored spreadsheets for
3910: # - the student level sheet of this user in course's homespace
3911: # - the assessment level sheet for this resource
3912: # for this user in user's homespace
1.553 albertel 3913: # - current conditional state info
1.325 www 3914: my $key=$uname.':'.$udom.':';
1.109 www 3915: my $status=
1.299 matthew 3916: &del('nohist_calculatedsheets',
1.391 matthew 3917: [$key.'studentcalc:'],
1.620 albertel 3918: $env{'course.'.$cid.'.domain'},
3919: $env{'course.'.$cid.'.num'})
1.133 albertel 3920: .' '.
3921: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3922: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3923: unless ($status eq 'ok ok') {
3924: &logthis('Could not devalidate spreadsheet '.
1.325 www 3925: $uname.' at '.$udom.' for '.
1.109 www 3926: $symb.': '.$status);
1.133 albertel 3927: }
1.553 albertel 3928: &delenv('user.state.'.$cid);
1.109 www 3929: }
3930: }
3931:
1.265 albertel 3932: sub get_scalar {
3933: my ($string,$end) = @_;
3934: my $value;
3935: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3936: $value = $1;
3937: } elsif ($$string =~ s/^([^&]*?)&//) {
3938: $value = $1;
3939: }
3940: return &unescape($value);
3941: }
3942:
3943: sub array2str {
3944: my (@array) = @_;
3945: my $result=&arrayref2str(\@array);
3946: $result=~s/^__ARRAY_REF__//;
3947: $result=~s/__END_ARRAY_REF__$//;
3948: return $result;
3949: }
3950:
1.204 albertel 3951: sub arrayref2str {
3952: my ($arrayref) = @_;
1.265 albertel 3953: my $result='__ARRAY_REF__';
1.204 albertel 3954: foreach my $elem (@$arrayref) {
1.265 albertel 3955: if(ref($elem) eq 'ARRAY') {
3956: $result.=&arrayref2str($elem).'&';
3957: } elsif(ref($elem) eq 'HASH') {
3958: $result.=&hashref2str($elem).'&';
3959: } elsif(ref($elem)) {
3960: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3961: } else {
3962: $result.=&escape($elem).'&';
3963: }
3964: }
3965: $result=~s/\&$//;
1.265 albertel 3966: $result .= '__END_ARRAY_REF__';
1.204 albertel 3967: return $result;
3968: }
3969:
1.168 albertel 3970: sub hash2str {
1.204 albertel 3971: my (%hash) = @_;
3972: my $result=&hashref2str(\%hash);
1.265 albertel 3973: $result=~s/^__HASH_REF__//;
3974: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3975: return $result;
3976: }
3977:
3978: sub hashref2str {
3979: my ($hashref)=@_;
1.265 albertel 3980: my $result='__HASH_REF__';
1.800 albertel 3981: foreach my $key (sort(keys(%$hashref))) {
3982: if (ref($key) eq 'ARRAY') {
3983: $result.=&arrayref2str($key).'=';
3984: } elsif (ref($key) eq 'HASH') {
3985: $result.=&hashref2str($key).'=';
3986: } elsif (ref($key)) {
1.265 albertel 3987: $result.='=';
1.800 albertel 3988: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3989: } else {
1.1132 raeburn 3990: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3991: }
3992:
1.800 albertel 3993: if(ref($hashref->{$key}) eq 'ARRAY') {
3994: $result.=&arrayref2str($hashref->{$key}).'&';
3995: } elsif(ref($hashref->{$key}) eq 'HASH') {
3996: $result.=&hashref2str($hashref->{$key}).'&';
3997: } elsif(ref($hashref->{$key})) {
1.265 albertel 3998: $result.='&';
1.800 albertel 3999: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4000: } else {
1.800 albertel 4001: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4002: }
4003: }
1.168 albertel 4004: $result=~s/\&$//;
1.265 albertel 4005: $result .= '__END_HASH_REF__';
1.168 albertel 4006: return $result;
4007: }
4008:
4009: sub str2hash {
1.265 albertel 4010: my ($string)=@_;
4011: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4012: return %$hash;
4013: }
4014:
4015: sub str2hashref {
1.168 albertel 4016: my ($string) = @_;
1.265 albertel 4017:
4018: my %hash;
4019:
4020: if($string !~ /^__HASH_REF__/) {
4021: if (! ($string eq '' || !defined($string))) {
4022: $hash{'error'}='Not hash reference';
4023: }
4024: return (\%hash, $string);
4025: }
4026:
4027: $string =~ s/^__HASH_REF__//;
4028:
4029: while($string !~ /^__END_HASH_REF__/) {
4030: #key
4031: my $key='';
4032: if($string =~ /^__HASH_REF__/) {
4033: ($key, $string)=&str2hashref($string);
4034: if(defined($key->{'error'})) {
4035: $hash{'error'}='Bad data';
4036: return (\%hash, $string);
4037: }
4038: } elsif($string =~ /^__ARRAY_REF__/) {
4039: ($key, $string)=&str2arrayref($string);
4040: if($key->[0] eq 'Array reference error') {
4041: $hash{'error'}='Bad data';
4042: return (\%hash, $string);
4043: }
4044: } else {
4045: $string =~ s/^(.*?)=//;
1.267 albertel 4046: $key=&unescape($1);
1.265 albertel 4047: }
4048: $string =~ s/^=//;
4049:
4050: #value
4051: my $value='';
4052: if($string =~ /^__HASH_REF__/) {
4053: ($value, $string)=&str2hashref($string);
4054: if(defined($value->{'error'})) {
4055: $hash{'error'}='Bad data';
4056: return (\%hash, $string);
4057: }
4058: } elsif($string =~ /^__ARRAY_REF__/) {
4059: ($value, $string)=&str2arrayref($string);
4060: if($value->[0] eq 'Array reference error') {
4061: $hash{'error'}='Bad data';
4062: return (\%hash, $string);
4063: }
4064: } else {
4065: $value=&get_scalar(\$string,'__END_HASH_REF__');
4066: }
4067: $string =~ s/^&//;
4068:
4069: $hash{$key}=$value;
1.204 albertel 4070: }
1.265 albertel 4071:
4072: $string =~ s/^__END_HASH_REF__//;
4073:
4074: return (\%hash, $string);
1.204 albertel 4075: }
4076:
4077: sub str2array {
1.265 albertel 4078: my ($string)=@_;
4079: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4080: return @$array;
4081: }
4082:
4083: sub str2arrayref {
1.204 albertel 4084: my ($string) = @_;
1.265 albertel 4085: my @array;
4086:
4087: if($string !~ /^__ARRAY_REF__/) {
4088: if (! ($string eq '' || !defined($string))) {
4089: $array[0]='Array reference error';
4090: }
4091: return (\@array, $string);
4092: }
4093:
4094: $string =~ s/^__ARRAY_REF__//;
4095:
4096: while($string !~ /^__END_ARRAY_REF__/) {
4097: my $value='';
4098: if($string =~ /^__HASH_REF__/) {
4099: ($value, $string)=&str2hashref($string);
4100: if(defined($value->{'error'})) {
4101: $array[0] ='Array reference error';
4102: return (\@array, $string);
4103: }
4104: } elsif($string =~ /^__ARRAY_REF__/) {
4105: ($value, $string)=&str2arrayref($string);
4106: if($value->[0] eq 'Array reference error') {
4107: $array[0] ='Array reference error';
4108: return (\@array, $string);
4109: }
4110: } else {
4111: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4112: }
4113: $string =~ s/^&//;
4114:
4115: push(@array, $value);
1.191 harris41 4116: }
1.265 albertel 4117:
4118: $string =~ s/^__END_ARRAY_REF__//;
4119:
4120: return (\@array, $string);
1.168 albertel 4121: }
4122:
1.167 albertel 4123: # -------------------------------------------------------------------Temp Store
4124:
1.168 albertel 4125: sub tmpreset {
4126: my ($symb,$namespace,$domain,$stuname) = @_;
4127: if (!$symb) {
4128: $symb=&symbread();
1.620 albertel 4129: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4130: }
4131: $symb=escape($symb);
4132:
1.620 albertel 4133: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4134: $namespace=~s/\//\_/g;
4135: $namespace=~s/\W//g;
4136:
1.620 albertel 4137: if (!$domain) { $domain=$env{'user.domain'}; }
4138: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4139: if ($domain eq 'public' && $stuname eq 'public') {
4140: $stuname=$ENV{'REMOTE_ADDR'};
4141: }
1.1117 foxr 4142: my $path=LONCAPA::tempdir();
1.168 albertel 4143: my %hash;
4144: if (tie(%hash,'GDBM_File',
4145: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4146: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4147: foreach my $key (keys(%hash)) {
1.180 albertel 4148: if ($key=~ /:$symb/) {
1.168 albertel 4149: delete($hash{$key});
4150: }
4151: }
4152: }
4153: }
4154:
1.167 albertel 4155: sub tmpstore {
1.168 albertel 4156: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4157:
4158: if (!$symb) {
4159: $symb=&symbread();
1.620 albertel 4160: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4161: }
4162: $symb=escape($symb);
4163:
4164: if (!$namespace) {
4165: # I don't think we would ever want to store this for a course.
4166: # it seems this will only be used if we don't have a course.
1.620 albertel 4167: #$namespace=$env{'request.course.id'};
1.168 albertel 4168: #if (!$namespace) {
1.620 albertel 4169: $namespace=$env{'request.state'};
1.168 albertel 4170: #}
4171: }
4172: $namespace=~s/\//\_/g;
4173: $namespace=~s/\W//g;
1.620 albertel 4174: if (!$domain) { $domain=$env{'user.domain'}; }
4175: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4176: if ($domain eq 'public' && $stuname eq 'public') {
4177: $stuname=$ENV{'REMOTE_ADDR'};
4178: }
1.168 albertel 4179: my $now=time;
4180: my %hash;
1.1117 foxr 4181: my $path=LONCAPA::tempdir();
1.168 albertel 4182: if (tie(%hash,'GDBM_File',
4183: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4184: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4185: $hash{"version:$symb"}++;
4186: my $version=$hash{"version:$symb"};
4187: my $allkeys='';
4188: foreach my $key (keys(%$storehash)) {
4189: $allkeys.=$key.':';
1.591 albertel 4190: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4191: }
4192: $hash{"$version:$symb:timestamp"}=$now;
4193: $allkeys.='timestamp';
4194: $hash{"$version:keys:$symb"}=$allkeys;
4195: if (untie(%hash)) {
4196: return 'ok';
4197: } else {
4198: return "error:$!";
4199: }
4200: } else {
4201: return "error:$!";
4202: }
4203: }
1.167 albertel 4204:
1.168 albertel 4205: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4206:
1.168 albertel 4207: sub tmprestore {
4208: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4209:
1.168 albertel 4210: if (!$symb) {
4211: $symb=&symbread();
1.620 albertel 4212: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4213: }
4214: $symb=escape($symb);
4215:
1.620 albertel 4216: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4217:
1.620 albertel 4218: if (!$domain) { $domain=$env{'user.domain'}; }
4219: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4220: if ($domain eq 'public' && $stuname eq 'public') {
4221: $stuname=$ENV{'REMOTE_ADDR'};
4222: }
1.168 albertel 4223: my %returnhash;
4224: $namespace=~s/\//\_/g;
4225: $namespace=~s/\W//g;
4226: my %hash;
1.1117 foxr 4227: my $path=LONCAPA::tempdir();
1.168 albertel 4228: if (tie(%hash,'GDBM_File',
4229: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4230: &GDBM_READER(),0640)) {
1.168 albertel 4231: my $version=$hash{"version:$symb"};
4232: $returnhash{'version'}=$version;
4233: my $scope;
4234: for ($scope=1;$scope<=$version;$scope++) {
4235: my $vkeys=$hash{"$scope:keys:$symb"};
4236: my @keys=split(/:/,$vkeys);
4237: my $key;
4238: $returnhash{"$scope:keys"}=$vkeys;
4239: foreach $key (@keys) {
1.591 albertel 4240: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4241: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4242: }
4243: }
1.168 albertel 4244: if (!(untie(%hash))) {
4245: return "error:$!";
4246: }
4247: } else {
4248: return "error:$!";
4249: }
4250: return %returnhash;
1.167 albertel 4251: }
4252:
1.9 www 4253: # ----------------------------------------------------------------------- Store
4254:
4255: sub store {
1.124 www 4256: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4257: my $home='';
4258:
1.168 albertel 4259: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4260:
1.213 www 4261: $symb=&symbclean($symb);
1.122 albertel 4262: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4263:
1.620 albertel 4264: if (!$domain) { $domain=$env{'user.domain'}; }
4265: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4266:
4267: &devalidate($symb,$stuname,$domain);
1.109 www 4268:
4269: $symb=escape($symb);
1.187 www 4270: if (!$namespace) {
1.620 albertel 4271: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4272: return '';
4273: }
4274: }
1.620 albertel 4275: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4276:
4277: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4278: $$storehash{'host'}=$perlvar{'lonHostID'};
4279:
1.12 www 4280: my $namevalue='';
1.800 albertel 4281: foreach my $key (keys(%$storehash)) {
4282: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4283: }
1.12 www 4284: $namevalue=~s/\&$//;
1.187 www 4285: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4286: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4287: }
4288:
1.47 www 4289: # -------------------------------------------------------------- Critical Store
4290:
4291: sub cstore {
1.124 www 4292: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4293: my $home='';
4294:
1.168 albertel 4295: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4296:
1.213 www 4297: $symb=&symbclean($symb);
1.122 albertel 4298: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4299:
1.620 albertel 4300: if (!$domain) { $domain=$env{'user.domain'}; }
4301: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4302:
4303: &devalidate($symb,$stuname,$domain);
1.109 www 4304:
4305: $symb=escape($symb);
1.187 www 4306: if (!$namespace) {
1.620 albertel 4307: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4308: return '';
4309: }
4310: }
1.620 albertel 4311: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4312:
4313: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4314: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4315:
1.47 www 4316: my $namevalue='';
1.800 albertel 4317: foreach my $key (keys(%$storehash)) {
4318: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4319: }
1.47 www 4320: $namevalue=~s/\&$//;
1.187 www 4321: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4322: return critical
4323: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4324: }
4325:
1.9 www 4326: # --------------------------------------------------------------------- Restore
4327:
4328: sub restore {
1.124 www 4329: my ($symb,$namespace,$domain,$stuname) = @_;
4330: my $home='';
4331:
1.168 albertel 4332: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4333:
1.122 albertel 4334: if (!$symb) {
4335: unless ($symb=escape(&symbread())) { return ''; }
4336: } else {
1.213 www 4337: $symb=&escape(&symbclean($symb));
1.122 albertel 4338: }
1.188 www 4339: if (!$namespace) {
1.620 albertel 4340: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4341: return '';
4342: }
4343: }
1.620 albertel 4344: if (!$domain) { $domain=$env{'user.domain'}; }
4345: if (!$stuname) { $stuname=$env{'user.name'}; }
4346: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4347: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4348:
1.12 www 4349: my %returnhash=();
1.800 albertel 4350: foreach my $line (split(/\&/,$answer)) {
4351: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4352: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4353: }
1.75 www 4354: my $version;
4355: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4356: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4357: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4358: }
1.75 www 4359: }
1.13 www 4360: return %returnhash;
1.34 www 4361: }
4362:
4363: # ---------------------------------------------------------- Course Description
1.1118 foxr 4364: #
4365: #
1.34 www 4366:
4367: sub coursedescription {
1.731 albertel 4368: my ($courseid,$args)=@_;
1.34 www 4369: $courseid=~s/^\///;
1.49 www 4370: $courseid=~s/\_/\//g;
1.34 www 4371: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4372: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4373: my $normalid=$cdomain.'_'.$cnum;
4374: # need to always cache even if we get errors otherwise we keep
4375: # trying and trying and trying to get the course description.
4376: my %envhash=();
4377: my %returnhash=();
1.731 albertel 4378:
4379: my $expiretime=600;
4380: if ($env{'request.course.id'} eq $normalid) {
4381: $expiretime=120;
4382: }
4383:
4384: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4385: if (!$args->{'freshen_cache'}
4386: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4387: foreach my $key (keys(%env)) {
4388: next if ($key !~ /^\Q$prefix\E(.*)/);
4389: my ($setting) = $1;
4390: $returnhash{$setting} = $env{$key};
4391: }
4392: return %returnhash;
4393: }
4394:
1.1118 foxr 4395: # get the data again
4396:
1.731 albertel 4397: if (!$args->{'one_time'}) {
4398: $envhash{'course.'.$normalid.'.last_cache'}=time;
4399: }
1.811 albertel 4400:
1.34 www 4401: if ($chome ne 'no_host') {
1.302 albertel 4402: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4403: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4404: my $username = $env{'user.name'}; # Defult username
4405: if(defined $args->{'user'}) {
4406: $username = $args->{'user'};
4407: }
1.129 albertel 4408: $returnhash{'home'}= $chome;
4409: $returnhash{'domain'} = $cdomain;
4410: $returnhash{'num'} = $cnum;
1.741 raeburn 4411: if (!defined($returnhash{'type'})) {
4412: $returnhash{'type'} = 'Course';
4413: }
1.130 albertel 4414: while (my ($name,$value) = each %returnhash) {
1.53 www 4415: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4416: }
1.270 www 4417: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4418: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4419: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4420: $envhash{'course.'.$normalid.'.home'}=$chome;
4421: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4422: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4423: }
4424: }
1.731 albertel 4425: if (!$args->{'one_time'}) {
1.949 raeburn 4426: &appenv(\%envhash);
1.731 albertel 4427: }
1.302 albertel 4428: return %returnhash;
1.461 www 4429: }
4430:
1.1080 raeburn 4431: sub update_released_required {
4432: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4433: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4434: $cid = $env{'request.course.id'};
4435: $cdom = $env{'course.'.$cid.'.domain'};
4436: $cnum = $env{'course.'.$cid.'.num'};
4437: $chome = $env{'course.'.$cid.'.home'};
4438: }
4439: if ($needsrelease) {
4440: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4441: my $needsupdate;
4442: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4443: $needsupdate = 1;
4444: } else {
4445: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4446: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4447: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4448: $needsupdate = 1;
4449: }
4450: }
4451: if ($needsupdate) {
4452: my %needshash = (
4453: 'internal.releaserequired' => $needsrelease,
4454: );
4455: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4456: if ($putresult eq 'ok') {
4457: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4458: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4459: if (ref($crsinfo{$cid}) eq 'HASH') {
4460: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4461: &courseidput($cdom,\%crsinfo,$chome,'notime');
4462: }
4463: }
4464: }
4465: }
4466: return;
4467: }
4468:
1.461 www 4469: # -------------------------------------------------See if a user is privileged
4470:
4471: sub privileged {
4472: my ($username,$domain)=@_;
4473: my $rolesdump=&reply("dump:$domain:$username:roles",
4474: &homeserver($username,$domain));
1.1033 raeburn 4475: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4476: ($rolesdump =~ /^error:/)) {
4477: return 0;
4478: }
1.461 www 4479: my $now=time;
4480: if ($rolesdump ne '') {
1.800 albertel 4481: foreach my $entry (split(/&/,$rolesdump)) {
4482: if ($entry!~/^rolesdef_/) {
4483: my ($area,$role)=split(/=/,$entry);
1.461 www 4484: $area=~s/\_\w\w$//;
4485: my ($trole,$tend,$tstart)=split(/_/,$role);
4486: if (($trole eq 'dc') || ($trole eq 'su')) {
4487: my $active=1;
4488: if ($tend) {
4489: if ($tend<$now) { $active=0; }
4490: }
4491: if ($tstart) {
4492: if ($tstart>$now) { $active=0; }
4493: }
4494: if ($active) { return 1; }
4495: }
4496: }
4497: }
4498: }
4499: return 0;
1.9 www 4500: }
1.1 albertel 4501:
1.103 harris41 4502: # -------------------------------------------------------- Get user privileges
1.11 www 4503:
4504: sub rolesinit {
4505: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4506: my $now=time;
4507: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4508: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4509: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4510: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4511: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4512: return \%userroles;
4513: }
1.11 www 4514: my %allroles=();
1.678 raeburn 4515: my %allgroups=();
1.11 www 4516:
4517: if ($rolesdump ne '') {
1.800 albertel 4518: foreach my $entry (split(/&/,$rolesdump)) {
4519: if ($entry!~/^rolesdef_/) {
4520: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4521: $area=~s/\_\w\w$//;
1.678 raeburn 4522: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4523: if ($role=~/^cr/) {
1.807 albertel 4524: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4525: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4526: ($tend,$tstart)=split('_',$trest);
4527: } else {
4528: $trole=$role;
4529: }
1.678 raeburn 4530: } elsif ($role =~ m|^gr/|) {
4531: ($trole,$tend,$tstart) = split(/_/,$role);
1.1104 raeburn 4532: next if ($tstart eq '-1');
1.678 raeburn 4533: ($trole,$group_privs) = split(/\//,$trole);
4534: $group_privs = &unescape($group_privs);
1.587 albertel 4535: } else {
4536: ($trole,$tend,$tstart)=split(/_/,$role);
4537: }
1.743 albertel 4538: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4539: $username);
4540: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4541: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4542: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4543: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4544: my $spec=$trole.'.'.$area;
4545: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4546: if ($trole =~ /^cr\//) {
1.567 raeburn 4547: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4548: } elsif ($trole eq 'gr') {
4549: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4550: } else {
1.567 raeburn 4551: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4552: }
1.12 www 4553: }
1.662 raeburn 4554: }
1.191 harris41 4555: }
1.743 albertel 4556: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4557: $userroles{'user.adv'} = $adv;
4558: $userroles{'user.author'} = $author;
1.620 albertel 4559: $env{'user.adv'}=$adv;
1.11 www 4560: }
1.743 albertel 4561: return \%userroles;
1.11 www 4562: }
4563:
1.567 raeburn 4564: sub set_arearole {
4565: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4566: # log the associated role with the area
4567: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4568: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4569: }
4570:
4571: sub custom_roleprivs {
4572: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4573: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4574: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4575: if (&hostname($homsvr) ne '') {
1.567 raeburn 4576: my ($rdummy,$roledef)=
4577: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4578: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4579: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4580: if (defined($syspriv)) {
1.1043 raeburn 4581: if ($trest =~ /^$match_community$/) {
4582: $syspriv =~ s/bre\&S//;
4583: }
1.567 raeburn 4584: $$allroles{'cm./'}.=':'.$syspriv;
4585: $$allroles{$spec.'./'}.=':'.$syspriv;
4586: }
4587: if ($tdomain ne '') {
4588: if (defined($dompriv)) {
4589: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4590: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4591: }
4592: if (($trest ne '') && (defined($coursepriv))) {
4593: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4594: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4595: }
4596: }
4597: }
4598: }
4599: }
4600:
1.678 raeburn 4601: sub group_roleprivs {
4602: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4603: my $access = 1;
4604: my $now = time;
4605: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4606: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4607: if ($access) {
1.811 albertel 4608: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4609: $$allgroups{$course}{$group} .=':'.$group_privs;
4610: }
4611: }
1.567 raeburn 4612:
4613: sub standard_roleprivs {
4614: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4615: if (defined($pr{$trole.':s'})) {
4616: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4617: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4618: }
4619: if ($tdomain ne '') {
4620: if (defined($pr{$trole.':d'})) {
4621: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4622: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4623: }
4624: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4625: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4626: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4627: }
4628: }
4629: }
4630:
4631: sub set_userprivs {
1.1064 raeburn 4632: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4633: my $author=0;
4634: my $adv=0;
1.678 raeburn 4635: my %grouproles = ();
4636: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4637: my @groupkeys;
1.1000 raeburn 4638: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4639: push(@groupkeys,$role);
4640: }
4641: if (ref($groups_roles) eq 'HASH') {
4642: foreach my $key (keys(%{$groups_roles})) {
4643: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4644: push(@groupkeys,$key);
4645: }
4646: }
4647: }
4648: if (@groupkeys > 0) {
4649: foreach my $role (@groupkeys) {
4650: my ($trole,$area,$sec,$extendedarea);
4651: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4652: $trole = $1;
4653: $area = $2;
4654: $sec = $3;
4655: $extendedarea = $area.$sec;
4656: if (exists($$allgroups{$area})) {
4657: foreach my $group (keys(%{$$allgroups{$area}})) {
4658: my $spec = $trole.'.'.$extendedarea;
4659: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4660: $$allgroups{$area}{$group};
1.1064 raeburn 4661: }
1.678 raeburn 4662: }
4663: }
4664: }
4665: }
4666: }
1.800 albertel 4667: foreach my $group (keys(%grouproles)) {
4668: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4669: }
1.800 albertel 4670: foreach my $role (keys(%{$allroles})) {
4671: my %thesepriv;
1.941 raeburn 4672: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4673: foreach my $item (split(/:/,$$allroles{$role})) {
4674: if ($item ne '') {
4675: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4676: if ($restrictions eq '') {
4677: $thesepriv{$privilege}='F';
4678: } elsif ($thesepriv{$privilege} ne 'F') {
4679: $thesepriv{$privilege}.=$restrictions;
4680: }
4681: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4682: }
4683: }
4684: my $thesestr='';
1.1104 raeburn 4685: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4686: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4687: }
4688: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4689: }
4690: return ($author,$adv);
4691: }
4692:
1.994 raeburn 4693: sub role_status {
1.1104 raeburn 4694: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4695: my @pwhere = ();
4696: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4697: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4698: unless (!defined($$role) || $$role eq '') {
4699: $$where=join('.',@pwhere);
4700: $$trolecode=$$role.'.'.$$where;
4701: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4702: $$tstatus='is';
1.1104 raeburn 4703: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4704: $$tstatus='future';
1.1034 raeburn 4705: if ($$tstart<$now) {
4706: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4707: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4708: my (%allroles,%allgroups,$group_privs,
4709: %groups_roles,@rolecodes);
1.1002 raeburn 4710: my %userroles = (
4711: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4712: );
1.1064 raeburn 4713: @rolecodes = ('cm');
1.1002 raeburn 4714: my $spec=$$role.'.'.$$where;
4715: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4716: if ($$role =~ /^cr\//) {
4717: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4718: push(@rolecodes,'cr');
1.1002 raeburn 4719: } elsif ($$role eq 'gr') {
1.1064 raeburn 4720: push(@rolecodes,$$role);
1.1002 raeburn 4721: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4722: $env{'user.name'});
1.1064 raeburn 4723: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4724: (undef,my $group_privs) = split(/\//,$trole);
4725: $group_privs = &unescape($group_privs);
4726: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4727: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104 raeburn 4728: &get_groups_roles($tdomain,$trest,
4729: \%course_roles,\@rolecodes,
4730: \%groups_roles);
1.1002 raeburn 4731: } else {
1.1064 raeburn 4732: push(@rolecodes,$$role);
1.1002 raeburn 4733: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4734: }
1.1064 raeburn 4735: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4736: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4737: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4738: }
4739: }
1.1034 raeburn 4740: $$tstatus = 'is';
1.1002 raeburn 4741: }
1.994 raeburn 4742: }
4743: if ($$tend) {
1.1104 raeburn 4744: if ($$tend<$update) {
1.994 raeburn 4745: $$tstatus='expired';
4746: } elsif ($$tend<$now) {
4747: $$tstatus='will_not';
4748: }
4749: }
4750: }
4751: }
4752: }
4753:
1.1104 raeburn 4754: sub get_groups_roles {
4755: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4756: return unless((ref($cdom_courseroles) eq 'HASH') &&
4757: (ref($rolecodes) eq 'ARRAY') &&
4758: (ref($groups_roles) eq 'HASH'));
4759: if (keys(%{$cdom_courseroles}) > 0) {
4760: my ($cnum) = ($rest =~ /^($match_courseid)/);
4761: if ($cdom ne '' && $cnum ne '') {
4762: foreach my $key (keys(%{$cdom_courseroles})) {
4763: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4764: my $crsrole = $1;
4765: my $crssec = $2;
4766: if ($crsrole =~ /^cr/) {
4767: unless (grep(/^cr$/,@{$rolecodes})) {
4768: push(@{$rolecodes},'cr');
4769: }
4770: } else {
4771: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4772: push(@{$rolecodes},$crsrole);
4773: }
4774: }
4775: my $rolekey = "$crsrole./$cdom/$cnum";
4776: if ($crssec ne '') {
4777: $rolekey .= "/$crssec";
4778: }
4779: $rolekey .= './';
4780: $groups_roles->{$rolekey} = $rolecodes;
4781: }
4782: }
4783: }
4784: }
4785: return;
4786: }
4787:
4788: sub delete_env_groupprivs {
4789: my ($where,$courseroles,$possroles) = @_;
4790: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4791: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4792: unless (ref($courseroles->{$udom}) eq 'HASH') {
4793: %{$courseroles->{$udom}} =
4794: &get_my_roles('','','userroles',['active'],
4795: $possroles,[$udom],1);
4796: }
4797: if (ref($courseroles->{$udom}) eq 'HASH') {
4798: foreach my $item (keys(%{$courseroles->{$udom}})) {
4799: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4800: my $area = '/'.$cdom.'/'.$cnum;
4801: my $privkey = "user.priv.$crsrole.$area";
4802: if ($crssec ne '') {
4803: $privkey .= '/'.$crssec;
4804: }
4805: $privkey .= ".$area/$group";
4806: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4807: }
4808: }
4809: return;
4810: }
4811:
1.994 raeburn 4812: sub check_adhoc_privs {
1.1104 raeburn 4813: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4814: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4815: if ($env{$cckey}) {
4816: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4817: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4818: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4819: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4820: }
4821: } else {
1.1088 raeburn 4822: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4823: }
4824: }
4825:
4826: sub set_adhoc_privileges {
4827: # role can be cc or ca
1.1088 raeburn 4828: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4829: my $area = '/'.$dcdom.'/'.$pickedcourse;
4830: my $spec = $role.'.'.$area;
4831: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4832: $env{'user.name'});
4833: my %ccrole = ();
4834: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4835: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4836: &appenv(\%userroles,[$role,'cm']);
4837: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 4838: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4839: &appenv( {'request.role' => $spec,
4840: 'request.role.domain' => $dcdom,
4841: 'request.course.sec' => ''
4842: }
4843: );
4844: my $tadv=0;
4845: if (&allowed('adv') eq 'F') { $tadv=1; }
4846: &appenv({'request.role.adv' => $tadv});
4847: }
1.994 raeburn 4848: }
4849:
1.12 www 4850: # --------------------------------------------------------------- get interface
4851:
4852: sub get {
1.131 albertel 4853: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4854: my $items='';
1.800 albertel 4855: foreach my $item (@$storearr) {
4856: $items.=&escape($item).'&';
1.191 harris41 4857: }
1.12 www 4858: $items=~s/\&$//;
1.620 albertel 4859: if (!$udomain) { $udomain=$env{'user.domain'}; }
4860: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4861: my $uhome=&homeserver($uname,$udomain);
4862:
1.133 albertel 4863: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4864: my @pairs=split(/\&/,$rep);
1.273 albertel 4865: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4866: return @pairs;
4867: }
1.15 www 4868: my %returnhash=();
1.42 www 4869: my $i=0;
1.800 albertel 4870: foreach my $item (@$storearr) {
4871: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4872: $i++;
1.191 harris41 4873: }
1.15 www 4874: return %returnhash;
1.27 www 4875: }
4876:
4877: # --------------------------------------------------------------- del interface
4878:
4879: sub del {
1.133 albertel 4880: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4881: my $items='';
1.800 albertel 4882: foreach my $item (@$storearr) {
4883: $items.=&escape($item).'&';
1.191 harris41 4884: }
1.984 neumanie 4885:
1.27 www 4886: $items=~s/\&$//;
1.620 albertel 4887: if (!$udomain) { $udomain=$env{'user.domain'}; }
4888: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4889: my $uhome=&homeserver($uname,$udomain);
4890: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4891: }
4892:
4893: # -------------------------------------------------------------- dump interface
4894:
4895: sub dump {
1.1086 raeburn 4896: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4897: if (!$udomain) { $udomain=$env{'user.domain'}; }
4898: if (!$uname) { $uname=$env{'user.name'}; }
4899: my $uhome=&homeserver($uname,$udomain);
4900: if ($regexp) {
4901: $regexp=&escape($regexp);
4902: } else {
4903: $regexp='.';
4904: }
1.1086 raeburn 4905: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4906: my @pairs=split(/\&/,$rep);
4907: my %returnhash=();
1.1098 foxr 4908: if (!($rep =~ /^error/ )) {
4909: foreach my $item (@pairs) {
4910: my ($key,$value)=split(/=/,$item,2);
4911: $key = &unescape($key);
4912: next if ($key =~ /^error: 2 /);
4913: $returnhash{$key}=&thaw_unescape($value);
4914: }
1.755 albertel 4915: }
4916: return %returnhash;
1.407 www 4917: }
4918:
1.1098 foxr 4919:
1.717 albertel 4920: # --------------------------------------------------------- dumpstore interface
4921:
4922: sub dumpstore {
4923: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4924: if (!$udomain) { $udomain=$env{'user.domain'}; }
4925: if (!$uname) { $uname=$env{'user.name'}; }
4926: my $uhome=&homeserver($uname,$udomain);
4927: if ($regexp) {
4928: $regexp=&escape($regexp);
4929: } else {
4930: $regexp='.';
4931: }
4932: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4933: my @pairs=split(/\&/,$rep);
4934: my %returnhash=();
4935: foreach my $item (@pairs) {
4936: my ($key,$value)=split(/=/,$item,2);
4937: next if ($key =~ /^error: 2 /);
4938: $returnhash{$key}=&thaw_unescape($value);
4939: }
4940: return %returnhash;
1.717 albertel 4941: }
4942:
1.407 www 4943: # -------------------------------------------------------------- keys interface
4944:
4945: sub getkeys {
4946: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4947: if (!$udomain) { $udomain=$env{'user.domain'}; }
4948: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4949: my $uhome=&homeserver($uname,$udomain);
4950: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4951: my @keyarray=();
1.800 albertel 4952: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4953: next if ($key =~ /^error: 2 /);
1.800 albertel 4954: push(@keyarray,&unescape($key));
1.407 www 4955: }
4956: return @keyarray;
1.318 matthew 4957: }
4958:
1.319 matthew 4959: # --------------------------------------------------------------- currentdump
4960: sub currentdump {
1.328 matthew 4961: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4962: $courseid = $env{'request.course.id'} if (! defined($courseid));
4963: $sdom = $env{'user.domain'} if (! defined($sdom));
4964: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4965: my $uhome = &homeserver($sname,$sdom);
4966: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4967: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4968: #
1.318 matthew 4969: my %returnhash=();
1.319 matthew 4970: #
4971: if ($rep eq "unknown_cmd") {
4972: # an old lond will not know currentdump
4973: # Do a dump and make it look like a currentdump
1.822 albertel 4974: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4975: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4976: my %hash = @tmp;
4977: @tmp=();
1.424 matthew 4978: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4979: } else {
4980: my @pairs=split(/\&/,$rep);
1.800 albertel 4981: foreach my $pair (@pairs) {
4982: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4983: my ($symb,$param) = split(/:/,$key);
4984: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4985: &thaw_unescape($value);
1.319 matthew 4986: }
1.191 harris41 4987: }
1.12 www 4988: return %returnhash;
1.424 matthew 4989: }
4990:
4991: sub convert_dump_to_currentdump{
4992: my %hash = %{shift()};
4993: my %returnhash;
4994: # Code ripped from lond, essentially. The only difference
4995: # here is the unescaping done by lonnet::dump(). Conceivably
4996: # we might run in to problems with parameter names =~ /^v\./
4997: while (my ($key,$value) = each(%hash)) {
4998: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4999: $symb = &unescape($symb);
5000: $param = &unescape($param);
1.424 matthew 5001: next if ($v eq 'version' || $symb eq 'keys');
5002: next if (exists($returnhash{$symb}) &&
5003: exists($returnhash{$symb}->{$param}) &&
5004: $returnhash{$symb}->{'v.'.$param} > $v);
5005: $returnhash{$symb}->{$param}=$value;
5006: $returnhash{$symb}->{'v.'.$param}=$v;
5007: }
5008: #
5009: # Remove all of the keys in the hashes which keep track of
5010: # the version of the parameter.
5011: while (my ($symb,$param_hash) = each(%returnhash)) {
5012: # use a foreach because we are going to delete from the hash.
5013: foreach my $key (keys(%$param_hash)) {
5014: delete($param_hash->{$key}) if ($key =~ /^v\./);
5015: }
5016: }
5017: return \%returnhash;
1.12 www 5018: }
5019:
1.627 albertel 5020: # ------------------------------------------------------ critical inc interface
5021:
5022: sub cinc {
5023: return &inc(@_,'critical');
5024: }
5025:
1.449 matthew 5026: # --------------------------------------------------------------- inc interface
5027:
5028: sub inc {
1.627 albertel 5029: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5030: if (!$udomain) { $udomain=$env{'user.domain'}; }
5031: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5032: my $uhome=&homeserver($uname,$udomain);
5033: my $items='';
5034: if (! ref($store)) {
5035: # got a single value, so use that instead
5036: $items = &escape($store).'=&';
5037: } elsif (ref($store) eq 'SCALAR') {
5038: $items = &escape($$store).'=&';
5039: } elsif (ref($store) eq 'ARRAY') {
5040: $items = join('=&',map {&escape($_);} @{$store});
5041: } elsif (ref($store) eq 'HASH') {
5042: while (my($key,$value) = each(%{$store})) {
5043: $items.= &escape($key).'='.&escape($value).'&';
5044: }
5045: }
5046: $items=~s/\&$//;
1.627 albertel 5047: if ($critical) {
5048: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5049: } else {
5050: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5051: }
1.449 matthew 5052: }
5053:
1.12 www 5054: # --------------------------------------------------------------- put interface
5055:
5056: sub put {
1.134 albertel 5057: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5058: if (!$udomain) { $udomain=$env{'user.domain'}; }
5059: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5060: my $uhome=&homeserver($uname,$udomain);
1.12 www 5061: my $items='';
1.800 albertel 5062: foreach my $item (keys(%$storehash)) {
5063: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5064: }
1.12 www 5065: $items=~s/\&$//;
1.134 albertel 5066: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5067: }
5068:
1.631 albertel 5069: # ------------------------------------------------------------ newput interface
5070:
5071: sub newput {
5072: my ($namespace,$storehash,$udomain,$uname)=@_;
5073: if (!$udomain) { $udomain=$env{'user.domain'}; }
5074: if (!$uname) { $uname=$env{'user.name'}; }
5075: my $uhome=&homeserver($uname,$udomain);
5076: my $items='';
5077: foreach my $key (keys(%$storehash)) {
5078: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5079: }
5080: $items=~s/\&$//;
5081: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5082: }
5083:
5084: # --------------------------------------------------------- putstore interface
5085:
1.524 raeburn 5086: sub putstore {
1.715 albertel 5087: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5088: if (!$udomain) { $udomain=$env{'user.domain'}; }
5089: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5090: my $uhome=&homeserver($uname,$udomain);
5091: my $items='';
1.715 albertel 5092: foreach my $key (keys(%$storehash)) {
5093: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5094: }
1.715 albertel 5095: $items=~s/\&$//;
1.716 albertel 5096: my $esc_symb=&escape($symb);
5097: my $esc_v=&escape($version);
1.715 albertel 5098: my $reply =
1.716 albertel 5099: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5100: $uhome);
5101: if ($reply eq 'unknown_cmd') {
1.716 albertel 5102: # gfall back to way things use to be done
1.715 albertel 5103: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5104: $uname);
1.524 raeburn 5105: }
1.715 albertel 5106: return $reply;
5107: }
5108:
5109: sub old_putstore {
1.716 albertel 5110: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5111: if (!$udomain) { $udomain=$env{'user.domain'}; }
5112: if (!$uname) { $uname=$env{'user.name'}; }
5113: my $uhome=&homeserver($uname,$udomain);
5114: my %newstorehash;
1.800 albertel 5115: foreach my $item (keys(%$storehash)) {
5116: my $key = $version.':'.&escape($symb).':'.$item;
5117: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5118: }
5119: my $items='';
5120: my %allitems = ();
1.800 albertel 5121: foreach my $item (keys(%newstorehash)) {
5122: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5123: my $key = $1.':keys:'.$2;
5124: $allitems{$key} .= $3.':';
5125: }
1.800 albertel 5126: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5127: }
1.800 albertel 5128: foreach my $item (keys(%allitems)) {
5129: $allitems{$item} =~ s/\:$//;
5130: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5131: }
5132: $items=~s/\&$//;
5133: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5134: }
5135:
1.47 www 5136: # ------------------------------------------------------ critical put interface
5137:
5138: sub cput {
1.134 albertel 5139: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5140: if (!$udomain) { $udomain=$env{'user.domain'}; }
5141: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5142: my $uhome=&homeserver($uname,$udomain);
1.47 www 5143: my $items='';
1.800 albertel 5144: foreach my $item (keys(%$storehash)) {
5145: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5146: }
1.47 www 5147: $items=~s/\&$//;
1.134 albertel 5148: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5149: }
5150:
5151: # -------------------------------------------------------------- eget interface
5152:
5153: sub eget {
1.133 albertel 5154: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5155: my $items='';
1.800 albertel 5156: foreach my $item (@$storearr) {
5157: $items.=&escape($item).'&';
1.191 harris41 5158: }
1.12 www 5159: $items=~s/\&$//;
1.620 albertel 5160: if (!$udomain) { $udomain=$env{'user.domain'}; }
5161: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5162: my $uhome=&homeserver($uname,$udomain);
5163: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5164: my @pairs=split(/\&/,$rep);
5165: my %returnhash=();
1.42 www 5166: my $i=0;
1.800 albertel 5167: foreach my $item (@$storearr) {
5168: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5169: $i++;
1.191 harris41 5170: }
1.12 www 5171: return %returnhash;
5172: }
5173:
1.667 albertel 5174: # ------------------------------------------------------------ tmpput interface
5175: sub tmpput {
1.802 raeburn 5176: my ($storehash,$server,$context)=@_;
1.667 albertel 5177: my $items='';
1.800 albertel 5178: foreach my $item (keys(%$storehash)) {
5179: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5180: }
5181: $items=~s/\&$//;
1.802 raeburn 5182: if (defined($context)) {
5183: $items .= ':'.&escape($context);
5184: }
1.667 albertel 5185: return &reply("tmpput:$items",$server);
5186: }
5187:
5188: # ------------------------------------------------------------ tmpget interface
5189: sub tmpget {
1.688 albertel 5190: my ($token,$server)=@_;
5191: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5192: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5193: my %returnhash;
5194: foreach my $item (split(/\&/,$rep)) {
5195: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5196: next if ($key =~ /^error: 2 /);
1.667 albertel 5197: $returnhash{&unescape($key)}=&thaw_unescape($value);
5198: }
5199: return %returnhash;
5200: }
5201:
1.1113 raeburn 5202: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5203: sub tmpdel {
5204: my ($token,$server)=@_;
5205: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5206: return &reply("tmpdel:$token",$server);
5207: }
5208:
1.765 albertel 5209: # -------------------------------------------------- portfolio access checking
5210:
5211: sub portfolio_access {
1.766 albertel 5212: my ($requrl) = @_;
1.765 albertel 5213: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5214: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5215: if ($result) {
5216: my %setters;
5217: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5218: my ($startblock,$endblock) =
5219: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5220: if ($startblock && $endblock) {
5221: return 'B';
5222: }
5223: } else {
5224: my ($startblock,$endblock) =
5225: &Apache::loncommon::blockcheck(\%setters,'port');
5226: if ($startblock && $endblock) {
5227: return 'B';
5228: }
5229: }
5230: }
1.765 albertel 5231: if ($result eq 'ok') {
1.766 albertel 5232: return 'F';
1.765 albertel 5233: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5234: return 'A';
1.765 albertel 5235: }
1.766 albertel 5236: return '';
1.765 albertel 5237: }
5238:
5239: sub get_portfolio_access {
1.767 albertel 5240: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5241:
5242: if (!ref($access_hash)) {
5243: my $current_perms = &get_portfile_permissions($udom,$unum);
5244: my %access_controls = &get_access_controls($current_perms,$group,
5245: $file_name);
5246: $access_hash = $access_controls{$file_name};
5247: }
5248:
1.765 albertel 5249: my ($public,$guest,@domains,@users,@courses,@groups);
5250: my $now = time;
5251: if (ref($access_hash) eq 'HASH') {
5252: foreach my $key (keys(%{$access_hash})) {
5253: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5254: if ($start > $now) {
5255: next;
5256: }
5257: if ($end && $end<$now) {
5258: next;
5259: }
5260: if ($scope eq 'public') {
5261: $public = $key;
5262: last;
5263: } elsif ($scope eq 'guest') {
5264: $guest = $key;
5265: } elsif ($scope eq 'domains') {
5266: push(@domains,$key);
5267: } elsif ($scope eq 'users') {
5268: push(@users,$key);
5269: } elsif ($scope eq 'course') {
5270: push(@courses,$key);
5271: } elsif ($scope eq 'group') {
5272: push(@groups,$key);
5273: }
5274: }
5275: if ($public) {
5276: return 'ok';
5277: }
5278: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5279: if ($guest) {
5280: return $guest;
5281: }
5282: } else {
5283: if (@domains > 0) {
5284: foreach my $domkey (@domains) {
5285: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5286: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5287: return 'ok';
5288: }
5289: }
5290: }
5291: }
5292: if (@users > 0) {
5293: foreach my $userkey (@users) {
1.865 raeburn 5294: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5295: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5296: if (ref($item) eq 'HASH') {
5297: if (($item->{'uname'} eq $env{'user.name'}) &&
5298: ($item->{'udom'} eq $env{'user.domain'})) {
5299: return 'ok';
5300: }
5301: }
5302: }
5303: }
1.765 albertel 5304: }
5305: }
5306: my %roleshash;
5307: my @courses_and_groups = @courses;
5308: push(@courses_and_groups,@groups);
5309: if (@courses_and_groups > 0) {
5310: my (%allgroups,%allroles);
5311: my ($start,$end,$role,$sec,$group);
5312: foreach my $envkey (%env) {
1.1060 raeburn 5313: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5314: my $cid = $2.'_'.$3;
5315: if ($1 eq 'gr') {
5316: $group = $4;
5317: $allgroups{$cid}{$group} = $env{$envkey};
5318: } else {
5319: if ($4 eq '') {
5320: $sec = 'none';
5321: } else {
5322: $sec = $4;
5323: }
5324: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5325: }
1.811 albertel 5326: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5327: my $cid = $2.'_'.$3;
5328: if ($4 eq '') {
5329: $sec = 'none';
5330: } else {
5331: $sec = $4;
5332: }
5333: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5334: }
5335: }
5336: if (keys(%allroles) == 0) {
5337: return;
5338: }
5339: foreach my $key (@courses_and_groups) {
5340: my %content = %{$$access_hash{$key}};
5341: my $cnum = $content{'number'};
5342: my $cdom = $content{'domain'};
5343: my $cid = $cdom.'_'.$cnum;
5344: if (!exists($allroles{$cid})) {
5345: next;
5346: }
5347: foreach my $role_id (keys(%{$content{'roles'}})) {
5348: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5349: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5350: my @status = @{$content{'roles'}{$role_id}{'access'}};
5351: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5352: foreach my $role (keys(%{$allroles{$cid}})) {
5353: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5354: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5355: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5356: if (grep/^all$/,@sections) {
5357: return 'ok';
5358: } else {
5359: if (grep/^$sec$/,@sections) {
5360: return 'ok';
5361: }
5362: }
5363: }
5364: }
5365: if (keys(%{$allgroups{$cid}}) == 0) {
5366: if (grep/^none$/,@groups) {
5367: return 'ok';
5368: }
5369: } else {
5370: if (grep/^all$/,@groups) {
5371: return 'ok';
5372: }
5373: foreach my $group (keys(%{$allgroups{$cid}})) {
5374: if (grep/^$group$/,@groups) {
5375: return 'ok';
5376: }
5377: }
5378: }
5379: }
5380: }
5381: }
5382: }
5383: }
5384: if ($guest) {
5385: return $guest;
5386: }
5387: }
5388: }
5389: return;
5390: }
5391:
5392: sub course_group_datechecker {
5393: my ($dates,$now,$status) = @_;
5394: my ($start,$end) = split(/\./,$dates);
5395: if (!$start && !$end) {
5396: return 'ok';
5397: }
5398: if (grep/^active$/,@{$status}) {
5399: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5400: return 'ok';
5401: }
5402: }
5403: if (grep/^previous$/,@{$status}) {
5404: if ($end > $now ) {
5405: return 'ok';
5406: }
5407: }
5408: if (grep/^future$/,@{$status}) {
5409: if ($start > $now) {
5410: return 'ok';
5411: }
5412: }
5413: return;
5414: }
5415:
5416: sub parse_portfolio_url {
5417: my ($url) = @_;
5418:
5419: my ($type,$udom,$unum,$group,$file_name);
5420:
1.823 albertel 5421: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5422: $type = 1;
5423: $udom = $1;
5424: $unum = $2;
5425: $file_name = $3;
1.823 albertel 5426: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5427: $type = 2;
5428: $udom = $1;
5429: $unum = $2;
5430: $group = $3;
5431: $file_name = $3.'/'.$4;
5432: }
5433: if (wantarray) {
5434: return ($type,$udom,$unum,$file_name,$group);
5435: }
5436: return $type;
5437: }
5438:
5439: sub is_portfolio_url {
5440: my ($url) = @_;
5441: return scalar(&parse_portfolio_url($url));
5442: }
5443:
1.798 raeburn 5444: sub is_portfolio_file {
5445: my ($file) = @_;
1.820 raeburn 5446: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5447: return 1;
5448: }
5449: return;
5450: }
5451:
1.976 raeburn 5452: sub usertools_access {
1.1084 raeburn 5453: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5454: my ($access,%tools);
5455: if ($context eq '') {
5456: $context = 'tools';
5457: }
5458: if ($context eq 'requestcourses') {
5459: %tools = (
5460: official => 1,
5461: unofficial => 1,
1.1006 raeburn 5462: community => 1,
1.985 raeburn 5463: );
5464: } else {
5465: %tools = (
5466: aboutme => 1,
5467: blog => 1,
5468: portfolio => 1,
5469: );
5470: }
1.976 raeburn 5471: return if (!defined($tools{$tool}));
5472:
5473: if ((!defined($udom)) || (!defined($uname))) {
5474: $udom = $env{'user.domain'};
5475: $uname = $env{'user.name'};
5476: }
5477:
1.978 raeburn 5478: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5479: if ($action ne 'reload') {
1.985 raeburn 5480: if ($context eq 'requestcourses') {
5481: return $env{'environment.canrequest.'.$tool};
5482: } else {
5483: return $env{'environment.availabletools.'.$tool};
5484: }
5485: }
1.976 raeburn 5486: }
5487:
5488: my ($toolstatus,$inststatus);
5489:
1.985 raeburn 5490: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5491: ($action ne 'reload')) {
5492: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5493: $inststatus = $env{'environment.inststatus'};
5494: } else {
1.1084 raeburn 5495: if (ref($userenvref) eq 'HASH') {
5496: $toolstatus = $userenvref->{$context.'.'.$tool};
5497: $inststatus = $userenvref->{'inststatus'};
5498: } else {
5499: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5500: $toolstatus = $userenv{$context.'.'.$tool};
5501: $inststatus = $userenv{'inststatus'};
5502: }
1.976 raeburn 5503: }
5504:
5505: if ($toolstatus ne '') {
5506: if ($toolstatus) {
5507: $access = 1;
5508: } else {
5509: $access = 0;
5510: }
5511: return $access;
5512: }
5513:
1.1084 raeburn 5514: my ($is_adv,%domdef);
5515: if (ref($is_advref) eq 'HASH') {
5516: $is_adv = $is_advref->{'is_adv'};
5517: } else {
5518: $is_adv = &is_advanced_user($udom,$uname);
5519: }
5520: if (ref($domdefref) eq 'HASH') {
5521: %domdef = %{$domdefref};
5522: } else {
5523: %domdef = &get_domain_defaults($udom);
5524: }
1.976 raeburn 5525: if (ref($domdef{$tool}) eq 'HASH') {
5526: if ($is_adv) {
5527: if ($domdef{$tool}{'_LC_adv'} ne '') {
5528: if ($domdef{$tool}{'_LC_adv'}) {
5529: $access = 1;
5530: } else {
5531: $access = 0;
5532: }
5533: return $access;
5534: }
5535: }
5536: if ($inststatus ne '') {
5537: my ($hasaccess,$hasnoaccess);
5538: foreach my $affiliation (split(/:/,$inststatus)) {
5539: if ($domdef{$tool}{$affiliation} ne '') {
5540: if ($domdef{$tool}{$affiliation}) {
5541: $hasaccess = 1;
5542: } else {
5543: $hasnoaccess = 1;
5544: }
5545: }
5546: }
5547: if ($hasaccess || $hasnoaccess) {
5548: if ($hasaccess) {
5549: $access = 1;
5550: } elsif ($hasnoaccess) {
5551: $access = 0;
5552: }
5553: return $access;
5554: }
5555: } else {
5556: if ($domdef{$tool}{'default'} ne '') {
5557: if ($domdef{$tool}{'default'}) {
5558: $access = 1;
5559: } elsif ($domdef{$tool}{'default'} == 0) {
5560: $access = 0;
5561: }
5562: return $access;
5563: }
5564: }
5565: } else {
1.985 raeburn 5566: if ($context eq 'tools') {
5567: $access = 1;
5568: } else {
5569: $access = 0;
5570: }
1.976 raeburn 5571: return $access;
5572: }
5573: }
5574:
1.1050 raeburn 5575: sub is_course_owner {
5576: my ($cdom,$cnum,$udom,$uname) = @_;
5577: if (($udom eq '') || ($uname eq '')) {
5578: $udom = $env{'user.domain'};
5579: $uname = $env{'user.name'};
5580: }
5581: unless (($udom eq '') || ($uname eq '')) {
5582: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5583: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5584: return 1;
5585: } else {
5586: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5587: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5588: return 1;
5589: }
5590: }
5591: }
5592: }
5593: return;
5594: }
5595:
1.976 raeburn 5596: sub is_advanced_user {
5597: my ($udom,$uname) = @_;
1.1085 raeburn 5598: if ($udom ne '' && $uname ne '') {
5599: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5600: if (wantarray) {
5601: return ($env{'user.adv'},$env{'user.author'});
5602: } else {
5603: return $env{'user.adv'};
5604: }
1.1085 raeburn 5605: }
5606: }
1.976 raeburn 5607: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5608: my %allroles;
1.1128 raeburn 5609: my ($is_adv,$is_author);
1.976 raeburn 5610: foreach my $role (keys(%roleshash)) {
5611: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5612: my $area = '/'.$tdomain.'/'.$trest;
5613: if ($sec ne '') {
5614: $area .= '/'.$sec;
5615: }
5616: if (($area ne '') && ($trole ne '')) {
5617: my $spec=$trole.'.'.$area;
5618: if ($trole =~ /^cr\//) {
5619: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5620: } elsif ($trole ne 'gr') {
5621: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5622: }
1.1128 raeburn 5623: if ($trole eq 'au') {
5624: $is_author = 1;
5625: }
1.976 raeburn 5626: }
5627: }
5628: foreach my $role (keys(%allroles)) {
5629: last if ($is_adv);
5630: foreach my $item (split(/:/,$allroles{$role})) {
5631: if ($item ne '') {
5632: my ($privilege,$restrictions)=split(/&/,$item);
5633: if ($privilege eq 'adv') {
5634: $is_adv = 1;
5635: last;
5636: }
5637: }
5638: }
5639: }
1.1128 raeburn 5640: if (wantarray) {
5641: return ($is_adv,$is_author);
5642: }
1.976 raeburn 5643: return $is_adv;
5644: }
1.798 raeburn 5645:
1.1035 raeburn 5646: sub check_can_request {
1.1036 raeburn 5647: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5648: my $canreq = 0;
5649: my ($types,$typename) = &Apache::loncommon::course_types();
5650: my @options = ('approval','validate','autolimit');
5651: my $optregex = join('|',@options);
5652: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5653: foreach my $type (@{$types}) {
5654: if (&usertools_access($env{'user.name'},
5655: $env{'user.domain'},
5656: $type,undef,'requestcourses')) {
5657: $canreq ++;
1.1036 raeburn 5658: if (ref($request_domains) eq 'HASH') {
5659: push(@{$request_domains->{$type}},$env{'user.domain'});
5660: }
1.1035 raeburn 5661: if ($dom eq $env{'user.domain'}) {
5662: $can_request->{$type} = 1;
5663: }
5664: }
5665: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5666: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5667: if (@curr > 0) {
1.1036 raeburn 5668: foreach my $item (@curr) {
5669: if (ref($request_domains) eq 'HASH') {
5670: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5671: if ($otherdom ne '') {
5672: if (ref($request_domains->{$type}) eq 'ARRAY') {
5673: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5674: push(@{$request_domains->{$type}},$otherdom);
5675: }
5676: } else {
5677: push(@{$request_domains->{$type}},$otherdom);
5678: }
5679: }
5680: }
5681: }
5682: unless($dom eq $env{'user.domain'}) {
5683: $canreq ++;
1.1035 raeburn 5684: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5685: $can_request->{$type} = 1;
5686: }
5687: }
5688: }
5689: }
5690: }
5691: }
5692: return $canreq;
5693: }
5694:
1.341 www 5695: # ---------------------------------------------- Custom access rule evaluation
5696:
5697: sub customaccess {
5698: my ($priv,$uri)=@_;
1.807 albertel 5699: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5700: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5701: $udom = &LONCAPA::clean_domain($udom);
5702: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5703: my $access=0;
1.800 albertel 5704: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5705: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5706: if ($type eq 'user') {
5707: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5708: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5709: if ($tdom) {
5710: if ($tdom ne $env{'user.domain'}) { next; }
5711: }
1.896 albertel 5712: if ($tuname) {
5713: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5714: }
5715: $access=($effect eq 'allow');
5716: last;
5717: }
5718: } else {
5719: if ($role) {
5720: if ($role ne $urole) { next; }
5721: }
5722: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5723: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5724: if ($tdom) {
5725: if ($tdom ne $udom) { next; }
5726: }
5727: if ($tcrs) {
5728: if ($tcrs ne $ucrs) { next; }
5729: }
5730: if ($tsec) {
5731: if ($tsec ne $usec) { next; }
5732: }
5733: $access=($effect eq 'allow');
5734: last;
5735: }
5736: if ($realm eq '' && $role eq '') {
5737: $access=($effect eq 'allow');
5738: }
1.402 bowersj2 5739: }
1.341 www 5740: }
5741: return $access;
5742: }
5743:
1.103 harris41 5744: # ------------------------------------------------- Check for a user privilege
1.12 www 5745:
5746: sub allowed {
1.810 raeburn 5747: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5748: my $ver_orguri=$uri;
1.439 www 5749: $uri=&deversion($uri);
1.152 www 5750: my $orguri=$uri;
1.52 www 5751: $uri=&declutter($uri);
1.809 raeburn 5752:
1.810 raeburn 5753: if ($priv eq 'evb') {
5754: # Evade communication block restrictions for specified role in a course
5755: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5756: return $1;
5757: } else {
5758: return;
5759: }
5760: }
5761:
1.620 albertel 5762: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5763: # Free bre access to adm and meta resources
1.775 albertel 5764: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5765: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5766: && ($priv eq 'bre')) {
1.14 www 5767: return 'F';
1.159 www 5768: }
5769:
1.545 banghart 5770: # Free bre access to user's own portfolio contents
1.714 raeburn 5771: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5772: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5773: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5774: my %setters;
5775: my ($startblock,$endblock) =
5776: &Apache::loncommon::blockcheck(\%setters,'port');
5777: if ($startblock && $endblock) {
5778: return 'B';
5779: } else {
5780: return 'F';
5781: }
1.545 banghart 5782: }
5783:
1.762 raeburn 5784: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5785: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5786: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5787: if (exists($env{'request.course.id'})) {
5788: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5789: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5790: if (($domain eq $cdom) && ($name eq $cnum)) {
5791: my $courseprivid=$env{'request.course.id'};
5792: $courseprivid=~s/\_/\//;
5793: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5794: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5795: return $1;
1.762 raeburn 5796: } else {
5797: if ($env{'request.course.sec'}) {
5798: $courseprivid.='/'.$env{'request.course.sec'};
5799: }
5800: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5801: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5802: return $2;
5803: }
1.714 raeburn 5804: }
5805: }
5806: }
5807: }
5808:
1.159 www 5809: # Free bre to public access
5810:
5811: if ($priv eq 'bre') {
1.238 www 5812: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5813: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5814: return 'F';
5815: }
1.238 www 5816: if ($copyright eq 'priv') {
5817: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5818: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5819: return '';
5820: }
5821: }
5822: if ($copyright eq 'domain') {
5823: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5824: unless (($env{'user.domain'} eq $1) ||
5825: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5826: return '';
5827: }
1.262 matthew 5828: }
1.620 albertel 5829: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5830: # Library role, so allow browsing of resources in this domain.
5831: return 'F';
1.238 www 5832: }
1.341 www 5833: if ($copyright eq 'custom') {
5834: unless (&customaccess($priv,$uri)) { return ''; }
5835: }
1.14 www 5836: }
1.264 matthew 5837: # Domain coordinator is trying to create a course
1.620 albertel 5838: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5839: # uri is the requested domain in this case.
5840: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5841: # a role of dc for the domain in question.
1.620 albertel 5842: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5843: }
1.29 www 5844:
1.52 www 5845: my $thisallowed='';
5846: my $statecond=0;
5847: my $courseprivid='';
5848:
1.1039 raeburn 5849: my $ownaccess;
1.1043 raeburn 5850: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5851: if (($priv eq 'bro') && ($env{'user.author'})) {
5852: if ($uri eq '') {
5853: $ownaccess = 1;
5854: } else {
5855: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5856: my $udom = $env{'user.domain'};
5857: my $uname = $env{'user.name'};
5858: if ($uri =~ m{^\Q$udom\E/?$}) {
5859: $ownaccess = 1;
1.1040 raeburn 5860: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5861: unless ($uri =~ m{\.\./}) {
5862: $ownaccess = 1;
5863: }
5864: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5865: my $now = time;
5866: if ($uri =~ m{^([^/]+)/?$}) {
5867: my $adom = $1;
5868: foreach my $key (keys(%env)) {
1.1042 raeburn 5869: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5870: my ($start,$end) = split('.',$env{$key});
5871: if (($now >= $start) && (!$end || $end < $now)) {
5872: $ownaccess = 1;
5873: last;
5874: }
5875: }
5876: }
5877: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5878: my $adom = $1;
5879: my $aname = $2;
1.1042 raeburn 5880: foreach my $role ('ca','aa') {
5881: if ($env{"user.role.$role./$adom/$aname"}) {
5882: my ($start,$end) =
5883: split('.',$env{"user.role.$role./$adom/$aname"});
5884: if (($now >= $start) && (!$end || $end < $now)) {
5885: $ownaccess = 1;
5886: last;
5887: }
1.1039 raeburn 5888: }
5889: }
5890: }
5891: }
5892: }
5893: }
5894: }
5895:
1.52 www 5896: # Course
5897:
1.620 albertel 5898: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5899: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5900: $thisallowed.=$1;
5901: }
1.52 www 5902: }
1.29 www 5903:
1.52 www 5904: # Domain
5905:
1.620 albertel 5906: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5907: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5908: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5909: $thisallowed.=$1;
5910: }
1.12 www 5911: }
1.52 www 5912:
1.1141 ! raeburn 5913: # User who is not author or co-author might still be able to edit
! 5914: # resource of an author in the domain (e.g., if Domain Coordinator).
! 5915: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
! 5916: (&allowed('mdc',$env{'request.course.id'}))) {
! 5917: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
! 5918: $thisallowed.=$1;
! 5919: }
! 5920: }
! 5921:
1.52 www 5922: # Course: uri itself is a course
1.66 www 5923: my $courseuri=$uri;
5924: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5925: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5926:
1.620 albertel 5927: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5928: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5929: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5930: $thisallowed.=$1;
5931: }
1.12 www 5932: }
1.29 www 5933:
1.665 albertel 5934: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5935: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5936: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5937: $thisallowed='';
1.671 raeburn 5938: my ($match)=&is_on_map($uri);
5939: if ($match) {
5940: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5941: =~/\Q$priv\E\&([^\:]*)/) {
5942: $thisallowed.=$1;
5943: }
5944: } else {
1.705 albertel 5945: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5946: if ($refuri) {
5947: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5948: $thisallowed='F';
1.671 raeburn 5949: } else {
5950: $refuri=&declutter($refuri);
5951: my ($match) = &is_on_map($refuri);
5952: if ($match) {
5953: $thisallowed='F';
5954: }
1.669 raeburn 5955: }
1.671 raeburn 5956: }
5957: }
1.314 www 5958: }
1.492 albertel 5959:
1.766 albertel 5960: if ($priv eq 'bre'
5961: && $thisallowed ne 'F'
5962: && $thisallowed ne '2'
5963: && &is_portfolio_url($uri)) {
5964: $thisallowed = &portfolio_access($uri);
5965: }
5966:
1.52 www 5967: # Full access at system, domain or course-wide level? Exit.
1.29 www 5968: if ($thisallowed=~/F/) {
5969: return 'F';
5970: }
5971:
1.52 www 5972: # If this is generating or modifying users, exit with special codes
1.29 www 5973:
1.643 www 5974: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5975: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5976: my ($audom,$auname)=split('/',$uri);
1.643 www 5977: # no author name given, so this just checks on the general right to make a co-author in this domain
5978: unless ($auname) { return $thisallowed; }
5979: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5980: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5981: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5982: ($audom ne $env{'request.role.domain'}))) { return ''; }
5983: }
1.52 www 5984: return $thisallowed;
5985: }
5986: #
1.103 harris41 5987: # Gathered so far: system, domain and course wide privileges
1.52 www 5988: #
5989: # Course: See if uri or referer is an individual resource that is part of
5990: # the course
5991:
1.620 albertel 5992: if ($env{'request.course.id'}) {
1.232 www 5993:
1.620 albertel 5994: $courseprivid=$env{'request.course.id'};
5995: if ($env{'request.course.sec'}) {
5996: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5997: }
5998: $courseprivid=~s/\_/\//;
5999: my $checkreferer=1;
1.232 www 6000: my ($match,$cond)=&is_on_map($uri);
6001: if ($match) {
6002: $statecond=$cond;
1.620 albertel 6003: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6004: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 6005: $thisallowed.=$1;
6006: $checkreferer=0;
6007: }
1.29 www 6008: }
1.83 www 6009:
1.148 www 6010: if ($checkreferer) {
1.620 albertel 6011: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6012: unless ($refuri) {
1.800 albertel 6013: foreach my $key (keys(%env)) {
6014: if ($key=~/^httpref\..*\*/) {
6015: my $pattern=$key;
1.156 www 6016: $pattern=~s/^httpref\.\/res\///;
1.148 www 6017: $pattern=~s/\*/\[\^\/\]\+/g;
6018: $pattern=~s/\//\\\//g;
1.152 www 6019: if ($orguri=~/$pattern/) {
1.800 albertel 6020: $refuri=$env{$key};
1.148 www 6021: }
6022: }
1.191 harris41 6023: }
1.148 www 6024: }
1.232 www 6025:
1.148 www 6026: if ($refuri) {
1.152 www 6027: $refuri=&declutter($refuri);
1.232 www 6028: my ($match,$cond)=&is_on_map($refuri);
6029: if ($match) {
6030: my $refstatecond=$cond;
1.620 albertel 6031: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6032: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 6033: $thisallowed.=$1;
1.53 www 6034: $uri=$refuri;
6035: $statecond=$refstatecond;
1.52 www 6036: }
6037: }
1.148 www 6038: }
1.29 www 6039: }
1.52 www 6040: }
1.29 www 6041:
1.52 www 6042: #
1.103 harris41 6043: # Gathered now: all privileges that could apply, and condition number
1.52 www 6044: #
6045: #
6046: # Full or no access?
6047: #
1.29 www 6048:
1.52 www 6049: if ($thisallowed=~/F/) {
6050: return 'F';
6051: }
1.29 www 6052:
1.52 www 6053: unless ($thisallowed) {
6054: return '';
6055: }
1.29 www 6056:
1.52 www 6057: # Restrictions exist, deal with them
6058: #
6059: # C:according to course preferences
6060: # R:according to resource settings
6061: # L:unless locked
6062: # X:according to user session state
6063: #
6064:
6065: # Possibly locked functionality, check all courses
1.54 www 6066: # Locks might take effect only after 10 minutes cache expiration for other
6067: # courses, and 2 minutes for current course
1.52 www 6068:
6069: my $envkey;
6070: if ($thisallowed=~/L/) {
1.1000 raeburn 6071: foreach $envkey (keys(%env)) {
1.54 www 6072: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6073: my $courseid=$2;
6074: my $roleid=$1.'.'.$2;
1.92 www 6075: $courseid=~s/^\///;
1.54 www 6076: my $expiretime=600;
1.620 albertel 6077: if ($env{'request.role'} eq $roleid) {
1.54 www 6078: $expiretime=120;
6079: }
6080: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6081: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6082: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6083: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6084: }
1.620 albertel 6085: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6086: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6087: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6088: &log($env{'user.domain'},$env{'user.name'},
6089: $env{'user.home'},
1.57 www 6090: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6091: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6092: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6093: return '';
6094: }
6095: }
1.620 albertel 6096: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6097: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6098: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6099: &log($env{'user.domain'},$env{'user.name'},
6100: $env{'user.home'},
1.57 www 6101: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6102: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6103: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6104: return '';
6105: }
6106: }
6107: }
1.29 www 6108: }
1.52 www 6109: }
6110:
6111: #
6112: # Rest of the restrictions depend on selected course
6113: #
6114:
1.620 albertel 6115: unless ($env{'request.course.id'}) {
1.766 albertel 6116: if ($thisallowed eq 'A') {
6117: return 'A';
1.814 raeburn 6118: } elsif ($thisallowed eq 'B') {
6119: return 'B';
1.766 albertel 6120: } else {
6121: return '1';
6122: }
1.52 www 6123: }
1.29 www 6124:
1.52 www 6125: #
6126: # Now user is definitely in a course
6127: #
1.53 www 6128:
6129:
6130: # Course preferences
6131:
6132: if ($thisallowed=~/C/) {
1.620 albertel 6133: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6134: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6135: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6136: =~/\Q$rolecode\E/) {
1.1103 raeburn 6137: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6138: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6139: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6140: $env{'request.course.id'});
6141: }
1.237 www 6142: return '';
6143: }
6144:
1.620 albertel 6145: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6146: =~/\Q$unamedom\E/) {
1.1103 raeburn 6147: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6148: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6149: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6150: $env{'request.course.id'});
6151: }
1.54 www 6152: return '';
6153: }
1.53 www 6154: }
6155:
6156: # Resource preferences
6157:
6158: if ($thisallowed=~/R/) {
1.620 albertel 6159: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6160: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6161: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6162: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6163: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6164: }
6165: return '';
1.54 www 6166: }
1.53 www 6167: }
1.30 www 6168:
1.246 www 6169: # Restricted by state or randomout?
1.30 www 6170:
1.52 www 6171: if ($thisallowed=~/X/) {
1.620 albertel 6172: if ($env{'acc.randomout'}) {
1.579 albertel 6173: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6174: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6175: return '';
6176: }
1.247 www 6177: }
6178: if (&condval($statecond)) {
1.52 www 6179: return '2';
6180: } else {
6181: return '';
6182: }
6183: }
1.30 www 6184:
1.766 albertel 6185: if ($thisallowed eq 'A') {
6186: return 'A';
1.814 raeburn 6187: } elsif ($thisallowed eq 'B') {
6188: return 'B';
1.766 albertel 6189: }
1.52 www 6190: return 'F';
1.232 www 6191: }
1.1133 foxr 6192: #
6193: # Removes the versino from a URI and
6194: # splits it in to its filename and path to the filename.
6195: # Seems like File::Basename could have done this more clearly.
6196: # Parameters:
6197: # $uri - input URI
6198: # Returns:
6199: # Two element list consisting of
6200: # $pathname - the URI up to and excluding the trailing /
6201: # $filename - The part of the URI following the last /
6202: # NOTE:
6203: # Another realization of this is simply:
6204: # use File::Basename;
6205: # ...
6206: # $uri = shift;
6207: # $filename = basename($uri);
6208: # $path = dirname($uri);
6209: # return ($filename, $path);
6210: #
6211: # The implementation below is probably faster however.
6212: #
1.710 albertel 6213: sub split_uri_for_cond {
6214: my $uri=&deversion(&declutter(shift));
6215: my @uriparts=split(/\//,$uri);
6216: my $filename=pop(@uriparts);
6217: my $pathname=join('/',@uriparts);
6218: return ($pathname,$filename);
6219: }
1.232 www 6220: # --------------------------------------------------- Is a resource on the map?
6221:
6222: sub is_on_map {
1.710 albertel 6223: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6224: #Trying to find the conditional for the file
1.620 albertel 6225: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6226: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6227: if ($match) {
1.289 bowersj2 6228: return (1,$1);
6229: } else {
1.434 www 6230: return (0,0);
1.289 bowersj2 6231: }
1.12 www 6232: }
6233:
1.427 www 6234: # --------------------------------------------------------- Get symb from alias
6235:
6236: sub get_symb_from_alias {
6237: my $symb=shift;
6238: my ($map,$resid,$url)=&decode_symb($symb);
6239: # Already is a symb
6240: if ($url) { return $symb; }
6241: # Must be an alias
6242: my $aliassymb='';
6243: my %bighash;
1.620 albertel 6244: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6245: &GDBM_READER(),0640)) {
6246: my $rid=$bighash{'mapalias_'.$symb};
6247: if ($rid) {
6248: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6249: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6250: $resid,$bighash{'src_'.$rid});
1.427 www 6251: }
6252: untie %bighash;
6253: }
6254: return $aliassymb;
6255: }
6256:
1.12 www 6257: # ----------------------------------------------------------------- Define Role
6258:
6259: sub definerole {
6260: if (allowed('mcr','/')) {
6261: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6262: foreach my $role (split(':',$sysrole)) {
6263: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6264: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6265: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6266: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6267: return "refused:s:$crole&$cqual";
6268: }
6269: }
1.191 harris41 6270: }
1.800 albertel 6271: foreach my $role (split(':',$domrole)) {
6272: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6273: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6274: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6275: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6276: return "refused:d:$crole&$cqual";
6277: }
6278: }
1.191 harris41 6279: }
1.800 albertel 6280: foreach my $role (split(':',$courole)) {
6281: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6282: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6283: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6284: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6285: return "refused:c:$crole&$cqual";
6286: }
6287: }
1.191 harris41 6288: }
1.620 albertel 6289: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6290: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6291: "rolesdef_$rolename=".
6292: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6293: return reply($command,$env{'user.home'});
1.12 www 6294: } else {
6295: return 'refused';
6296: }
1.105 harris41 6297: }
6298:
6299: # ---------------- Make a metadata query against the network of library servers
6300:
6301: sub metadata_query {
1.244 matthew 6302: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6303: my %rhash;
1.845 albertel 6304: my %libserv = &all_library();
1.244 matthew 6305: my @server_list = (defined($server_array) ? @$server_array
6306: : keys(%libserv) );
6307: for my $server (@server_list) {
1.118 harris41 6308: unless ($custom or $customshow) {
6309: my $reply=&reply("querysend:".&escape($query),$server);
6310: $rhash{$server}=$reply;
6311: }
6312: else {
6313: my $reply=&reply("querysend:".&escape($query).':'.
6314: &escape($custom).':'.&escape($customshow),
6315: $server);
6316: $rhash{$server}=$reply;
6317: }
1.112 harris41 6318: }
1.118 harris41 6319: return \%rhash;
1.240 www 6320: }
6321:
6322: # ----------------------------------------- Send log queries and wait for reply
6323:
6324: sub log_query {
6325: my ($uname,$udom,$query,%filters)=@_;
6326: my $uhome=&homeserver($uname,$udom);
6327: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6328: my $uhost=&hostname($uhome);
1.800 albertel 6329: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6330: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6331: $uhome);
1.479 albertel 6332: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6333: return get_query_reply($queryid);
6334: }
6335:
1.818 raeburn 6336: # -------------------------- Update MySQL table for portfolio file
6337:
6338: sub update_portfolio_table {
1.821 raeburn 6339: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6340: if ($group ne '') {
6341: $file_name =~s /^\Q$group\E//;
6342: }
1.818 raeburn 6343: my $homeserver = &homeserver($uname,$udom);
6344: my $queryid=
1.821 raeburn 6345: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6346: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6347: my $reply = &get_query_reply($queryid);
6348: return $reply;
6349: }
6350:
1.899 raeburn 6351: # -------------------------- Update MySQL allusers table
6352:
6353: sub update_allusers_table {
6354: my ($uname,$udom,$names) = @_;
6355: my $homeserver = &homeserver($uname,$udom);
6356: my $queryid=
6357: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6358: 'lastname='.&escape($names->{'lastname'}).'%%'.
6359: 'firstname='.&escape($names->{'firstname'}).'%%'.
6360: 'middlename='.&escape($names->{'middlename'}).'%%'.
6361: 'generation='.&escape($names->{'generation'}).'%%'.
6362: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6363: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6364: return;
1.899 raeburn 6365: }
6366:
1.508 raeburn 6367: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6368:
6369: sub fetch_enrollment_query {
1.511 raeburn 6370: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6371: my $homeserver;
1.547 raeburn 6372: my $maxtries = 1;
1.508 raeburn 6373: if ($context eq 'automated') {
6374: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6375: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6376: } else {
6377: $homeserver = &homeserver($cnum,$dom);
6378: }
1.838 albertel 6379: my $host=&hostname($homeserver);
1.506 raeburn 6380: my $cmd = '';
1.1000 raeburn 6381: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6382: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6383: }
6384: $cmd =~ s/%%$//;
6385: $cmd = &escape($cmd);
6386: my $query = 'fetchenrollment';
1.620 albertel 6387: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6388: unless ($queryid=~/^\Q$host\E\_/) {
6389: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6390: return 'error: '.$queryid;
6391: }
1.506 raeburn 6392: my $reply = &get_query_reply($queryid);
1.547 raeburn 6393: my $tries = 1;
6394: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6395: $reply = &get_query_reply($queryid);
6396: $tries ++;
6397: }
1.526 raeburn 6398: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6399: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6400: } else {
1.901 albertel 6401: my @responses = split(/:/,$reply);
1.515 raeburn 6402: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6403: foreach my $line (@responses) {
6404: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6405: $$replyref{$key} = $value;
6406: }
6407: } else {
1.1117 foxr 6408: my $pathname = LONCAPA::tempdir();
1.800 albertel 6409: foreach my $line (@responses) {
6410: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6411: $$replyref{$key} = $value;
6412: if ($value > 0) {
1.800 albertel 6413: foreach my $item (@{$$affiliatesref{$key}}) {
6414: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6415: my $destname = $pathname.'/'.$filename;
6416: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6417: if ($xml_classlist =~ /^error/) {
6418: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6419: } else {
1.506 raeburn 6420: if ( open(FILE,">$destname") ) {
6421: print FILE &unescape($xml_classlist);
6422: close(FILE);
1.526 raeburn 6423: } else {
6424: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6425: }
6426: }
6427: }
6428: }
6429: }
6430: }
6431: return 'ok';
6432: }
6433: return 'error';
6434: }
6435:
1.242 www 6436: sub get_query_reply {
6437: my $queryid=shift;
1.1117 foxr 6438: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6439: my $reply='';
6440: for (1..100) {
6441: sleep 2;
6442: if (-e $replyfile.'.end') {
1.448 albertel 6443: if (open(my $fh,$replyfile)) {
1.904 albertel 6444: $reply = join('',<$fh>);
6445: close($fh);
1.240 www 6446: } else { return 'error: reply_file_error'; }
1.242 www 6447: return &unescape($reply);
6448: }
1.240 www 6449: }
1.242 www 6450: return 'timeout:'.$queryid;
1.240 www 6451: }
6452:
6453: sub courselog_query {
1.241 www 6454: #
6455: # possible filters:
6456: # url: url or symb
6457: # username
6458: # domain
6459: # action: view, submit, grade
6460: # start: timestamp
6461: # end: timestamp
6462: #
1.240 www 6463: my (%filters)=@_;
1.620 albertel 6464: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6465: if ($filters{'url'}) {
6466: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6467: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6468: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6469: }
1.620 albertel 6470: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6471: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6472: return &log_query($cname,$cdom,'courselog',%filters);
6473: }
6474:
6475: sub userlog_query {
1.858 raeburn 6476: #
6477: # possible filters:
6478: # action: log check role
6479: # start: timestamp
6480: # end: timestamp
6481: #
1.240 www 6482: my ($uname,$udom,%filters)=@_;
6483: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6484: }
6485:
1.506 raeburn 6486: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6487:
6488: sub auto_run {
1.508 raeburn 6489: my ($cnum,$cdom) = @_;
1.876 raeburn 6490: my $response = 0;
6491: my $settings;
6492: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6493: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6494: $settings = $domconfig{'autoenroll'};
6495: if ($settings->{'run'} eq '1') {
6496: $response = 1;
6497: }
6498: } else {
1.934 raeburn 6499: my $homeserver;
6500: if (&is_course($cdom,$cnum)) {
6501: $homeserver = &homeserver($cnum,$cdom);
6502: } else {
6503: $homeserver = &domain($cdom,'primary');
6504: }
6505: if ($homeserver ne 'no_host') {
6506: $response = &reply('autorun:'.$cdom,$homeserver);
6507: }
1.876 raeburn 6508: }
1.506 raeburn 6509: return $response;
6510: }
1.776 albertel 6511:
1.506 raeburn 6512: sub auto_get_sections {
1.508 raeburn 6513: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6514: my $homeserver;
6515: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6516: $homeserver = &homeserver($cnum,$cdom);
6517: }
6518: if (!defined($homeserver)) {
6519: if ($cdom =~ /^$match_domain$/) {
6520: $homeserver = &domain($cdom,'primary');
6521: }
6522: }
6523: my @secs;
6524: if (defined($homeserver)) {
6525: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6526: unless ($response eq 'refused') {
6527: @secs = split(/:/,$response);
6528: }
1.506 raeburn 6529: }
6530: return @secs;
6531: }
1.776 albertel 6532:
1.506 raeburn 6533: sub auto_new_course {
1.1099 raeburn 6534: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6535: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6536: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6537: return $response;
6538: }
1.776 albertel 6539:
1.506 raeburn 6540: sub auto_validate_courseID {
1.508 raeburn 6541: my ($cnum,$cdom,$inst_course_id) = @_;
6542: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6543: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6544: return $response;
6545: }
1.776 albertel 6546:
1.1007 raeburn 6547: sub auto_validate_instcode {
1.1020 raeburn 6548: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6549: my ($homeserver,$response);
6550: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6551: $homeserver = &homeserver($cnum,$cdom);
6552: }
6553: if (!defined($homeserver)) {
6554: if ($cdom =~ /^$match_domain$/) {
6555: $homeserver = &domain($cdom,'primary');
6556: }
6557: }
1.1065 raeburn 6558: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6559: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6560: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6561: return ($outcome,$description);
1.1007 raeburn 6562: }
6563:
1.506 raeburn 6564: sub auto_create_password {
1.873 raeburn 6565: my ($cnum,$cdom,$authparam,$udom) = @_;
6566: my ($homeserver,$response);
1.506 raeburn 6567: my $create_passwd = 0;
6568: my $authchk = '';
1.873 raeburn 6569: if ($udom =~ /^$match_domain$/) {
6570: $homeserver = &domain($udom,'primary');
6571: }
6572: if ($homeserver eq '') {
6573: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6574: $homeserver = &homeserver($cnum,$cdom);
6575: }
6576: }
6577: if ($homeserver eq '') {
6578: $authchk = 'nodomain';
1.506 raeburn 6579: } else {
1.873 raeburn 6580: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6581: if ($response eq 'refused') {
6582: $authchk = 'refused';
6583: } else {
1.901 albertel 6584: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6585: }
1.506 raeburn 6586: }
6587: return ($authparam,$create_passwd,$authchk);
6588: }
6589:
1.706 raeburn 6590: sub auto_photo_permission {
6591: my ($cnum,$cdom,$students) = @_;
6592: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6593: my ($outcome,$perm_reqd,$conditions) =
6594: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6595: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6596: return (undef,undef);
6597: }
1.706 raeburn 6598: return ($outcome,$perm_reqd,$conditions);
6599: }
6600:
6601: sub auto_checkphotos {
6602: my ($uname,$udom,$pid) = @_;
6603: my $homeserver = &homeserver($uname,$udom);
6604: my ($result,$resulttype);
6605: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6606: &escape($uname).':'.&escape($pid),
6607: $homeserver));
1.709 albertel 6608: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6609: return (undef,undef);
6610: }
1.706 raeburn 6611: if ($outcome) {
6612: ($result,$resulttype) = split(/:/,$outcome);
6613: }
6614: return ($result,$resulttype);
6615: }
6616:
6617: sub auto_photochoice {
6618: my ($cnum,$cdom) = @_;
6619: my $homeserver = &homeserver($cnum,$cdom);
6620: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6621: &escape($cdom),
6622: $homeserver)));
1.709 albertel 6623: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6624: return (undef,undef);
6625: }
1.706 raeburn 6626: return ($update,$comment);
6627: }
6628:
6629: sub auto_photoupdate {
6630: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6631: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6632: my $host=&hostname($homeserver);
1.706 raeburn 6633: my $cmd = '';
6634: my $maxtries = 1;
1.800 albertel 6635: foreach my $affiliate (keys(%{$affiliatesref})) {
6636: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6637: }
6638: $cmd =~ s/%%$//;
6639: $cmd = &escape($cmd);
6640: my $query = 'institutionalphotos';
6641: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6642: unless ($queryid=~/^\Q$host\E\_/) {
6643: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6644: return 'error: '.$queryid;
6645: }
6646: my $reply = &get_query_reply($queryid);
6647: my $tries = 1;
6648: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6649: $reply = &get_query_reply($queryid);
6650: $tries ++;
6651: }
6652: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6653: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6654: } else {
6655: my @responses = split(/:/,$reply);
6656: my $outcome = shift(@responses);
6657: foreach my $item (@responses) {
6658: my ($key,$value) = split(/=/,$item);
6659: $$photo{$key} = $value;
6660: }
6661: return $outcome;
6662: }
6663: return 'error';
6664: }
6665:
1.521 raeburn 6666: sub auto_instcode_format {
1.793 albertel 6667: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6668: $cat_order) = @_;
1.521 raeburn 6669: my $courses = '';
1.772 raeburn 6670: my @homeservers;
1.521 raeburn 6671: if ($caller eq 'global') {
1.841 albertel 6672: my %servers = &get_servers($codedom,'library');
6673: foreach my $tryserver (keys(%servers)) {
6674: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6675: push(@homeservers,$tryserver);
6676: }
1.584 raeburn 6677: }
1.1022 raeburn 6678: } elsif ($caller eq 'requests') {
6679: if ($codedom =~ /^$match_domain$/) {
6680: my $chome = &domain($codedom,'primary');
6681: unless ($chome eq 'no_host') {
6682: push(@homeservers,$chome);
6683: }
6684: }
1.521 raeburn 6685: } else {
1.772 raeburn 6686: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6687: }
1.793 albertel 6688: foreach my $code (keys(%{$instcodes})) {
6689: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6690: }
6691: chop($courses);
1.772 raeburn 6692: my $ok_response = 0;
6693: my $response;
6694: while (@homeservers > 0 && $ok_response == 0) {
6695: my $server = shift(@homeservers);
6696: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6697: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6698: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6699: split(/:/,$response);
1.772 raeburn 6700: %{$codes} = (%{$codes},&str2hash($codes_str));
6701: push(@{$codetitles},&str2array($codetitles_str));
6702: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6703: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6704: $ok_response = 1;
6705: }
6706: }
6707: if ($ok_response) {
1.521 raeburn 6708: return 'ok';
1.772 raeburn 6709: } else {
6710: return $response;
1.521 raeburn 6711: }
6712: }
6713:
1.792 raeburn 6714: sub auto_instcode_defaults {
6715: my ($domain,$returnhash,$code_order) = @_;
6716: my @homeservers;
1.841 albertel 6717:
6718: my %servers = &get_servers($domain,'library');
6719: foreach my $tryserver (keys(%servers)) {
6720: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6721: push(@homeservers,$tryserver);
6722: }
1.792 raeburn 6723: }
1.841 albertel 6724:
1.792 raeburn 6725: my $response;
1.841 albertel 6726: foreach my $server (@homeservers) {
1.792 raeburn 6727: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6728: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6729:
6730: foreach my $pair (split(/\&/,$response)) {
6731: my ($name,$value)=split(/\=/,$pair);
6732: if ($name eq 'code_order') {
6733: @{$code_order} = split(/\&/,&unescape($value));
6734: } else {
6735: $returnhash->{&unescape($name)}=&unescape($value);
6736: }
6737: }
6738: return 'ok';
1.792 raeburn 6739: }
1.841 albertel 6740:
6741: return $response;
1.1003 raeburn 6742: }
6743:
6744: sub auto_possible_instcodes {
1.1007 raeburn 6745: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6746: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6747: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6748: return;
6749: }
1.1003 raeburn 6750: my (@homeservers,$uhome);
6751: if (defined(&domain($domain,'primary'))) {
6752: $uhome=&domain($domain,'primary');
6753: push(@homeservers,&domain($domain,'primary'));
6754: } else {
6755: my %servers = &get_servers($domain,'library');
6756: foreach my $tryserver (keys(%servers)) {
6757: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6758: push(@homeservers,$tryserver);
6759: }
6760: }
6761: }
6762: my $response;
6763: foreach my $server (@homeservers) {
6764: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6765: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6766: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6767: split(':',$response);
6768: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6769: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6770: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6771: my ($name,$value)=split('=',$item);
6772: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6773: }
6774: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6775: my ($name,$value)=split('=',$item);
6776: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6777: }
6778: return 'ok';
6779: }
6780: return $response;
6781: }
1.792 raeburn 6782:
1.1010 raeburn 6783: sub auto_courserequest_checks {
6784: my ($dom) = @_;
1.1020 raeburn 6785: my ($homeserver,%validations);
6786: if ($dom =~ /^$match_domain$/) {
6787: $homeserver = &domain($dom,'primary');
6788: }
6789: unless ($homeserver eq 'no_host') {
6790: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6791: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6792: my @items = split(/&/,$response);
6793: foreach my $item (@items) {
6794: my ($key,$value) = split('=',$item);
6795: $validations{&unescape($key)} = &thaw_unescape($value);
6796: }
6797: }
6798: }
1.1010 raeburn 6799: return %validations;
6800: }
6801:
1.1020 raeburn 6802: sub auto_courserequest_validation {
6803: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6804: my ($homeserver,$response);
6805: if ($dom =~ /^$match_domain$/) {
6806: $homeserver = &domain($dom,'primary');
6807: }
6808: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6809:
1.1020 raeburn 6810: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6811: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6812: ':'.&escape($instcode).':'.&escape($instseclist),
6813: $homeserver));
6814: }
6815: return $response;
6816: }
6817:
1.777 albertel 6818: sub auto_validate_class_sec {
1.918 raeburn 6819: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6820: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6821: my $ownerlist;
6822: if (ref($owners) eq 'ARRAY') {
6823: $ownerlist = join(',',@{$owners});
6824: } else {
6825: $ownerlist = $owners;
6826: }
1.773 raeburn 6827: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6828: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6829: return $response;
6830: }
6831:
1.679 raeburn 6832: # ------------------------------------------------------- Course Group routines
6833:
6834: sub get_coursegroups {
1.809 raeburn 6835: my ($cdom,$cnum,$group,$namespace) = @_;
6836: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6837: }
6838:
1.679 raeburn 6839: sub modify_coursegroup {
6840: my ($cdom,$cnum,$groupsettings) = @_;
6841: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6842: }
6843:
1.809 raeburn 6844: sub toggle_coursegroup_status {
6845: my ($cdom,$cnum,$group,$action) = @_;
6846: my ($from_namespace,$to_namespace);
6847: if ($action eq 'delete') {
6848: $from_namespace = 'coursegroups';
6849: $to_namespace = 'deleted_groups';
6850: } else {
6851: $from_namespace = 'deleted_groups';
6852: $to_namespace = 'coursegroups';
6853: }
6854: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6855: if (my $tmp = &error(%curr_group)) {
6856: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6857: return ('read error',$tmp);
6858: } else {
6859: my %savedsettings = %curr_group;
1.809 raeburn 6860: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6861: my $deloutcome;
6862: if ($result eq 'ok') {
1.809 raeburn 6863: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6864: } else {
6865: return ('write error',$result);
6866: }
6867: if ($deloutcome eq 'ok') {
6868: return 'ok';
6869: } else {
6870: return ('delete error',$deloutcome);
6871: }
6872: }
6873: }
6874:
1.679 raeburn 6875: sub modify_group_roles {
1.957 raeburn 6876: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6877: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6878: my $role = 'gr/'.&escape($userprivs);
6879: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6880: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6881: if ($result eq 'ok') {
6882: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6883: }
1.679 raeburn 6884: return $result;
6885: }
6886:
6887: sub modify_coursegroup_membership {
6888: my ($cdom,$cnum,$membership) = @_;
6889: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6890: return $result;
6891: }
6892:
1.682 raeburn 6893: sub get_active_groups {
6894: my ($udom,$uname,$cdom,$cnum) = @_;
6895: my $now = time;
6896: my %groups = ();
6897: foreach my $key (keys(%env)) {
1.811 albertel 6898: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6899: my ($start,$end) = split(/\./,$env{$key});
6900: if (($end!=0) && ($end<$now)) { next; }
6901: if (($start!=0) && ($start>$now)) { next; }
6902: if ($1 eq $cdom && $2 eq $cnum) {
6903: $groups{$3} = $env{$key} ;
6904: }
6905: }
6906: }
6907: return %groups;
6908: }
6909:
1.683 raeburn 6910: sub get_group_membership {
6911: my ($cdom,$cnum,$group) = @_;
6912: return(&dump('groupmembership',$cdom,$cnum,$group));
6913: }
6914:
6915: sub get_users_groups {
6916: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6917: my @usersgroups;
1.683 raeburn 6918: my $cachetime=1800;
6919:
6920: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6921: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6922: if (defined($cached)) {
1.734 albertel 6923: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6924: } else {
6925: $grouplist = '';
1.816 raeburn 6926: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 6927: my $extra = &freeze_escape({'skipcheck' => 1});
6928: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6929: my $access_end = $env{'course.'.$courseid.
6930: '.default_enrollment_end_date'};
6931: my $now = time;
6932: foreach my $key (keys(%roleshash)) {
6933: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6934: my $group = $1;
6935: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6936: my $start = $2;
6937: my $end = $1;
6938: if ($start == -1) { next; } # deleted from group
6939: if (($start!=0) && ($start>$now)) { next; }
6940: if (($end!=0) && ($end<$now)) {
6941: if ($access_end && $access_end < $now) {
6942: if ($access_end - $end < 86400) {
6943: push(@usersgroups,$group);
1.733 raeburn 6944: }
6945: }
1.817 raeburn 6946: next;
1.733 raeburn 6947: }
1.817 raeburn 6948: push(@usersgroups,$group);
1.683 raeburn 6949: }
6950: }
6951: }
1.817 raeburn 6952: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6953: $grouplist = join(':',@usersgroups);
6954: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6955: }
1.733 raeburn 6956: return @usersgroups;
1.683 raeburn 6957: }
6958:
6959: sub devalidate_getgroups_cache {
6960: my ($udom,$uname,$cdom,$cnum)=@_;
6961: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6962:
1.683 raeburn 6963: my $hashid="$udom:$uname:$courseid";
6964: &devalidate_cache_new('getgroups',$hashid);
6965: }
6966:
1.12 www 6967: # ------------------------------------------------------------------ Plain Text
6968:
6969: sub plaintext {
1.988 raeburn 6970: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6971: if ($short =~ m{^cr/}) {
1.758 albertel 6972: return (split('/',$short))[-1];
6973: }
1.742 raeburn 6974: if (!defined($cid)) {
6975: $cid = $env{'request.course.id'};
6976: }
6977: my %rolenames = (
1.1008 raeburn 6978: Course => 'std',
6979: Community => 'alt1',
1.742 raeburn 6980: );
1.1037 raeburn 6981: if ($cid ne '') {
6982: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6983: unless ($forcedefault) {
6984: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6985: &Apache::lonlocal::mt_escape(\$roletext);
6986: return &Apache::lonlocal::mt($roletext);
6987: }
6988: }
6989: }
6990: if ((defined($type)) && (defined($rolenames{$type})) &&
6991: (defined($rolenames{$type})) &&
6992: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6993: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6994: } elsif ($cid ne '') {
6995: my $crstype = $env{'course.'.$cid.'.type'};
6996: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6997: (defined($prp{$short}{$rolenames{$crstype}}))) {
6998: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6999: }
1.742 raeburn 7000: }
1.1037 raeburn 7001: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7002: }
7003:
7004: # ----------------------------------------------------------------- Assign Role
7005:
7006: sub assignrole {
1.957 raeburn 7007: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7008: $context)=@_;
1.21 www 7009: my $mrole;
7010: if ($role =~ /^cr\//) {
1.393 www 7011: my $cwosec=$url;
1.811 albertel 7012: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7013: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7014: my $refused = 1;
7015: if ($context eq 'requestcourses') {
7016: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7017: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7018: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7019: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7020: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7021: if ($crsenv{'internal.courseowner'} eq
7022: $env{'user.name'}.':'.$env{'user.domain'}) {
7023: $refused = '';
7024: }
7025: }
7026: }
7027: }
7028: }
7029: if ($refused) {
7030: &logthis('Refused custom assignrole: '.
7031: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7032: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7033: return 'refused';
7034: }
1.104 www 7035: }
1.21 www 7036: $mrole='cr';
1.678 raeburn 7037: } elsif ($role =~ /^gr\//) {
7038: my $cwogrp=$url;
1.811 albertel 7039: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7040: unless (&allowed('mdg',$cwogrp)) {
7041: &logthis('Refused group assignrole: '.
7042: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7043: $env{'user.name'}.' at '.$env{'user.domain'});
7044: return 'refused';
7045: }
7046: $mrole='gr';
1.21 www 7047: } else {
1.82 www 7048: my $cwosec=$url;
1.811 albertel 7049: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7050: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7051: my $refused;
7052: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7053: if (!(&allowed('c'.$role,$url))) {
7054: $refused = 1;
7055: }
7056: } else {
7057: $refused = 1;
7058: }
1.947 raeburn 7059: if ($refused) {
1.1045 raeburn 7060: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7061: if (!$selfenroll && $context eq 'course') {
7062: my %crsenv;
7063: if ($role eq 'cc' || $role eq 'co') {
7064: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7065: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7066: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7067: if ($crsenv{'internal.courseowner'} eq
7068: $env{'user.name'}.':'.$env{'user.domain'}) {
7069: $refused = '';
7070: }
7071: }
7072: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7073: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7074: if ($crsenv{'internal.courseowner'} eq
7075: $env{'user.name'}.':'.$env{'user.domain'}) {
7076: $refused = '';
7077: }
7078: }
7079: }
7080: }
7081: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7082: $refused = '';
1.1017 raeburn 7083: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7084: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7085: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7086: my $wrongcc;
7087: if ($cnum =~ /^$match_community$/) {
7088: $wrongcc = 1 if ($role eq 'cc');
7089: } else {
7090: $wrongcc = 1 if ($role eq 'co');
7091: }
7092: unless ($wrongcc) {
7093: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7094: if ($crsenv{'internal.courseowner'} eq
7095: $env{'user.name'}.':'.$env{'user.domain'}) {
7096: $refused = '';
7097: }
1.1017 raeburn 7098: }
7099: }
7100: }
7101: if ($refused) {
1.947 raeburn 7102: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7103: ' '.$role.' '.$end.' '.$start.' by '.
7104: $env{'user.name'}.' at '.$env{'user.domain'});
7105: return 'refused';
7106: }
1.932 raeburn 7107: }
1.1131 raeburn 7108: } elsif ($role eq 'au') {
7109: if ($url ne '/'.$udom.'/') {
7110: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7111: ' to assign author role for '.$uname.':'.$udom.
7112: ' in domain: '.$url.' refused (wrong domain).');
7113: return 'refused';
7114: }
1.104 www 7115: }
1.21 www 7116: $mrole=$role;
7117: }
1.620 albertel 7118: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7119: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7120: if ($end) { $command.='_'.$end; }
1.21 www 7121: if ($start) {
7122: if ($end) {
1.81 www 7123: $command.='_'.$start;
1.21 www 7124: } else {
1.81 www 7125: $command.='_0_'.$start;
1.21 www 7126: }
7127: }
1.739 raeburn 7128: my $origstart = $start;
7129: my $origend = $end;
1.957 raeburn 7130: my $delflag;
1.357 www 7131: # actually delete
7132: if ($deleteflag) {
1.373 www 7133: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7134: # modify command to delete the role
1.620 albertel 7135: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7136: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7137: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7138: # set start and finish to negative values for userrolelog
7139: $start=-1;
7140: $end=-1;
1.957 raeburn 7141: $delflag = 1;
1.357 www 7142: }
7143: }
7144: # send command
1.349 www 7145: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7146: # log new user role if status is ok
1.349 www 7147: if ($answer eq 'ok') {
1.663 raeburn 7148: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7149: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 7150: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 7151: unless ($role =~ /^gr/) {
7152: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7153: $origstart,$selfenroll,$context);
1.739 raeburn 7154: }
1.1053 raeburn 7155: if ($role eq 'cc') {
7156: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7157: }
1.349 www 7158: }
7159: return $answer;
1.169 harris41 7160: }
7161:
1.1053 raeburn 7162: sub autoupdate_coowners {
7163: my ($url,$end,$start,$uname,$udom) = @_;
7164: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7165: if (($cdom ne '') && ($cnum ne '')) {
7166: my $now = time;
7167: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7168: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7169: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7170: my $instcode = $coursehash{'internal.coursecode'};
7171: if ($instcode ne '') {
1.1056 raeburn 7172: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7173: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7174: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7175: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7176: if ($result eq 'valid') {
7177: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7178: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7179: push(@newcoowners,$coowner);
7180: }
7181: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7182: push(@newcoowners,$uname.':'.$udom);
7183: }
7184: @newcoowners = sort(@newcoowners);
7185: } else {
7186: push(@newcoowners,$uname.':'.$udom);
7187: }
7188: } else {
7189: if ($coursehash{'internal.co-owners'}) {
7190: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7191: unless ($coowner eq $uname.':'.$udom) {
7192: push(@newcoowners,$coowner);
7193: }
7194: }
7195: unless (@newcoowners > 0) {
7196: $delcoowners = 1;
7197: $coowners = '';
7198: }
7199: }
7200: }
7201: if (@newcoowners || $delcoowners) {
7202: &store_coowners($cdom,$cnum,$coursehash{'home'},
7203: $delcoowners,@newcoowners);
7204: }
7205: }
7206: }
7207: }
7208: }
7209: }
7210: }
7211:
7212: sub store_coowners {
7213: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7214: my $cid = $cdom.'_'.$cnum;
7215: my ($coowners,$delresult,$putresult);
7216: if (@newcoowners) {
7217: $coowners = join(',',@newcoowners);
7218: my %coownershash = (
7219: 'internal.co-owners' => $coowners,
7220: );
7221: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7222: if ($putresult eq 'ok') {
7223: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7224: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7225: }
7226: }
7227: }
7228: if ($delcoowners) {
7229: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7230: if ($delresult eq 'ok') {
7231: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7232: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7233: }
7234: }
7235: }
7236: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7237: my %crsinfo =
7238: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7239: if (ref($crsinfo{$cid}) eq 'HASH') {
7240: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7241: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7242: }
7243: }
7244: }
7245:
1.169 harris41 7246: # -------------------------------------------------- Modify user authentication
1.197 www 7247: # Overrides without validation
7248:
1.169 harris41 7249: sub modifyuserauth {
7250: my ($udom,$uname,$umode,$upass)=@_;
7251: my $uhome=&homeserver($uname,$udom);
1.197 www 7252: unless (&allowed('mau',$udom)) { return 'refused'; }
7253: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7254: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7255: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7256: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7257: &escape($upass),$uhome);
1.620 albertel 7258: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7259: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7260: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7261: &log($udom,,$uname,$uhome,
1.620 albertel 7262: 'Authentication changed by '.$env{'user.domain'}.', '.
7263: $env{'user.name'}.', '.$umode.
1.197 www 7264: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7265: unless ($reply eq 'ok') {
1.197 www 7266: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7267: return 'error: '.$reply;
7268: }
1.170 harris41 7269: return 'ok';
1.80 www 7270: }
7271:
1.81 www 7272: # --------------------------------------------------------------- Modify a user
1.80 www 7273:
1.81 www 7274: sub modifyuser {
1.206 matthew 7275: my ($udom, $uname, $uid,
7276: $umode, $upass, $first,
7277: $middle, $last, $gene,
1.1058 raeburn 7278: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7279: $udom= &LONCAPA::clean_domain($udom);
7280: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7281: my $showcandelete = 'none';
7282: if (ref($candelete) eq 'ARRAY') {
7283: if (@{$candelete} > 0) {
7284: $showcandelete = join(', ',@{$candelete});
7285: }
7286: }
1.81 www 7287: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7288: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7289: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7290: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7291: ' desiredhome not specified').
1.620 albertel 7292: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7293: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7294: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7295: my $newuser;
7296: if ($uhome eq 'no_host') {
7297: $newuser = 1;
7298: }
1.80 www 7299: # ----------------------------------------------------------------- Create User
1.406 albertel 7300: if (($uhome eq 'no_host') &&
7301: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7302: my $unhome='';
1.844 albertel 7303: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7304: $unhome = $desiredhome;
1.620 albertel 7305: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7306: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7307: } else { # load balancing routine for determining $unhome
1.81 www 7308: my $loadm=10000000;
1.841 albertel 7309: my %servers = &get_servers($udom,'library');
7310: foreach my $tryserver (keys(%servers)) {
7311: my $answer=reply('load',$tryserver);
7312: if (($answer=~/\d+/) && ($answer<$loadm)) {
7313: $loadm=$answer;
7314: $unhome=$tryserver;
7315: }
1.80 www 7316: }
7317: }
7318: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7319: return 'error: unable to find a home server for '.$uname.
7320: ' in domain '.$udom;
1.80 www 7321: }
7322: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7323: &escape($upass),$unhome);
7324: unless ($reply eq 'ok') {
7325: return 'error: '.$reply;
7326: }
1.230 stredwic 7327: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7328: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7329: return 'error: unable verify users home machine.';
1.80 www 7330: }
1.209 matthew 7331: } # End of creation of new user
1.80 www 7332: # ---------------------------------------------------------------------- Add ID
7333: if ($uid) {
7334: $uid=~tr/A-Z/a-z/;
7335: my %uidhash=&idrget($udom,$uname);
1.196 www 7336: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7337: && (!$forceid)) {
1.80 www 7338: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7339: return 'error: user id "'.$uid.'" does not match '.
7340: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7341: }
7342: } else {
7343: &idput($udom,($uname => $uid));
7344: }
7345: }
7346: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7347: my @tmp=&get('environment',
1.899 raeburn 7348: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7349: 'permanentemail','inststatus'],
1.134 albertel 7350: $udom,$uname);
1.1075 raeburn 7351: my (%names,%oldnames);
1.313 matthew 7352: if ($tmp[0] =~ m/^error:.*/) {
7353: %names=();
7354: } else {
7355: %names = @tmp;
1.1075 raeburn 7356: %oldnames = %names;
1.313 matthew 7357: }
1.388 www 7358: #
1.1058 raeburn 7359: # If name, email and/or uid are blank (e.g., because an uploaded file
7360: # of users did not contain them), do not overwrite existing values
7361: # unless field is in $candelete array ref.
7362: #
7363:
7364: my @fields = ('firstname','middlename','lastname','generation',
7365: 'permanentemail','id');
7366: my %newvalues;
7367: if (ref($candelete) eq 'ARRAY') {
7368: foreach my $field (@fields) {
7369: if (grep(/^\Q$field\E$/,@{$candelete})) {
7370: if ($field eq 'firstname') {
7371: $names{$field} = $first;
7372: } elsif ($field eq 'middlename') {
7373: $names{$field} = $middle;
7374: } elsif ($field eq 'lastname') {
7375: $names{$field} = $last;
7376: } elsif ($field eq 'generation') {
7377: $names{$field} = $gene;
7378: } elsif ($field eq 'permanentemail') {
7379: $names{$field} = $email;
7380: } elsif ($field eq 'id') {
7381: $names{$field} = $uid;
7382: }
7383: }
7384: }
7385: }
1.388 www 7386: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7387: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7388: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7389: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7390: if ($email) {
7391: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7392: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7393: }
1.899 raeburn 7394: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7395: if (defined($inststatus)) {
7396: $names{'inststatus'} = '';
7397: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7398: if (ref($usertypes) eq 'HASH') {
7399: my @okstatuses;
7400: foreach my $item (split(/:/,$inststatus)) {
7401: if (defined($usertypes->{$item})) {
7402: push(@okstatuses,$item);
7403: }
7404: }
7405: if (@okstatuses) {
7406: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7407: }
7408: }
7409: }
1.1075 raeburn 7410: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7411: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7412: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7413: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7414: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7415: } else {
7416: $logmsg .= ' during self creation';
7417: }
1.1075 raeburn 7418: my $changed;
7419: if ($newuser) {
7420: $changed = 1;
7421: } else {
7422: foreach my $field (@fields) {
7423: if ($names{$field} ne $oldnames{$field}) {
7424: $changed = 1;
7425: last;
7426: }
7427: }
7428: }
7429: unless ($changed) {
7430: $logmsg = 'No changes in user information needed for: '.$logmsg;
7431: &logthis($logmsg);
7432: return 'ok';
7433: }
7434: my $reply = &put('environment', \%names, $udom,$uname);
7435: if ($reply ne 'ok') {
7436: return 'error: '.$reply;
7437: }
1.1087 raeburn 7438: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7439: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7440: }
1.1075 raeburn 7441: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7442: &devalidate_cache_new('namescache',$uname.':'.$udom);
7443: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7444: &logthis($logmsg);
1.134 albertel 7445: return 'ok';
1.80 www 7446: }
7447:
1.81 www 7448: # -------------------------------------------------------------- Modify student
1.80 www 7449:
1.81 www 7450: sub modifystudent {
7451: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7452: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7453: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7454: if (!$cid) {
1.620 albertel 7455: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7456: return 'not_in_class';
7457: }
1.80 www 7458: }
7459: # --------------------------------------------------------------- Make the user
1.81 www 7460: my $reply=&modifyuser
1.209 matthew 7461: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7462: $desiredhome,$email,$inststatus);
1.80 www 7463: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7464: # This will cause &modify_student_enrollment to get the uid from the
7465: # students environment
7466: $uid = undef if (!$forceid);
1.455 albertel 7467: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7468: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7469: return $reply;
7470: }
7471:
7472: sub modify_student_enrollment {
1.957 raeburn 7473: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7474: my ($cdom,$cnum,$chome);
7475: if (!$cid) {
1.620 albertel 7476: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7477: return 'not_in_class';
7478: }
1.620 albertel 7479: $cdom=$env{'course.'.$cid.'.domain'};
7480: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7481: } else {
7482: ($cdom,$cnum)=split(/_/,$cid);
7483: }
1.620 albertel 7484: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7485: if (!$chome) {
1.457 raeburn 7486: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7487: }
1.455 albertel 7488: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7489: # Make sure the user exists
1.81 www 7490: my $uhome=&homeserver($uname,$udom);
7491: if (($uhome eq '') || ($uhome eq 'no_host')) {
7492: return 'error: no such user';
7493: }
1.297 matthew 7494: # Get student data if we were not given enough information
7495: if (!defined($first) || $first eq '' ||
7496: !defined($last) || $last eq '' ||
7497: !defined($uid) || $uid eq '' ||
7498: !defined($middle) || $middle eq '' ||
7499: !defined($gene) || $gene eq '') {
1.294 matthew 7500: # They did not supply us with enough data to enroll the student, so
7501: # we need to pick up more information.
1.297 matthew 7502: my %tmp = &get('environment',
1.294 matthew 7503: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7504: ,$udom,$uname);
7505:
1.800 albertel 7506: #foreach my $key (keys(%tmp)) {
7507: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7508: #}
1.294 matthew 7509: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7510: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7511: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7512: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7513: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7514: }
1.556 albertel 7515: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7516: my $reply=cput('classlist',
7517: {"$uname:$udom" =>
1.515 raeburn 7518: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7519: $cdom,$cnum);
1.81 www 7520: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7521: return 'error: '.$reply;
1.652 albertel 7522: } else {
7523: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7524: }
1.297 matthew 7525: # Add student role to user
1.83 www 7526: my $uurl='/'.$cid;
1.81 www 7527: $uurl=~s/\_/\//g;
7528: if ($usec) {
7529: $uurl.='/'.$usec;
7530: }
1.957 raeburn 7531: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7532: }
7533:
1.556 albertel 7534: sub format_name {
7535: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7536: my $name;
7537: if ($first ne 'lastname') {
7538: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7539: } else {
7540: if ($lastname=~/\S/) {
7541: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7542: $name=~s/\s+,/,/;
7543: } else {
7544: $name.= $firstname.' '.$middlename.' '.$generation;
7545: }
7546: }
7547: $name=~s/^\s+//;
7548: $name=~s/\s+$//;
7549: $name=~s/\s+/ /g;
7550: return $name;
7551: }
7552:
1.84 www 7553: # ------------------------------------------------- Write to course preferences
7554:
7555: sub writecoursepref {
7556: my ($courseid,%prefs)=@_;
7557: $courseid=~s/^\///;
7558: $courseid=~s/\_/\//g;
7559: my ($cdomain,$cnum)=split(/\//,$courseid);
7560: my $chome=homeserver($cnum,$cdomain);
7561: if (($chome eq '') || ($chome eq 'no_host')) {
7562: return 'error: no such course';
7563: }
7564: my $cstring='';
1.800 albertel 7565: foreach my $pref (keys(%prefs)) {
7566: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7567: }
1.84 www 7568: $cstring=~s/\&$//;
7569: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7570: }
7571:
7572: # ---------------------------------------------------------- Make/modify course
7573:
7574: sub createcourse {
1.741 raeburn 7575: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7576: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7577: $url=&declutter($url);
7578: my $cid='';
1.1028 raeburn 7579: if ($context eq 'requestcourses') {
7580: my $can_create = 0;
7581: my ($ownername,$ownerdom) = split(':',$course_owner);
7582: if ($udom eq $ownerdom) {
7583: if (&usertools_access($ownername,$ownerdom,$category,undef,
7584: $context)) {
7585: $can_create = 1;
7586: }
7587: } else {
7588: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7589: $category);
7590: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7591: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7592: if (@curr > 0) {
7593: my @options = qw(approval validate autolimit);
7594: my $optregex = join('|',@options);
7595: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7596: $can_create = 1;
7597: }
7598: }
7599: }
7600: }
7601: if ($can_create) {
7602: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7603: unless (&allowed('ccc',$udom)) {
7604: return 'refused';
7605: }
1.1017 raeburn 7606: }
7607: } else {
7608: return 'refused';
7609: }
1.1028 raeburn 7610: } elsif (!&allowed('ccc',$udom)) {
7611: return 'refused';
1.84 www 7612: }
1.1011 raeburn 7613: # --------------------------------------------------------------- Get Unique ID
7614: my $uname;
7615: if ($cnum =~ /^$match_courseid$/) {
7616: my $chome=&homeserver($cnum,$udom,'true');
7617: if (($chome eq '') || ($chome eq 'no_host')) {
7618: $uname = $cnum;
7619: } else {
1.1038 raeburn 7620: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7621: }
7622: } else {
1.1038 raeburn 7623: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7624: }
7625: return $uname if ($uname =~ /^error/);
7626: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7627: if (!defined($course_server)) {
7628: if (defined(&domain($udom,'primary'))) {
7629: $course_server = &domain($udom,'primary');
7630: } else {
7631: $course_server = $env{'user.home'};
7632: }
7633: }
7634: my %host_servers =
7635: &Apache::lonnet::get_servers($udom,'library');
7636: unless ($host_servers{$course_server}) {
7637: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7638: }
1.84 www 7639: # ------------------------------------------------------------- Make the course
7640: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7641: $course_server);
1.84 www 7642: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7643: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7644: if (($uhome eq '') || ($uhome eq 'no_host')) {
7645: return 'error: no such course';
7646: }
1.271 www 7647: # ----------------------------------------------------------------- Course made
1.516 raeburn 7648: # log existence
1.1029 raeburn 7649: my $now = time;
1.918 raeburn 7650: my $newcourse = {
7651: $udom.'_'.$uname => {
1.921 raeburn 7652: description => $description,
7653: inst_code => $inst_code,
7654: owner => $course_owner,
7655: type => $crstype,
1.1029 raeburn 7656: creator => $env{'user.name'}.':'.
7657: $env{'user.domain'},
7658: created => $now,
7659: context => $context,
1.918 raeburn 7660: },
7661: };
1.921 raeburn 7662: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7663: # set toplevel url
1.271 www 7664: my $topurl=$url;
7665: unless ($nonstandard) {
7666: # ------------------------------------------ For standard courses, make top url
7667: my $mapurl=&clutter($url);
1.278 www 7668: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7669: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7670: <map>
7671: <resource id="1" type="start"></resource>
7672: <resource id="2" src="$mapurl"></resource>
7673: <resource id="3" type="finish"></resource>
7674: <link index="1" from="1" to="2"></link>
7675: <link index="2" from="2" to="3"></link>
7676: </map>
7677: ENDINITMAP
7678: $topurl=&declutter(
1.638 albertel 7679: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7680: );
7681: }
7682: # ----------------------------------------------------------- Write preferences
1.84 www 7683: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7684: ('description' => $description,
7685: 'url' => $topurl,
7686: 'internal.creator' => $env{'user.name'}.':'.
7687: $env{'user.domain'},
7688: 'internal.created' => $now,
7689: 'internal.creationcontext' => $context)
7690: );
1.84 www 7691: return '/'.$udom.'/'.$uname;
7692: }
7693:
1.1011 raeburn 7694: # ------------------------------------------------------------------- Create ID
7695: sub generate_coursenum {
1.1038 raeburn 7696: my ($udom,$crstype) = @_;
1.1011 raeburn 7697: my $domdesc = &domain($udom);
7698: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7699: my $first;
7700: if ($crstype eq 'Community') {
7701: $first = '0';
7702: } else {
7703: $first = int(1+rand(9));
7704: }
7705: my $uname=$first.
1.1011 raeburn 7706: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7707: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7708: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7709: # ----------------------------------------------- Make sure that does not exist
7710: my $uhome=&homeserver($uname,$udom,'true');
7711: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7712: if ($crstype eq 'Community') {
7713: $first = '0';
7714: } else {
7715: $first = int(1+rand(9));
7716: }
7717: $uname=$first.
1.1011 raeburn 7718: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7719: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7720: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7721: $uhome=&homeserver($uname,$udom,'true');
7722: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7723: return 'error: unable to generate unique course-ID';
7724: }
7725: }
7726: return $uname;
7727: }
7728:
1.813 albertel 7729: sub is_course {
7730: my ($cdom,$cnum) = @_;
7731: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7732: undef,'.');
1.813 albertel 7733: if (exists($courses{$cdom.'_'.$cnum})) {
7734: return 1;
7735: }
7736: return 0;
7737: }
7738:
1.1015 raeburn 7739: sub store_userdata {
7740: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7741: my $result;
1.1016 raeburn 7742: if ($datakey ne '') {
1.1013 raeburn 7743: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7744: if ($udom eq '' || $uname eq '') {
7745: $udom = $env{'user.domain'};
7746: $uname = $env{'user.name'};
7747: }
7748: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7749: if (($uhome eq '') || ($uhome eq 'no_host')) {
7750: $result = 'error: no_host';
7751: } else {
7752: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7753: $storehash->{'host'} = $perlvar{'lonHostID'};
7754:
7755: my $namevalue='';
7756: foreach my $key (keys(%{$storehash})) {
7757: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7758: }
7759: $namevalue=~s/\&$//;
1.1105 raeburn 7760: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7761: $namevalue,$uhome);
1.1013 raeburn 7762: }
7763: } else {
7764: $result = 'error: data to store was not a hash reference';
7765: }
7766: } else {
7767: $result= 'error: invalid requestkey';
7768: }
7769: return $result;
7770: }
7771:
1.21 www 7772: # ---------------------------------------------------------- Assign Custom Role
7773:
7774: sub assigncustomrole {
1.957 raeburn 7775: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7776: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7777: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7778: }
7779:
7780: # ----------------------------------------------------------------- Revoke Role
7781:
7782: sub revokerole {
1.957 raeburn 7783: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7784: my $now=time;
1.965 raeburn 7785: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7786: }
7787:
7788: # ---------------------------------------------------------- Revoke Custom Role
7789:
7790: sub revokecustomrole {
1.957 raeburn 7791: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7792: my $now=time;
1.357 www 7793: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7794: $deleteflag,$selfenroll,$context);
1.17 www 7795: }
7796:
1.533 banghart 7797: # ------------------------------------------------------------ Disk usage
1.535 albertel 7798: sub diskusage {
1.955 raeburn 7799: my ($udom,$uname,$directorypath,$getpropath)=@_;
7800: $directorypath =~ s/\/$//;
7801: my $listing=&reply('du2:'.&escape($directorypath).':'
7802: .&escape($getpropath).':'.&escape($uname).':'
7803: .&escape($udom),homeserver($uname,$udom));
7804: if ($listing eq 'unknown_cmd') {
7805: if ($getpropath) {
7806: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7807: }
7808: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7809: }
1.514 albertel 7810: return $listing;
1.512 banghart 7811: }
7812:
1.566 banghart 7813: sub is_locked {
1.1096 raeburn 7814: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7815: my @check;
7816: my $is_locked;
1.1093 raeburn 7817: push (@check,$file_name);
1.613 albertel 7818: my %locked = &get('file_permissions',\@check,
1.620 albertel 7819: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7820: my ($tmp)=keys(%locked);
7821: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7822:
1.566 banghart 7823: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7824: $is_locked = 'false';
7825: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 7826: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7827: $is_locked = 'true';
1.1096 raeburn 7828: if (ref($which) eq 'ARRAY') {
7829: push(@{$which},$entry);
7830: } else {
7831: last;
7832: }
1.745 raeburn 7833: }
7834: }
1.566 banghart 7835: } else {
7836: $is_locked = 'false';
7837: }
1.1093 raeburn 7838: return $is_locked;
1.566 banghart 7839: }
7840:
1.759 albertel 7841: sub declutter_portfile {
7842: my ($file) = @_;
1.833 albertel 7843: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7844: return $file;
7845: }
7846:
1.559 banghart 7847: # ------------------------------------------------------------- Mark as Read Only
7848:
7849: sub mark_as_readonly {
7850: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7851: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7852: my ($tmp)=keys(%current_permissions);
7853: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7854: foreach my $file (@{$files}) {
1.759 albertel 7855: $file = &declutter_portfile($file);
1.561 banghart 7856: push(@{$current_permissions{$file}},$what);
1.559 banghart 7857: }
1.613 albertel 7858: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7859: return;
7860: }
7861:
1.572 banghart 7862: # ------------------------------------------------------------Save Selected Files
7863:
7864: sub save_selected_files {
7865: my ($user, $path, @files) = @_;
7866: my $filename = $user."savedfiles";
1.573 banghart 7867: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7868: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7869: foreach my $file (@files) {
1.620 albertel 7870: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7871: }
7872: foreach my $file (@other_files) {
1.574 banghart 7873: print (OUT $file."\n");
1.572 banghart 7874: }
1.574 banghart 7875: close (OUT);
1.572 banghart 7876: return 'ok';
7877: }
7878:
1.574 banghart 7879: sub clear_selected_files {
7880: my ($user) = @_;
7881: my $filename = $user."savedfiles";
1.1117 foxr 7882: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 7883: print (OUT undef);
7884: close (OUT);
7885: return ("ok");
7886: }
7887:
1.572 banghart 7888: sub files_in_path {
7889: my ($user, $path) = @_;
7890: my $filename = $user."savedfiles";
7891: my %return_files;
1.1117 foxr 7892: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 7893: while (my $line_in = <IN>) {
1.574 banghart 7894: chomp ($line_in);
7895: my @paths_and_file = split (m!/!, $line_in);
7896: my $file_part = pop (@paths_and_file);
7897: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7898: $path_part.='/';
7899: my $path_and_file = $path_part.$file_part;
7900: if ($path_part eq $path) {
7901: $return_files{$file_part}= 'selected';
7902: }
7903: }
1.574 banghart 7904: close (IN);
7905: return (\%return_files);
1.572 banghart 7906: }
7907:
7908: # called in portfolio select mode, to show files selected NOT in current directory
7909: sub files_not_in_path {
7910: my ($user, $path) = @_;
7911: my $filename = $user."savedfiles";
7912: my @return_files;
7913: my $path_part;
1.1117 foxr 7914: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 7915: while (my $line = <IN>) {
1.572 banghart 7916: #ok, I know it's clunky, but I want it to work
1.800 albertel 7917: my @paths_and_file = split(m|/|, $line);
7918: my $file_part = pop(@paths_and_file);
7919: chomp($file_part);
7920: my $path_part = join('/', @paths_and_file);
1.572 banghart 7921: $path_part .= '/';
7922: my $path_and_file = $path_part.$file_part;
7923: if ($path_part ne $path) {
1.800 albertel 7924: push(@return_files, ($path_and_file));
1.572 banghart 7925: }
7926: }
1.800 albertel 7927: close(OUT);
1.574 banghart 7928: return (@return_files);
1.572 banghart 7929: }
7930:
1.745 raeburn 7931: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7932:
1.745 raeburn 7933: sub get_portfile_permissions {
7934: my ($domain,$user) = @_;
1.613 albertel 7935: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7936: my ($tmp)=keys(%current_permissions);
7937: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7938: return \%current_permissions;
7939: }
7940:
7941: #---------------------------------------------Get portfolio file access controls
7942:
1.749 raeburn 7943: sub get_access_controls {
1.745 raeburn 7944: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7945: my %access;
7946: my $real_file = $file;
7947: $file =~ s/\.meta$//;
1.745 raeburn 7948: if (defined($file)) {
1.749 raeburn 7949: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7950: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7951: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7952: }
7953: }
1.745 raeburn 7954: } else {
1.749 raeburn 7955: foreach my $key (keys(%{$current_permissions})) {
7956: if ($key =~ /\0accesscontrol$/) {
7957: if (defined($group)) {
7958: if ($key !~ m-^\Q$group\E/-) {
7959: next;
7960: }
7961: }
7962: my ($fullpath) = split(/\0/,$key);
7963: if (ref($$current_permissions{$key}) eq 'HASH') {
7964: foreach my $control (keys(%{$$current_permissions{$key}})) {
7965: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7966: }
7967: }
7968: }
7969: }
7970: }
7971: return %access;
7972: }
7973:
7974: sub modify_access_controls {
7975: my ($file_name,$changes,$domain,$user)=@_;
7976: my ($outcome,$deloutcome);
7977: my %store_permissions;
7978: my %new_values;
7979: my %new_control;
7980: my %translation;
7981: my @deletions = ();
7982: my $now = time;
7983: if (exists($$changes{'activate'})) {
7984: if (ref($$changes{'activate'}) eq 'HASH') {
7985: my @newitems = sort(keys(%{$$changes{'activate'}}));
7986: my $numnew = scalar(@newitems);
7987: for (my $i=0; $i<$numnew; $i++) {
7988: my $newkey = $newitems[$i];
7989: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7990: if ($newkey =~ /^\d+:/) {
7991: $newkey =~ s/^(\d+)/$newid/;
7992: $translation{$1} = $newid;
7993: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7994: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7995: $translation{$1} = $newid;
7996: }
1.749 raeburn 7997: $new_values{$file_name."\0".$newkey} =
7998: $$changes{'activate'}{$newitems[$i]};
7999: $new_control{$newkey} = $now;
8000: }
8001: }
8002: }
8003: my %todelete;
8004: my %changed_items;
8005: foreach my $action ('delete','update') {
8006: if (exists($$changes{$action})) {
8007: if (ref($$changes{$action}) eq 'HASH') {
8008: foreach my $key (keys(%{$$changes{$action}})) {
8009: my ($itemnum) = ($key =~ /^([^:]+):/);
8010: if ($action eq 'delete') {
8011: $todelete{$itemnum} = 1;
8012: } else {
8013: $changed_items{$itemnum} = $key;
8014: }
8015: }
1.745 raeburn 8016: }
8017: }
1.749 raeburn 8018: }
8019: # get lock on access controls for file.
8020: my $lockhash = {
8021: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8022: ':'.$env{'user.domain'},
8023: };
8024: my $tries = 0;
8025: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8026:
8027: while (($gotlock ne 'ok') && $tries <3) {
8028: $tries ++;
8029: sleep 1;
8030: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8031: }
8032: if ($gotlock eq 'ok') {
8033: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8034: my ($tmp)=keys(%curr_permissions);
8035: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8036: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8037: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8038: if (ref($curr_controls) eq 'HASH') {
8039: foreach my $control_item (keys(%{$curr_controls})) {
8040: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8041: if (defined($todelete{$itemnum})) {
8042: push(@deletions,$file_name."\0".$control_item);
8043: } else {
8044: if (defined($changed_items{$itemnum})) {
8045: $new_control{$changed_items{$itemnum}} = $now;
8046: push(@deletions,$file_name."\0".$control_item);
8047: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8048: } else {
8049: $new_control{$control_item} = $$curr_controls{$control_item};
8050: }
8051: }
1.745 raeburn 8052: }
8053: }
8054: }
1.970 raeburn 8055: my ($group);
8056: if (&is_course($domain,$user)) {
8057: ($group,my $file) = split(/\//,$file_name,2);
8058: }
1.749 raeburn 8059: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8060: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8061: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8062: # remove lock
8063: my @del_lock = ($file_name."\0".'locked_access_records');
8064: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8065: my $sqlresult =
1.970 raeburn 8066: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8067: $group);
1.749 raeburn 8068: } else {
8069: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8070: }
1.749 raeburn 8071: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8072: }
8073:
1.827 raeburn 8074: sub make_public_indefinitely {
8075: my ($requrl) = @_;
8076: my $now = time;
8077: my $action = 'activate';
8078: my $aclnum = 0;
8079: if (&is_portfolio_url($requrl)) {
8080: my (undef,$udom,$unum,$file_name,$group) =
8081: &parse_portfolio_url($requrl);
8082: my $current_perms = &get_portfile_permissions($udom,$unum);
8083: my %access_controls = &get_access_controls($current_perms,
8084: $group,$file_name);
8085: foreach my $key (keys(%{$access_controls{$file_name}})) {
8086: my ($num,$scope,$end,$start) =
8087: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8088: if ($scope eq 'public') {
8089: if ($start <= $now && $end == 0) {
8090: $action = 'none';
8091: } else {
8092: $action = 'update';
8093: $aclnum = $num;
8094: }
8095: last;
8096: }
8097: }
8098: if ($action eq 'none') {
8099: return 'ok';
8100: } else {
8101: my %changes;
8102: my $newend = 0;
8103: my $newstart = $now;
8104: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8105: $changes{$action}{$newkey} = {
8106: type => 'public',
8107: time => {
8108: start => $newstart,
8109: end => $newend,
8110: },
8111: };
8112: my ($outcome,$deloutcome,$new_values,$translation) =
8113: &modify_access_controls($file_name,\%changes,$udom,$unum);
8114: return $outcome;
8115: }
8116: } else {
8117: return 'invalid';
8118: }
8119: }
8120:
1.745 raeburn 8121: #------------------------------------------------------Get Marked as Read Only
8122:
8123: sub get_marked_as_readonly {
8124: my ($domain,$user,$what,$group) = @_;
8125: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8126: my @readonly_files;
1.629 banghart 8127: my $cmp1=$what;
8128: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8129: while (my ($file_name,$value) = each(%{$current_permissions})) {
8130: if (defined($group)) {
8131: if ($file_name !~ m-^\Q$group\E/-) {
8132: next;
8133: }
8134: }
1.561 banghart 8135: if (ref($value) eq "ARRAY"){
8136: foreach my $stored_what (@{$value}) {
1.629 banghart 8137: my $cmp2=$stored_what;
1.759 albertel 8138: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8139: $cmp2=join('',@{$stored_what});
1.745 raeburn 8140: }
1.629 banghart 8141: if ($cmp1 eq $cmp2) {
1.561 banghart 8142: push(@readonly_files, $file_name);
1.745 raeburn 8143: last;
1.563 banghart 8144: } elsif (!defined($what)) {
8145: push(@readonly_files, $file_name);
1.745 raeburn 8146: last;
1.561 banghart 8147: }
8148: }
1.745 raeburn 8149: }
1.561 banghart 8150: }
8151: return @readonly_files;
8152: }
1.577 banghart 8153: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8154:
1.577 banghart 8155: sub get_marked_as_readonly_hash {
1.745 raeburn 8156: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8157: my %readonly_files;
1.745 raeburn 8158: while (my ($file_name,$value) = each(%{$current_permissions})) {
8159: if (defined($group)) {
8160: if ($file_name !~ m-^\Q$group\E/-) {
8161: next;
8162: }
8163: }
1.577 banghart 8164: if (ref($value) eq "ARRAY"){
8165: foreach my $stored_what (@{$value}) {
1.745 raeburn 8166: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8167: foreach my $lock_descriptor(@{$stored_what}) {
8168: if ($lock_descriptor eq 'graded') {
8169: $readonly_files{$file_name} = 'graded';
8170: } elsif ($lock_descriptor eq 'handback') {
8171: $readonly_files{$file_name} = 'handback';
8172: } else {
8173: if (!exists($readonly_files{$file_name})) {
8174: $readonly_files{$file_name} = 'locked';
8175: }
8176: }
1.745 raeburn 8177: }
1.750 banghart 8178: }
1.577 banghart 8179: }
8180: }
8181: }
8182: return %readonly_files;
8183: }
1.559 banghart 8184: # ------------------------------------------------------------ Unmark as Read Only
8185:
8186: sub unmark_as_readonly {
1.629 banghart 8187: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8188: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8189: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8190: $file_name = &declutter_portfile($file_name);
1.634 albertel 8191: my $symb_crs = $what;
8192: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8193: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8194: my ($tmp)=keys(%current_permissions);
8195: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8196: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8197: foreach my $file (@readonly_files) {
1.759 albertel 8198: my $clean_file = &declutter_portfile($file);
8199: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8200: my $current_locks = $current_permissions{$file};
1.563 banghart 8201: my @new_locks;
8202: my @del_keys;
8203: if (ref($current_locks) eq "ARRAY"){
8204: foreach my $locker (@{$current_locks}) {
1.632 albertel 8205: my $compare=$locker;
1.749 raeburn 8206: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8207: $compare=join('',@{$locker});
1.746 raeburn 8208: if ($compare ne $symb_crs) {
8209: push(@new_locks, $locker);
8210: }
1.563 banghart 8211: }
8212: }
1.650 albertel 8213: if (scalar(@new_locks) > 0) {
1.563 banghart 8214: $current_permissions{$file} = \@new_locks;
8215: } else {
8216: push(@del_keys, $file);
1.613 albertel 8217: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8218: delete($current_permissions{$file});
1.563 banghart 8219: }
8220: }
1.561 banghart 8221: }
1.613 albertel 8222: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8223: return;
8224: }
1.512 banghart 8225:
1.17 www 8226: # ------------------------------------------------------------ Directory lister
8227:
8228: sub dirlist {
1.955 raeburn 8229: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8230: $uri=~s/^\///;
8231: $uri=~s/\/$//;
1.253 stredwic 8232: my ($udom, $uname);
1.955 raeburn 8233: if ($getuserdir) {
1.253 stredwic 8234: $udom = $userdomain;
8235: $uname = $username;
1.955 raeburn 8236: } else {
8237: (undef,$udom,$uname)=split(/\//,$uri);
8238: if(defined($userdomain)) {
8239: $udom = $userdomain;
8240: }
8241: if(defined($username)) {
8242: $uname = $username;
8243: }
1.253 stredwic 8244: }
1.955 raeburn 8245: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8246:
1.955 raeburn 8247: $dirRoot = $perlvar{'lonDocRoot'};
8248: if (defined($getpropath)) {
8249: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8250: $dirRoot =~ s/\/$//;
1.955 raeburn 8251: } elsif (defined($getuserdir)) {
8252: my $subdir=$uname.'__';
8253: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8254: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8255: ."/$udom/$subdir/$uname";
8256: } elsif (defined($alternateRoot)) {
8257: $dirRoot = $alternateRoot;
1.751 banghart 8258: }
1.253 stredwic 8259:
8260: if($udom) {
8261: if($uname) {
1.1135 raeburn 8262: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8263: if ($uhome eq 'no_host') {
8264: return ([],'no_host');
8265: }
1.955 raeburn 8266: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8267: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8268: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8269: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8270: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8271: } else {
8272: @listing_results = map { &unescape($_); } split(/:/,$listing);
8273: }
1.605 matthew 8274: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8275: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8276: @listing_results = split(/:/,$listing);
8277: } else {
8278: @listing_results = map { &unescape($_); } split(/:/,$listing);
8279: }
1.1135 raeburn 8280: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8281: ($listing eq 'rejected') || ($listing eq 'refused') ||
8282: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8283: return ([],$listing);
8284: } else {
8285: return (\@listing_results);
1.1135 raeburn 8286: }
1.955 raeburn 8287: } elsif(!$alternateRoot) {
1.1136 raeburn 8288: my (%allusers,%listerror);
1.841 albertel 8289: my %servers = &get_servers($udom,'library');
1.955 raeburn 8290: foreach my $tryserver (keys(%servers)) {
8291: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8292: &escape($udom),$tryserver);
8293: if ($listing eq 'unknown_cmd') {
8294: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8295: $udom, $tryserver);
8296: } else {
8297: @listing_results = map { &unescape($_); } split(/:/,$listing);
8298: }
1.841 albertel 8299: if ($listing eq 'unknown_cmd') {
8300: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8301: $udom, $tryserver);
8302: @listing_results = split(/:/,$listing);
8303: } else {
8304: @listing_results =
8305: map { &unescape($_); } split(/:/,$listing);
8306: }
1.1136 raeburn 8307: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8308: ($listing eq 'rejected') || ($listing eq 'refused') ||
8309: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8310: $listerror{$tryserver} = $listing;
8311: } else {
1.841 albertel 8312: foreach my $line (@listing_results) {
8313: my ($entry) = split(/&/,$line,2);
8314: $allusers{$entry} = 1;
8315: }
8316: }
1.253 stredwic 8317: }
1.1136 raeburn 8318: my @alluserslist=();
1.800 albertel 8319: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8320: push(@alluserslist,$user.'&user');
1.253 stredwic 8321: }
1.1136 raeburn 8322: return (\@alluserslist);
1.253 stredwic 8323: } else {
1.1136 raeburn 8324: return ([],'missing username');
1.253 stredwic 8325: }
1.955 raeburn 8326: } elsif(!defined($getpropath)) {
1.1136 raeburn 8327: my $path = $perlvar{'lonDocRoot'}.'/res/';
8328: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8329: return (\@all_domains);
1.955 raeburn 8330: } else {
1.1136 raeburn 8331: return ([],'missing domain');
1.275 stredwic 8332: }
8333: }
8334:
8335: # --------------------------------------------- GetFileTimestamp
8336: # This function utilizes dirlist and returns the date stamp for
8337: # when it was last modified. It will also return an error of -1
8338: # if an error occurs
8339:
8340: sub GetFileTimestamp {
1.955 raeburn 8341: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8342: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8343: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8344: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8345: undef,$getuserdir);
8346: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8347: return -1;
8348: }
8349: if (ref($fileref) eq 'ARRAY') {
8350: my @stats = split('&',$fileref->[0]);
1.375 matthew 8351: # @stats contains first the filename, then the stat output
8352: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8353: } else {
8354: return -1;
1.253 stredwic 8355: }
1.26 www 8356: }
8357:
1.712 albertel 8358: sub stat_file {
8359: my ($uri) = @_;
1.787 albertel 8360: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8361:
1.955 raeburn 8362: my ($udom,$uname,$file);
1.712 albertel 8363: if ($uri =~ m-^/(uploaded|editupload)/-) {
8364: ($udom,$uname,$file) =
1.811 albertel 8365: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8366: $file = 'userfiles/'.$file;
8367: }
8368: if ($uri =~ m-^/res/-) {
8369: ($udom,$uname) =
1.807 albertel 8370: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8371: $file = $uri;
8372: }
8373:
8374: if (!$udom || !$uname || !$file) {
8375: # unable to handle the uri
8376: return ();
8377: }
1.956 raeburn 8378: my $getpropath;
8379: if ($file =~ /^userfiles\//) {
8380: $getpropath = 1;
8381: }
1.1136 raeburn 8382: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8383: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8384: return ();
8385: } else {
8386: if (ref($listref) eq 'ARRAY') {
8387: my @stats = split('&',$listref->[0]);
8388: shift(@stats); #filename is first
8389: return @stats;
8390: }
1.712 albertel 8391: }
8392: return ();
8393: }
8394:
1.26 www 8395: # -------------------------------------------------------- Value of a Condition
8396:
1.713 albertel 8397: # gets the value of a specific preevaluated condition
8398: # stored in the string $env{user.state.<cid>}
8399: # or looks up a condition reference in the bighash and if if hasn't
8400: # already been evaluated recurses into docondval to get the value of
8401: # the condition, then memoizing it to
8402: # $env{user.state.<cid>.<condition>}
1.40 www 8403: sub directcondval {
8404: my $number=shift;
1.620 albertel 8405: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8406: &Apache::lonuserstate::evalstate();
8407: }
1.713 albertel 8408: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8409: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8410: } elsif ($number =~ /^_/) {
8411: my $sub_condition;
8412: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8413: &GDBM_READER(),0640)) {
8414: $sub_condition=$bighash{'conditions'.$number};
8415: untie(%bighash);
8416: }
8417: my $value = &docondval($sub_condition);
1.949 raeburn 8418: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8419: return $value;
8420: }
1.620 albertel 8421: if ($env{'user.state.'.$env{'request.course.id'}}) {
8422: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8423: } else {
8424: return 2;
8425: }
8426: }
8427:
1.713 albertel 8428: # get the collection of conditions for this resource
1.26 www 8429: sub condval {
8430: my $condidx=shift;
1.54 www 8431: my $allpathcond='';
1.713 albertel 8432: foreach my $cond (split(/\|/,$condidx)) {
8433: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8434: $allpathcond.=
8435: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8436: }
1.191 harris41 8437: }
1.54 www 8438: $allpathcond=~s/\|$//;
1.713 albertel 8439: return &docondval($allpathcond);
8440: }
8441:
8442: #evaluates an expression of conditions
8443: sub docondval {
8444: my ($allpathcond) = @_;
8445: my $result=0;
8446: if ($env{'request.course.id'}
8447: && defined($allpathcond)) {
8448: my $operand='|';
8449: my @stack;
8450: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8451: if ($chunk eq '(') {
8452: push @stack,($operand,$result);
8453: } elsif ($chunk eq ')') {
8454: my $before=pop @stack;
8455: if (pop @stack eq '&') {
8456: $result=$result>$before?$before:$result;
8457: } else {
8458: $result=$result>$before?$result:$before;
8459: }
8460: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8461: $operand=$chunk;
8462: } else {
8463: my $new=directcondval($chunk);
8464: if ($operand eq '&') {
8465: $result=$result>$new?$new:$result;
8466: } else {
8467: $result=$result>$new?$result:$new;
8468: }
8469: }
8470: }
1.26 www 8471: }
8472: return $result;
1.421 albertel 8473: }
8474:
8475: # ---------------------------------------------------- Devalidate courseresdata
8476:
8477: sub devalidatecourseresdata {
8478: my ($coursenum,$coursedomain)=@_;
8479: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8480: &devalidate_cache_new('courseres',$hashid);
1.28 www 8481: }
8482:
1.763 www 8483:
1.200 www 8484: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8485: #
8486: # Parameters:
8487: # $coursenum - Number of the course.
8488: # $coursedomain - Domain at which the course was created.
8489: # Returns:
8490: # A hash of the course parameters along (I think) with timestamps
8491: # and version info.
1.877 foxr 8492:
1.624 albertel 8493: sub get_courseresdata {
8494: my ($coursenum,$coursedomain)=@_;
1.200 www 8495: my $coursehom=&homeserver($coursenum,$coursedomain);
8496: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8497: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8498: my %dumpreply;
1.417 albertel 8499: unless (defined($cached)) {
1.624 albertel 8500: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8501: $result=\%dumpreply;
1.251 albertel 8502: my ($tmp) = keys(%dumpreply);
8503: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8504: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8505: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8506: return $tmp;
1.416 albertel 8507: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8508: $result=undef;
1.599 albertel 8509: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8510: }
8511: }
1.624 albertel 8512: return $result;
8513: }
8514:
1.633 albertel 8515: sub devalidateuserresdata {
8516: my ($uname,$udom)=@_;
8517: my $hashid="$udom:$uname";
8518: &devalidate_cache_new('userres',$hashid);
8519: }
8520:
1.624 albertel 8521: sub get_userresdata {
8522: my ($uname,$udom)=@_;
8523: #most student don\'t have any data set, check if there is some data
8524: if (&EXT_cache_status($udom,$uname)) { return undef; }
8525:
8526: my $hashid="$udom:$uname";
8527: my ($result,$cached)=&is_cached_new('userres',$hashid);
8528: if (!defined($cached)) {
8529: my %resourcedata=&dump('resourcedata',$udom,$uname);
8530: $result=\%resourcedata;
8531: &do_cache_new('userres',$hashid,$result,600);
8532: }
8533: my ($tmp)=keys(%$result);
8534: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8535: return $result;
8536: }
8537: #error 2 occurs when the .db doesn't exist
8538: if ($tmp!~/error: 2 /) {
1.672 albertel 8539: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8540: " Trying to get resource data for ".
8541: $uname." at ".$udom.": ".
8542: $tmp."</font>");
8543: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8544: #&EXT_cache_set($udom,$uname);
8545: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8546: undef($tmp); # not really an error so don't send it back
1.624 albertel 8547: }
8548: return $tmp;
8549: }
1.879 foxr 8550: #----------------------------------------------- resdata - return resource data
8551: # Purpose:
8552: # Return resource data for either users or for a course.
8553: # Parameters:
8554: # $name - Course/user name.
8555: # $domain - Name of the domain the user/course is registered on.
8556: # $type - Type of thing $name is (must be 'course' or 'user'
8557: # @which - Array of names of resources desired.
8558: # Returns:
8559: # The value of the first reasource in @which that is found in the
8560: # resource hash.
8561: # Exceptional Conditions:
8562: # If the $type passed in is not valid (not the string 'course' or
8563: # 'user', an undefined reference is returned.
8564: # If none of the resources are found, an undef is returned
1.624 albertel 8565: sub resdata {
8566: my ($name,$domain,$type,@which)=@_;
8567: my $result;
8568: if ($type eq 'course') {
8569: $result=&get_courseresdata($name,$domain);
8570: } elsif ($type eq 'user') {
8571: $result=&get_userresdata($name,$domain);
8572: }
8573: if (!ref($result)) { return $result; }
1.251 albertel 8574: foreach my $item (@which) {
1.927 albertel 8575: if (defined($result->{$item->[0]})) {
8576: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8577: }
1.250 albertel 8578: }
1.291 albertel 8579: return undef;
1.200 www 8580: }
8581:
1.379 matthew 8582: #
8583: # EXT resource caching routines
8584: #
8585:
8586: sub clear_EXT_cache_status {
1.383 albertel 8587: &delenv('cache.EXT.');
1.379 matthew 8588: }
8589:
8590: sub EXT_cache_status {
8591: my ($target_domain,$target_user) = @_;
1.383 albertel 8592: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8593: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8594: # We know already the user has no data
8595: return 1;
8596: } else {
8597: return 0;
8598: }
8599: }
8600:
8601: sub EXT_cache_set {
8602: my ($target_domain,$target_user) = @_;
1.383 albertel 8603: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8604: #&appenv({$cachename => time});
1.379 matthew 8605: }
8606:
1.28 www 8607: # --------------------------------------------------------- Value of a Variable
1.58 www 8608: sub EXT {
1.715 albertel 8609:
1.395 albertel 8610: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8611: unless ($varname) { return ''; }
1.218 albertel 8612: #get real user name/domain, courseid and symb
8613: my $courseid;
1.359 albertel 8614: my $publicuser;
1.427 www 8615: if ($symbparm) {
8616: $symbparm=&get_symb_from_alias($symbparm);
8617: }
1.218 albertel 8618: if (!($uname && $udom)) {
1.790 albertel 8619: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8620: if (!$symbparm) { $symbparm=$cursymb; }
8621: } else {
1.620 albertel 8622: $courseid=$env{'request.course.id'};
1.218 albertel 8623: }
1.48 www 8624: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8625: my $rest;
1.320 albertel 8626: if (defined($therest[0])) {
1.48 www 8627: $rest=join('.',@therest);
8628: } else {
8629: $rest='';
8630: }
1.320 albertel 8631:
1.57 www 8632: my $qualifierrest=$qualifier;
8633: if ($rest) { $qualifierrest.='.'.$rest; }
8634: my $spacequalifierrest=$space;
8635: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8636: if ($realm eq 'user') {
1.48 www 8637: # --------------------------------------------------------------- user.resource
8638: if ($space eq 'resource') {
1.651 albertel 8639: if ( (defined($Apache::lonhomework::parsing_a_problem)
8640: || defined($Apache::lonhomework::parsing_a_task))
8641: &&
1.744 albertel 8642: ($symbparm eq &symbread()) ) {
8643: # if we are in the middle of processing the resource the
8644: # get the value we are planning on committing
8645: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8646: return $Apache::lonhomework::results{$qualifierrest};
8647: } else {
8648: return $Apache::lonhomework::history{$qualifierrest};
8649: }
1.335 albertel 8650: } else {
1.359 albertel 8651: my %restored;
1.620 albertel 8652: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8653: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8654: } else {
8655: %restored=&restore($symbparm,$courseid,$udom,$uname);
8656: }
1.335 albertel 8657: return $restored{$qualifierrest};
8658: }
1.48 www 8659: # ----------------------------------------------------------------- user.access
8660: } elsif ($space eq 'access') {
1.218 albertel 8661: # FIXME - not supporting calls for a specific user
1.48 www 8662: return &allowed($qualifier,$rest);
8663: # ------------------------------------------ user.preferences, user.environment
8664: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8665: if (($uname eq $env{'user.name'}) &&
8666: ($udom eq $env{'user.domain'})) {
8667: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8668: } else {
1.359 albertel 8669: my %returnhash;
8670: if (!$publicuser) {
8671: %returnhash=&userenvironment($udom,$uname,
8672: $qualifierrest);
8673: }
1.218 albertel 8674: return $returnhash{$qualifierrest};
8675: }
1.48 www 8676: # ----------------------------------------------------------------- user.course
8677: } elsif ($space eq 'course') {
1.218 albertel 8678: # FIXME - not supporting calls for a specific user
1.620 albertel 8679: return $env{join('.',('request.course',$qualifier))};
1.48 www 8680: # ------------------------------------------------------------------- user.role
8681: } elsif ($space eq 'role') {
1.218 albertel 8682: # FIXME - not supporting calls for a specific user
1.620 albertel 8683: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8684: if ($qualifier eq 'value') {
8685: return $role;
8686: } elsif ($qualifier eq 'extent') {
8687: return $where;
8688: }
8689: # ----------------------------------------------------------------- user.domain
8690: } elsif ($space eq 'domain') {
1.218 albertel 8691: return $udom;
1.48 www 8692: # ------------------------------------------------------------------- user.name
8693: } elsif ($space eq 'name') {
1.218 albertel 8694: return $uname;
1.48 www 8695: # ---------------------------------------------------- Any other user namespace
1.29 www 8696: } else {
1.359 albertel 8697: my %reply;
8698: if (!$publicuser) {
8699: %reply=&get($space,[$qualifierrest],$udom,$uname);
8700: }
8701: return $reply{$qualifierrest};
1.48 www 8702: }
1.236 www 8703: } elsif ($realm eq 'query') {
8704: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8705: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8706: [$spacequalifierrest]);
1.620 albertel 8707: return $env{'form.'.$spacequalifierrest};
1.236 www 8708: } elsif ($realm eq 'request') {
1.48 www 8709: # ------------------------------------------------------------- request.browser
8710: if ($space eq 'browser') {
1.430 www 8711: if ($qualifier eq 'textremote') {
1.676 albertel 8712: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8713: return 1;
8714: } else {
8715: return 0;
8716: }
8717: } else {
1.620 albertel 8718: return $env{'browser.'.$qualifier};
1.430 www 8719: }
1.57 www 8720: # ------------------------------------------------------------ request.filename
8721: } else {
1.620 albertel 8722: return $env{'request.'.$spacequalifierrest};
1.29 www 8723: }
1.28 www 8724: } elsif ($realm eq 'course') {
1.48 www 8725: # ---------------------------------------------------------- course.description
1.620 albertel 8726: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8727: } elsif ($realm eq 'resource') {
1.165 www 8728:
1.620 albertel 8729: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8730: if (!$symbparm) { $symbparm=&symbread(); }
8731: }
1.693 albertel 8732:
8733: if ($space eq 'title') {
8734: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8735: return &gettitle($symbparm);
8736: }
8737:
8738: if ($space eq 'map') {
8739: my ($map) = &decode_symb($symbparm);
8740: return &symbread($map);
8741: }
1.905 albertel 8742: if ($space eq 'filename') {
8743: if ($symbparm) {
8744: return &clutter((&decode_symb($symbparm))[2]);
8745: }
8746: return &hreflocation('',$env{'request.filename'});
8747: }
1.693 albertel 8748:
8749: my ($section, $group, @groups);
1.593 albertel 8750: my ($courselevelm,$courselevel);
1.539 albertel 8751: if ($symbparm && defined($courseid) &&
1.620 albertel 8752: $courseid eq $env{'request.course.id'}) {
1.165 www 8753:
1.218 albertel 8754: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8755:
1.60 www 8756: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8757: my $symbp=$symbparm;
1.735 albertel 8758: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8759:
8760: my $symbparm=$symbp.'.'.$spacequalifierrest;
8761: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8762:
1.620 albertel 8763: if (($env{'user.name'} eq $uname) &&
8764: ($env{'user.domain'} eq $udom)) {
8765: $section=$env{'request.course.sec'};
1.733 raeburn 8766: @groups = split(/:/,$env{'request.course.groups'});
8767: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8768: } else {
1.539 albertel 8769: if (! defined($usection)) {
1.551 albertel 8770: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8771: } else {
8772: $section = $usection;
8773: }
1.733 raeburn 8774: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8775: }
8776:
8777: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8778: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8779: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8780:
1.593 albertel 8781: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8782: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8783: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8784:
1.60 www 8785: # ----------------------------------------------------------- first, check user
1.624 albertel 8786:
8787: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8788: ([$courselevelr,'resource'],
8789: [$courselevelm,'map' ],
8790: [$courselevel, 'course' ]));
1.931 albertel 8791: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8792:
1.594 albertel 8793: # ------------------------------------------------ second, check some of course
1.684 raeburn 8794: my $coursereply;
1.691 raeburn 8795: if (@groups > 0) {
8796: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8797: $mapparm,$spacequalifierrest);
1.927 albertel 8798: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8799: }
1.96 www 8800:
1.684 raeburn 8801: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8802: $env{'course.'.$courseid.'.domain'},
8803: 'course',
8804: ([$seclevelr, 'resource'],
8805: [$seclevelm, 'map' ],
8806: [$seclevel, 'course' ],
8807: [$courselevelr,'resource']));
8808: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8809:
1.60 www 8810: # ------------------------------------------------------ third, check map parms
1.218 albertel 8811: my %parmhash=();
8812: my $thisparm='';
8813: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8814: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8815: &GDBM_READER(),0640)) {
1.218 albertel 8816: $thisparm=$parmhash{$symbparm};
8817: untie(%parmhash);
8818: }
1.927 albertel 8819: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8820: }
1.594 albertel 8821: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8822:
1.218 albertel 8823: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8824: my $filename;
8825: if (!$symbparm) { $symbparm=&symbread(); }
8826: if ($symbparm) {
1.409 www 8827: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8828: } else {
1.620 albertel 8829: $filename=$env{'request.filename'};
1.282 albertel 8830: }
8831: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8832: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8833: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8834: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8835:
1.927 albertel 8836: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8837: if ($symbparm && defined($courseid) &&
1.620 albertel 8838: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8839: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8840: $env{'course.'.$courseid.'.domain'},
8841: 'course',
1.927 albertel 8842: ([$courselevelm,'map' ],
8843: [$courselevel, 'course']));
8844: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8845: }
1.145 www 8846: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8847: unless ($space eq '0') {
1.336 albertel 8848: my @parts=split(/_/,$space);
8849: my $id=pop(@parts);
8850: my $part=join('_',@parts);
8851: if ($part eq '') { $part='0'; }
1.927 albertel 8852: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8853: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8854: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8855: }
1.395 albertel 8856: if ($recurse) { return undef; }
8857: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8858: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8859: # ---------------------------------------------------- Any other user namespace
8860: } elsif ($realm eq 'environment') {
8861: # ----------------------------------------------------------------- environment
1.620 albertel 8862: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8863: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8864: } else {
1.770 albertel 8865: if ($uname eq 'anonymous' && $udom eq '') {
8866: return '';
8867: }
1.219 albertel 8868: my %returnhash=&userenvironment($udom,$uname,
8869: $spacequalifierrest);
8870: return $returnhash{$spacequalifierrest};
8871: }
1.28 www 8872: } elsif ($realm eq 'system') {
1.48 www 8873: # ----------------------------------------------------------------- system.time
8874: if ($space eq 'time') {
8875: return time;
8876: }
1.696 albertel 8877: } elsif ($realm eq 'server') {
8878: # ----------------------------------------------------------------- system.time
8879: if ($space eq 'name') {
8880: return $ENV{'SERVER_NAME'};
8881: }
1.28 www 8882: }
1.48 www 8883: return '';
1.61 www 8884: }
8885:
1.927 albertel 8886: sub get_reply {
8887: my ($reply_value) = @_;
1.940 raeburn 8888: if (ref($reply_value) eq 'ARRAY') {
8889: if (wantarray) {
8890: return @$reply_value;
8891: }
8892: return $reply_value->[0];
8893: } else {
8894: return $reply_value;
1.927 albertel 8895: }
8896: }
8897:
1.691 raeburn 8898: sub check_group_parms {
8899: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8900: my @groupitems = ();
8901: my $resultitem;
1.927 albertel 8902: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8903: foreach my $group (@{$groups}) {
8904: foreach my $level (@levels) {
1.927 albertel 8905: my $item = $courseid.'.['.$group.'].'.$level->[0];
8906: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8907: }
8908: }
8909: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8910: $env{'course.'.$courseid.'.domain'},
8911: 'course',@groupitems);
8912: return $coursereply;
8913: }
8914:
8915: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8916: my ($courseid,@groups) = @_;
8917: @groups = sort(@groups);
1.691 raeburn 8918: return @groups;
8919: }
8920:
1.395 albertel 8921: sub packages_tab_default {
8922: my ($uri,$varname)=@_;
8923: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8924:
8925: my (@extension,@specifics,$do_default);
8926: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8927: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8928: if ($pack_type eq 'default') {
8929: $do_default=1;
8930: } elsif ($pack_type eq 'extension') {
8931: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8932: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8933: # only look at packages defaults for packages that this id is
1.738 albertel 8934: push(@specifics,[$package,$pack_type,$pack_part]);
8935: }
8936: }
8937: # first look for a package that matches the requested part id
8938: foreach my $package (@specifics) {
8939: my (undef,$pack_type,$pack_part)=@{$package};
8940: next if ($pack_part ne $part);
8941: if (defined($packagetab{"$pack_type&$name&default"})) {
8942: return $packagetab{"$pack_type&$name&default"};
8943: }
8944: }
8945: # look for any possible matching non extension_ package
8946: foreach my $package (@specifics) {
8947: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8948: if (defined($packagetab{"$pack_type&$name&default"})) {
8949: return $packagetab{"$pack_type&$name&default"};
8950: }
1.585 albertel 8951: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8952: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8953: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8954: }
8955: }
1.738 albertel 8956: # look for any posible extension_ match
8957: foreach my $package (@extension) {
8958: my ($package,$pack_type)=@{$package};
8959: if (defined($packagetab{"$pack_type&$name&default"})) {
8960: return $packagetab{"$pack_type&$name&default"};
8961: }
8962: if (defined($packagetab{$package."&$name&default"})) {
8963: return $packagetab{$package."&$name&default"};
8964: }
8965: }
8966: # look for a global default setting
8967: if ($do_default && defined($packagetab{"default&$name&default"})) {
8968: return $packagetab{"default&$name&default"};
8969: }
1.395 albertel 8970: return undef;
8971: }
8972:
1.334 albertel 8973: sub add_prefix_and_part {
8974: my ($prefix,$part)=@_;
8975: my $keyroot;
8976: if (defined($prefix) && $prefix !~ /^__/) {
8977: # prefix that has a part already
8978: $keyroot=$prefix;
8979: } elsif (defined($prefix)) {
8980: # prefix that is missing a part
8981: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8982: } else {
8983: # no prefix at all
8984: if (defined($part)) { $keyroot='_'.$part; }
8985: }
8986: return $keyroot;
8987: }
8988:
1.71 www 8989: # ---------------------------------------------------------------- Get metadata
8990:
1.599 albertel 8991: my %metaentry;
1.1070 www 8992: my %importedpartids;
1.71 www 8993: sub metadata {
1.176 www 8994: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8995: $uri=&declutter($uri);
1.288 albertel 8996: # if it is a non metadata possible uri return quickly
1.529 albertel 8997: if (($uri eq '') ||
8998: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8999: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9000: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9001: return undef;
9002: }
1.1140 www 9003: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9004: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9005: return undef;
1.288 albertel 9006: }
1.73 www 9007: my $filename=$uri;
9008: $uri=~s/\.meta$//;
1.172 www 9009: #
9010: # Is the metadata already cached?
1.177 www 9011: # Look at timestamp of caching
1.172 www 9012: # Everything is cached by the main uri, libraries are never directly cached
9013: #
1.428 albertel 9014: if (!defined($liburi)) {
1.599 albertel 9015: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9016: if (defined($cached)) { return $result->{':'.$what}; }
9017: }
9018: {
1.1069 www 9019: # Imported parts would go here
1.1070 www 9020: my %importedids=();
9021: my @origfileimportpartids=();
1.1069 www 9022: my $importedparts=0;
1.172 www 9023: #
9024: # Is this a recursive call for a library?
9025: #
1.599 albertel 9026: # if (! exists($metacache{$uri})) {
9027: # $metacache{$uri}={};
9028: # }
1.924 albertel 9029: my $cachetime = 60*60;
1.171 www 9030: if ($liburi) {
9031: $liburi=&declutter($liburi);
9032: $filename=$liburi;
1.401 bowersj2 9033: } else {
1.599 albertel 9034: &devalidate_cache_new('meta',$uri);
9035: undef(%metaentry);
1.401 bowersj2 9036: }
1.140 www 9037: my %metathesekeys=();
1.73 www 9038: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9039: my $metastring;
1.1140 www 9040: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9041: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9042: $metastring =
1.929 albertel 9043: &Apache::lonnet::ssi_body($which,
1.924 albertel 9044: ('grade_target' => 'meta'));
9045: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9046: } elsif (($uri !~ m -^(editupload)/-) &&
9047: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9048: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9049: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9050: $metastring=&getfile($file);
1.489 albertel 9051: }
1.208 albertel 9052: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9053: my $token;
1.140 www 9054: undef %metathesekeys;
1.71 www 9055: while ($token=$parser->get_token) {
1.339 albertel 9056: if ($token->[0] eq 'S') {
9057: if (defined($token->[2]->{'package'})) {
1.172 www 9058: #
9059: # This is a package - get package info
9060: #
1.339 albertel 9061: my $package=$token->[2]->{'package'};
9062: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9063: if (defined($token->[2]->{'id'})) {
9064: $keyroot.='_'.$token->[2]->{'id'};
9065: }
1.599 albertel 9066: if ($metaentry{':packages'}) {
9067: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9068: } else {
1.599 albertel 9069: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9070: }
1.736 albertel 9071: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9072: my $part=$keyroot;
9073: $part=~s/^\_//;
1.736 albertel 9074: if ($pack_entry=~/^\Q$package\E\&/ ||
9075: $pack_entry=~/^\Q$package\E_0\&/) {
9076: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9077: # ignore package.tab specified default values
9078: # here &package_tab_default() will fetch those
9079: if ($subp eq 'default') { next; }
1.736 albertel 9080: my $value=$packagetab{$pack_entry};
1.432 albertel 9081: my $unikey;
9082: if ($pack =~ /_0$/) {
9083: $unikey='parameter_0_'.$name;
9084: $part=0;
9085: } else {
9086: $unikey='parameter'.$keyroot.'_'.$name;
9087: }
1.339 albertel 9088: if ($subp eq 'display') {
9089: $value.=' [Part: '.$part.']';
9090: }
1.599 albertel 9091: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9092: $metathesekeys{$unikey}=1;
1.599 albertel 9093: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9094: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9095: }
1.599 albertel 9096: if (defined($metaentry{':'.$unikey.'.default'})) {
9097: $metaentry{':'.$unikey}=
9098: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9099: }
1.339 albertel 9100: }
9101: }
9102: } else {
1.172 www 9103: #
9104: # This is not a package - some other kind of start tag
1.339 albertel 9105: #
9106: my $entry=$token->[1];
1.1068 www 9107: my $unikey='';
1.175 www 9108:
1.339 albertel 9109: if ($entry eq 'import') {
1.175 www 9110: #
9111: # Importing a library here
1.339 albertel 9112: #
1.1067 www 9113: my $location=$parser->get_text('/import');
9114: my $dir=$filename;
9115: $dir=~s|[^/]*$||;
9116: $location=&filelocation($dir,$location);
1.1069 www 9117:
1.1068 www 9118: my $importmode=$token->[2]->{'importmode'};
9119: if ($importmode eq 'problem') {
1.1069 www 9120: # Import as problem/response
1.1068 www 9121: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9122: } elsif ($importmode eq 'part') {
9123: # Import as part(s)
1.1069 www 9124: $importedparts=1;
9125: # We need to get the original file and the imported file to get the part order correct
9126: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9127: # Load and inspect original file
1.1070 www 9128: if ($#origfileimportpartids<0) {
9129: undef(%importedpartids);
9130: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9131: my $origfile=&getfile($origfilelocation);
9132: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9133: }
9134:
1.1069 www 9135: # Load and inspect imported file
9136: my $impfile=&getfile($location);
9137: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9138: if ($#impfilepartids>=0) {
9139: # This problem had parts
1.1070 www 9140: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9141: } else {
9142: # Importing by turning a single problem into a problem part
9143: # It gets the import-tags ID as part-ID
9144: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9145: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9146: }
1.1068 www 9147: } else {
9148: # Normal import
9149: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9150: if (defined($token->[2]->{'id'})) {
9151: $unikey.='_'.$token->[2]->{'id'};
9152: }
1.1067 www 9153: }
9154:
1.339 albertel 9155: if ($depthcount<20) {
1.736 albertel 9156: my $metadata =
9157: &metadata($uri,'keys', $location,$unikey,
9158: $depthcount+1);
9159: foreach my $meta (split(',',$metadata)) {
9160: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9161: $metathesekeys{$meta}=1;
1.339 albertel 9162: }
1.1068 www 9163:
9164: }
1.1067 www 9165: } else {
9166: #
9167: # Not importing, some other kind of non-package, non-library start tag
9168: #
9169: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9170: if (defined($token->[2]->{'id'})) {
9171: $unikey.='_'.$token->[2]->{'id'};
9172: }
1.339 albertel 9173: if (defined($token->[2]->{'name'})) {
9174: $unikey.='_'.$token->[2]->{'name'};
9175: }
9176: $metathesekeys{$unikey}=1;
1.736 albertel 9177: foreach my $param (@{$token->[3]}) {
9178: $metaentry{':'.$unikey.'.'.$param} =
9179: $token->[2]->{$param};
1.339 albertel 9180: }
9181: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9182: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9183: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9184: # only ws inside the tag, and not in default, so use default
9185: # as value
1.599 albertel 9186: $metaentry{':'.$unikey}=$default;
1.908 albertel 9187: } elsif ( $internaltext =~ /\S/ ) {
9188: # something interesting inside the tag
9189: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9190: } else {
1.908 albertel 9191: # no interesting values, don't set a default
1.339 albertel 9192: }
1.172 www 9193: # end of not-a-package not-a-library import
1.339 albertel 9194: }
1.172 www 9195: # end of not-a-package start tag
1.339 albertel 9196: }
1.172 www 9197: # the next is the end of "start tag"
1.339 albertel 9198: }
9199: }
1.483 albertel 9200: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9201: $extension = lc($extension);
9202: if ($extension eq 'htm') { $extension='html'; }
9203:
1.737 albertel 9204: foreach my $key (keys(%packagetab)) {
1.483 albertel 9205: #no specific packages #how's our extension
9206: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9207: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9208: \%metathesekeys);
9209: }
1.883 albertel 9210:
9211: if (!exists($metaentry{':packages'})
9212: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9213: foreach my $key (keys(%packagetab)) {
1.483 albertel 9214: #no specific packages well let's get default then
9215: if ($key!~/^default&/) { next; }
1.488 albertel 9216: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9217: \%metathesekeys);
9218: }
9219: }
1.338 www 9220: # are there custom rights to evaluate
1.599 albertel 9221: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9222:
1.338 www 9223: #
9224: # Importing a rights file here
1.339 albertel 9225: #
9226: unless ($depthcount) {
1.599 albertel 9227: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9228: my $dir=$filename;
9229: $dir=~s|[^/]*$||;
9230: $location=&filelocation($dir,$location);
1.736 albertel 9231: my $rights_metadata =
9232: &metadata($uri,'keys',$location,'_rights',
9233: $depthcount+1);
9234: foreach my $rights (split(',',$rights_metadata)) {
9235: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9236: $metathesekeys{$rights}=1;
1.339 albertel 9237: }
9238: }
9239: }
1.737 albertel 9240: # uniqifiy package listing
9241: my %seen;
9242: my @uniq_packages =
9243: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9244: $metaentry{':packages'} = join(',',@uniq_packages);
9245:
1.1070 www 9246: if ($importedparts) {
9247: # We had imported parts and need to rebuild partorder
9248: $metaentry{':partorder'}='';
9249: $metathesekeys{'partorder'}=1;
9250: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9251: if ($origfileimportpartids[$index] eq 'part') {
9252: # original part, part of the problem
9253: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9254: } else {
9255: # we have imported parts at this position
9256: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9257: }
9258: }
9259: $metaentry{':partorder'}=~s/^\,//;
9260: }
9261:
1.737 albertel 9262: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9263: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9264: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9265: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9266: # this is the end of "was not already recently cached
1.71 www 9267: }
1.599 albertel 9268: return $metaentry{':'.$what};
1.261 albertel 9269: }
9270:
1.488 albertel 9271: sub metadata_create_package_def {
1.483 albertel 9272: my ($uri,$key,$package,$metathesekeys)=@_;
9273: my ($pack,$name,$subp)=split(/\&/,$key);
9274: if ($subp eq 'default') { next; }
9275:
1.599 albertel 9276: if (defined($metaentry{':packages'})) {
9277: $metaentry{':packages'}.=','.$package;
1.483 albertel 9278: } else {
1.599 albertel 9279: $metaentry{':packages'}=$package;
1.483 albertel 9280: }
9281: my $value=$packagetab{$key};
9282: my $unikey;
9283: $unikey='parameter_0_'.$name;
1.599 albertel 9284: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9285: $$metathesekeys{$unikey}=1;
1.599 albertel 9286: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9287: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9288: }
1.599 albertel 9289: if (defined($metaentry{':'.$unikey.'.default'})) {
9290: $metaentry{':'.$unikey}=
9291: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9292: }
9293: }
9294:
1.261 albertel 9295: sub metadata_generate_part0 {
9296: my ($metadata,$metacache,$uri) = @_;
9297: my %allnames;
1.737 albertel 9298: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9299: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9300: my $part=$$metacache{':'.$metakey.'.part'};
9301: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9302: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9303: $allnames{$name}=$part;
9304: }
9305: }
9306: }
9307: foreach my $name (keys(%allnames)) {
9308: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9309: my $key=":parameter_0_$name";
1.261 albertel 9310: $$metacache{"$key.part"}='0';
9311: $$metacache{"$key.name"}=$name;
1.428 albertel 9312: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9313: $allnames{$name}.'_'.$name.
9314: '.type'};
1.428 albertel 9315: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9316: '.display'};
1.644 www 9317: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9318: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9319: $$metacache{"$key.display"}=$olddis;
9320: }
1.71 www 9321: }
9322:
1.764 albertel 9323: # ------------------------------------------------------ Devalidate title cache
9324:
9325: sub devalidate_title_cache {
9326: my ($url)=@_;
9327: if (!$env{'request.course.id'}) { return; }
9328: my $symb=&symbread($url);
9329: if (!$symb) { return; }
9330: my $key=$env{'request.course.id'}."\0".$symb;
9331: &devalidate_cache_new('title',$key);
9332: }
9333:
1.1014 droeschl 9334: # ------------------------------------------------- Get the title of a course
9335:
9336: sub current_course_title {
9337: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9338: }
1.301 www 9339: # ------------------------------------------------- Get the title of a resource
9340:
9341: sub gettitle {
9342: my $urlsymb=shift;
9343: my $symb=&symbread($urlsymb);
1.534 albertel 9344: if ($symb) {
1.620 albertel 9345: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9346: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9347: if (defined($cached)) {
9348: return $result;
9349: }
1.534 albertel 9350: my ($map,$resid,$url)=&decode_symb($symb);
9351: my $title='';
1.907 albertel 9352: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9353: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9354: } else {
9355: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9356: &GDBM_READER(),0640)) {
9357: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9358: $title=$bighash{'title_'.$mapid.'.'.$resid};
9359: untie(%bighash);
9360: }
1.534 albertel 9361: }
9362: $title=~s/\&colon\;/\:/gs;
9363: if ($title) {
1.599 albertel 9364: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9365: }
9366: $urlsymb=$url;
9367: }
9368: my $title=&metadata($urlsymb,'title');
9369: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9370: return $title;
1.301 www 9371: }
1.613 albertel 9372:
1.614 albertel 9373: sub get_slot {
9374: my ($which,$cnum,$cdom)=@_;
9375: if (!$cnum || !$cdom) {
1.790 albertel 9376: (undef,my $courseid)=&whichuser();
1.620 albertel 9377: $cdom=$env{'course.'.$courseid.'.domain'};
9378: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9379: }
1.703 albertel 9380: my $key=join("\0",'slots',$cdom,$cnum,$which);
9381: my %slotinfo;
9382: if (exists($remembered{$key})) {
9383: $slotinfo{$which} = $remembered{$key};
9384: } else {
9385: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9386: &Apache::lonhomework::showhash(%slotinfo);
9387: my ($tmp)=keys(%slotinfo);
9388: if ($tmp=~/^error:/) { return (); }
9389: $remembered{$key} = $slotinfo{$which};
9390: }
1.616 albertel 9391: if (ref($slotinfo{$which}) eq 'HASH') {
9392: return %{$slotinfo{$which}};
9393: }
9394: return $slotinfo{$which};
1.614 albertel 9395: }
1.31 www 9396: # ------------------------------------------------- Update symbolic store links
9397:
9398: sub symblist {
9399: my ($mapname,%newhash)=@_;
1.438 www 9400: $mapname=&deversion(&declutter($mapname));
1.31 www 9401: my %hash;
1.620 albertel 9402: if (($env{'request.course.fn'}) && (%newhash)) {
9403: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9404: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9405: foreach my $url (keys(%newhash)) {
1.711 albertel 9406: next if ($url eq 'last_known'
9407: && $env{'form.no_update_last_known'});
9408: $hash{declutter($url)}=&encode_symb($mapname,
9409: $newhash{$url}->[1],
9410: $newhash{$url}->[0]);
1.191 harris41 9411: }
1.31 www 9412: if (untie(%hash)) {
9413: return 'ok';
9414: }
9415: }
9416: }
9417: return 'error';
1.212 www 9418: }
9419:
9420: # --------------------------------------------------------------- Verify a symb
9421:
9422: sub symbverify {
1.510 www 9423: my ($symb,$thisurl)=@_;
9424: my $thisfn=$thisurl;
1.439 www 9425: $thisfn=&declutter($thisfn);
1.215 www 9426: # direct jump to resource in page or to a sequence - will construct own symbs
9427: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9428: # check URL part
1.409 www 9429: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9430:
1.431 www 9431: unless ($url eq $thisfn) { return 0; }
1.213 www 9432:
1.216 www 9433: $symb=&symbclean($symb);
1.510 www 9434: $thisurl=&deversion($thisurl);
1.439 www 9435: $thisfn=&deversion($thisfn);
1.213 www 9436:
9437: my %bighash;
9438: my $okay=0;
1.431 www 9439:
1.620 albertel 9440: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9441: &GDBM_READER(),0640)) {
1.1032 raeburn 9442: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9443: $thisurl =~ s/\?.+$//;
9444: }
1.510 www 9445: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9446: unless ($ids) {
9447: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9448: $ids=$bighash{$idkey};
1.216 www 9449: }
9450: if ($ids) {
9451: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9452: foreach my $id (split(/\,/,$ids)) {
9453: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9454: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9455: $symb =~ s/\?.+$//;
9456: }
1.216 www 9457: if (
9458: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9459: eq $symb) {
1.620 albertel 9460: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9461: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9462: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9463: $okay=1;
9464: }
9465: }
1.216 www 9466: }
9467: }
1.213 www 9468: untie(%bighash);
9469: }
9470: return $okay;
1.31 www 9471: }
9472:
1.210 www 9473: # --------------------------------------------------------------- Clean-up symb
9474:
9475: sub symbclean {
9476: my $symb=shift;
1.568 albertel 9477: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9478: # remove version from map
9479: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9480:
1.210 www 9481: # remove version from URL
9482: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9483:
1.507 www 9484: # remove wrapper
9485:
1.510 www 9486: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9487: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9488: return $symb;
1.409 www 9489: }
9490:
9491: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9492:
9493: sub encode_symb {
9494: my ($map,$resid,$url)=@_;
9495: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9496: }
1.409 www 9497:
9498: sub decode_symb {
1.568 albertel 9499: my $symb=shift;
9500: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9501: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9502: return (&fixversion($map),$resid,&fixversion($url));
9503: }
9504:
9505: sub fixversion {
9506: my $fn=shift;
1.609 banghart 9507: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9508: my %bighash;
9509: my $uri=&clutter($fn);
1.620 albertel 9510: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9511: # is this cached?
1.599 albertel 9512: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9513: if (defined($cached)) { return $result; }
9514: # unfortunately not cached, or expired
1.620 albertel 9515: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9516: &GDBM_READER(),0640)) {
9517: if ($bighash{'version_'.$uri}) {
9518: my $version=$bighash{'version_'.$uri};
1.444 www 9519: unless (($version eq 'mostrecent') ||
9520: ($version==&getversion($uri))) {
1.440 www 9521: $uri=~s/\.(\w+)$/\.$version\.$1/;
9522: }
9523: }
9524: untie %bighash;
1.413 www 9525: }
1.599 albertel 9526: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9527: }
9528:
9529: sub deversion {
9530: my $url=shift;
9531: $url=~s/\.\d+\.(\w+)$/\.$1/;
9532: return $url;
1.210 www 9533: }
9534:
1.31 www 9535: # ------------------------------------------------------ Return symb list entry
9536:
9537: sub symbread {
1.249 www 9538: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9539: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9540: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9541: # no filename provided? try from environment
1.44 www 9542: unless ($thisfn) {
1.620 albertel 9543: if ($env{'request.symb'}) {
9544: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9545: }
1.620 albertel 9546: $thisfn=$env{'request.filename'};
1.44 www 9547: }
1.569 albertel 9548: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9549: # is that filename actually a symb? Verify, clean, and return
9550: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9551: if (&symbverify($thisfn,$1)) {
1.620 albertel 9552: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9553: }
1.242 www 9554: }
1.44 www 9555: $thisfn=declutter($thisfn);
1.31 www 9556: my %hash;
1.37 www 9557: my %bighash;
9558: my $syval='';
1.620 albertel 9559: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9560: my $targetfn = $thisfn;
1.609 banghart 9561: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9562: $targetfn = 'adm/wrapper/'.$thisfn;
9563: }
1.687 albertel 9564: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9565: $targetfn=$1;
9566: }
1.620 albertel 9567: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9568: &GDBM_READER(),0640)) {
1.481 raeburn 9569: $syval=$hash{$targetfn};
1.37 www 9570: untie(%hash);
9571: }
9572: # ---------------------------------------------------------- There was an entry
9573: if ($syval) {
1.601 albertel 9574: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9575: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9576: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9577: #return $env{$cache_str}='';
1.601 albertel 9578: #}
9579: #$syval.=$1;
9580: #}
1.37 www 9581: } else {
9582: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9583: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9584: &GDBM_READER(),0640)) {
1.37 www 9585: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9586: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9587: unless ($ids) {
9588: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9589: }
9590: unless ($ids) {
9591: # alias?
9592: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9593: }
1.37 www 9594: if ($ids) {
9595: # ------------------------------------------------------------------- Has ID(s)
9596: my @possibilities=split(/\,/,$ids);
1.39 www 9597: if ($#possibilities==0) {
9598: # ----------------------------------------------- There is only one possibility
1.37 www 9599: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9600: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9601: $resid,$thisfn);
1.249 www 9602: } elsif (!$donotrecurse) {
1.39 www 9603: # ------------------------------------------ There is more than one possibility
9604: my $realpossible=0;
1.800 albertel 9605: foreach my $id (@possibilities) {
9606: my $file=$bighash{'src_'.$id};
1.39 www 9607: if (&allowed('bre',$file)) {
1.800 albertel 9608: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9609: if ($bighash{'map_type_'.$mapid} ne 'page') {
9610: $realpossible++;
1.626 albertel 9611: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9612: $resid,$thisfn);
1.39 www 9613: }
9614: }
1.191 harris41 9615: }
1.39 www 9616: if ($realpossible!=1) { $syval=''; }
1.249 www 9617: } else {
9618: $syval='';
1.37 www 9619: }
9620: }
9621: untie(%bighash)
1.481 raeburn 9622: }
1.31 www 9623: }
1.62 www 9624: if ($syval) {
1.620 albertel 9625: return $env{$cache_str}=$syval;
1.62 www 9626: }
1.31 www 9627: }
1.949 raeburn 9628: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9629: return $env{$cache_str}='';
1.31 www 9630: }
9631:
9632: # ---------------------------------------------------------- Return random seed
9633:
1.32 www 9634: sub numval {
9635: my $txt=shift;
9636: $txt=~tr/A-J/0-9/;
9637: $txt=~tr/a-j/0-9/;
9638: $txt=~tr/K-T/0-9/;
9639: $txt=~tr/k-t/0-9/;
9640: $txt=~tr/U-Z/0-5/;
9641: $txt=~tr/u-z/0-5/;
9642: $txt=~s/\D//g;
1.564 albertel 9643: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9644: return int($txt);
1.368 albertel 9645: }
9646:
1.484 albertel 9647: sub numval2 {
9648: my $txt=shift;
9649: $txt=~tr/A-J/0-9/;
9650: $txt=~tr/a-j/0-9/;
9651: $txt=~tr/K-T/0-9/;
9652: $txt=~tr/k-t/0-9/;
9653: $txt=~tr/U-Z/0-5/;
9654: $txt=~tr/u-z/0-5/;
9655: $txt=~s/\D//g;
9656: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9657: my $total;
9658: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9659: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9660: return int($total);
9661: }
9662:
1.575 albertel 9663: sub numval3 {
9664: use integer;
9665: my $txt=shift;
9666: $txt=~tr/A-J/0-9/;
9667: $txt=~tr/a-j/0-9/;
9668: $txt=~tr/K-T/0-9/;
9669: $txt=~tr/k-t/0-9/;
9670: $txt=~tr/U-Z/0-5/;
9671: $txt=~tr/u-z/0-5/;
9672: $txt=~s/\D//g;
9673: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9674: my $total;
9675: foreach my $val (@txts) { $total+=$val; }
9676: if ($_64bit) { $total=(($total<<32)>>32); }
9677: return $total;
9678: }
9679:
1.675 albertel 9680: sub digest {
9681: my ($data)=@_;
9682: my $digest=&Digest::MD5::md5($data);
9683: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9684: my ($e,$f);
9685: {
9686: use integer;
9687: $e=($a+$b);
9688: $f=($c+$d);
9689: if ($_64bit) {
9690: $e=(($e<<32)>>32);
9691: $f=(($f<<32)>>32);
9692: }
9693: }
9694: if (wantarray) {
9695: return ($e,$f);
9696: } else {
9697: my $g;
9698: {
9699: use integer;
9700: $g=($e+$f);
9701: if ($_64bit) {
9702: $g=(($g<<32)>>32);
9703: }
9704: }
9705: return $g;
9706: }
9707: }
9708:
1.368 albertel 9709: sub latest_rnd_algorithm_id {
1.675 albertel 9710: return '64bit5';
1.366 albertel 9711: }
1.32 www 9712:
1.503 albertel 9713: sub get_rand_alg {
9714: my ($courseid)=@_;
1.790 albertel 9715: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9716: if ($courseid) {
1.620 albertel 9717: return $env{"course.$courseid.rndseed"};
1.503 albertel 9718: }
9719: return &latest_rnd_algorithm_id();
9720: }
9721:
1.562 albertel 9722: sub validCODE {
9723: my ($CODE)=@_;
9724: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9725: return 0;
9726: }
9727:
1.491 albertel 9728: sub getCODE {
1.620 albertel 9729: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9730: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9731: defined($Apache::lonhomework::parsing_a_task) ) &&
9732: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9733: return $Apache::lonhomework::history{'resource.CODE'};
9734: }
9735: return undef;
9736: }
1.1133 foxr 9737: #
9738: # Determines the random seed for a specific context:
9739: #
9740: # parameters:
9741: # symb - in course context the symb for the seed.
9742: # course_id - The course id of the form domain_coursenum.
9743: # domain - Domain for the user.
9744: # course - Course for the user.
9745: # cenv - environment of the course.
9746: #
9747: # NOTE:
9748: # All parameters are picked out of the environment if missing
9749: # or not defined.
9750: # If a symb cannot be determined the current time is used instead.
9751: #
9752: # For a given well defined symb, courside, domain, username,
9753: # and course environment, the seed is reproducible.
9754: #
1.31 www 9755: sub rndseed {
1.1133 foxr 9756: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 9757: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9758: if (!defined($symb)) {
1.366 albertel 9759: unless ($symb=$wsymb) { return time; }
9760: }
9761: if (!$courseid) { $courseid=$wcourseid; }
9762: if (!$domain) { $domain=$wdomain; }
9763: if (!$username) { $username=$wusername }
1.1133 foxr 9764:
9765: my $which;
9766: if (defined($cenv->{'rndseed'})) {
9767: $which = $cenv->{'rndseed'};
9768: } else {
9769: $which =&get_rand_alg($courseid);
9770: }
1.1110 www 9771:
1.491 albertel 9772: if (defined(&getCODE())) {
1.1133 foxr 9773:
1.675 albertel 9774: if ($which eq '64bit5') {
9775: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9776: } elsif ($which eq '64bit4') {
1.575 albertel 9777: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9778: } else {
9779: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9780: }
1.675 albertel 9781: } elsif ($which eq '64bit5') {
9782: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9783: } elsif ($which eq '64bit4') {
9784: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9785: } elsif ($which eq '64bit3') {
9786: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9787: } elsif ($which eq '64bit2') {
9788: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9789: } elsif ($which eq '64bit') {
9790: return &rndseed_64bit($symb,$courseid,$domain,$username);
9791: }
9792: return &rndseed_32bit($symb,$courseid,$domain,$username);
9793: }
9794:
9795: sub rndseed_32bit {
9796: my ($symb,$courseid,$domain,$username)=@_;
9797: {
9798: use integer;
9799: my $symbchck=unpack("%32C*",$symb) << 27;
9800: my $symbseed=numval($symb) << 22;
9801: my $namechck=unpack("%32C*",$username) << 17;
9802: my $nameseed=numval($username) << 12;
9803: my $domainseed=unpack("%32C*",$domain) << 7;
9804: my $courseseed=unpack("%32C*",$courseid);
9805: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9806: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9807: #&logthis("rndseed :$num:$symb");
1.564 albertel 9808: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9809: return $num;
9810: }
9811: }
9812:
9813: sub rndseed_64bit {
9814: my ($symb,$courseid,$domain,$username)=@_;
9815: {
9816: use integer;
9817: my $symbchck=unpack("%32S*",$symb) << 21;
9818: my $symbseed=numval($symb) << 10;
9819: my $namechck=unpack("%32S*",$username);
9820:
9821: my $nameseed=numval($username) << 21;
9822: my $domainseed=unpack("%32S*",$domain) << 10;
9823: my $courseseed=unpack("%32S*",$courseid);
9824:
9825: my $num1=$symbchck+$symbseed+$namechck;
9826: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9827: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9828: #&logthis("rndseed :$num:$symb");
1.564 albertel 9829: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9830: return "$num1,$num2";
1.155 albertel 9831: }
1.366 albertel 9832: }
9833:
1.443 albertel 9834: sub rndseed_64bit2 {
9835: my ($symb,$courseid,$domain,$username)=@_;
9836: {
9837: use integer;
9838: # strings need to be an even # of cahracters long, it it is odd the
9839: # last characters gets thrown away
9840: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9841: my $symbseed=numval($symb) << 10;
9842: my $namechck=unpack("%32S*",$username.' ');
9843:
9844: my $nameseed=numval($username) << 21;
1.501 albertel 9845: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9846: my $courseseed=unpack("%32S*",$courseid.' ');
9847:
9848: my $num1=$symbchck+$symbseed+$namechck;
9849: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9850: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9851: #&logthis("rndseed :$num:$symb");
1.803 albertel 9852: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9853: return "$num1,$num2";
9854: }
9855: }
9856:
9857: sub rndseed_64bit3 {
9858: my ($symb,$courseid,$domain,$username)=@_;
9859: {
9860: use integer;
9861: # strings need to be an even # of cahracters long, it it is odd the
9862: # last characters gets thrown away
9863: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9864: my $symbseed=numval2($symb) << 10;
9865: my $namechck=unpack("%32S*",$username.' ');
9866:
9867: my $nameseed=numval2($username) << 21;
1.443 albertel 9868: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9869: my $courseseed=unpack("%32S*",$courseid.' ');
9870:
9871: my $num1=$symbchck+$symbseed+$namechck;
9872: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9873: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9874: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9875: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9876:
1.503 albertel 9877: return "$num1:$num2";
1.443 albertel 9878: }
9879: }
9880:
1.575 albertel 9881: sub rndseed_64bit4 {
9882: my ($symb,$courseid,$domain,$username)=@_;
9883: {
9884: use integer;
9885: # strings need to be an even # of cahracters long, it it is odd the
9886: # last characters gets thrown away
9887: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9888: my $symbseed=numval3($symb) << 10;
9889: my $namechck=unpack("%32S*",$username.' ');
9890:
9891: my $nameseed=numval3($username) << 21;
9892: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9893: my $courseseed=unpack("%32S*",$courseid.' ');
9894:
9895: my $num1=$symbchck+$symbseed+$namechck;
9896: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9897: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9898: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9899: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9900:
1.575 albertel 9901: return "$num1:$num2";
9902: }
9903: }
9904:
1.675 albertel 9905: sub rndseed_64bit5 {
9906: my ($symb,$courseid,$domain,$username)=@_;
9907: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9908: return "$num1:$num2";
9909: }
9910:
1.366 albertel 9911: sub rndseed_CODE_64bit {
9912: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9913: {
1.366 albertel 9914: use integer;
1.443 albertel 9915: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9916: my $symbseed=numval2($symb);
1.491 albertel 9917: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9918: my $CODEseed=numval(&getCODE());
1.443 albertel 9919: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9920: my $num1=$symbseed+$CODEchck;
9921: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9922: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9923: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9924: if ($_64bit) { $num1=(($num1<<32)>>32); }
9925: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9926: return "$num1:$num2";
1.366 albertel 9927: }
9928: }
9929:
1.575 albertel 9930: sub rndseed_CODE_64bit4 {
9931: my ($symb,$courseid,$domain,$username)=@_;
9932: {
9933: use integer;
9934: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9935: my $symbseed=numval3($symb);
9936: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9937: my $CODEseed=numval3(&getCODE());
9938: my $courseseed=unpack("%32S*",$courseid.' ');
9939: my $num1=$symbseed+$CODEchck;
9940: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9941: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9942: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9943: if ($_64bit) { $num1=(($num1<<32)>>32); }
9944: if ($_64bit) { $num2=(($num2<<32)>>32); }
9945: return "$num1:$num2";
9946: }
9947: }
9948:
1.675 albertel 9949: sub rndseed_CODE_64bit5 {
9950: my ($symb,$courseid,$domain,$username)=@_;
9951: my $code = &getCODE();
9952: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9953: return "$num1:$num2";
9954: }
9955:
1.366 albertel 9956: sub setup_random_from_rndseed {
9957: my ($rndseed)=@_;
1.503 albertel 9958: if ($rndseed =~/([,:])/) {
9959: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9960: &Math::Random::random_set_seed(abs($num1),abs($num2));
9961: } else {
9962: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9963: }
1.36 albertel 9964: }
9965:
1.474 albertel 9966: sub latest_receipt_algorithm_id {
1.835 albertel 9967: return 'receipt3';
1.474 albertel 9968: }
9969:
1.480 www 9970: sub recunique {
9971: my $fucourseid=shift;
9972: my $unique;
1.835 albertel 9973: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9974: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9975: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9976: } else {
9977: $unique=$perlvar{'lonReceipt'};
9978: }
9979: return unpack("%32C*",$unique);
9980: }
9981:
9982: sub recprefix {
9983: my $fucourseid=shift;
9984: my $prefix;
1.835 albertel 9985: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9986: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9987: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9988: } else {
9989: $prefix=$perlvar{'lonHostID'};
9990: }
9991: return unpack("%32C*",$prefix);
9992: }
9993:
1.76 www 9994: sub ireceipt {
1.474 albertel 9995: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9996:
9997: my $return =&recprefix($fucourseid).'-';
9998:
9999: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10000: $env{'request.state'} eq 'construct') {
10001: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10002: return $return;
10003: }
10004:
1.76 www 10005: my $cuname=unpack("%32C*",$funame);
10006: my $cudom=unpack("%32C*",$fudom);
10007: my $cucourseid=unpack("%32C*",$fucourseid);
10008: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10009: my $cunique=&recunique($fucourseid);
1.474 albertel 10010: my $cpart=unpack("%32S*",$part);
1.835 albertel 10011: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10012:
1.790 albertel 10013: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10014:
10015: $return.= ($cunique%$cuname+
10016: $cunique%$cudom+
10017: $cusymb%$cuname+
10018: $cusymb%$cudom+
10019: $cucourseid%$cuname+
10020: $cucourseid%$cudom+
10021: $cpart%$cuname+
10022: $cpart%$cudom);
10023: } else {
10024: $return.= ($cunique%$cuname+
10025: $cunique%$cudom+
10026: $cusymb%$cuname+
10027: $cusymb%$cudom+
10028: $cucourseid%$cuname+
10029: $cucourseid%$cudom);
10030: }
10031: return $return;
1.76 www 10032: }
10033:
10034: sub receipt {
1.474 albertel 10035: my ($part)=@_;
1.790 albertel 10036: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10037: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10038: }
1.260 ng 10039:
1.790 albertel 10040: sub whichuser {
10041: my ($passedsymb)=@_;
10042: my ($symb,$courseid,$domain,$name,$publicuser);
10043: if (defined($env{'form.grade_symb'})) {
10044: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10045: my $allowed=&allowed('vgr',$tmp_courseid);
10046: if (!$allowed &&
10047: exists($env{'request.course.sec'}) &&
10048: $env{'request.course.sec'} !~ /^\s*$/) {
10049: $allowed=&allowed('vgr',$tmp_courseid.
10050: '/'.$env{'request.course.sec'});
10051: }
10052: if ($allowed) {
10053: ($symb)=&get_env_multiple('form.grade_symb');
10054: $courseid=$tmp_courseid;
10055: ($domain)=&get_env_multiple('form.grade_domain');
10056: ($name)=&get_env_multiple('form.grade_username');
10057: return ($symb,$courseid,$domain,$name,$publicuser);
10058: }
10059: }
10060: if (!$passedsymb) {
10061: $symb=&symbread();
10062: } else {
10063: $symb=$passedsymb;
10064: }
10065: $courseid=$env{'request.course.id'};
10066: $domain=$env{'user.domain'};
10067: $name=$env{'user.name'};
10068: if ($name eq 'public' && $domain eq 'public') {
10069: if (!defined($env{'form.username'})) {
10070: $env{'form.username'}.=time.rand(10000000);
10071: }
10072: $name.=$env{'form.username'};
10073: }
10074: return ($symb,$courseid,$domain,$name,$publicuser);
10075:
10076: }
10077:
1.36 albertel 10078: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10079: # returns either the contents of the file or
10080: # -1 if the file doesn't exist
1.481 raeburn 10081: #
10082: # if the target is a file that was uploaded via DOCS,
10083: # a check will be made to see if a current copy exists on the local server,
10084: # if it does this will be served, otherwise a copy will be retrieved from
10085: # the home server for the course and stored in /home/httpd/html/userfiles on
10086: # the local server.
1.472 albertel 10087:
1.36 albertel 10088: sub getfile {
1.538 albertel 10089: my ($file) = @_;
1.609 banghart 10090: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10091: &repcopy($file);
10092: return &readfile($file);
10093: }
10094:
10095: sub repcopy_userfile {
10096: my ($file)=@_;
1.609 banghart 10097: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 10098: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 10099: my ($cdom,$cnum,$filename) =
1.811 albertel 10100: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10101: my $uri="/uploaded/$cdom/$cnum/$filename";
10102: if (-e "$file") {
1.828 www 10103: # we already have a local copy, check it out
1.538 albertel 10104: my @fileinfo = stat($file);
1.828 www 10105: my $rtncode;
10106: my $info;
1.538 albertel 10107: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10108: if ($lwpresp ne 'ok') {
1.828 www 10109: # there is no such file anymore, even though we had a local copy
1.482 albertel 10110: if ($rtncode eq '404') {
1.538 albertel 10111: unlink($file);
1.482 albertel 10112: }
10113: return -1;
10114: }
10115: if ($info < $fileinfo[9]) {
1.828 www 10116: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10117: return 'ok';
1.828 www 10118: } else {
10119: # the file is outdated, get rid of it
10120: unlink($file);
1.482 albertel 10121: }
1.828 www 10122: }
10123: # one way or the other, at this point, we don't have the file
10124: # construct the correct path for the file
10125: my @parts = ($cdom,$cnum);
10126: if ($filename =~ m|^(.+)/[^/]+$|) {
10127: push @parts, split(/\//,$1);
10128: }
10129: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10130: foreach my $part (@parts) {
10131: $path .= '/'.$part;
10132: if (!-e $path) {
10133: mkdir($path,0770);
1.482 albertel 10134: }
10135: }
1.828 www 10136: # now the path exists for sure
10137: # get a user agent
10138: my $ua=new LWP::UserAgent;
10139: my $transferfile=$file.'.in.transfer';
10140: # FIXME: this should flock
10141: if (-e $transferfile) { return 'ok'; }
10142: my $request;
10143: $uri=~s/^\///;
1.980 raeburn 10144: my $homeserver = &homeserver($cnum,$cdom);
10145: my $protocol = $protocol{$homeserver};
10146: $protocol = 'http' if ($protocol ne 'https');
10147: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10148: my $response=$ua->request($request,$transferfile);
10149: # did it work?
10150: if ($response->is_error()) {
10151: unlink($transferfile);
10152: &logthis("Userfile repcopy failed for $uri");
10153: return -1;
10154: }
10155: # worked, rename the transfer file
10156: rename($transferfile,$file);
1.607 raeburn 10157: return 'ok';
1.481 raeburn 10158: }
10159:
1.517 albertel 10160: sub tokenwrapper {
10161: my $uri=shift;
1.980 raeburn 10162: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10163: $uri=~s|^/||;
1.620 albertel 10164: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10165: my $token=$1;
1.552 albertel 10166: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10167: if ($udom && $uname && $file) {
10168: $file=~s|(\?\.*)*$||;
1.949 raeburn 10169: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10170: my $homeserver = &homeserver($uname,$udom);
10171: my $protocol = $protocol{$homeserver};
10172: $protocol = 'http' if ($protocol ne 'https');
10173: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10174: (($uri=~/\?/)?'&':'?').'token='.$token.
10175: '&tokenissued='.$perlvar{'lonHostID'};
10176: } else {
10177: return '/adm/notfound.html';
10178: }
10179: }
10180:
1.828 www 10181: # call with reqtype HEAD: get last modification time
10182: # call with reqtype GET: get the file contents
10183: # Do not call this with reqtype GET for large files! It loads everything into memory
10184: #
1.481 raeburn 10185: sub getuploaded {
10186: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10187: $uri=~s/^\///;
1.980 raeburn 10188: my $homeserver = &homeserver($cnum,$cdom);
10189: my $protocol = $protocol{$homeserver};
10190: $protocol = 'http' if ($protocol ne 'https');
10191: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10192: my $ua=new LWP::UserAgent;
10193: my $request=new HTTP::Request($reqtype,$uri);
10194: my $response=$ua->request($request);
10195: $$rtncode = $response->code;
1.482 albertel 10196: if (! $response->is_success()) {
10197: return 'failed';
10198: }
10199: if ($reqtype eq 'HEAD') {
1.486 www 10200: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10201: } elsif ($reqtype eq 'GET') {
10202: $$info = $response->content;
1.472 albertel 10203: }
1.482 albertel 10204: return 'ok';
1.36 albertel 10205: }
10206:
1.481 raeburn 10207: sub readfile {
10208: my $file = shift;
10209: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10210: my $fh;
10211: open($fh,"<$file");
10212: my $a='';
1.800 albertel 10213: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10214: return $a;
10215: }
10216:
1.36 albertel 10217: sub filelocation {
1.590 banghart 10218: my ($dir,$file) = @_;
10219: my $location;
10220: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10221:
10222: if ($file =~ m-^/adm/-) {
10223: $file=~s-^/adm/wrapper/-/-;
10224: $file=~s-^/adm/coursedocs/showdoc/-/-;
10225: }
1.882 albertel 10226:
1.1139 www 10227: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10228: $location = $file;
1.609 banghart 10229: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10230: my ($udom,$uname,$filename)=
1.811 albertel 10231: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10232: my $home=&homeserver($uname,$udom);
10233: my $is_me=0;
10234: my @ids=¤t_machine_ids();
10235: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10236: if ($is_me) {
1.1117 foxr 10237: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10238: } else {
10239: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10240: $udom.'/'.$uname.'/'.$filename;
10241: }
1.882 albertel 10242: } elsif ($file =~ m-^/adm/-) {
10243: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10244: } else {
10245: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10246: $file=~s:^/(res|priv)/:/:;
10247: my $space=$1;
1.590 banghart 10248: if ( !( $file =~ m:^/:) ) {
10249: $location = $dir. '/'.$file;
10250: } else {
1.1139 www 10251: $location = '/home/httpd/html/'.$space.$file;
1.590 banghart 10252: }
1.59 albertel 10253: }
1.590 banghart 10254: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10255: while ($location=~m{/\.\./}) {
10256: if ($location =~ m{/[^/]+/\.\./}) {
10257: $location=~ s{/[^/]+/\.\./}{/}g;
10258: } else {
10259: $location=~ s{/\.\./}{/}g;
10260: }
10261: } #remove dir/..
1.590 banghart 10262: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10263: return $location;
1.46 www 10264: }
1.36 albertel 10265:
1.46 www 10266: sub hreflocation {
10267: my ($dir,$file)=@_;
1.980 raeburn 10268: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10269: $file=filelocation($dir,$file);
1.700 albertel 10270: } elsif ($file=~m-^/adm/-) {
10271: $file=~s-^/adm/wrapper/-/-;
10272: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10273: }
10274: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10275: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10276: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 10277: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 10278: -/uploaded/$1/$2/-x;
1.46 www 10279: }
1.913 albertel 10280: if ($file=~ m{^/userfiles/}) {
10281: $file =~ s{^/userfiles/}{/uploaded/};
10282: }
1.462 albertel 10283: return $file;
1.465 albertel 10284: }
10285:
1.1139 www 10286:
10287:
10288:
10289:
1.465 albertel 10290: sub current_machine_domains {
1.853 albertel 10291: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10292: }
10293:
10294: sub machine_domains {
10295: my ($hostname) = @_;
1.465 albertel 10296: my @domains;
1.838 albertel 10297: my %hostname = &all_hostnames();
1.465 albertel 10298: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10299: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10300: if ($hostname eq $name) {
1.844 albertel 10301: push(@domains,&host_domain($id));
1.465 albertel 10302: }
10303: }
10304: return @domains;
10305: }
10306:
10307: sub current_machine_ids {
1.853 albertel 10308: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10309: }
10310:
10311: sub machine_ids {
10312: my ($hostname) = @_;
10313: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10314: my @ids;
1.888 albertel 10315: my %name_to_host = &all_names();
1.889 albertel 10316: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10317: return @{ $name_to_host{$hostname} };
10318: }
10319: return;
1.31 www 10320: }
10321:
1.824 raeburn 10322: sub additional_machine_domains {
10323: my @domains;
10324: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10325: while( my $line = <$fh>) {
10326: $line =~ s/\s//g;
10327: push(@domains,$line);
10328: }
10329: return @domains;
10330: }
10331:
10332: sub default_login_domain {
10333: my $domain = $perlvar{'lonDefDomain'};
10334: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10335: foreach my $posdom (¤t_machine_domains(),
10336: &additional_machine_domains()) {
10337: if (lc($posdom) eq lc($testdomain)) {
10338: $domain=$posdom;
10339: last;
10340: }
10341: }
10342: return $domain;
10343: }
10344:
1.31 www 10345: # ------------------------------------------------------------- Declutters URLs
10346:
10347: sub declutter {
10348: my $thisfn=shift;
1.569 albertel 10349: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10350: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10351: $thisfn=~s/^\///;
1.697 albertel 10352: $thisfn=~s|^adm/wrapper/||;
10353: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10354: $thisfn=~s/^res\///;
1.1032 raeburn 10355: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10356: $thisfn=~s/\?.+$//;
10357: }
1.268 www 10358: return $thisfn;
10359: }
10360:
10361: # ------------------------------------------------------------- Clutter up URLs
10362:
10363: sub clutter {
10364: my $thisfn='/'.&declutter(shift);
1.887 albertel 10365: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10366: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10367: $thisfn='/res'.$thisfn;
10368: }
1.1031 raeburn 10369: if ($thisfn !~m|^/adm|) {
10370: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10371: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10372: } else {
10373: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10374: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10375: if ($embstyle eq 'ssi'
10376: || ($embstyle eq 'hdn')
10377: || ($embstyle eq 'rat')
10378: || ($embstyle eq 'prv')
10379: || ($embstyle eq 'ign')) {
10380: #do nothing with these
10381: } elsif (($embstyle eq 'img')
1.695 albertel 10382: || ($embstyle eq 'emb')
10383: || ($embstyle eq 'wrp')) {
10384: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10385: } elsif ($embstyle eq 'unk'
10386: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10387: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10388: } else {
1.718 www 10389: # &logthis("Got a blank emb style");
1.695 albertel 10390: }
1.694 albertel 10391: }
10392: }
1.31 www 10393: return $thisfn;
1.12 www 10394: }
10395:
1.787 albertel 10396: sub clutter_with_no_wrapper {
10397: my $uri = &clutter(shift);
10398: if ($uri =~ m-^/adm/-) {
10399: $uri =~ s-^/adm/wrapper/-/-;
10400: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10401: }
10402: return $uri;
10403: }
10404:
1.557 albertel 10405: sub freeze_escape {
10406: my ($value)=@_;
10407: if (ref($value)) {
10408: $value=&nfreeze($value);
10409: return '__FROZEN__'.&escape($value);
10410: }
10411: return &escape($value);
10412: }
10413:
1.11 www 10414:
1.557 albertel 10415: sub thaw_unescape {
10416: my ($value)=@_;
10417: if ($value =~ /^__FROZEN__/) {
10418: substr($value,0,10,undef);
10419: $value=&unescape($value);
10420: return &thaw($value);
10421: }
10422: return &unescape($value);
10423: }
10424:
1.436 albertel 10425: sub correct_line_ends {
10426: my ($result)=@_;
10427: $$result =~s/\r\n/\n/mg;
10428: $$result =~s/\r/\n/mg;
1.415 albertel 10429: }
1.1 albertel 10430: # ================================================================ Main Program
10431:
1.184 www 10432: sub goodbye {
1.204 albertel 10433: &logthis("Starting Shut down");
1.443 albertel 10434: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10435: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10436: #converted
1.599 albertel 10437: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10438: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10439: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10440: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10441: #1.1 only
1.870 albertel 10442: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10443: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10444: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10445: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10446: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10447: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10448: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10449: &flushcourselogs();
10450: &logthis("Shutting down");
10451: }
10452:
1.852 albertel 10453: sub get_dns {
1.869 albertel 10454: my ($url,$func,$ignore_cache) = @_;
10455: if (!$ignore_cache) {
10456: my ($content,$cached)=
10457: &Apache::lonnet::is_cached_new('dns',$url);
10458: if ($cached) {
10459: &$func($content);
10460: return;
10461: }
10462: }
10463:
10464: my %alldns;
1.852 albertel 10465: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10466: foreach my $dns (<$config>) {
10467: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10468: my $line = $1;
10469: my ($host,$protocol) = split(/:/,$line);
10470: if ($protocol ne 'https') {
10471: $protocol = 'http';
10472: }
10473: $alldns{$host} = $protocol;
1.869 albertel 10474: }
10475: while (%alldns) {
10476: my ($dns) = keys(%alldns);
1.852 albertel 10477: my $ua=new LWP::UserAgent;
1.1134 raeburn 10478: $ua->timeout(30);
1.979 raeburn 10479: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10480: my $response=$ua->request($request);
1.979 raeburn 10481: delete($alldns{$dns});
1.852 albertel 10482: next if ($response->is_error());
10483: my @content = split("\n",$response->content);
1.869 albertel 10484: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10485: &$func(\@content);
1.869 albertel 10486: return;
1.852 albertel 10487: }
10488: close($config);
1.871 albertel 10489: my $which = (split('/',$url))[3];
10490: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10491: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10492: my @content = <$config>;
10493: &$func(\@content);
10494: return;
1.852 albertel 10495: }
1.327 albertel 10496: # ------------------------------------------------------------ Read domain file
10497: {
1.852 albertel 10498: my $loaded;
1.846 albertel 10499: my %domain;
10500:
1.852 albertel 10501: sub parse_domain_tab {
10502: my ($lines) = @_;
10503: foreach my $line (@$lines) {
10504: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10505:
1.846 albertel 10506: chomp($line);
1.852 albertel 10507: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10508: my %this_domain;
10509: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10510: 'lang_def', 'city', 'longi', 'lati',
10511: 'primary') {
10512: $this_domain{$field} = shift(@elements);
10513: }
10514: $domain{$name} = \%this_domain;
1.852 albertel 10515: }
10516: }
1.864 albertel 10517:
10518: sub reset_domain_info {
10519: undef($loaded);
10520: undef(%domain);
10521: }
10522:
1.852 albertel 10523: sub load_domain_tab {
1.869 albertel 10524: my ($ignore_cache) = @_;
10525: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10526: my $fh;
10527: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10528: my @lines = <$fh>;
10529: &parse_domain_tab(\@lines);
1.448 albertel 10530: }
1.852 albertel 10531: close($fh);
10532: $loaded = 1;
1.327 albertel 10533: }
1.846 albertel 10534:
10535: sub domain {
1.852 albertel 10536: &load_domain_tab() if (!$loaded);
10537:
1.846 albertel 10538: my ($name,$what) = @_;
10539: return if ( !exists($domain{$name}) );
10540:
10541: if (!$what) {
10542: return $domain{$name}{'description'};
10543: }
10544: return $domain{$name}{$what};
10545: }
1.974 raeburn 10546:
10547: sub domain_info {
10548: &load_domain_tab() if (!$loaded);
10549: return %domain;
10550: }
10551:
1.327 albertel 10552: }
10553:
10554:
1.1 albertel 10555: # ------------------------------------------------------------- Read hosts file
10556: {
1.838 albertel 10557: my %hostname;
1.844 albertel 10558: my %hostdom;
1.845 albertel 10559: my %libserv;
1.852 albertel 10560: my $loaded;
1.888 albertel 10561: my %name_to_host;
1.1074 raeburn 10562: my %internetdom;
1.1107 raeburn 10563: my %LC_dns_serv;
1.852 albertel 10564:
10565: sub parse_hosts_tab {
10566: my ($file) = @_;
10567: foreach my $configline (@$file) {
10568: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10569: chomp($configline);
10570: if ($configline =~ /^\^/) {
10571: if ($configline =~ /^\^([\w.\-]+)/) {
10572: $LC_dns_serv{$1} = 1;
10573: }
10574: next;
10575: }
1.1074 raeburn 10576: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10577: $name=~s/\s//g;
10578: if ($id && $domain && $role && $name) {
10579: $hostname{$id}=$name;
1.888 albertel 10580: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10581: $hostdom{$id}=$domain;
10582: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10583: if (defined($protocol)) {
10584: if ($protocol eq 'https') {
10585: $protocol{$id} = $protocol;
10586: } else {
10587: $protocol{$id} = 'http';
10588: }
1.968 raeburn 10589: } else {
1.969 raeburn 10590: $protocol{$id} = 'http';
1.968 raeburn 10591: }
1.1074 raeburn 10592: if (defined($intdom)) {
10593: $internetdom{$id} = $intdom;
10594: }
1.852 albertel 10595: }
10596: }
10597: }
1.864 albertel 10598:
10599: sub reset_hosts_info {
1.897 albertel 10600: &purge_remembered();
1.864 albertel 10601: &reset_domain_info();
10602: &reset_hosts_ip_info();
1.892 albertel 10603: undef(%name_to_host);
1.864 albertel 10604: undef(%hostname);
10605: undef(%hostdom);
10606: undef(%libserv);
10607: undef($loaded);
10608: }
1.1 albertel 10609:
1.852 albertel 10610: sub load_hosts_tab {
1.869 albertel 10611: my ($ignore_cache) = @_;
10612: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10613: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10614: my @config = <$config>;
10615: &parse_hosts_tab(\@config);
10616: close($config);
10617: $loaded=1;
1.1 albertel 10618: }
1.852 albertel 10619:
1.838 albertel 10620: sub hostname {
1.852 albertel 10621: &load_hosts_tab() if (!$loaded);
10622:
1.838 albertel 10623: my ($lonid) = @_;
10624: return $hostname{$lonid};
10625: }
1.845 albertel 10626:
1.838 albertel 10627: sub all_hostnames {
1.852 albertel 10628: &load_hosts_tab() if (!$loaded);
10629:
1.838 albertel 10630: return %hostname;
10631: }
1.845 albertel 10632:
1.888 albertel 10633: sub all_names {
10634: &load_hosts_tab() if (!$loaded);
10635:
10636: return %name_to_host;
10637: }
10638:
1.974 raeburn 10639: sub all_host_domain {
10640: &load_hosts_tab() if (!$loaded);
10641: return %hostdom;
10642: }
10643:
1.845 albertel 10644: sub is_library {
1.852 albertel 10645: &load_hosts_tab() if (!$loaded);
10646:
1.845 albertel 10647: return exists($libserv{$_[0]});
10648: }
10649:
10650: sub all_library {
1.852 albertel 10651: &load_hosts_tab() if (!$loaded);
10652:
1.845 albertel 10653: return %libserv;
10654: }
10655:
1.1062 droeschl 10656: sub unique_library {
10657: #2x reverse removes all hostnames that appear more than once
10658: my %unique = reverse &all_library();
10659: return reverse %unique;
10660: }
10661:
1.841 albertel 10662: sub get_servers {
1.852 albertel 10663: &load_hosts_tab() if (!$loaded);
10664:
1.841 albertel 10665: my ($domain,$type) = @_;
10666: my %possible_hosts = ($type eq 'library') ? %libserv
10667: : %hostname;
10668: my %result;
1.842 albertel 10669: if (ref($domain) eq 'ARRAY') {
10670: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10671: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10672: $result{$host} = $hostname;
10673: }
10674: }
10675: } else {
10676: while ( my ($host,$hostname) = each(%possible_hosts)) {
10677: if ($hostdom{$host} eq $domain) {
10678: $result{$host} = $hostname;
10679: }
1.841 albertel 10680: }
10681: }
10682: return %result;
10683: }
1.845 albertel 10684:
1.1062 droeschl 10685: sub get_unique_servers {
10686: my %unique = reverse &get_servers(@_);
10687: return reverse %unique;
10688: }
10689:
1.844 albertel 10690: sub host_domain {
1.852 albertel 10691: &load_hosts_tab() if (!$loaded);
10692:
1.844 albertel 10693: my ($lonid) = @_;
10694: return $hostdom{$lonid};
10695: }
10696:
1.841 albertel 10697: sub all_domains {
1.852 albertel 10698: &load_hosts_tab() if (!$loaded);
10699:
1.841 albertel 10700: my %seen;
10701: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10702: return @uniq;
10703: }
1.1074 raeburn 10704:
10705: sub internet_dom {
10706: &load_hosts_tab() if (!$loaded);
10707:
10708: my ($lonid) = @_;
10709: return $internetdom{$lonid};
10710: }
1.1107 raeburn 10711:
10712: sub is_LC_dns {
10713: &load_hosts_tab() if (!$loaded);
10714:
10715: my ($hostname) = @_;
10716: return exists($LC_dns_serv{$hostname});
10717: }
10718:
1.1 albertel 10719: }
10720:
1.847 albertel 10721: {
10722: my %iphost;
1.856 albertel 10723: my %name_to_ip;
10724: my %lonid_to_ip;
1.869 albertel 10725:
1.847 albertel 10726: sub get_hosts_from_ip {
10727: my ($ip) = @_;
10728: my %iphosts = &get_iphost();
10729: if (ref($iphosts{$ip})) {
10730: return @{$iphosts{$ip}};
10731: }
10732: return;
1.839 albertel 10733: }
1.864 albertel 10734:
10735: sub reset_hosts_ip_info {
10736: undef(%iphost);
10737: undef(%name_to_ip);
10738: undef(%lonid_to_ip);
10739: }
1.856 albertel 10740:
10741: sub get_host_ip {
10742: my ($lonid) = @_;
10743: if (exists($lonid_to_ip{$lonid})) {
10744: return $lonid_to_ip{$lonid};
10745: }
10746: my $name=&hostname($lonid);
10747: my $ip = gethostbyname($name);
10748: return if (!$ip || length($ip) ne 4);
10749: $ip=inet_ntoa($ip);
10750: $name_to_ip{$name} = $ip;
10751: $lonid_to_ip{$lonid} = $ip;
10752: return $ip;
10753: }
1.847 albertel 10754:
10755: sub get_iphost {
1.869 albertel 10756: my ($ignore_cache) = @_;
1.894 albertel 10757:
1.869 albertel 10758: if (!$ignore_cache) {
10759: if (%iphost) {
10760: return %iphost;
10761: }
10762: my ($ip_info,$cached)=
10763: &Apache::lonnet::is_cached_new('iphost','iphost');
10764: if ($cached) {
10765: %iphost = %{$ip_info->[0]};
10766: %name_to_ip = %{$ip_info->[1]};
10767: %lonid_to_ip = %{$ip_info->[2]};
10768: return %iphost;
10769: }
10770: }
1.894 albertel 10771:
10772: # get yesterday's info for fallback
10773: my %old_name_to_ip;
10774: my ($ip_info,$cached)=
10775: &Apache::lonnet::is_cached_new('iphost','iphost');
10776: if ($cached) {
10777: %old_name_to_ip = %{$ip_info->[1]};
10778: }
10779:
1.888 albertel 10780: my %name_to_host = &all_names();
10781: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10782: my $ip;
10783: if (!exists($name_to_ip{$name})) {
10784: $ip = gethostbyname($name);
10785: if (!$ip || length($ip) ne 4) {
1.894 albertel 10786: if (defined($old_name_to_ip{$name})) {
10787: $ip = $old_name_to_ip{$name};
10788: &logthis("Can't find $name defaulting to old $ip");
10789: } else {
10790: &logthis("Name $name no IP found");
10791: next;
10792: }
10793: } else {
10794: $ip=inet_ntoa($ip);
1.847 albertel 10795: }
10796: $name_to_ip{$name} = $ip;
10797: } else {
10798: $ip = $name_to_ip{$name};
1.653 albertel 10799: }
1.888 albertel 10800: foreach my $id (@{ $name_to_host{$name} }) {
10801: $lonid_to_ip{$id} = $ip;
10802: }
10803: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10804: }
1.869 albertel 10805: &Apache::lonnet::do_cache_new('iphost','iphost',
10806: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10807: 48*60*60);
1.869 albertel 10808:
1.847 albertel 10809: return %iphost;
1.598 albertel 10810: }
10811:
1.992 raeburn 10812: #
10813: # Given a DNS returns the loncapa host name for that DNS
10814: #
10815: sub host_from_dns {
10816: my ($dns) = @_;
10817: my @hosts;
10818: my $ip;
10819:
1.993 raeburn 10820: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10821: $ip = $name_to_ip{$dns};
10822: }
10823: if (!$ip) {
10824: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10825: if (length($ip) == 4) {
10826: $ip = &IO::Socket::inet_ntoa($ip);
10827: }
10828: }
10829: if ($ip) {
10830: @hosts = get_hosts_from_ip($ip);
10831: return $hosts[0];
10832: }
10833: return undef;
1.986 foxr 10834: }
1.992 raeburn 10835:
1.1074 raeburn 10836: sub get_internet_names {
10837: my ($lonid) = @_;
10838: return if ($lonid eq '');
10839: my ($idnref,$cached)=
10840: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10841: if ($cached) {
10842: return $idnref;
10843: }
10844: my $ip = &get_host_ip($lonid);
10845: my @hosts = &get_hosts_from_ip($ip);
10846: my %iphost = &get_iphost();
10847: my (@idns,%seen);
10848: foreach my $id (@hosts) {
10849: my $dom = &host_domain($id);
10850: my $prim_id = &domain($dom,'primary');
10851: my $prim_ip = &get_host_ip($prim_id);
10852: next if ($seen{$prim_ip});
10853: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10854: foreach my $id (@{$iphost{$prim_ip}}) {
10855: my $intdom = &internet_dom($id);
10856: unless (grep(/^\Q$intdom\E$/,@idns)) {
10857: push(@idns,$intdom);
10858: }
10859: }
10860: }
10861: $seen{$prim_ip} = 1;
10862: }
10863: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10864: }
10865:
1.986 foxr 10866: }
10867:
1.1079 raeburn 10868: sub all_loncaparevs {
10869: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
10870: }
10871:
1.862 albertel 10872: BEGIN {
10873:
10874: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10875: unless ($readit) {
10876: {
10877: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10878: %perlvar = (%perlvar,%{$configvars});
10879: }
10880:
10881:
1.1 albertel 10882: # ------------------------------------------------------ Read spare server file
10883: {
1.448 albertel 10884: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10885:
10886: while (my $configline=<$config>) {
10887: chomp($configline);
1.284 matthew 10888: if ($configline) {
1.784 albertel 10889: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10890: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10891: push(@{ $spareid{$type} }, $host);
1.1 albertel 10892: }
10893: }
1.448 albertel 10894: close($config);
1.1 albertel 10895: }
1.11 www 10896: # ------------------------------------------------------------ Read permissions
10897: {
1.448 albertel 10898: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10899:
10900: while (my $configline=<$config>) {
1.448 albertel 10901: chomp($configline);
10902: if ($configline) {
10903: my ($role,$perm)=split(/ /,$configline);
10904: if ($perm ne '') { $pr{$role}=$perm; }
10905: }
1.11 www 10906: }
1.448 albertel 10907: close($config);
1.11 www 10908: }
10909:
10910: # -------------------------------------------- Read plain texts for permissions
10911: {
1.448 albertel 10912: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10913:
10914: while (my $configline=<$config>) {
1.448 albertel 10915: chomp($configline);
10916: if ($configline) {
1.742 raeburn 10917: my ($short,@plain)=split(/:/,$configline);
10918: %{$prp{$short}} = ();
10919: if (@plain > 0) {
10920: $prp{$short}{'std'} = $plain[0];
10921: for (my $i=1; $i<@plain; $i++) {
10922: $prp{$short}{'alt'.$i} = $plain[$i];
10923: }
10924: }
1.448 albertel 10925: }
1.135 www 10926: }
1.448 albertel 10927: close($config);
1.135 www 10928: }
10929:
10930: # ---------------------------------------------------------- Read package table
10931: {
1.448 albertel 10932: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10933:
10934: while (my $configline=<$config>) {
1.483 albertel 10935: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10936: chomp($configline);
10937: my ($short,$plain)=split(/:/,$configline);
10938: my ($pack,$name)=split(/\&/,$short);
10939: if ($plain ne '') {
10940: $packagetab{$pack.'&'.$name.'&name'}=$name;
10941: $packagetab{$short}=$plain;
10942: }
1.11 www 10943: }
1.448 albertel 10944: close($config);
1.329 matthew 10945: }
10946:
1.1073 raeburn 10947: # ---------------------------------------------------------- Read loncaparev table
10948: {
10949: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10950: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10951: while (my $configline=<$config>) {
10952: chomp($configline);
10953: my ($hostid,$loncaparev)=split(/:/,$configline);
10954: $loncaparevs{$hostid}=$loncaparev;
10955: }
10956: close($config);
10957: }
10958: }
10959: }
10960:
1.1074 raeburn 10961: # ---------------------------------------------------------- Read serverhostID table
10962: {
10963: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10964: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10965: while (my $configline=<$config>) {
10966: chomp($configline);
10967: my ($name,$id)=split(/:/,$configline);
10968: $serverhomeIDs{$name}=$id;
10969: }
10970: close($config);
10971: }
10972: }
10973: }
10974:
1.1079 raeburn 10975: {
10976: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10977: if (-e $file) {
10978: my $parser = HTML::LCParser->new($file);
10979: while (my $token = $parser->get_token()) {
10980: if ($token->[0] eq 'S') {
10981: my $item = $token->[1];
10982: my $name = $token->[2]{'name'};
10983: my $value = $token->[2]{'value'};
10984: if ($item ne '' && $name ne '' && $value ne '') {
10985: my $release = $parser->get_text();
10986: $release =~ s/(^\s*|\s*$ )//gx;
10987: $needsrelease{$item.':'.$name.':'.$value} = $release;
10988: }
10989: }
10990: }
10991: }
1.1073 raeburn 10992: }
10993:
1.1138 raeburn 10994: # ---------------------------------------------------------- Read managers table
10995: {
10996: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
10997: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
10998: while (my $configline=<$config>) {
10999: chomp($configline);
11000: next if ($configline =~ /^\#/);
11001: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11002: $managerstab{$configline} = 1;
11003: }
11004: }
11005: close($config);
11006: }
11007: }
11008: }
11009:
1.329 matthew 11010: # ------------- set up temporary directory
11011: {
1.1117 foxr 11012: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11013:
1.11 www 11014: }
11015:
1.794 albertel 11016: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11017: 'compress_threshold'=> 20_000,
11018: });
1.185 www 11019:
1.281 www 11020: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11021: $dumpcount=0;
1.958 www 11022: $locknum=0;
1.22 www 11023:
1.163 harris41 11024: &logtouch();
1.672 albertel 11025: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11026: $readit=1;
1.564 albertel 11027: {
11028: use integer;
11029: my $test=(2**32)+1;
1.568 albertel 11030: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11031: &logthis(" Detected 64bit platform ($_64bit)");
11032: }
1.195 www 11033: }
1.1 albertel 11034: }
1.179 www 11035:
1.1 albertel 11036: 1;
1.191 harris41 11037: __END__
11038:
1.243 albertel 11039: =pod
11040:
1.191 harris41 11041: =head1 NAME
11042:
1.243 albertel 11043: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11044:
11045: =head1 SYNOPSIS
11046:
1.243 albertel 11047: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11048:
11049: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11050:
1.243 albertel 11051: Common parameters:
11052:
11053: =over 4
11054:
11055: =item *
11056:
11057: $uname : an internal username (if $cname expecting a course Id specifically)
11058:
11059: =item *
11060:
11061: $udom : a domain (if $cdom expecting a course's domain specifically)
11062:
11063: =item *
11064:
11065: $symb : a resource instance identifier
11066:
11067: =item *
11068:
11069: $namespace : the name of a .db file that contains the data needed or
11070: being set.
11071:
11072: =back
11073:
1.394 bowersj2 11074: =head1 OVERVIEW
1.191 harris41 11075:
1.394 bowersj2 11076: lonnet provides subroutines which interact with the
11077: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11078: about classes, users, and resources.
1.243 albertel 11079:
11080: For many of these objects you can also use this to store data about
11081: them or modify them in various ways.
1.191 harris41 11082:
1.394 bowersj2 11083: =head2 Symbs
1.191 harris41 11084:
1.394 bowersj2 11085: To identify a specific instance of a resource, LON-CAPA uses symbols
11086: or "symbs"X<symb>. These identifiers are built from the URL of the
11087: map, the resource number of the resource in the map, and the URL of
11088: the resource itself. The latter is somewhat redundant, but might help
11089: if maps change.
11090:
11091: An example is
11092:
11093: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11094:
11095: The respective map entry is
11096:
11097: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11098: title="Problem 2">
11099: </resource>
11100:
11101: Symbs are used by the random number generator, as well as to store and
11102: restore data specific to a certain instance of for example a problem.
11103:
11104: =head2 Storing And Retrieving Data
11105:
11106: X<store()>X<cstore()>X<restore()>Three of the most important functions
11107: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11108: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11109: is is the non-critical message twin of cstore. These functions are for
11110: handlers to store a perl hash to a user's permanent data space in an
11111: easy manner, and to retrieve it again on another call. It is expected
11112: that a handler would use this once at the beginning to retrieve data,
11113: and then again once at the end to send only the new data back.
11114:
11115: The data is stored in the user's data directory on the user's
11116: homeserver under the ID of the course.
11117:
11118: The hash that is returned by restore will have all of the previous
11119: value for all of the elements of the hash.
11120:
11121: Example:
11122:
11123: #creating a hash
11124: my %hash;
11125: $hash{'foo'}='bar';
11126:
11127: #storing it
11128: &Apache::lonnet::cstore(\%hash);
11129:
11130: #changing a value
11131: $hash{'foo'}='notbar';
11132:
11133: #adding a new value
11134: $hash{'bar'}='foo';
11135: &Apache::lonnet::cstore(\%hash);
11136:
11137: #retrieving the hash
11138: my %history=&Apache::lonnet::restore();
11139:
11140: #print the hash
11141: foreach my $key (sort(keys(%history))) {
11142: print("\%history{$key} = $history{$key}");
11143: }
11144:
11145: Will print out:
1.191 harris41 11146:
1.394 bowersj2 11147: %history{1:foo} = bar
11148: %history{1:keys} = foo:timestamp
11149: %history{1:timestamp} = 990455579
11150: %history{2:bar} = foo
11151: %history{2:foo} = notbar
11152: %history{2:keys} = foo:bar:timestamp
11153: %history{2:timestamp} = 990455580
11154: %history{bar} = foo
11155: %history{foo} = notbar
11156: %history{timestamp} = 990455580
11157: %history{version} = 2
11158:
11159: Note that the special hash entries C<keys>, C<version> and
11160: C<timestamp> were added to the hash. C<version> will be equal to the
11161: total number of versions of the data that have been stored. The
11162: C<timestamp> attribute will be the UNIX time the hash was
11163: stored. C<keys> is available in every historical section to list which
11164: keys were added or changed at a specific historical revision of a
11165: hash.
11166:
11167: B<Warning>: do not store the hash that restore returns directly. This
11168: will cause a mess since it will restore the historical keys as if the
11169: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11170:
1.394 bowersj2 11171: Calling convention:
1.191 harris41 11172:
1.394 bowersj2 11173: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11174: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11175:
1.394 bowersj2 11176: For more detailed information, see lonnet specific documentation.
1.191 harris41 11177:
1.394 bowersj2 11178: =head1 RETURN MESSAGES
1.191 harris41 11179:
1.394 bowersj2 11180: =over 4
1.191 harris41 11181:
1.394 bowersj2 11182: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11183:
1.394 bowersj2 11184: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11185: when the connection is brought back up
1.191 harris41 11186:
1.394 bowersj2 11187: =item * B<con_failed>: unable to contact remote host and unable to save message
11188: for later delivery
1.191 harris41 11189:
1.967 bisitz 11190: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11191:
1.394 bowersj2 11192: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11193: that was requested
1.191 harris41 11194:
1.243 albertel 11195: =back
1.191 harris41 11196:
1.243 albertel 11197: =head1 PUBLIC SUBROUTINES
1.191 harris41 11198:
1.243 albertel 11199: =head2 Session Environment Functions
1.191 harris41 11200:
1.243 albertel 11201: =over 4
1.191 harris41 11202:
1.394 bowersj2 11203: =item *
11204: X<appenv()>
1.949 raeburn 11205: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11206: the user envirnoment file, and will be restored for each access this
1.620 albertel 11207: user makes during this session, also modifies the %env for the current
1.949 raeburn 11208: process. Optional rolesarrayref - if defined contains a reference to an array
11209: of roles which are exempt from the restriction on modifying user.role entries
11210: in the user's environment.db and in %env.
1.191 harris41 11211:
11212: =item *
1.394 bowersj2 11213: X<delenv()>
1.987 raeburn 11214: B<delenv($delthis,$regexp)>: removes all items from the session
11215: environment file that begin with $delthis. If the
11216: optional second arg - $regexp - is true, $delthis is treated as a
11217: regular expression, otherwise \Q$delthis\E is used.
11218: The values are also deleted from the current processes %env.
1.191 harris41 11219:
1.795 albertel 11220: =item * get_env_multiple($name)
11221:
11222: gets $name from the %env hash, it seemlessly handles the cases where multiple
11223: values may be defined and end up as an array ref.
11224:
11225: returns an array of values
11226:
1.243 albertel 11227: =back
11228:
11229: =head2 User Information
1.191 harris41 11230:
1.243 albertel 11231: =over 4
1.191 harris41 11232:
11233: =item *
1.394 bowersj2 11234: X<queryauthenticate()>
11235: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11236: authentication scheme
11237:
11238: =item *
1.394 bowersj2 11239: X<authenticate()>
1.1073 raeburn 11240: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11241: authenticate user from domain's lib servers (first use the current
11242: one). C<$upass> should be the users password.
1.1073 raeburn 11243: $checkdefauth is optional (value is 1 if a check should be made to
11244: authenticate user using default authentication method, and allow
11245: account creation if username does not have account in the domain).
11246: $clientcancheckhost is optional (value is 1 if checking whether the
11247: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11248:
11249: =item *
1.394 bowersj2 11250: X<homeserver()>
11251: B<homeserver($uname,$udom)>: find the server which has
11252: the user's directory and files (there must be only one), this caches
11253: the answer, and also caches if there is a borken connection.
1.191 harris41 11254:
11255: =item *
1.394 bowersj2 11256: X<idget()>
11257: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11258: (IDs are a unique resource in a domain, there must be only 1 ID per
11259: username, and only 1 username per ID in a specific domain) (returns
11260: hash: id=>name,id=>name)
1.191 harris41 11261:
11262: =item *
1.394 bowersj2 11263: X<idrget()>
11264: B<idrget($udom,@unames)>: find the IDs behind a list of
11265: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11266:
11267: =item *
1.394 bowersj2 11268: X<idput()>
11269: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11270:
11271: =item *
1.394 bowersj2 11272: X<rolesinit()>
11273: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 11274:
11275: =item *
1.551 albertel 11276: X<getsection()>
11277: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11278: course $cname, return section name/number or '' for "not in course"
11279: and '-1' for "no section"
11280:
11281: =item *
1.394 bowersj2 11282: X<userenvironment()>
11283: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11284: passed in @what from the requested user's environment, returns a hash
11285:
1.858 raeburn 11286: =item *
11287: X<userlog_query()>
1.859 albertel 11288: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11289: activity.log file. %filters defines filters applied when parsing the
11290: log file. These can be start or end timestamps, or the type of action
11291: - log to look for Login or Logout events, check for Checkin or
11292: Checkout, role for role selection. The response is in the form
11293: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11294: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11295:
1.243 albertel 11296: =back
11297:
11298: =head2 User Roles
11299:
11300: =over 4
11301:
11302: =item *
11303:
1.810 raeburn 11304: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11305: F: full access
11306: U,I,K: authentication modes (cxx only)
11307: '': forbidden
11308: 1: user needs to choose course
11309: 2: browse allowed
1.766 albertel 11310: A: passphrase authentication needed
1.243 albertel 11311:
11312: =item *
11313:
11314: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11315: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11316: and course level
11317:
11318: =item *
11319:
1.988 raeburn 11320: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11321: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11322: $type is Course (default) or Community.
1.988 raeburn 11323: If $forcedefault evaluates to true, text returned will be default
11324: text for $type. Otherwise, if this is a course, the text returned
11325: will be a custom name for the role (if defined in the course's
11326: environment). If no custom name is defined the default is returned.
11327:
1.832 raeburn 11328: =item *
11329:
1.935 raeburn 11330: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11331: All arguments are optional. Returns a hash of a roles, either for
11332: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11333: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11334: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11335: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11336: For each key, value is set to colon-separated start and end times for
11337: the role. If no username and domain are specified, will default to
1.934 raeburn 11338: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11339: of role statuses (active, future or previous), roles
11340: (e.g., cc,in, st etc.) and domains of the roles which can be used
11341: to restrict the list of roles reported. If no array ref is
11342: provided for types, will default to return only active roles.
1.834 albertel 11343:
1.243 albertel 11344: =back
11345:
11346: =head2 User Modification
11347:
11348: =over 4
11349:
11350: =item *
11351:
1.957 raeburn 11352: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11353: user for the level given by URL. Optional start and end dates (leave empty
11354: string or zero for "no date")
1.191 harris41 11355:
11356: =item *
11357:
1.243 albertel 11358: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11359: change a users, password, possible return values are: ok,
11360: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11361: refused
1.191 harris41 11362:
11363: =item *
11364:
1.243 albertel 11365: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11366:
11367: =item *
11368:
1.1058 raeburn 11369: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11370: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11371:
11372: will update user information (firstname,middlename,lastname,generation,
11373: permanentemail), and if forceid is true, student/employee ID also.
11374: A user's institutional affiliation(s) can also be updated.
11375: User information fields will not be overwritten with empty entries
11376: unless the field is included in the $candelete array reference.
11377: This array is included when a single user is modified via "Manage Users",
11378: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11379:
11380: =item *
11381:
1.286 matthew 11382: modifystudent
11383:
1.957 raeburn 11384: modify a student's enrollment and identification information.
1.286 matthew 11385: The course id is resolved based on the current users environment.
11386: This means the envoking user must be a course coordinator or otherwise
11387: associated with a course.
11388:
1.297 matthew 11389: This call is essentially a wrapper for lonnet::modifyuser and
11390: lonnet::modify_student_enrollment
1.286 matthew 11391:
11392: Inputs:
11393:
11394: =over 4
11395:
1.957 raeburn 11396: =item B<$udom> Student's loncapa domain
1.286 matthew 11397:
1.957 raeburn 11398: =item B<$uname> Student's loncapa login name
1.286 matthew 11399:
1.964 bisitz 11400: =item B<$uid> Student/Employee ID
1.286 matthew 11401:
1.957 raeburn 11402: =item B<$umode> Student's authentication mode
1.286 matthew 11403:
1.957 raeburn 11404: =item B<$upass> Student's password
1.286 matthew 11405:
1.957 raeburn 11406: =item B<$first> Student's first name
1.286 matthew 11407:
1.957 raeburn 11408: =item B<$middle> Student's middle name
1.286 matthew 11409:
1.957 raeburn 11410: =item B<$last> Student's last name
1.286 matthew 11411:
1.957 raeburn 11412: =item B<$gene> Student's generation
1.286 matthew 11413:
1.957 raeburn 11414: =item B<$usec> Student's section in course
1.286 matthew 11415:
11416: =item B<$end> Unix time of the roles expiration
11417:
11418: =item B<$start> Unix time of the roles start date
11419:
11420: =item B<$forceid> If defined, allow $uid to be changed
11421:
11422: =item B<$desiredhome> server to use as home server for student
11423:
1.957 raeburn 11424: =item B<$email> Student's permanent e-mail address
11425:
11426: =item B<$type> Type of enrollment (auto or manual)
11427:
1.963 raeburn 11428: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11429:
11430: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11431:
1.963 raeburn 11432: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11433:
1.963 raeburn 11434: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11435:
1.963 raeburn 11436: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11437:
1.286 matthew 11438: =back
1.297 matthew 11439:
11440: =item *
11441:
11442: modify_student_enrollment
11443:
11444: Change a students enrollment status in a class. The environment variable
11445: 'role.request.course' must be defined for this function to proceed.
11446:
11447: Inputs:
11448:
11449: =over 4
11450:
11451: =item $udom, students domain
11452:
11453: =item $uname, students name
11454:
11455: =item $uid, students user id
11456:
11457: =item $first, students first name
11458:
11459: =item $middle
11460:
11461: =item $last
11462:
11463: =item $gene
11464:
11465: =item $usec
11466:
11467: =item $end
11468:
11469: =item $start
11470:
1.957 raeburn 11471: =item $type
11472:
11473: =item $locktype
11474:
11475: =item $cid
11476:
11477: =item $selfenroll
11478:
11479: =item $context
11480:
1.297 matthew 11481: =back
11482:
1.191 harris41 11483:
11484: =item *
11485:
1.243 albertel 11486: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11487: custom role; give a custom role to a user for the level given by URL. Specify
11488: name and domain of role author, and role name
1.191 harris41 11489:
11490: =item *
11491:
1.243 albertel 11492: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11493:
11494: =item *
11495:
1.243 albertel 11496: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11497:
11498: =back
11499:
11500: =head2 Course Infomation
11501:
11502: =over 4
1.191 harris41 11503:
11504: =item *
11505:
1.1118 foxr 11506: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 11507: specified course id, including all environment settings for the
11508: course, the description of the course will be in the hash under the
11509: key 'description'
1.191 harris41 11510:
1.1118 foxr 11511: $options is an optional parameter that if supplied is a hash reference that controls
11512: what how this function works. It has the following key/values:
11513:
11514: =over 4
11515:
11516: =item freshen_cache
11517:
11518: If defined, and the environment cache for the course is valid, it is
11519: returned in the returned hash.
11520:
11521: =item one_time
11522:
11523: If defined, the last cache time is set to _now_
11524:
11525: =item user
11526:
11527: If defined, the supplied username is used instead of the current user.
11528:
11529:
11530: =back
11531:
1.191 harris41 11532: =item *
11533:
1.624 albertel 11534: resdata($name,$domain,$type,@which) : request for current parameter
11535: setting for a specific $type, where $type is either 'course' or 'user',
11536: @what should be a list of parameters to ask about. This routine caches
11537: answers for 5 minutes.
1.243 albertel 11538:
1.877 foxr 11539: =item *
11540:
11541: get_courseresdata($courseid, $domain) : dump the entire course resource
11542: data base, returning a hash that is keyed by the resource name and has
11543: values that are the resource value. I believe that the timestamps and
11544: versions are also returned.
11545:
11546:
1.243 albertel 11547: =back
11548:
11549: =head2 Course Modification
11550:
11551: =over 4
1.191 harris41 11552:
11553: =item *
11554:
1.243 albertel 11555: writecoursepref($courseid,%prefs) : write preferences (environment
11556: database) for a course
1.191 harris41 11557:
11558: =item *
11559:
1.1011 raeburn 11560: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11561:
11562: =item *
11563:
1.1038 raeburn 11564: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11565:
11566: =back
11567:
11568: =head2 Resource Subroutines
11569:
11570: =over 4
1.191 harris41 11571:
11572: =item *
11573:
1.243 albertel 11574: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11575:
11576: =item *
11577:
1.243 albertel 11578: repcopy($filename) : subscribes to the requested file, and attempts to
11579: replicate from the owning library server, Might return
1.607 raeburn 11580: 'unavailable', 'not_found', 'forbidden', 'ok', or
11581: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11582: resource. Expects the local filesystem pathname
11583: (/home/httpd/html/res/....)
11584:
11585: =back
11586:
11587: =head2 Resource Information
11588:
11589: =over 4
1.191 harris41 11590:
11591: =item *
11592:
1.243 albertel 11593: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11594: a vairety of different possible values, $varname should be a request
11595: string, and the other parameters can be used to specify who and what
11596: one is asking about.
11597:
11598: Possible values for $varname are environment.lastname (or other item
11599: from the envirnment hash), user.name (or someother aspect about the
11600: user), resource.0.maxtries (or some other part and parameter of a
11601: resource)
1.204 albertel 11602:
11603: =item *
11604:
1.243 albertel 11605: directcondval($number) : get current value of a condition; reads from a state
11606: string
1.204 albertel 11607:
11608: =item *
11609:
1.243 albertel 11610: condval($condidx) : value of condition index based on state
1.204 albertel 11611:
11612: =item *
11613:
1.243 albertel 11614: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11615: resource's metadata, $what should be either a specific key, or either
11616: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11617: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11618:
11619: this function automatically caches all requests
1.191 harris41 11620:
11621: =item *
11622:
1.243 albertel 11623: metadata_query($query,$custom,$customshow) : make a metadata query against the
11624: network of library servers; returns file handle of where SQL and regex results
11625: will be stored for query
1.191 harris41 11626:
11627: =item *
11628:
1.243 albertel 11629: symbread($filename) : return symbolic list entry (filename argument optional);
11630: returns the data handle
1.191 harris41 11631:
11632: =item *
11633:
1.243 albertel 11634: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11635: a possible symb for the URL in $thisfn, and if is an encryypted
11636: resource that the user accessed using /enc/ returns a 1 on success, 0
11637: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11638: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11639:
1.191 harris41 11640:
11641: =item *
11642:
1.243 albertel 11643: symbclean($symb) : removes versions numbers from a symb, returns the
11644: cleaned symb
1.191 harris41 11645:
11646: =item *
11647:
1.243 albertel 11648: is_on_map($uri) : checks if the $uri is somewhere on the current
11649: course map, user must be in a course for it to work.
1.191 harris41 11650:
11651: =item *
11652:
1.243 albertel 11653: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11654:
11655: =item *
11656:
1.243 albertel 11657: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11658: a random seed, all arguments are optional, if they aren't sent it uses the
11659: environment to derive them. Note: if symb isn't sent and it can't get one
11660: from &symbread it will use the current time as its return value
1.191 harris41 11661:
11662: =item *
11663:
1.243 albertel 11664: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11665: unfakeable, receipt
1.191 harris41 11666:
11667: =item *
11668:
1.620 albertel 11669: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11670:
11671: =item *
11672:
1.243 albertel 11673: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11674:
11675: =item *
11676:
1.243 albertel 11677: 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
1.191 harris41 11678:
11679: =item *
11680:
1.243 albertel 11681: 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)
1.191 harris41 11682:
11683: =item *
11684:
1.243 albertel 11685: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11686:
11687: =item *
11688:
1.243 albertel 11689: devalidate($symb) : devalidate temporary spreadsheet calculations,
11690: forcing spreadsheet to reevaluate the resource scores next time.
11691:
11692: =back
11693:
11694: =head2 Storing/Retreiving Data
11695:
11696: =over 4
1.191 harris41 11697:
11698: =item *
11699:
1.243 albertel 11700: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11701: for this url; hashref needs to be given and should be a \%hashname; the
11702: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11703: be derived from the env
1.191 harris41 11704:
11705: =item *
11706:
1.243 albertel 11707: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11708: uses critical subroutine
1.191 harris41 11709:
11710: =item *
11711:
1.243 albertel 11712: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11713: all args are optional
1.191 harris41 11714:
11715: =item *
11716:
1.717 albertel 11717: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11718: dumps the complete (or key matching regexp) namespace into a hash
11719: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11720: normally &store()ed into
11721:
11722: $range should be either an integer '100' (give me the first 100
11723: matching records)
11724: or be two integers sperated by a - with no spaces
11725: '30-50' (give me the 30th through the 50th matching
11726: records)
11727:
11728:
11729: =item *
11730:
11731: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11732: replaces a &store() version of data with a replacement set of data
11733: for a particular resource in a namespace passed in the $storehash hash
11734: reference
11735:
11736: =item *
11737:
1.243 albertel 11738: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11739: works very similar to store/cstore, but all data is stored in a
11740: temporary location and can be reset using tmpreset, $storehash should
11741: be a hash reference, returns nothing on success
1.191 harris41 11742:
11743: =item *
11744:
1.243 albertel 11745: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11746: similar to restore, but all data is stored in a temporary location and
11747: can be reset using tmpreset. Returns a hash of values on success,
11748: error string otherwise.
1.191 harris41 11749:
11750: =item *
11751:
1.243 albertel 11752: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11753: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11754:
11755: =item *
11756:
1.243 albertel 11757: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11758: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11759:
11760: =item *
11761:
1.243 albertel 11762: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11763: namesp ($udom and $uname are optional)
1.191 harris41 11764:
11765: =item *
11766:
1.702 albertel 11767: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11768: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11769: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11770:
1.702 albertel 11771: $range should be either an integer '100' (give me the first 100
11772: matching records)
11773: or be two integers sperated by a - with no spaces
11774: '30-50' (give me the 30th through the 50th matching
11775: records)
1.449 matthew 11776: =item *
11777:
11778: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11779: $store can be a scalar, an array reference, or if the amount to be
11780: incremented is > 1, a hash reference.
11781:
11782: ($udom and $uname are optional)
1.191 harris41 11783:
11784: =item *
11785:
1.243 albertel 11786: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11787: ($udom and $uname are optional)
1.191 harris41 11788:
11789: =item *
11790:
1.243 albertel 11791: cput($namespace,$storehash,$udom,$uname) : critical put
11792: ($udom and $uname are optional)
1.191 harris41 11793:
11794: =item *
11795:
1.748 albertel 11796: newput($namespace,$storehash,$udom,$uname) :
11797:
11798: Attempts to store the items in the $storehash, but only if they don't
11799: currently exist, if this succeeds you can be certain that you have
11800: successfully created a new key value pair in the $namespace db.
11801:
11802:
11803: Args:
11804: $namespace: name of database to store values to
11805: $storehash: hashref to store to the db
11806: $udom: (optional) domain of user containing the db
11807: $uname: (optional) name of user caontaining the db
11808:
11809: Returns:
11810: 'ok' -> succeeded in storing all keys of $storehash
11811: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11812: least <key> already existed in the db (other
11813: requested keys may also already exist)
1.967 bisitz 11814: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11815: 'con_lost' -> unable to contact request server
11816: 'refused' -> action was not allowed by remote machine
11817:
11818:
11819: =item *
11820:
1.243 albertel 11821: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11822: reference filled in from namesp (encrypts the return communication)
11823: ($udom and $uname are optional)
1.191 harris41 11824:
11825: =item *
11826:
1.243 albertel 11827: log($udom,$name,$home,$message) : write to permanent log for user; use
11828: critical subroutine
11829:
1.806 raeburn 11830: =item *
11831:
1.860 raeburn 11832: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11833: array reference filled in from namespace found in domain level on either
11834: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11835:
11836: =item *
11837:
1.860 raeburn 11838: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11839: domain level either on specified domain server ($uhome) or primary domain
11840: server ($udom and $uhome are optional)
1.806 raeburn 11841:
1.943 raeburn 11842: =item *
11843:
11844: get_domain_defaults($target_domain) : returns hash with defaults for
11845: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11846: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11847: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11848: Values are retrieved from cache (if current), or from domain's configuration.db
11849: (if available), or lastly from values in lonTabs/dns_domain,tab,
11850: or lonTabs/domain.tab.
11851:
11852: %domdefaults = &get_auth_defaults($target_domain);
11853:
1.243 albertel 11854: =back
11855:
11856: =head2 Network Status Functions
11857:
11858: =over 4
1.191 harris41 11859:
11860: =item *
11861:
1.1137 raeburn 11862: dirlist() : return directory list based on URI (first arg).
11863:
11864: Inputs: 1 required, 5 optional.
11865:
11866: =over
11867:
11868: =item
11869: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
11870:
11871: =item
11872: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
11873:
11874: =item
11875: $username - username of user/course to be listed. Extracted from $uri if absent.
11876:
11877: =item
11878: $getpropath - boolean: 1 if prepend path using &propath().
11879:
11880: =item
11881: $getuserdir - boolean: 1 if prepend path for "userfiles".
11882:
11883: =item
11884: $alternateRoot - path to prepend in place of path from $uri.
11885:
11886: =back
11887:
11888: Returns: Array of up to two items.
11889:
11890: =over
11891:
11892: a reference to an array of files/subdirectories
11893:
11894: =over
11895:
11896: Each element in the array of files/subdirectories is a & separated list of
11897: item name and the result of running stat on the item. If dirlist was requested
11898: for a file instead of a directory, the item name will be ''. For a directory
11899: listing, if the item is a metadata file, the element will end &N&M
11900: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
11901: default copyright set (1).
11902:
11903: =back
11904:
11905: a scalar containing error condition (if encountered).
11906:
11907: =over
11908:
11909: =item
11910: no_host (no homeserver identified for $username:$domain).
11911:
11912: =item
11913: no_such_host (server contacted for listing not identified as valid host).
11914:
11915: =item
11916: con_lost (connection to remote server failed).
11917:
11918: =item
11919: refused (invalid $username:$domain received on lond side).
11920:
11921: =item
11922: no_such_dir (directory at specified path on lond side does not exist).
11923:
11924: =item
11925: empty (directory at specified path on lond side is empty).
11926:
11927: =over
11928:
11929: This is currently not encountered because the &ls3, &ls2,
11930: &ls (_handler) routines on the lond side do not filter out
11931: . and .. from a directory listing.
11932:
11933: =back
11934:
11935: =back
11936:
11937: =back
1.191 harris41 11938:
11939: =item *
11940:
1.243 albertel 11941: spareserver() : find server with least workload from spare.tab
11942:
1.986 foxr 11943:
11944: =item *
11945:
11946: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11947: if there is no corresponding loncapa host.
11948:
1.243 albertel 11949: =back
11950:
1.986 foxr 11951:
1.243 albertel 11952: =head2 Apache Request
11953:
11954: =over 4
1.191 harris41 11955:
11956: =item *
11957:
1.243 albertel 11958: ssi($url,%hash) : server side include, does a complete request cycle on url to
11959: localhost, posts hash
11960:
11961: =back
11962:
11963: =head2 Data to String to Data
11964:
11965: =over 4
1.191 harris41 11966:
11967: =item *
11968:
1.243 albertel 11969: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11970: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11971:
11972: =item *
11973:
1.243 albertel 11974: hashref2str($hashref) : convert a hashref into a string complete with
11975: escaping and '=' and '&' separators, supports elements that are
11976: arrayrefs and hashrefs
1.191 harris41 11977:
11978: =item *
11979:
1.243 albertel 11980: arrayref2str($arrayref) : convert an arrayref into a string complete
11981: with escaping and '&' separators, supports elements that are arrayrefs
11982: and hashrefs
1.191 harris41 11983:
11984: =item *
11985:
1.243 albertel 11986: str2hash($string) : convert string to hash using unescaping and
11987: splitting on '=' and '&', supports elements that are arrayrefs and
11988: hashrefs
1.191 harris41 11989:
11990: =item *
11991:
1.243 albertel 11992: str2array($string) : convert string to hash using unescaping and
11993: splitting on '&', supports elements that are arrayrefs and hashrefs
11994:
11995: =back
11996:
11997: =head2 Logging Routines
11998:
11999:
12000: These routines allow one to make log messages in the lonnet.log and
12001: lonnet.perm logfiles.
1.191 harris41 12002:
1.1119 foxr 12003: =over 4
12004:
1.191 harris41 12005: =item *
12006:
1.243 albertel 12007: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12008:
12009: =item *
12010:
1.243 albertel 12011: logthis() : append message to the normal lonnet.log file, it gets
12012: preiodically rolled over and deleted.
1.191 harris41 12013:
12014: =item *
12015:
1.243 albertel 12016: logperm() : append a permanent message to lonnet.perm.log, this log
12017: file never gets deleted by any automated portion of the system, only
12018: messages of critical importance should go in here.
12019:
1.1119 foxr 12020:
1.243 albertel 12021: =back
12022:
12023: =head2 General File Helper Routines
12024:
12025: =over 4
1.191 harris41 12026:
12027: =item *
12028:
1.481 raeburn 12029: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12030: (a) files in /uploaded
12031: (i) If a local copy of the file exists -
12032: compares modification date of local copy with last-modified date for
12033: definitive version stored on home server for course. If local copy is
12034: stale, requests a new version from the home server and stores it.
12035: If the original has been removed from the home server, then local copy
12036: is unlinked.
12037: (ii) If local copy does not exist -
12038: requests the file from the home server and stores it.
12039:
12040: If $caller is 'uploadrep':
12041: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12042: for request for files originally uploaded via DOCS.
12043: - returns 'ok' if fresh local copy now available, -1 otherwise.
12044:
12045: Otherwise:
12046: This indicates a call from the content generation phase of the request.
12047: - returns the entire contents of the file or -1.
12048:
12049: (b) files in /res
12050: - returns the entire contents of a file or -1;
12051: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12052:
1.712 albertel 12053:
12054: =item *
12055:
12056: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12057: reference
12058:
12059: returns either a stat() list of data about the file or an empty list
12060: if the file doesn't exist or couldn't find out about it (connection
12061: problems or user unknown)
12062:
1.191 harris41 12063: =item *
12064:
1.243 albertel 12065: filelocation($dir,$file) : returns file system location of a file
12066: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12067: directory that relative $file lookups are to looked in ($dir of /a/dir
12068: and a file of ../bob will become /a/bob)
1.191 harris41 12069:
12070: =item *
12071:
12072: hreflocation($dir,$file) : returns file system location or a URL; same as
12073: filelocation except for hrefs
12074:
12075: =item *
12076:
12077: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12078:
1.243 albertel 12079: =back
12080:
1.608 albertel 12081: =head2 Usererfile file routines (/uploaded*)
12082:
12083: =over 4
12084:
12085: =item *
12086:
12087: userfileupload(): main rotine for putting a file in a user or course's
12088: filespace, arguments are,
12089:
1.620 albertel 12090: formname - required - this is the name of the element in $env where the
1.608 albertel 12091: filename, and the contents of the file to create/modifed exist
1.620 albertel 12092: the filename is in $env{'form.'.$formname.'.filename'} and the
12093: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12094: context - if coursedoc, store the file in the course of the active role
12095: of the current user;
12096: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12097: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12098: subdir - required - subdirectory to put the file in under ../userfiles/
12099: if undefined, it will be placed in "unknown"
12100:
12101: (This routine calls clean_filename() to remove any dangerous
12102: characters from the filename, and then calls finuserfileupload() to
12103: complete the transaction)
12104:
12105: returns either the url of the uploaded file (/uploaded/....) if successful
12106: and /adm/notfound.html if unsuccessful
12107:
12108: =item *
12109:
12110: clean_filename(): routine for cleaing a filename up for storage in
12111: userfile space, argument is:
12112:
12113: filename - proposed filename
12114:
12115: returns: the new clean filename
12116:
12117: =item *
12118:
1.1090 raeburn 12119: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12120: userspace, probably shouldn't be called directly
12121:
12122: docuname: username or courseid of destination for the file
12123: docudom: domain of user/course of destination for the file
12124: formname: same as for userfileupload()
1.1090 raeburn 12125: fname: filename (including subdirectories) for the file
12126: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12127: allfiles: reference to hash used to store objects found by parser
12128: codebase: reference to hash used for codebases of java objects found by parser
12129: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12130: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12131: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12132: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12133: context: if 'overwrite', will move the uploaded file from its temporary location to
12134: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12135: mimetype: reference to scalar to accommodate mime type determined
12136: from File::MMagic if $parser = parse.
1.608 albertel 12137:
12138: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12139: and /adm/notfound.html if unsuccessful (or an error message if context
12140: was 'overwrite').
12141:
1.608 albertel 12142:
12143: =item *
12144:
12145: renameuserfile(): renames an existing userfile to a new name
12146:
12147: Args:
12148: docuname: username or courseid of destination for the file
12149: docudom: domain of user/course of destination for the file
12150: old: current file name (including any subdirs under userfiles)
12151: new: desired file name (including any subdirs under userfiles)
12152:
12153: =item *
12154:
12155: mkdiruserfile(): creates a directory is a userfiles dir
12156:
12157: Args:
12158: docuname: username or courseid of destination for the file
12159: docudom: domain of user/course of destination for the file
12160: dir: dir to create (including any subdirs under userfiles)
12161:
12162: =item *
12163:
12164: removeuserfile(): removes a file that exists in userfiles
12165:
12166: Args:
12167: docuname: username or courseid of destination for the file
12168: docudom: domain of user/course of destination for the file
12169: fname: filname to delete (including any subdirs under userfiles)
12170:
12171: =item *
12172:
12173: removeuploadedurl(): convience function for removeuserfile()
12174:
12175: Args:
12176: url: a full /uploaded/... url to delete
12177:
1.747 albertel 12178: =item *
12179:
12180: get_portfile_permissions():
12181: Args:
12182: domain: domain of user or course contain the portfolio files
12183: user: name of user or num of course contain the portfolio files
12184: Returns:
12185: hashref of a dump of the proper file_permissions.db
12186:
12187:
12188: =item *
12189:
12190: get_access_controls():
12191:
12192: Args:
12193: current_permissions: the hash ref returned from get_portfile_permissions()
12194: group: (optional) the group you want the files associated with
12195: file: (optional) the file you want access info on
12196:
12197: Returns:
1.749 raeburn 12198: a hash (keys are file names) of hashes containing
12199: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12200: values are XML containing access control settings (see below)
1.747 albertel 12201:
12202: Internal notes:
12203:
1.749 raeburn 12204: access controls are stored in file_permissions.db as key=value pairs.
12205: key -> path to file/file_name\0uniqueID:scope_end_start
12206: where scope -> public,guest,course,group,domains or users.
12207: end -> UNIX time for end of access (0 -> no end date)
12208: start -> UNIX time for start of access
12209:
12210: value -> XML description of access control
12211: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12212: <start></start>
12213: <end></end>
12214:
12215: <password></password> for scope type = guest
12216:
12217: <domain></domain> for scope type = course or group
12218: <number></number>
12219: <roles id="">
12220: <role></role>
12221: <access></access>
12222: <section></section>
12223: <group></group>
12224: </roles>
12225:
12226: <dom></dom> for scope type = domains
12227:
12228: <users> for scope type = users
12229: <user>
12230: <uname></uname>
12231: <udom></udom>
12232: </user>
12233: </users>
12234: </scope>
12235:
12236: Access data is also aggregated for each file in an additional key=value pair:
12237: key -> path to file/file_name\0accesscontrol
12238: value -> reference to hash
12239: hash contains key = value pairs
12240: where key = uniqueID:scope_end_start
12241: value = UNIX time record was last updated
12242:
12243: Used to improve speed of look-ups of access controls for each file.
12244:
12245: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12246:
12247: modify_access_controls():
12248:
12249: Modifies access controls for a portfolio file
12250: Args
12251: 1. file name
12252: 2. reference to hash of required changes,
12253: 3. domain
12254: 4. username
12255: where domain,username are the domain of the portfolio owner
12256: (either a user or a course)
12257:
12258: Returns:
12259: 1. result of additions or updates ('ok' or 'error', with error message).
12260: 2. result of deletions ('ok' or 'error', with error message).
12261: 3. reference to hash of any new or updated access controls.
12262: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12263: key = integer (inbound ID)
12264: value = uniqueID
1.747 albertel 12265:
1.608 albertel 12266: =back
12267:
1.243 albertel 12268: =head2 HTTP Helper Routines
12269:
12270: =over 4
12271:
1.191 harris41 12272: =item *
12273:
12274: escape() : unpack non-word characters into CGI-compatible hex codes
12275:
12276: =item *
12277:
12278: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12279:
1.243 albertel 12280: =back
12281:
12282: =head1 PRIVATE SUBROUTINES
12283:
12284: =head2 Underlying communication routines (Shouldn't call)
12285:
12286: =over 4
12287:
12288: =item *
12289:
12290: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12291:
12292: =item *
12293:
12294: reply() : uses subreply to send a message to remote machine, logs all failures
12295:
12296: =item *
12297:
12298: critical() : passes a critical message to another server; if cannot
12299: get through then place message in connection buffer directory and
12300: returns con_delayed, if incapable of saving message, returns
12301: con_failed
12302:
12303: =item *
12304:
12305: reconlonc() : tries to reconnect lonc client processes.
12306:
12307: =back
12308:
12309: =head2 Resource Access Logging
12310:
12311: =over 4
12312:
12313: =item *
12314:
12315: flushcourselogs() : flush (save) buffer logs and access logs
12316:
12317: =item *
12318:
12319: courselog($what) : save message for course in hash
12320:
12321: =item *
12322:
12323: courseacclog($what) : save message for course using &courselog(). Perform
12324: special processing for specific resource types (problems, exams, quizzes, etc).
12325:
1.191 harris41 12326: =item *
12327:
12328: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12329: as a PerlChildExitHandler
1.243 albertel 12330:
12331: =back
12332:
12333: =head2 Other
12334:
12335: =over 4
12336:
12337: =item *
12338:
12339: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12340:
12341: =back
12342:
12343: =cut
1.877 foxr 12344:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>