Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.31
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.31! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.30 2013/08/04 03:00:12 raeburn 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.1172.2.18 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
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.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.550 foxr 105: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
145: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.448 albertel 157: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.448 albertel 170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
355: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 356: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 357: return $response;
358: }
359:
1.1 albertel 360: # -------------------------------------------------- Non-critical communication
361: sub subreply {
362: my ($cmd,$server)=@_;
1.838 albertel 363: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 364: #
365: # With loncnew process trimming, there's a timing hole between lonc server
366: # process exit and the master server picking up the listen on the AF_UNIX
367: # socket. In that time interval, a lock file will exist:
368:
369: my $lockfile=$peerfile.".lock";
370: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
371: sleep(1);
372: }
373: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 374: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 375: #
1.550 foxr 376: # We'll give the connection a few tries before abandoning it. If
377: # connection is not possible, we'll con_lost back to the client.
378: #
379: my $client;
380: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
381: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
382: Type => SOCK_STREAM,
383: Timeout => 10);
1.869 albertel 384: if ($client) {
1.550 foxr 385: last; # Connected!
1.850 albertel 386: } else {
1.853 albertel 387: &create_connection(&hostname($server),$server);
1.550 foxr 388: }
1.850 albertel 389: sleep(1); # Try again later if failed connection.
1.550 foxr 390: }
391: my $answer;
392: if ($client) {
1.704 albertel 393: print $client "sethost:$server:$cmd\n";
1.550 foxr 394: $answer=<$client>;
395: if (!$answer) { $answer="con_lost"; }
396: chomp($answer);
397: } else {
398: $answer = 'con_lost'; # Failed connection.
399: }
1.1 albertel 400: return $answer;
401: }
402:
403: sub reply {
404: my ($cmd,$server)=@_;
1.838 albertel 405: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 406: my $answer=subreply($cmd,$server);
1.65 www 407: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 408: &logthis("<font color=\"blue\">WARNING:".
1.12 www 409: " $cmd to $server returned $answer</font>");
410: }
1.1 albertel 411: return $answer;
412: }
413:
414: # ----------------------------------------------------------- Send USR1 to lonc
415:
416: sub reconlonc {
1.891 albertel 417: my ($lonid) = @_;
418: my $hostname = &hostname($lonid);
419: if ($lonid) {
420: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
421: if ($hostname && -e $peerfile) {
422: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
423: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
424: Type => SOCK_STREAM,
425: Timeout => 10);
426: if ($client) {
427: print $client ("reset_retries\n");
428: my $answer=<$client>;
429: #reset just this one.
430: }
431: }
432: return;
433: }
434:
1.836 www 435: &logthis("Trying to reconnect lonc");
1.1 albertel 436: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 437: if (open(my $fh,"<$loncfile")) {
1.1 albertel 438: my $loncpid=<$fh>;
439: chomp($loncpid);
440: if (kill 0 => $loncpid) {
441: &logthis("lonc at pid $loncpid responding, sending USR1");
442: kill USR1 => $loncpid;
443: sleep 1;
1.836 www 444: } else {
1.12 www 445: &logthis(
1.672 albertel 446: "<font color=\"blue\">WARNING:".
1.12 www 447: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 448: }
449: } else {
1.836 www 450: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 451: }
452: }
453:
454: # ------------------------------------------------------ Critical communication
1.12 www 455:
1.1 albertel 456: sub critical {
457: my ($cmd,$server)=@_;
1.838 albertel 458: unless (&hostname($server)) {
1.672 albertel 459: &logthis("<font color=\"blue\">WARNING:".
1.89 www 460: " Critical message to unknown server ($server)</font>");
461: return 'no_such_host';
462: }
1.1 albertel 463: my $answer=reply($cmd,$server);
464: if ($answer eq 'con_lost') {
465: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 466: my $answer=reply($cmd,$server);
1.1 albertel 467: if ($answer eq 'con_lost') {
468: my $now=time;
469: my $middlename=$cmd;
1.5 www 470: $middlename=substr($middlename,0,16);
1.1 albertel 471: $middlename=~s/\W//g;
472: my $dfilename=
1.305 www 473: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
474: $dumpcount++;
1.1 albertel 475: {
1.448 albertel 476: my $dfh;
477: if (open($dfh,">$dfilename")) {
478: print $dfh "$cmd\n";
479: close($dfh);
480: }
1.1 albertel 481: }
482: sleep 2;
483: my $wcmd='';
484: {
1.448 albertel 485: my $dfh;
486: if (open($dfh,"<$dfilename")) {
487: $wcmd=<$dfh>;
488: close($dfh);
489: }
1.1 albertel 490: }
491: chomp($wcmd);
1.7 www 492: if ($wcmd eq $cmd) {
1.672 albertel 493: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 494: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 495: &logperm("D:$server:$cmd");
496: return 'con_delayed';
497: } else {
1.672 albertel 498: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 499: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 500: &logperm("F:$server:$cmd");
501: return 'con_failed';
502: }
503: }
504: }
505: return $answer;
1.405 albertel 506: }
507:
1.755 albertel 508: # ------------------------------------------- check if return value is an error
509:
510: sub error {
511: my ($result) = @_;
1.756 albertel 512: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 513: if ($2 == 2) { return undef; }
514: return $1;
515: }
516: return undef;
517: }
518:
1.783 albertel 519: sub convert_and_load_session_env {
520: my ($lonidsdir,$handle)=@_;
521: my @profile;
522: {
1.917 albertel 523: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
524: if (!$opened) {
1.915 albertel 525: return 0;
526: }
1.783 albertel 527: flock($idf,LOCK_SH);
528: @profile=<$idf>;
529: close($idf);
530: }
531: my %temp_env;
532: foreach my $line (@profile) {
1.786 albertel 533: if ($line !~ m/=/) {
534: return 0;
535: }
1.783 albertel 536: chomp($line);
537: my ($envname,$envvalue)=split(/=/,$line,2);
538: $temp_env{&unescape($envname)} = &unescape($envvalue);
539: }
540: unlink("$lonidsdir/$handle.id");
541: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
542: 0640)) {
543: %disk_env = %temp_env;
544: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
545: untie(%disk_env);
546: }
1.786 albertel 547: return 1;
1.783 albertel 548: }
549:
1.374 www 550: # ------------------------------------------- Transfer profile into environment
1.780 albertel 551: my $env_loaded;
552: sub transfer_profile_to_env {
1.788 albertel 553: my ($lonidsdir,$handle,$force_transfer) = @_;
554: if (!$force_transfer && $env_loaded) { return; }
1.374 www 555:
1.720 albertel 556: if (!defined($lonidsdir)) {
557: $lonidsdir = $perlvar{'lonIDsDir'};
558: }
559: if (!defined($handle)) {
560: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
561: }
562:
1.786 albertel 563: my $convert;
564: {
1.917 albertel 565: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
566: if (!$opened) {
1.915 albertel 567: return;
568: }
1.786 albertel 569: flock($idf,LOCK_SH);
570: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
571: &GDBM_READER(),0640)) {
572: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
573: untie(%disk_env);
574: } else {
575: $convert = 1;
576: }
577: }
578: if ($convert) {
579: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
580: &logthis("Failed to load session, or convert session.");
581: }
1.374 www 582: }
1.783 albertel 583:
1.786 albertel 584: my %remove;
1.783 albertel 585: while ( my $envname = each(%env) ) {
1.433 matthew 586: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
587: if ($time < time-300) {
1.783 albertel 588: $remove{$key}++;
1.433 matthew 589: }
590: }
591: }
1.783 albertel 592:
1.619 albertel 593: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 594: $env_loaded=1;
1.783 albertel 595: foreach my $expired_key (keys(%remove)) {
1.433 matthew 596: &delenv($expired_key);
1.374 www 597: }
1.1 albertel 598: }
599:
1.916 albertel 600: # ---------------------------------------------------- Check for valid session
601: sub check_for_valid_session {
1.1155 raeburn 602: my ($r,$name) = @_;
1.916 albertel 603: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 604: if ($name eq '') {
605: $name = 'lonID';
606: }
607: my $lonid=$cookies{$name};
1.916 albertel 608: return undef if (!$lonid);
609:
610: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 611: my $lonidsdir;
612: if ($name eq 'lonDAV') {
613: $lonidsdir=$r->dir_config('lonDAVsessDir');
614: } else {
615: $lonidsdir=$r->dir_config('lonIDsDir');
616: }
1.916 albertel 617: return undef if (!-e "$lonidsdir/$handle.id");
618:
1.917 albertel 619: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
620: return undef if (!$opened);
1.916 albertel 621:
622: flock($idf,LOCK_SH);
623: my %disk_env;
624: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
625: &GDBM_READER(),0640)) {
626: return undef;
627: }
628:
629: if (!defined($disk_env{'user.name'})
630: || !defined($disk_env{'user.domain'})) {
631: return undef;
632: }
1.1172.2.18 raeburn 633:
634: if (($r->user() eq '') && ($apache >= 2.4)) {
635: if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
636: $r->user($disk_env{'user.name'});
637: } else {
638: $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
639: }
640: }
641:
1.916 albertel 642: return $handle;
643: }
644:
1.830 albertel 645: sub timed_flock {
646: my ($file,$lock_type) = @_;
647: my $failed=0;
648: eval {
649: local $SIG{__DIE__}='DEFAULT';
650: local $SIG{ALRM}=sub {
651: $failed=1;
652: die("failed lock");
653: };
654: alarm(13);
655: flock($file,$lock_type);
656: alarm(0);
657: };
658: if ($failed) {
659: return undef;
660: } else {
661: return 1;
662: }
663: }
664:
1.5 www 665: # ---------------------------------------------------------- Append Environment
666:
667: sub appenv {
1.949 raeburn 668: my ($newenv,$roles) = @_;
669: if (ref($newenv) eq 'HASH') {
670: foreach my $key (keys(%{$newenv})) {
671: my $refused = 0;
672: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
673: $refused = 1;
674: if (ref($roles) eq 'ARRAY') {
675: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
676: if (grep(/^\Q$role\E$/,@{$roles})) {
677: $refused = 0;
678: }
679: }
680: }
681: if ($refused) {
682: &logthis("<font color=\"blue\">WARNING: ".
683: "Attempt to modify environment ".$key." to ".$newenv->{$key}
684: .'</font>');
685: delete($newenv->{$key});
686: } else {
687: $env{$key}=$newenv->{$key};
688: }
689: }
690: my $opened = open(my $env_file,'+<',$env{'user.environment'});
691: if ($opened
692: && &timed_flock($env_file,LOCK_EX)
693: &&
694: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
695: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
696: while (my ($key,$value) = each(%{$newenv})) {
697: $disk_env{$key} = $value;
698: }
699: untie(%disk_env);
1.35 www 700: }
1.191 harris41 701: }
1.56 www 702: return 'ok';
703: }
704: # ----------------------------------------------------- Delete from Environment
705:
706: sub delenv {
1.1104 raeburn 707: my ($delthis,$regexp,$roles) = @_;
708: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
709: my $refused = 1;
710: if (ref($roles) eq 'ARRAY') {
711: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
712: if (grep(/^\Q$role\E$/,@{$roles})) {
713: $refused = 0;
714: }
715: }
716: if ($refused) {
717: &logthis("<font color=\"blue\">WARNING: ".
718: "Attempt to delete from environment ".$delthis);
719: return 'error';
720: }
1.56 www 721: }
1.917 albertel 722: my $opened = open(my $env_file,'+<',$env{'user.environment'});
723: if ($opened
1.915 albertel 724: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 725: &&
726: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
727: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 728: foreach my $key (keys(%disk_env)) {
1.987 raeburn 729: if ($regexp) {
730: if ($key=~/^$delthis/) {
731: delete($env{$key});
732: delete($disk_env{$key});
733: }
734: } else {
735: if ($key=~/^\Q$delthis\E/) {
736: delete($env{$key});
737: delete($disk_env{$key});
738: }
739: }
1.448 albertel 740: }
1.783 albertel 741: untie(%disk_env);
1.5 www 742: }
743: return 'ok';
1.369 albertel 744: }
745:
1.790 albertel 746: sub get_env_multiple {
747: my ($name) = @_;
748: my @values;
749: if (defined($env{$name})) {
750: # exists is it an array
751: if (ref($env{$name})) {
752: @values=@{ $env{$name} };
753: } else {
754: $values[0]=$env{$name};
755: }
756: }
757: return(@values);
758: }
759:
1.958 www 760: # ------------------------------------------------------------------- Locking
761:
762: sub set_lock {
763: my ($text)=@_;
764: $locknum++;
765: my $id=$$.'-'.$locknum;
766: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
767: 'session.lock.'.$id => $text});
768: return $id;
769: }
770:
771: sub get_locks {
772: my $num=0;
773: my %texts=();
774: foreach my $lock (split(/\,/,$env{'session.locks'})) {
775: if ($lock=~/\w/) {
776: $num++;
777: $texts{$lock}=$env{'session.lock.'.$lock};
778: }
779: }
780: return ($num,%texts);
781: }
782:
783: sub remove_lock {
784: my ($id)=@_;
785: my $newlocks='';
786: foreach my $lock (split(/\,/,$env{'session.locks'})) {
787: if (($lock=~/\w/) && ($lock ne $id)) {
788: $newlocks.=','.$lock;
789: }
790: }
791: &appenv({'session.locks' => $newlocks});
792: &delenv('session.lock.'.$id);
793: }
794:
795: sub remove_all_locks {
796: my $activelocks=$env{'session.locks'};
797: foreach my $lock (split(/\,/,$env{'session.locks'})) {
798: if ($lock=~/\w/) {
799: &remove_lock($lock);
800: }
801: }
802: }
803:
804:
1.369 albertel 805: # ------------------------------------------ Find out current server userload
806: sub userload {
807: my $numusers=0;
808: {
809: opendir(LONIDS,$perlvar{'lonIDsDir'});
810: my $filename;
811: my $curtime=time;
812: while ($filename=readdir(LONIDS)) {
1.925 albertel 813: next if ($filename eq '.' || $filename eq '..');
814: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 815: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 816: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 817: }
818: closedir(LONIDS);
819: }
820: my $userloadpercent=0;
821: my $maxuserload=$perlvar{'lonUserLoadLim'};
822: if ($maxuserload) {
1.371 albertel 823: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 824: }
1.372 albertel 825: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 826: return $userloadpercent;
1.283 www 827: }
828:
1.1 albertel 829: # ------------------------------ Find server with least workload from spare.tab
1.11 www 830:
1.1 albertel 831: sub spareserver {
1.1083 raeburn 832: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 833: my $spare_server;
1.370 albertel 834: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 835: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
836: : $userloadpercent;
1.1083 raeburn 837: my ($uint_dom,$remotesessions);
838: if (($udom ne '') && (&domain($udom) ne '')) {
839: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
840: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
841: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
842: $remotesessions = $udomdefaults{'remotesessions'};
843: }
1.1123 raeburn 844: my $spareshash = &this_host_spares($udom);
845: if (ref($spareshash) eq 'HASH') {
846: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
847: foreach my $try_server (@{ $spareshash->{'primary'} }) {
848: if ($uint_dom) {
849: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
850: $try_server));
851: }
852: ($spare_server, $lowest_load) =
853: &compare_server_load($try_server, $spare_server, $lowest_load);
854: }
1.1083 raeburn 855: }
1.784 albertel 856:
1.1123 raeburn 857: my $found_server = ($spare_server ne '' && $lowest_load < 100);
858:
859: if (!$found_server) {
860: if (ref($spareshash->{'default'}) eq 'ARRAY') {
861: foreach my $try_server (@{ $spareshash->{'default'} }) {
862: if ($uint_dom) {
863: next unless (&spare_can_host($udom,$uint_dom,
864: $remotesessions,$try_server));
865: }
866: ($spare_server, $lowest_load) =
867: &compare_server_load($try_server, $spare_server, $lowest_load);
868: }
869: }
870: }
1.784 albertel 871: }
872:
873: if (!$want_server_name) {
1.968 raeburn 874: my $protocol = 'http';
875: if ($protocol{$spare_server} eq 'https') {
876: $protocol = $protocol{$spare_server};
877: }
1.1001 raeburn 878: if (defined($spare_server)) {
879: my $hostname = &hostname($spare_server);
1.1083 raeburn 880: if (defined($hostname)) {
1.1001 raeburn 881: $spare_server = $protocol.'://'.$hostname;
882: }
883: }
1.784 albertel 884: }
885: return $spare_server;
886: }
887:
888: sub compare_server_load {
889: my ($try_server, $spare_server, $lowest_load) = @_;
890:
891: my $loadans = &reply('load', $try_server);
892: my $userloadans = &reply('userload',$try_server);
893:
894: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 895: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 896: }
897:
898: my $load;
899: if ($loadans =~ /\d/) {
900: if ($userloadans =~ /\d/) {
901: #both are numbers, pick the bigger one
902: $load = ($loadans > $userloadans) ? $loadans
903: : $userloadans;
1.411 albertel 904: } else {
1.784 albertel 905: $load = $loadans;
1.411 albertel 906: }
1.784 albertel 907: } else {
908: $load = $userloadans;
909: }
910:
911: if (($load =~ /\d/) && ($load < $lowest_load)) {
912: $spare_server = $try_server;
913: $lowest_load = $load;
1.370 albertel 914: }
1.784 albertel 915: return ($spare_server,$lowest_load);
1.202 matthew 916: }
1.914 albertel 917:
918: # --------------------------- ask offload servers if user already has a session
919: sub find_existing_session {
920: my ($udom,$uname) = @_;
1.1123 raeburn 921: my $spareshash = &this_host_spares($udom);
922: if (ref($spareshash) eq 'HASH') {
923: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
924: foreach my $try_server (@{ $spareshash->{'primary'} }) {
925: return $try_server if (&has_user_session($try_server, $udom, $uname));
926: }
927: }
928: if (ref($spareshash->{'default'}) eq 'ARRAY') {
929: foreach my $try_server (@{ $spareshash->{'default'} }) {
930: return $try_server if (&has_user_session($try_server, $udom, $uname));
931: }
932: }
1.914 albertel 933: }
934: return;
935: }
936:
937: # -------------------------------- ask if server already has a session for user
938: sub has_user_session {
939: my ($lonid,$udom,$uname) = @_;
940: my $result = &reply(join(':','userhassession',
941: map {&escape($_)} ($udom,$uname)),$lonid);
942: return 1 if ($result eq 'ok');
943:
944: return 0;
945: }
946:
1.1076 raeburn 947: # --------- determine least loaded server in a user's domain which allows login
948:
949: sub choose_server {
1.1115 raeburn 950: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 951: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 952: my %servers = &get_servers($udom);
1.1076 raeburn 953: my $lowest_load = 30000;
1.1151 raeburn 954: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 955: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 956: my $loginvia;
957: if ($checkloginvia) {
958: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 959: if ($loginvia) {
960: my ($server,$path) = split(/:/,$loginvia);
961: ($login_host, $lowest_load) =
962: &compare_server_load($server, $login_host, $lowest_load);
963: if ($login_host eq $server) {
964: $portal_path = $path;
1.1151 raeburn 965: $isredirect = 1;
1.1116 raeburn 966: }
967: } else {
968: ($login_host, $lowest_load) =
969: &compare_server_load($lonhost, $login_host, $lowest_load);
970: if ($login_host eq $lonhost) {
971: $portal_path = '';
1.1151 raeburn 972: $isredirect = '';
1.1116 raeburn 973: }
974: }
975: } else {
1.1076 raeburn 976: ($login_host, $lowest_load) =
1.1116 raeburn 977: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 978: }
979: }
980: if ($login_host ne '') {
1.1116 raeburn 981: $hostname = &hostname($login_host);
1.1076 raeburn 982: }
1.1151 raeburn 983: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 984: }
985:
1.202 matthew 986: # --------------------------------------------- Try to change a user's password
987:
988: sub changepass {
1.799 raeburn 989: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 990: $currentpass = &escape($currentpass);
991: $newpass = &escape($newpass);
1.1030 raeburn 992: my $lonhost = $perlvar{'lonHostID'};
993: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 994: $server);
995: if (! $answer) {
996: &logthis("No reply on password change request to $server ".
997: "by $uname in domain $udom.");
998: } elsif ($answer =~ "^ok") {
999: &logthis("$uname in $udom successfully changed their password ".
1000: "on $server.");
1001: } elsif ($answer =~ "^pwchange_failure") {
1002: &logthis("$uname in $udom was unable to change their password ".
1003: "on $server. The action was blocked by either lcpasswd ".
1004: "or pwchange");
1005: } elsif ($answer =~ "^non_authorized") {
1006: &logthis("$uname in $udom did not get their password correct when ".
1007: "attempting to change it on $server.");
1008: } elsif ($answer =~ "^auth_mode_error") {
1009: &logthis("$uname in $udom attempted to change their password despite ".
1010: "not being locally or internally authenticated on $server.");
1011: } elsif ($answer =~ "^unknown_user") {
1012: &logthis("$uname in $udom attempted to change their password ".
1013: "on $server but were unable to because $server is not ".
1014: "their home server.");
1015: } elsif ($answer =~ "^refused") {
1016: &logthis("$server refused to change $uname in $udom password because ".
1017: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1018: } elsif ($answer =~ "invalid_client") {
1019: &logthis("$server refused to change $uname in $udom password because ".
1020: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1021: }
1022: return $answer;
1.1 albertel 1023: }
1024:
1.169 harris41 1025: # ----------------------- Try to determine user's current authentication scheme
1026:
1027: sub queryauthenticate {
1028: my ($uname,$udom)=@_;
1.456 albertel 1029: my $uhome=&homeserver($uname,$udom);
1030: if (!$uhome) {
1031: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1032: return 'no_host';
1033: }
1034: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1035: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1036: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1037: }
1.456 albertel 1038: return $answer;
1.169 harris41 1039: }
1040:
1.1 albertel 1041: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1042:
1.1 albertel 1043: sub authenticate {
1.1073 raeburn 1044: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1045: $upass=&escape($upass);
1046: $uname= &LONCAPA::clean_username($uname);
1.836 www 1047: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1048: my $newhome;
1.836 www 1049: if ((!$uhome) || ($uhome eq 'no_host')) {
1050: # Maybe the machine was offline and only re-appeared again recently?
1051: &reconlonc();
1052: # One more
1.952 raeburn 1053: $uhome=&homeserver($uname,$udom,1);
1054: if (($uhome eq 'no_host') && $checkdefauth) {
1055: if (defined(&domain($udom,'primary'))) {
1056: $newhome=&domain($udom,'primary');
1057: }
1058: if ($newhome ne '') {
1059: $uhome = $newhome;
1060: }
1061: }
1.836 www 1062: if ((!$uhome) || ($uhome eq 'no_host')) {
1063: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1064: return 'no_host';
1065: }
1.1 albertel 1066: }
1.1073 raeburn 1067: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1068: if ($answer eq 'authorized') {
1.952 raeburn 1069: if ($newhome) {
1070: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1071: return 'no_account_on_host';
1072: } else {
1073: &logthis("User $uname at $udom authorized by $uhome");
1074: return $uhome;
1075: }
1.471 albertel 1076: }
1077: if ($answer eq 'non_authorized') {
1078: &logthis("User $uname at $udom rejected by $uhome");
1079: return 'no_host';
1.9 www 1080: }
1.471 albertel 1081: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1082: return 'no_host';
1083: }
1084:
1.1073 raeburn 1085: sub can_host_session {
1.1074 raeburn 1086: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1087: my $canhost = 1;
1.1074 raeburn 1088: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1089: if (ref($remotesessions) eq 'HASH') {
1090: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1091: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1092: $canhost = 0;
1093: } else {
1094: $canhost = 1;
1095: }
1096: }
1097: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1098: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1099: $canhost = 1;
1100: } else {
1101: $canhost = 0;
1102: }
1103: }
1104: if ($canhost) {
1105: if ($remotesessions->{'version'} ne '') {
1106: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1107: if ($reqmajor ne '' && $reqminor ne '') {
1108: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1109: my $major = $1;
1110: my $minor = $2;
1111: if (($major < $reqmajor ) ||
1112: (($major == $reqmajor) && ($minor < $reqminor))) {
1113: $canhost = 0;
1114: }
1115: } else {
1116: $canhost = 0;
1117: }
1118: }
1119: }
1120: }
1121: }
1122: if ($canhost) {
1123: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1124: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1125: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1126: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1127: if (($uint_dom ne '') &&
1128: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1129: $canhost = 0;
1130: } else {
1131: $canhost = 1;
1132: }
1133: }
1134: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1135: if (($uint_dom ne '') &&
1136: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1137: $canhost = 1;
1138: } else {
1139: $canhost = 0;
1140: }
1141: }
1142: }
1143: }
1144: return $canhost;
1145: }
1146:
1.1083 raeburn 1147: sub spare_can_host {
1148: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1149: my $canhost=1;
1150: my @intdoms;
1151: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1152: if (ref($internet_names) eq 'ARRAY') {
1153: @intdoms = @{$internet_names};
1154: }
1155: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1156: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1157: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1158: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1159: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1160: $canhost = &can_host_session($udom,$try_server,$remoterev,
1161: $remotesessions,
1162: $defdomdefaults{'hostedsessions'});
1163: }
1164: return $canhost;
1165: }
1166:
1.1123 raeburn 1167: sub this_host_spares {
1168: my ($dom) = @_;
1.1126 raeburn 1169: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1170: my @hosts = ¤t_machine_ids();
1171: foreach my $lonhost (@hosts) {
1172: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1173: $dom_in_use = $dom;
1174: $lonhost_in_use = $lonhost;
1.1123 raeburn 1175: last;
1176: }
1177: }
1.1126 raeburn 1178: if ($dom_in_use ne '') {
1179: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1180: }
1181: if (ref($result) ne 'HASH') {
1182: $lonhost_in_use = $perlvar{'lonHostID'};
1183: $dom_in_use = &host_domain($lonhost_in_use);
1184: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1185: if (ref($result) ne 'HASH') {
1186: $result = \%spareid;
1187: }
1188: }
1189: return $result;
1190: }
1191:
1192: sub spares_for_offload {
1193: my ($dom_in_use,$lonhost_in_use) = @_;
1194: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1195: if (defined($cached)) {
1196: return $result;
1197: } else {
1.1126 raeburn 1198: my $cachetime = 60*60*24;
1199: my %domconfig =
1200: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1201: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1202: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1203: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1204: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1205: }
1206: }
1207: }
1208: }
1.1126 raeburn 1209: return;
1.1123 raeburn 1210: }
1211:
1.1129 raeburn 1212: sub get_lonbalancer_config {
1213: my ($servers) = @_;
1214: my ($currbalancer,$currtargets);
1215: if (ref($servers) eq 'HASH') {
1216: foreach my $server (keys(%{$servers})) {
1217: my %what = (
1218: spareid => 1,
1219: perlvar => 1,
1220: );
1221: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1222: if ($result eq 'ok') {
1223: if (ref($returnhash) eq 'HASH') {
1224: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1225: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1226: $currbalancer = $server;
1227: $currtargets = {};
1228: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1229: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1230: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1231: }
1232: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1233: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1234: }
1235: }
1236: last;
1237: }
1238: }
1239: }
1240: }
1241: }
1242: }
1243: return ($currbalancer,$currtargets);
1244: }
1245:
1246: sub check_loadbalancing {
1247: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1248: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1249: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1250: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1251: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1252: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1253: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1254: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1255: my $serverhomedom = &host_domain($lonhost);
1256:
1257: my $cachetime = 60*60*24;
1258:
1259: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1260: $dom_in_use = $udom;
1261: $homeintdom = 1;
1262: } else {
1263: $dom_in_use = $serverhomedom;
1264: }
1265: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1266: unless (defined($cached)) {
1267: my %domconfig =
1268: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1269: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1270: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1271: }
1272: }
1273: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1274: ($is_balancer,$currtargets,$currrules) =
1275: &check_balancer_result($result,@hosts);
1.1129 raeburn 1276: if ($is_balancer) {
1277: if (ref($currrules) eq 'HASH') {
1278: if ($homeintdom) {
1279: if ($uname ne '') {
1280: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1281: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1282: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1283: $rule_in_effect = $currrules->{'_LC_author'};
1284: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1285: $rule_in_effect = $currrules->{'_LC_adv'}
1286: }
1287: }
1288: if ($rule_in_effect eq '') {
1289: my %userenv = &userenvironment($udom,$uname,'inststatus');
1290: if ($userenv{'inststatus'} ne '') {
1291: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1292: my ($othertitle,$usertypes,$types) =
1293: &Apache::loncommon::sorted_inst_types($udom);
1294: if (ref($types) eq 'ARRAY') {
1295: foreach my $type (@{$types}) {
1296: if (grep(/^\Q$type\E$/,@statuses)) {
1297: if (exists($currrules->{$type})) {
1298: $rule_in_effect = $currrules->{$type};
1299: }
1300: }
1301: }
1302: }
1303: } else {
1304: if (exists($currrules->{'default'})) {
1305: $rule_in_effect = $currrules->{'default'};
1306: }
1307: }
1308: }
1309: } else {
1310: if (exists($currrules->{'default'})) {
1311: $rule_in_effect = $currrules->{'default'};
1312: }
1313: }
1314: } else {
1315: if ($currrules->{'_LC_external'} ne '') {
1316: $rule_in_effect = $currrules->{'_LC_external'};
1317: }
1318: }
1319: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1320: $uname,$udom);
1321: }
1322: }
1323: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1324: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1325: unless (defined($cached)) {
1326: my %domconfig =
1327: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1328: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1329: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1330: }
1331: }
1332: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1333: ($is_balancer,$currtargets,$currrules) =
1334: &check_balancer_result($result,@hosts);
1335: if ($is_balancer) {
1.1129 raeburn 1336: if (ref($currrules) eq 'HASH') {
1337: if ($currrules->{'_LC_internetdom'} ne '') {
1338: $rule_in_effect = $currrules->{'_LC_internetdom'};
1339: }
1340: }
1341: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1342: $uname,$udom);
1343: }
1344: } else {
1345: if ($perlvar{'lonBalancer'} eq 'yes') {
1346: $is_balancer = 1;
1347: $offloadto = &this_host_spares($dom_in_use);
1348: }
1349: }
1350: } else {
1351: if ($perlvar{'lonBalancer'} eq 'yes') {
1352: $is_balancer = 1;
1353: $offloadto = &this_host_spares($dom_in_use);
1354: }
1355: }
1.1172.2.5 raeburn 1356: if ($is_balancer) {
1357: my $lowest_load = 30000;
1358: if (ref($offloadto) eq 'HASH') {
1359: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1360: foreach my $try_server (@{$offloadto->{'primary'}}) {
1361: ($otherserver,$lowest_load) =
1362: &compare_server_load($try_server,$otherserver,$lowest_load);
1363: }
1.1129 raeburn 1364: }
1.1172.2.5 raeburn 1365: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1366:
1.1172.2.5 raeburn 1367: if (!$found_server) {
1368: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1369: foreach my $try_server (@{$offloadto->{'default'}}) {
1370: ($otherserver,$lowest_load) =
1371: &compare_server_load($try_server,$otherserver,$lowest_load);
1372: }
1373: }
1374: }
1375: } elsif (ref($offloadto) eq 'ARRAY') {
1376: if (@{$offloadto} == 1) {
1377: $otherserver = $offloadto->[0];
1378: } elsif (@{$offloadto} > 1) {
1379: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1380: ($otherserver,$lowest_load) =
1381: &compare_server_load($try_server,$otherserver,$lowest_load);
1382: }
1383: }
1384: }
1.1172.2.5 raeburn 1385: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1386: $is_balancer = 0;
1387: if ($uname ne '' && $udom ne '') {
1388: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1389:
1390: &appenv({'user.loadbalexempt' => $lonhost,
1391: 'user.loadbalcheck.time' => time});
1392: }
1.1129 raeburn 1393: }
1394: }
1395: }
1396: return ($is_balancer,$otherserver);
1397: }
1398:
1.1172.2.12 raeburn 1399: sub check_balancer_result {
1400: my ($result,@hosts) = @_;
1401: my ($is_balancer,$currtargets,$currrules);
1402: if (ref($result) eq 'HASH') {
1403: if ($result->{'lonhost'} ne '') {
1404: my $currbalancer = $result->{'lonhost'};
1405: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1406: $is_balancer = 1;
1407: $currtargets = $result->{'targets'};
1408: $currrules = $result->{'rules'};
1409: }
1410: } else {
1411: foreach my $key (keys(%{$result})) {
1412: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1413: (ref($result->{$key}) eq 'HASH')) {
1414: $is_balancer = 1;
1415: $currrules = $result->{$key}{'rules'};
1416: $currtargets = $result->{$key}{'targets'};
1417: last;
1418: }
1419: }
1420: }
1421: }
1422: return ($is_balancer,$currtargets,$currrules);
1423: }
1424:
1.1129 raeburn 1425: sub get_loadbalancer_targets {
1426: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1427: my $offloadto;
1.1172.2.4 raeburn 1428: if ($rule_in_effect eq 'none') {
1429: return [$perlvar{'lonHostID'}];
1430: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1431: $offloadto = $currtargets;
1432: } else {
1433: if ($rule_in_effect eq 'homeserver') {
1434: my $homeserver = &homeserver($uname,$udom);
1435: if ($homeserver ne 'no_host') {
1436: $offloadto = [$homeserver];
1437: }
1438: } elsif ($rule_in_effect eq 'externalbalancer') {
1439: my %domconfig =
1440: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1441: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1442: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1443: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1444: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1445: }
1446: }
1447: } else {
1.1172.2.7 raeburn 1448: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1449: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1450: if (&hostname($remotebalancer) ne '') {
1451: $offloadto = [$remotebalancer];
1452: }
1453: }
1454: } elsif (&hostname($rule_in_effect) ne '') {
1455: $offloadto = [$rule_in_effect];
1456: }
1457: }
1458: return $offloadto;
1459: }
1460:
1.1127 raeburn 1461: sub internet_dom_servers {
1462: my ($dom) = @_;
1463: my (%uniqservers,%servers);
1464: my $primaryserver = &hostname(&domain($dom,'primary'));
1465: my @machinedoms = &machine_domains($primaryserver);
1466: foreach my $mdom (@machinedoms) {
1467: my %currservers = %servers;
1468: my %server = &get_servers($mdom);
1469: %servers = (%currservers,%server);
1470: }
1471: my %by_hostname;
1472: foreach my $id (keys(%servers)) {
1473: push(@{$by_hostname{$servers{$id}}},$id);
1474: }
1475: foreach my $hostname (sort(keys(%by_hostname))) {
1476: if (@{$by_hostname{$hostname}} > 1) {
1477: my $match = 0;
1478: foreach my $id (@{$by_hostname{$hostname}}) {
1479: if (&host_domain($id) eq $dom) {
1480: $uniqservers{$id} = $hostname;
1481: $match = 1;
1482: }
1483: }
1484: unless ($match) {
1485: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1486: }
1487: } else {
1488: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1489: }
1490: }
1491: return %uniqservers;
1492: }
1493:
1.1 albertel 1494: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1495:
1.599 albertel 1496: my %homecache;
1.1 albertel 1497: sub homeserver {
1.230 stredwic 1498: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1499: my $index="$uname:$udom";
1.426 albertel 1500:
1.599 albertel 1501: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1502:
1503: my %servers = &get_servers($udom,'library');
1504: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1505: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1506: exists($badServerCache{$tryserver}));
1.841 albertel 1507:
1508: my $answer=reply("home:$udom:$uname",$tryserver);
1509: if ($answer eq 'found') {
1510: delete($badServerCache{$tryserver});
1511: return $homecache{$index}=$tryserver;
1512: } elsif ($answer eq 'no_host') {
1513: $badServerCache{$tryserver}=1;
1514: }
1.1 albertel 1515: }
1516: return 'no_host';
1.70 www 1517: }
1518:
1519: # ------------------------------------- Find the usernames behind a list of IDs
1520:
1521: sub idget {
1522: my ($udom,@ids)=@_;
1523: my %returnhash=();
1524:
1.841 albertel 1525: my %servers = &get_servers($udom,'library');
1526: foreach my $tryserver (keys(%servers)) {
1527: my $idlist=join('&',@ids);
1528: $idlist=~tr/A-Z/a-z/;
1529: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1530: my @answer=();
1531: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1532: @answer=split(/\&/,$reply);
1533: } ;
1534: my $i;
1535: for ($i=0;$i<=$#ids;$i++) {
1536: if ($answer[$i]) {
1537: $returnhash{$ids[$i]}=$answer[$i];
1538: }
1539: }
1540: }
1.70 www 1541: return %returnhash;
1542: }
1543:
1544: # ------------------------------------- Find the IDs behind a list of usernames
1545:
1546: sub idrget {
1547: my ($udom,@unames)=@_;
1548: my %returnhash=();
1.800 albertel 1549: foreach my $uname (@unames) {
1550: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1551: }
1.70 www 1552: return %returnhash;
1553: }
1554:
1555: # ------------------------------- Store away a list of names and associated IDs
1556:
1557: sub idput {
1558: my ($udom,%ids)=@_;
1559: my %servers=();
1.800 albertel 1560: foreach my $uname (keys(%ids)) {
1561: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1562: my $uhom=&homeserver($uname,$udom);
1.70 www 1563: if ($uhom ne 'no_host') {
1.800 albertel 1564: my $id=&escape($ids{$uname});
1.70 www 1565: $id=~tr/A-Z/a-z/;
1.800 albertel 1566: my $esc_unam=&escape($uname);
1.70 www 1567: if ($servers{$uhom}) {
1.800 albertel 1568: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1569: } else {
1.800 albertel 1570: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1571: }
1572: }
1.191 harris41 1573: }
1.800 albertel 1574: foreach my $server (keys(%servers)) {
1575: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1576: }
1.344 www 1577: }
1578:
1.1172.2.30 raeburn 1579: # ---------------------------------------- Delete unwanted IDs from ids.db file
1580:
1581: sub iddel {
1582: my ($udom,$idshashref,$uhome)=@_;
1583: my %result=();
1584: unless (ref($idshashref) eq 'HASH') {
1585: return %result;
1586: }
1587: my %servers=();
1588: while (my ($id,$uname) = each(%{$idshashref})) {
1589: my $uhom;
1590: if ($uhome) {
1591: $uhom = $uhome;
1592: } else {
1593: $uhom=&homeserver($uname,$udom);
1594: }
1595: if ($uhom ne 'no_host') {
1596: if ($servers{$uhom}) {
1597: $servers{$uhom}.='&'.&escape($id);
1598: } else {
1599: $servers{$uhom}=&escape($id);
1600: }
1601: }
1602: }
1603: foreach my $server (keys(%servers)) {
1604: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1605: }
1606: return %result;
1607: }
1608:
1.1023 raeburn 1609: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1610: sub dump_dom {
1.1165 droeschl 1611: my ($namespace, $udom, $regexp) = @_;
1612:
1613: $udom ||= $env{'user.domain'};
1614:
1615: return () unless $udom;
1616:
1617: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1618: }
1619:
1.1023 raeburn 1620: # ------------------------------------------ get items from domain db files
1.806 raeburn 1621:
1622: sub get_dom {
1.860 raeburn 1623: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1624: my $items='';
1625: foreach my $item (@$storearr) {
1626: $items.=&escape($item).'&';
1627: }
1628: $items=~s/\&$//;
1.860 raeburn 1629: if (!$udom) {
1630: $udom=$env{'user.domain'};
1631: if (defined(&domain($udom,'primary'))) {
1632: $uhome=&domain($udom,'primary');
1633: } else {
1.874 albertel 1634: undef($uhome);
1.860 raeburn 1635: }
1636: } else {
1637: if (!$uhome) {
1638: if (defined(&domain($udom,'primary'))) {
1639: $uhome=&domain($udom,'primary');
1640: }
1641: }
1642: }
1643: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1644: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1645: my %returnhash;
1.875 albertel 1646: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1647: return %returnhash;
1648: }
1.806 raeburn 1649: my @pairs=split(/\&/,$rep);
1650: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1651: return @pairs;
1652: }
1653: my $i=0;
1654: foreach my $item (@$storearr) {
1655: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1656: $i++;
1657: }
1658: return %returnhash;
1659: } else {
1.880 banghart 1660: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1661: }
1662: }
1663:
1664: # -------------------------------------------- put items in domain db files
1665:
1666: sub put_dom {
1.860 raeburn 1667: my ($namespace,$storehash,$udom,$uhome)=@_;
1668: if (!$udom) {
1669: $udom=$env{'user.domain'};
1670: if (defined(&domain($udom,'primary'))) {
1671: $uhome=&domain($udom,'primary');
1672: } else {
1.874 albertel 1673: undef($uhome);
1.860 raeburn 1674: }
1675: } else {
1676: if (!$uhome) {
1677: if (defined(&domain($udom,'primary'))) {
1678: $uhome=&domain($udom,'primary');
1679: }
1680: }
1681: }
1682: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1683: my $items='';
1684: foreach my $item (keys(%$storehash)) {
1685: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1686: }
1687: $items=~s/\&$//;
1688: return &reply("putdom:$udom:$namespace:$items",$uhome);
1689: } else {
1.860 raeburn 1690: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1691: }
1692: }
1693:
1.1023 raeburn 1694: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1695: sub newput_dom {
1.1023 raeburn 1696: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1697: my $result;
1698: if (!$udom) {
1699: $udom=$env{'user.domain'};
1700: }
1.1023 raeburn 1701: if ($udom) {
1702: my $uname = &get_domainconfiguser($udom);
1703: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1704: }
1705: return $result;
1706: }
1707:
1.1023 raeburn 1708: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1709: sub del_dom {
1.1023 raeburn 1710: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1711: if (ref($storearr) eq 'ARRAY') {
1712: if (!$udom) {
1713: $udom=$env{'user.domain'};
1714: }
1.1023 raeburn 1715: if ($udom) {
1716: my $uname = &get_domainconfiguser($udom);
1717: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1718: }
1719: }
1720: }
1721:
1.1023 raeburn 1722: # ----------------------------------construct domainconfig user for a domain
1723: sub get_domainconfiguser {
1724: my ($udom) = @_;
1725: return $udom.'-domainconfig';
1726: }
1727:
1.837 raeburn 1728: sub retrieve_inst_usertypes {
1729: my ($udom) = @_;
1730: my (%returnhash,@order);
1.989 raeburn 1731: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1732: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1733: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1734: %returnhash = %{$domdefs{'inststatustypes'}};
1735: @order = @{$domdefs{'inststatusorder'}};
1736: } else {
1737: if (defined(&domain($udom,'primary'))) {
1738: my $uhome=&domain($udom,'primary');
1739: my $rep=&reply("inst_usertypes:$udom",$uhome);
1740: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1741: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1742: return (\%returnhash,\@order);
1743: }
1744: my ($hashitems,$orderitems) = split(/:/,$rep);
1745: my @pairs=split(/\&/,$hashitems);
1746: foreach my $item (@pairs) {
1747: my ($key,$value)=split(/=/,$item,2);
1748: $key = &unescape($key);
1749: next if ($key =~ /^error: 2 /);
1750: $returnhash{$key}=&thaw_unescape($value);
1751: }
1752: my @esc_order = split(/\&/,$orderitems);
1753: foreach my $item (@esc_order) {
1754: push(@order,&unescape($item));
1755: }
1756: } else {
1757: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1758: }
1759: }
1760: return (\%returnhash,\@order);
1761: }
1762:
1.868 raeburn 1763: sub is_domainimage {
1764: my ($url) = @_;
1765: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1766: if (&domain($1) ne '') {
1767: return '1';
1768: }
1769: }
1770: return;
1771: }
1772:
1.899 raeburn 1773: sub inst_directory_query {
1774: my ($srch) = @_;
1775: my $udom = $srch->{'srchdomain'};
1776: my %results;
1777: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1778: my $outcome;
1.899 raeburn 1779: if ($homeserver ne '') {
1.904 albertel 1780: my $queryid=&reply("querysend:instdirsearch:".
1781: &escape($srch->{'srchby'}).':'.
1782: &escape($srch->{'srchterm'}).':'.
1783: &escape($srch->{'srchtype'}),$homeserver);
1784: my $host=&hostname($homeserver);
1785: if ($queryid !~/^\Q$host\E\_/) {
1786: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1787: return;
1788: }
1789: my $response = &get_query_reply($queryid);
1790: my $maxtries = 5;
1791: my $tries = 1;
1792: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1793: $response = &get_query_reply($queryid);
1794: $tries ++;
1795: }
1796:
1797: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1798: if ($response eq 'unavailable') {
1799: $outcome = $response;
1800: } else {
1801: $outcome = 'ok';
1802: my @matches = split(/\n/,$response);
1803: foreach my $match (@matches) {
1804: my ($key,$value) = split(/=/,$match);
1805: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1806: }
1.899 raeburn 1807: }
1808: }
1809: }
1.909 raeburn 1810: return ($outcome,%results);
1.899 raeburn 1811: }
1812:
1813: sub usersearch {
1814: my ($srch) = @_;
1815: my $dom = $srch->{'srchdomain'};
1816: my %results;
1817: my %libserv = &all_library();
1818: my $query = 'usersearch';
1819: foreach my $tryserver (keys(%libserv)) {
1820: if (&host_domain($tryserver) eq $dom) {
1821: my $host=&hostname($tryserver);
1822: my $queryid=
1.911 raeburn 1823: &reply("querysend:".&escape($query).':'.
1824: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1825: &escape($srch->{'srchtype'}).':'.
1826: &escape($srch->{'srchterm'}),$tryserver);
1827: if ($queryid !~/^\Q$host\E\_/) {
1828: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1829: next;
1.899 raeburn 1830: }
1831: my $reply = &get_query_reply($queryid);
1832: my $maxtries = 1;
1833: my $tries = 1;
1834: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1835: $reply = &get_query_reply($queryid);
1836: $tries ++;
1837: }
1838: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1839: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1840: } else {
1.911 raeburn 1841: my @matches;
1842: if ($reply =~ /\n/) {
1843: @matches = split(/\n/,$reply);
1844: } else {
1845: @matches = split(/\&/,$reply);
1846: }
1.899 raeburn 1847: foreach my $match (@matches) {
1848: my ($uname,$udom,%userhash);
1.911 raeburn 1849: foreach my $entry (split(/:/,$match)) {
1850: my ($key,$value) =
1851: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1852: $userhash{$key} = $value;
1853: if ($key eq 'username') {
1854: $uname = $value;
1855: } elsif ($key eq 'domain') {
1856: $udom = $value;
1.911 raeburn 1857: }
1.899 raeburn 1858: }
1859: $results{$uname.':'.$udom} = \%userhash;
1860: }
1861: }
1862: }
1863: }
1864: return %results;
1865: }
1866:
1.912 raeburn 1867: sub get_instuser {
1868: my ($udom,$uname,$id) = @_;
1869: my $homeserver = &domain($udom,'primary');
1870: my ($outcome,%results);
1871: if ($homeserver ne '') {
1872: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1873: &escape($id).':'.&escape($udom),$homeserver);
1874: my $host=&hostname($homeserver);
1875: if ($queryid !~/^\Q$host\E\_/) {
1876: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1877: return;
1878: }
1879: my $response = &get_query_reply($queryid);
1880: my $maxtries = 5;
1881: my $tries = 1;
1882: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1883: $response = &get_query_reply($queryid);
1884: $tries ++;
1885: }
1886: if (!&error($response) && $response ne 'refused') {
1887: if ($response eq 'unavailable') {
1888: $outcome = $response;
1889: } else {
1890: $outcome = 'ok';
1891: my @matches = split(/\n/,$response);
1892: foreach my $match (@matches) {
1893: my ($key,$value) = split(/=/,$match);
1894: $results{&unescape($key)} = &thaw_unescape($value);
1895: }
1896: }
1897: }
1898: }
1899: my %userinfo;
1900: if (ref($results{$uname}) eq 'HASH') {
1901: %userinfo = %{$results{$uname}};
1902: }
1903: return ($outcome,%userinfo);
1904: }
1905:
1906: sub inst_rulecheck {
1.923 raeburn 1907: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1908: my %returnhash;
1909: if ($udom ne '') {
1910: if (ref($rules) eq 'ARRAY') {
1911: @{$rules} = map {&escape($_);} (@{$rules});
1912: my $rulestr = join(':',@{$rules});
1913: my $homeserver=&domain($udom,'primary');
1914: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1915: my $response;
1916: if ($item eq 'username') {
1917: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1918: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1919: $homeserver));
1.923 raeburn 1920: } elsif ($item eq 'id') {
1921: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1922: ':'.&escape($id).':'.$rulestr,
1923: $homeserver));
1.945 raeburn 1924: } elsif ($item eq 'selfcreate') {
1925: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1926: &escape($udom).':'.&escape($uname).
1927: ':'.$rulestr,$homeserver));
1.923 raeburn 1928: }
1.912 raeburn 1929: if ($response ne 'refused') {
1930: my @pairs=split(/\&/,$response);
1931: foreach my $item (@pairs) {
1932: my ($key,$value)=split(/=/,$item,2);
1933: $key = &unescape($key);
1934: next if ($key =~ /^error: 2 /);
1935: $returnhash{$key}=&thaw_unescape($value);
1936: }
1937: }
1938: }
1939: }
1940: }
1941: return %returnhash;
1942: }
1943:
1944: sub inst_userrules {
1.923 raeburn 1945: my ($udom,$check) = @_;
1.912 raeburn 1946: my (%ruleshash,@ruleorder);
1947: if ($udom ne '') {
1948: my $homeserver=&domain($udom,'primary');
1949: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1950: my $response;
1951: if ($check eq 'id') {
1952: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1953: $homeserver);
1.943 raeburn 1954: } elsif ($check eq 'email') {
1955: $response=&reply('instemailrules:'.&escape($udom),
1956: $homeserver);
1.923 raeburn 1957: } else {
1958: $response=&reply('instuserrules:'.&escape($udom),
1959: $homeserver);
1960: }
1.912 raeburn 1961: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1962: ($response ne 'unknown_cmd') &&
1.912 raeburn 1963: ($response ne 'no_such_host')) {
1964: my ($hashitems,$orderitems) = split(/:/,$response);
1965: my @pairs=split(/\&/,$hashitems);
1966: foreach my $item (@pairs) {
1967: my ($key,$value)=split(/=/,$item,2);
1968: $key = &unescape($key);
1969: next if ($key =~ /^error: 2 /);
1970: $ruleshash{$key}=&thaw_unescape($value);
1971: }
1972: my @esc_order = split(/\&/,$orderitems);
1973: foreach my $item (@esc_order) {
1974: push(@ruleorder,&unescape($item));
1975: }
1976: }
1977: }
1978: }
1979: return (\%ruleshash,\@ruleorder);
1980: }
1981:
1.976 raeburn 1982: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1983:
1984: sub get_domain_defaults {
1985: my ($domain) = @_;
1986: my $cachetime = 60*60*24;
1987: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1988: if (defined($cached)) {
1989: if (ref($result) eq 'HASH') {
1990: return %{$result};
1991: }
1992: }
1993: my %domdefaults;
1994: my %domconfig =
1.989 raeburn 1995: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1996: 'requestcourses','inststatus',
1.1172.2.9 raeburn 1997: 'coursedefaults','usersessions',
1998: 'requestauthor'],$domain);
1.943 raeburn 1999: if (ref($domconfig{'defaults'}) eq 'HASH') {
2000: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2001: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2002: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2003: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2004: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2005: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2006: } else {
2007: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2008: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2009: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2010: }
1.976 raeburn 2011: if (ref($domconfig{'quotas'}) eq 'HASH') {
2012: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2013: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2014: } else {
2015: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2016: }
1.1172.2.6 raeburn 2017: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2018: foreach my $item (@usertools) {
2019: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2020: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2021: }
2022: }
1.1172.2.29 raeburn 2023: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2024: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2025: }
1.976 raeburn 2026: }
1.985 raeburn 2027: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 2028: foreach my $item ('official','unofficial','community') {
1.985 raeburn 2029: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2030: }
2031: }
1.1172.2.9 raeburn 2032: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2033: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2034: }
1.989 raeburn 2035: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2036: foreach my $item ('inststatustypes','inststatusorder') {
2037: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2038: }
2039: }
1.1047 raeburn 2040: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19 raeburn 2041: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2042: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2043: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1047 raeburn 2044: }
1.1172.2.30 raeburn 2045: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2046: $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
2047: $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
2048: $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
2049: }
1.1047 raeburn 2050: }
1.1073 raeburn 2051: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2052: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2053: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2054: }
2055: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2056: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2057: }
2058: }
1.1172.2.23 raeburn 2059: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2060: return %domdefaults;
2061: }
2062:
1.344 www 2063: # --------------------------------------------------- Assign a key to a student
2064:
2065: sub assign_access_key {
1.364 www 2066: #
2067: # a valid key looks like uname:udom#comments
2068: # comments are being appended
2069: #
1.498 www 2070: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2071: $kdom=
1.620 albertel 2072: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2073: $knum=
1.620 albertel 2074: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2075: $cdom=
1.620 albertel 2076: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2077: $cnum=
1.620 albertel 2078: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2079: $udom=$env{'user.name'} unless (defined($udom));
2080: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2081: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2082: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2083: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2084: # assigned to this person
2085: # - this should not happen,
1.345 www 2086: # unless something went wrong
2087: # the first time around
2088: # ready to assign
1.364 www 2089: $logentry=$1.'; '.$logentry;
1.496 www 2090: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2091: $kdom,$knum) eq 'ok') {
1.345 www 2092: # key now belongs to user
1.346 www 2093: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2094: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2095: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2096: return 'ok';
2097: } else {
2098: return
2099: 'error: Count not permanently assign key, will need to be re-entered later.';
2100: }
2101: } else {
2102: return 'error: Could not assign key, try again later.';
2103: }
1.364 www 2104: } elsif (!$existing{$ckey}) {
1.345 www 2105: # the key does not exist
2106: return 'error: The key does not exist';
2107: } else {
2108: # the key is somebody else's
2109: return 'error: The key is already in use';
2110: }
1.344 www 2111: }
2112:
1.364 www 2113: # ------------------------------------------ put an additional comment on a key
2114:
2115: sub comment_access_key {
2116: #
2117: # a valid key looks like uname:udom#comments
2118: # comments are being appended
2119: #
2120: my ($ckey,$cdom,$cnum,$logentry)=@_;
2121: $cdom=
1.620 albertel 2122: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2123: $cnum=
1.620 albertel 2124: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2125: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2126: if ($existing{$ckey}) {
2127: $existing{$ckey}.='; '.$logentry;
2128: # ready to assign
1.367 www 2129: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2130: $cdom,$cnum) eq 'ok') {
2131: return 'ok';
2132: } else {
2133: return 'error: Count not store comment.';
2134: }
2135: } else {
2136: # the key does not exist
2137: return 'error: The key does not exist';
2138: }
2139: }
2140:
1.344 www 2141: # ------------------------------------------------------ Generate a set of keys
2142:
2143: sub generate_access_keys {
1.364 www 2144: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2145: $cdom=
1.620 albertel 2146: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2147: $cnum=
1.620 albertel 2148: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2149: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2150: unless (($cdom) && ($cnum)) { return 0; }
2151: if ($number>10000) { return 0; }
2152: sleep(2); # make sure don't get same seed twice
2153: srand(time()^($$+($$<<15))); # from "Programming Perl"
2154: my $total=0;
2155: for (my $i=1;$i<=$number;$i++) {
2156: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2157: sprintf("%lx",int(100000*rand)).'-'.
2158: sprintf("%lx",int(100000*rand));
2159: $newkey=~s/1/g/g; # folks mix up 1 and l
2160: $newkey=~s/0/h/g; # and also 0 and O
2161: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2162: if ($existing{$newkey}) {
2163: $i--;
2164: } else {
1.364 www 2165: if (&put('accesskeys',
2166: { $newkey => '# generated '.localtime().
1.620 albertel 2167: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2168: '; '.$logentry },
2169: $cdom,$cnum) eq 'ok') {
1.344 www 2170: $total++;
2171: }
2172: }
2173: }
1.620 albertel 2174: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2175: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2176: return $total;
2177: }
2178:
2179: # ------------------------------------------------------- Validate an accesskey
2180:
2181: sub validate_access_key {
2182: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2183: $cdom=
1.620 albertel 2184: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2185: $cnum=
1.620 albertel 2186: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2187: $udom=$env{'user.domain'} unless (defined($udom));
2188: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2189: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2190: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2191: }
2192:
2193: # ------------------------------------- Find the section of student in a course
1.652 albertel 2194: sub devalidate_getsection_cache {
2195: my ($udom,$unam,$courseid)=@_;
2196: my $hashid="$udom:$unam:$courseid";
2197: &devalidate_cache_new('getsection',$hashid);
2198: }
1.298 matthew 2199:
1.815 albertel 2200: sub courseid_to_courseurl {
2201: my ($courseid) = @_;
2202: #already url style courseid
2203: return $courseid if ($courseid =~ m{^/});
2204:
2205: if (exists($env{'course.'.$courseid.'.num'})) {
2206: my $cnum = $env{'course.'.$courseid.'.num'};
2207: my $cdom = $env{'course.'.$courseid.'.domain'};
2208: return "/$cdom/$cnum";
2209: }
2210:
2211: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2212: if (exists($courseinfo{'num'})) {
2213: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2214: }
2215:
2216: return undef;
2217: }
2218:
1.298 matthew 2219: sub getsection {
2220: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2221: my $cachetime=1800;
1.551 albertel 2222:
2223: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2224: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2225: if (defined($cached)) { return $result; }
2226:
1.298 matthew 2227: my %Pending;
2228: my %Expired;
2229: #
2230: # Each role can either have not started yet (pending), be active,
2231: # or have expired.
2232: #
2233: # If there is an active role, we are done.
2234: #
2235: # If there is more than one role which has not started yet,
2236: # choose the one which will start sooner
2237: # If there is one role which has not started yet, return it.
2238: #
2239: # If there is more than one expired role, choose the one which ended last.
2240: # If there is a role which has expired, return it.
2241: #
1.815 albertel 2242: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2243: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2244: foreach my $key (keys(%roleshash)) {
1.479 albertel 2245: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2246: my $section=$1;
2247: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2248: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2249: my $now=time;
1.548 albertel 2250: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2251: $Expired{$end}=$section;
2252: next;
2253: }
1.548 albertel 2254: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2255: $Pending{$start}=$section;
2256: next;
2257: }
1.599 albertel 2258: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2259: }
2260: #
2261: # Presumedly there will be few matching roles from the above
2262: # loop and the sorting time will be negligible.
2263: if (scalar(keys(%Pending))) {
2264: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2265: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2266: }
2267: if (scalar(keys(%Expired))) {
2268: my @sorted = sort {$a <=> $b} keys(%Expired);
2269: my $time = pop(@sorted);
1.599 albertel 2270: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2271: }
1.599 albertel 2272: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2273: }
1.70 www 2274:
1.599 albertel 2275: sub save_cache {
2276: &purge_remembered();
1.722 albertel 2277: #&Apache::loncommon::validate_page();
1.620 albertel 2278: undef(%env);
1.780 albertel 2279: undef($env_loaded);
1.599 albertel 2280: }
1.452 albertel 2281:
1.599 albertel 2282: my $to_remember=-1;
2283: my %remembered;
2284: my %accessed;
2285: my $kicks=0;
2286: my $hits=0;
1.849 albertel 2287: sub make_key {
2288: my ($name,$id) = @_;
1.872 albertel 2289: if (length($id) > 65
2290: && length(&escape($id)) > 200) {
2291: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2292: }
1.849 albertel 2293: return &escape($name.':'.$id);
2294: }
2295:
1.599 albertel 2296: sub devalidate_cache_new {
2297: my ($name,$id,$debug) = @_;
2298: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2299: $id=&make_key($name,$id);
1.599 albertel 2300: $memcache->delete($id);
2301: delete($remembered{$id});
2302: delete($accessed{$id});
2303: }
2304:
2305: sub is_cached_new {
2306: my ($name,$id,$debug) = @_;
1.849 albertel 2307: $id=&make_key($name,$id);
1.599 albertel 2308: if (exists($remembered{$id})) {
1.1133 foxr 2309: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2310: $accessed{$id}=[&gettimeofday()];
2311: $hits++;
2312: return ($remembered{$id},1);
2313: }
2314: my $value = $memcache->get($id);
2315: if (!(defined($value))) {
2316: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2317: return (undef,undef);
1.416 albertel 2318: }
1.599 albertel 2319: if ($value eq '__undef__') {
2320: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2321: $value=undef;
2322: }
2323: &make_room($id,$value,$debug);
2324: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2325: return ($value,1);
2326: }
2327:
2328: sub do_cache_new {
2329: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2330: $id=&make_key($name,$id);
1.599 albertel 2331: my $setvalue=$value;
2332: if (!defined($setvalue)) {
2333: $setvalue='__undef__';
2334: }
1.623 albertel 2335: if (!defined($time) ) {
2336: $time=600;
2337: }
1.599 albertel 2338: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2339: my $result = $memcache->set($id,$setvalue,$time);
2340: if (! $result) {
1.872 albertel 2341: &logthis("caching of id -> $id failed");
1.910 albertel 2342: $memcache->disconnect_all();
1.872 albertel 2343: }
1.600 albertel 2344: # need to make a copy of $value
1.919 albertel 2345: &make_room($id,$value,$debug);
1.599 albertel 2346: return $value;
2347: }
2348:
2349: sub make_room {
2350: my ($id,$value,$debug)=@_;
1.919 albertel 2351:
2352: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2353: : $value;
1.599 albertel 2354: if ($to_remember<0) { return; }
2355: $accessed{$id}=[&gettimeofday()];
2356: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2357: my $to_kick;
2358: my $max_time=0;
2359: foreach my $other (keys(%accessed)) {
2360: if (&tv_interval($accessed{$other}) > $max_time) {
2361: $to_kick=$other;
2362: $max_time=&tv_interval($accessed{$other});
2363: }
2364: }
2365: delete($remembered{$to_kick});
2366: delete($accessed{$to_kick});
2367: $kicks++;
2368: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2369: return;
2370: }
2371:
1.599 albertel 2372: sub purge_remembered {
1.604 albertel 2373: #&logthis("Tossing ".scalar(keys(%remembered)));
2374: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2375: undef(%remembered);
2376: undef(%accessed);
1.428 albertel 2377: }
1.70 www 2378: # ------------------------------------- Read an entry from a user's environment
2379:
2380: sub userenvironment {
2381: my ($udom,$unam,@what)=@_;
1.976 raeburn 2382: my $items;
2383: foreach my $item (@what) {
2384: $items.=&escape($item).'&';
2385: }
2386: $items=~s/\&$//;
1.70 www 2387: my %returnhash=();
1.1009 raeburn 2388: my $uhome = &homeserver($unam,$udom);
2389: unless ($uhome eq 'no_host') {
2390: my @answer=split(/\&/,
2391: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2392: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2393: return %returnhash;
2394: }
1.1009 raeburn 2395: my $i;
2396: for ($i=0;$i<=$#what;$i++) {
2397: $returnhash{$what[$i]}=&unescape($answer[$i]);
2398: }
1.70 www 2399: }
2400: return %returnhash;
1.1 albertel 2401: }
2402:
1.617 albertel 2403: # ---------------------------------------------------------- Get a studentphoto
2404: sub studentphoto {
2405: my ($udom,$unam,$ext) = @_;
2406: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2407: if (defined($env{'request.course.id'})) {
1.708 raeburn 2408: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2409: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2410: return(&retrievestudentphoto($udom,$unam,$ext));
2411: } else {
2412: my ($result,$perm_reqd)=
1.707 albertel 2413: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2414: if ($result eq 'ok') {
2415: if (!($perm_reqd eq 'yes')) {
2416: return(&retrievestudentphoto($udom,$unam,$ext));
2417: }
2418: }
2419: }
2420: }
2421: } else {
2422: my ($result,$perm_reqd) =
1.707 albertel 2423: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2424: if ($result eq 'ok') {
2425: if (!($perm_reqd eq 'yes')) {
2426: return(&retrievestudentphoto($udom,$unam,$ext));
2427: }
2428: }
2429: }
2430: return '/adm/lonKaputt/lonlogo_broken.gif';
2431: }
2432:
2433: sub retrievestudentphoto {
2434: my ($udom,$unam,$ext,$type) = @_;
2435: my $home=&Apache::lonnet::homeserver($unam,$udom);
2436: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2437: if ($ret eq 'ok') {
2438: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2439: if ($type eq 'thumbnail') {
2440: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2441: }
2442: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2443: return $tokenurl;
2444: } else {
2445: if ($type eq 'thumbnail') {
2446: return '/adm/lonKaputt/genericstudent_tn.gif';
2447: } else {
2448: return '/adm/lonKaputt/lonlogo_broken.gif';
2449: }
1.617 albertel 2450: }
2451: }
2452:
1.263 www 2453: # -------------------------------------------------------------------- New chat
2454:
2455: sub chatsend {
1.724 raeburn 2456: my ($newentry,$anon,$group)=@_;
1.620 albertel 2457: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2458: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2459: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2460: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2461: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2462: &escape($newentry)).':'.$group,$chome);
1.292 www 2463: }
2464:
2465: # ------------------------------------------ Find current version of a resource
2466:
2467: sub getversion {
2468: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2469: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2470: return ¤tversion(&filelocation('',$fname));
2471: }
2472:
2473: sub currentversion {
2474: my $fname=shift;
2475: my $author=$fname;
2476: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2477: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2478: my $home=&homeserver($uname,$udom);
1.292 www 2479: if ($home eq 'no_host') {
2480: return -1;
2481: }
1.1112 www 2482: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2483: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2484: return -1;
2485: }
1.1112 www 2486: return $answer;
1.263 www 2487: }
2488:
1.1111 www 2489: #
2490: # Return special version number of resource if set by override, empty otherwise
2491: #
2492: sub usedversion {
2493: my $fname=shift;
2494: unless ($fname) { $fname=$env{'request.uri'}; }
2495: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2496: if ($urlversion) { return $urlversion; }
2497: return '';
2498: }
2499:
1.1 albertel 2500: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2501:
1.1 albertel 2502: sub subscribe {
2503: my $fname=shift;
1.761 raeburn 2504: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2505: $fname=~s/[\n\r]//g;
1.1 albertel 2506: my $author=$fname;
2507: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2508: my ($udom,$uname)=split(/\//,$author);
2509: my $home=homeserver($uname,$udom);
1.335 albertel 2510: if ($home eq 'no_host') {
2511: return 'not_found';
1.1 albertel 2512: }
2513: my $answer=reply("sub:$fname",$home);
1.64 www 2514: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2515: $answer.=' by '.$home;
2516: }
1.1 albertel 2517: return $answer;
2518: }
2519:
1.8 www 2520: # -------------------------------------------------------------- Replicate file
2521:
2522: sub repcopy {
2523: my $filename=shift;
1.23 www 2524: $filename=~s/\/+/\//g;
1.1142 raeburn 2525: my $londocroot = $perlvar{'lonDocRoot'};
2526: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2527: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2528: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2529: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2530: return &repcopy_userfile($filename);
2531: }
1.532 albertel 2532: $filename=~s/[\n\r]//g;
1.8 www 2533: my $transname="$filename.in.transfer";
1.828 www 2534: # FIXME: this should flock
1.607 raeburn 2535: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2536: my $remoteurl=subscribe($filename);
1.64 www 2537: if ($remoteurl =~ /^con_lost by/) {
2538: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2539: return 'unavailable';
1.8 www 2540: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2541: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2542: return 'not_found';
1.64 www 2543: } elsif ($remoteurl =~ /^rejected by/) {
2544: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2545: return 'forbidden';
1.20 www 2546: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2547: return 'ok';
1.8 www 2548: } else {
1.290 www 2549: my $author=$filename;
2550: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2551: my ($udom,$uname)=split(/\//,$author);
2552: my $home=homeserver($uname,$udom);
2553: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2554: my @parts=split(/\//,$filename);
2555: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2556: if ($path ne "$londocroot/res") {
1.8 www 2557: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2558: return 'bad_request';
1.8 www 2559: }
2560: my $count;
2561: for ($count=5;$count<$#parts;$count++) {
2562: $path.="/$parts[$count]";
2563: if ((-e $path)!=1) {
2564: mkdir($path,0777);
2565: }
2566: }
2567: my $ua=new LWP::UserAgent;
2568: my $request=new HTTP::Request('GET',"$remoteurl");
2569: my $response=$ua->request($request,$transname);
2570: if ($response->is_error()) {
2571: unlink($transname);
2572: my $message=$response->status_line;
1.672 albertel 2573: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2574: ." LWP get: $message: $filename</font>");
1.607 raeburn 2575: return 'unavailable';
1.8 www 2576: } else {
1.16 www 2577: if ($remoteurl!~/\.meta$/) {
2578: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2579: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2580: if ($mresponse->is_error()) {
2581: unlink($filename.'.meta');
2582: &logthis(
1.672 albertel 2583: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2584: }
2585: }
1.8 www 2586: rename($transname,$filename);
1.607 raeburn 2587: return 'ok';
1.8 www 2588: }
1.290 www 2589: }
1.8 www 2590: }
1.330 www 2591: }
2592:
2593: # ------------------------------------------------ Get server side include body
2594: sub ssi_body {
1.381 albertel 2595: my ($filelink,%form)=@_;
1.606 matthew 2596: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2597: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2598: }
1.953 www 2599: my $output='';
2600: my $response;
1.980 raeburn 2601: if ($filelink=~/^https?\:/) {
1.954 raeburn 2602: ($output,$response)=&externalssi($filelink);
1.953 www 2603: } else {
1.1004 droeschl 2604: $filelink .= $filelink=~/\?/ ? '&' : '?';
2605: $filelink .= 'inhibitmenu=yes';
1.953 www 2606: ($output,$response)=&ssi($filelink,%form);
2607: }
1.778 albertel 2608: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2609: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2610: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2611: if (wantarray) {
2612: return ($output, $response);
2613: } else {
2614: return $output;
2615: }
1.8 www 2616: }
2617:
1.15 www 2618: # --------------------------------------------------------- Server Side Include
2619:
1.782 albertel 2620: sub absolute_url {
2621: my ($host_name) = @_;
2622: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2623: if ($host_name eq '') {
2624: $host_name = $ENV{'SERVER_NAME'};
2625: }
2626: return $protocol.$host_name;
2627: }
2628:
1.942 foxr 2629: #
2630: # Server side include.
2631: # Parameters:
2632: # fn Possibly encrypted resource name/id.
2633: # form Hash that describes how the rendering should be done
2634: # and other things.
1.944 foxr 2635: # Returns:
1.950 raeburn 2636: # Scalar context: The content of the response.
2637: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2638: #
1.15 www 2639: sub ssi {
2640:
1.944 foxr 2641: my ($fn,%form)=@_;
1.15 www 2642: my $ua=new LWP::UserAgent;
1.23 www 2643: my $request;
1.711 albertel 2644:
2645: $form{'no_update_last_known'}=1;
1.895 albertel 2646: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2647: if (%form) {
1.782 albertel 2648: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2649: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2650: } else {
1.782 albertel 2651: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2652: }
2653:
1.15 www 2654: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2655: my $response= $ua->request($request);
1.944 foxr 2656: if (wantarray) {
1.1172.2.3 raeburn 2657: return ($response->content, $response);
1.944 foxr 2658: } else {
1.1172.2.3 raeburn 2659: return $response->content;
1.942 foxr 2660: }
1.324 www 2661: }
2662:
2663: sub externalssi {
2664: my ($url)=@_;
2665: my $ua=new LWP::UserAgent;
2666: my $request=new HTTP::Request('GET',$url);
2667: my $response=$ua->request($request);
1.954 raeburn 2668: if (wantarray) {
2669: return ($response->content, $response);
2670: } else {
2671: return $response->content;
2672: }
1.15 www 2673: }
1.254 www 2674:
1.492 albertel 2675: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2676:
2677: sub allowuploaded {
2678: my ($srcurl,$url)=@_;
2679: $url=&clutter(&declutter($url));
2680: my $dir=$url;
2681: $dir=~s/\/[^\/]+$//;
2682: my %httpref=();
2683: my $httpurl=&hreflocation('',$url);
2684: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2685: &Apache::lonnet::appenv(\%httpref);
1.254 www 2686: }
1.477 raeburn 2687:
1.1172.2.13 raeburn 2688: #
2689: # Determine if the current user should be able to edit a particular resource,
2690: # when viewing in course context.
2691: # (a) When viewing resource used to determine if "Edit" item is included in
2692: # Functions.
2693: # (b) When displaying folder contents in course editor, used to determine if
2694: # "Edit" link will be displayed alongside resource.
2695: #
2696: # input: six args -- filename (decluttered), course number, course domain,
2697: # url, symb (if registered) and group (if this is a group
2698: # item -- e.g., bulletin board, group page etc.).
2699: # output: array of five scalars --
2700: # $cfile -- url for file editing if editable on current server
2701: # $home -- homeserver of resource (i.e., for author if published,
2702: # or course if uploaded.).
2703: # $switchserver -- 1 if server switch will be needed.
2704: # $forceedit -- 1 if icon/link should be to go to edit mode
2705: # $forceview -- 1 if icon/link should be to go to view mode
2706: #
2707:
2708: sub can_edit_resource {
2709: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2710: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2711: #
2712: # For aboutme pages user can only edit his/her own.
2713: #
2714: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2715: my ($sdom,$sname) = ($1,$2);
2716: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2717: $home = $env{'user.home'};
2718: $cfile = $resurl;
2719: if ($env{'form.forceedit'}) {
2720: $forceview = 1;
2721: } else {
2722: $forceedit = 1;
2723: }
2724: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2725: } else {
2726: return;
2727: }
2728: }
2729:
2730: if ($env{'request.course.id'}) {
2731: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2732: if ($group ne '') {
2733: # if this is a group homepage or group bulletin board, check group privs
2734: my $allowed = 0;
2735: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2736: if ((&allowed('mdg',$env{'request.course.id'}.
2737: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2738: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2739: $allowed = 1;
2740: }
2741: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2742: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2743: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2744: $allowed = 1;
2745: }
2746: }
2747: if ($allowed) {
2748: $home=&homeserver($cnum,$cdom);
2749: if ($env{'form.forceedit'}) {
2750: $forceview = 1;
2751: } else {
2752: $forceedit = 1;
2753: }
2754: $cfile = $resurl;
2755: } else {
2756: return;
2757: }
2758: } else {
1.1172.2.15 raeburn 2759: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2760: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2761: return;
2762: }
2763: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2764: #
2765: # No edit allowed where CC has switched to student role.
2766: #
2767: return;
2768: }
2769: }
2770: }
2771:
2772: if ($file ne '') {
2773: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2774: if (&is_course_upload($file,$cnum,$cdom)) {
2775: $uploaded = 1;
2776: $incourse = 1;
2777: if ($file =~/\.(htm|html|css|js|txt)$/) {
2778: $cfile = &hreflocation('',$file);
2779: if ($env{'form.forceedit'}) {
2780: $forceview = 1;
2781: } else {
2782: $forceedit = 1;
2783: }
2784: }
2785: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2786: $incourse = 1;
2787: if ($env{'form.forceedit'}) {
2788: $forceview = 1;
2789: } else {
2790: $forceedit = 1;
2791: }
2792: $cfile = $resurl;
2793: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2794: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2795: $incourse = 1;
2796: if ($env{'form.forceedit'}) {
2797: $forceview = 1;
2798: } else {
2799: $forceedit = 1;
2800: }
2801: $cfile = $resurl;
2802: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2803: $incourse = 1;
2804: $cfile = $resurl.'/smpedit';
2805: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2806: $incourse = 1;
2807: if ($env{'form.forceedit'}) {
2808: $forceview = 1;
2809: } else {
2810: $forceedit = 1;
2811: }
2812: $cfile = $resurl;
1.1172.2.15 raeburn 2813: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2814: $incourse = 1;
2815: if ($env{'form.forceedit'}) {
2816: $forceview = 1;
2817: } else {
2818: $forceedit = 1;
2819: }
2820: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2821: }
2822: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2823: my $template = '/res/lib/templates/simpleproblem.problem';
2824: if (&is_on_map($template)) {
2825: $incourse = 1;
2826: $forceview = 1;
2827: $cfile = $template;
2828: }
2829: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2830: $incourse = 1;
2831: if ($env{'form.forceedit'}) {
2832: $forceview = 1;
2833: } else {
2834: $forceedit = 1;
2835: }
2836: $cfile = $resurl;
2837: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2838: $incourse = 1;
2839: $forceview = 1;
2840: if ($symb) {
2841: my ($map,$id,$res)=&decode_symb($symb);
2842: $env{'request.symb'} = $symb;
2843: $cfile = &clutter($res);
2844: } else {
2845: $cfile = $env{'form.suppurl'};
2846: $cfile =~ s{^http://}{};
2847: $cfile = '/adm/wrapper/ext/'.$cfile;
2848: }
1.1172.2.31! raeburn 2849: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
! 2850: if ($env{'form.forceedit'}) {
! 2851: $forceview = 1;
! 2852: } else {
! 2853: $forceedit = 1;
! 2854: }
! 2855: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2856: }
2857: }
2858: if ($uploaded || $incourse) {
2859: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2860: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2861: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2862: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2863: # Check that the user has permission to edit this resource
2864: my $setpriv = 1;
2865: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2866: if (defined($cfudom)) {
2867: $home=&homeserver($cfuname,$cfudom);
2868: $cfile=$file;
2869: }
2870: }
2871: if (($cfile ne '') && (!$incourse || $uploaded) &&
2872: (($home ne '') && ($home ne 'no_host'))) {
2873: my @ids=¤t_machine_ids();
2874: unless (grep(/^\Q$home\E$/,@ids)) {
2875: $switchserver=1;
2876: }
2877: }
2878: }
2879: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2880: }
2881:
2882: sub is_course_upload {
2883: my ($file,$cnum,$cdom) = @_;
2884: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2885: $uploadpath =~ s{^\/}{};
2886: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2887: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2888: return 1;
2889: }
2890: return;
2891: }
2892:
2893: sub in_course {
2894: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2895: if ($hideprivileged) {
2896: my $skipuser;
1.1172.2.23 raeburn 2897: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2898: my @possdoms = ($cdom);
2899: if ($coursehash{'checkforpriv'}) {
2900: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2901: }
2902: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2903: $skipuser = 1;
2904: if ($coursehash{'nothideprivileged'}) {
2905: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2906: my $user;
2907: if ($item =~ /:/) {
2908: $user = $item;
2909: } else {
2910: $user = join(':',split(/[\@]/,$item));
2911: }
2912: if ($user eq $uname.':'.$udom) {
2913: undef($skipuser);
2914: last;
2915: }
2916: }
2917: }
2918: if ($skipuser) {
2919: return 0;
2920: }
2921: }
2922: }
2923: $type ||= 'any';
2924: if (!defined($cdom) || !defined($cnum)) {
2925: my $cid = $env{'request.course.id'};
2926: $cdom = $env{'course.'.$cid.'.domain'};
2927: $cnum = $env{'course.'.$cid.'.num'};
2928: }
2929: my $typesref;
2930: if (($type eq 'any') || ($type eq 'all')) {
2931: $typesref = ['active','previous','future'];
2932: } elsif ($type eq 'previous' || $type eq 'future') {
2933: $typesref = [$type];
2934: }
2935: my %roles = &get_my_roles($uname,$udom,'userroles',
2936: $typesref,undef,[$cdom]);
2937: my ($tmp) = keys(%roles);
2938: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2939: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2940: if (@course_roles > 0) {
2941: return 1;
2942: }
2943: return 0;
2944: }
2945:
1.478 albertel 2946: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2947: # input: action, courseID, current domain, intended
1.637 raeburn 2948: # path to file, source of file, instruction to parse file for objects,
2949: # ref to hash for embedded objects,
2950: # ref to hash for codebase of java objects.
1.1095 raeburn 2951: # reference to scalar to accommodate mime type determined
2952: # from File::MMagic if $parser = parse.
1.637 raeburn 2953: #
1.485 raeburn 2954: # output: url to file (if action was uploaddoc),
2955: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2956: #
1.478 albertel 2957: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2958: # course.
1.477 raeburn 2959: #
1.478 albertel 2960: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2961: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2962: # course's home server.
1.477 raeburn 2963: #
1.478 albertel 2964: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2965: # be copied from $source (current location) to
2966: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2967: # and will then be copied to
2968: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2969: # course's home server.
1.485 raeburn 2970: #
1.481 raeburn 2971: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2972: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2973: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2974: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2975: # in course's home server.
1.637 raeburn 2976: #
1.477 raeburn 2977:
2978: sub process_coursefile {
1.1095 raeburn 2979: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2980: $mimetype)=@_;
1.477 raeburn 2981: my $fetchresult;
1.638 albertel 2982: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2983: if ($action eq 'propagate') {
1.638 albertel 2984: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2985: $home);
1.481 raeburn 2986: } else {
1.477 raeburn 2987: my $fpath = '';
2988: my $fname = $file;
1.478 albertel 2989: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2990: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2991: my $filepath = &build_filepath($fpath);
1.481 raeburn 2992: if ($action eq 'copy') {
2993: if ($source eq '') {
2994: $fetchresult = 'no source file';
2995: return $fetchresult;
2996: } else {
2997: my $destination = $filepath.'/'.$fname;
2998: rename($source,$destination);
2999: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3000: $home);
1.481 raeburn 3001: }
3002: } elsif ($action eq 'uploaddoc') {
3003: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3004: print $fh $env{'form.'.$source};
1.481 raeburn 3005: close($fh);
1.637 raeburn 3006: if ($parser eq 'parse') {
1.1024 raeburn 3007: my $mm = new File::MMagic;
1.1095 raeburn 3008: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3009: if ($type eq 'text/html') {
1.1024 raeburn 3010: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3011: unless ($parse_result eq 'ok') {
3012: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3013: }
1.637 raeburn 3014: }
1.1095 raeburn 3015: if (ref($mimetype)) {
3016: $$mimetype = $type;
3017: }
1.637 raeburn 3018: }
1.477 raeburn 3019: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3020: $home);
1.481 raeburn 3021: if ($fetchresult eq 'ok') {
3022: return '/uploaded/'.$fpath.'/'.$fname;
3023: } else {
3024: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3025: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3026: return '/adm/notfound.html';
3027: }
1.477 raeburn 3028: }
3029: }
1.485 raeburn 3030: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3031: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3032: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3033: }
3034: return $fetchresult;
3035: }
3036:
1.637 raeburn 3037: sub build_filepath {
3038: my ($fpath) = @_;
3039: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3040: unless ($fpath eq '') {
3041: my @parts=split('/',$fpath);
3042: foreach my $part (@parts) {
3043: $filepath.= '/'.$part;
3044: if ((-e $filepath)!=1) {
3045: mkdir($filepath,0777);
3046: }
3047: }
3048: }
3049: return $filepath;
3050: }
3051:
3052: sub store_edited_file {
1.638 albertel 3053: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3054: my $file = $primary_url;
3055: $file =~ s#^/uploaded/$docudom/$docuname/##;
3056: my $fpath = '';
3057: my $fname = $file;
3058: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3059: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3060: my $filepath = &build_filepath($fpath);
3061: open(my $fh,'>'.$filepath.'/'.$fname);
3062: print $fh $content;
3063: close($fh);
1.638 albertel 3064: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3065: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3066: $home);
1.637 raeburn 3067: if ($$fetchresult eq 'ok') {
3068: return '/uploaded/'.$fpath.'/'.$fname;
3069: } else {
1.638 albertel 3070: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3071: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3072: return '/adm/notfound.html';
3073: }
3074: }
3075:
1.531 albertel 3076: sub clean_filename {
1.831 albertel 3077: my ($fname,$args)=@_;
1.315 www 3078: # Replace Windows backslashes by forward slashes
1.257 www 3079: $fname=~s/\\/\//g;
1.831 albertel 3080: if (!$args->{'keep_path'}) {
3081: # Get rid of everything but the actual filename
3082: $fname=~s/^.*\/([^\/]+)$/$1/;
3083: }
1.315 www 3084: # Replace spaces by underscores
3085: $fname=~s/\s+/\_/g;
3086: # Replace all other weird characters by nothing
1.831 albertel 3087: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3088: # Replace all .\d. sequences with _\d. so they no longer look like version
3089: # numbers
3090: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3091: return $fname;
3092: }
1.1051 raeburn 3093: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3094: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3095: # image with the same aspect ratio as the original, but with dimensions which do
3096: # not exceed $resizewidth and $resizeheight.
3097:
1.984 neumanie 3098: sub resizeImage {
1.1051 raeburn 3099: my ($img_path,$resizewidth,$resizeheight) = @_;
3100: my $ima = Image::Magick->new;
3101: my $resized;
3102: if (-e $img_path) {
3103: $ima->Read($img_path);
3104: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3105: my $width = $ima->Get('width');
3106: my $height = $ima->Get('height');
3107: if ($width > $resizewidth) {
3108: my $factor = $width/$resizewidth;
3109: my $newheight = $height/$factor;
3110: $ima->Scale(width=>$resizewidth,height=>$newheight);
3111: $resized = 1;
3112: }
3113: }
3114: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3115: my $width = $ima->Get('width');
3116: my $height = $ima->Get('height');
3117: if ($height > $resizeheight) {
3118: my $factor = $height/$resizeheight;
3119: my $newwidth = $width/$factor;
3120: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3121: $resized = 1;
3122: }
3123: }
3124: if ($resized) {
3125: $ima->Write($img_path);
3126: }
3127: }
3128: return;
1.977 amueller 3129: }
3130:
1.608 albertel 3131: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3132: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3133: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3134: # $context - possible values: coursedoc, existingfile, overwrite,
3135: # canceloverwrite, or ''.
3136: # if 'coursedoc': upload to the current course
3137: # if 'existingfile': write file to tmp/overwrites directory
3138: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3139: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3140: # $subdir - directory in userfile to store the file into
1.858 raeburn 3141: # $parser - instruction to parse file for objects ($parser = parse)
3142: # $allfiles - reference to hash for embedded objects
3143: # $codebase - reference to hash for codebase of java objects
3144: # $desuname - username for permanent storage of uploaded file
3145: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3146: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3147: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3148: # $resizewidth - width (pixels) to which to resize uploaded image
3149: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3150: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3151: # from File::MMagic.
1.858 raeburn 3152: #
1.686 albertel 3153: # output: url of file in userspace, or error: <message>
3154: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3155:
1.531 albertel 3156: sub userfileupload {
1.1090 raeburn 3157: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3158: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3159: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3160: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3161: $fname=&clean_filename($fname);
1.1090 raeburn 3162: # See if there is anything left
1.257 www 3163: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3164: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3165: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3166: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3167: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3168: my $now = time;
1.1090 raeburn 3169: my $filepath;
1.1095 raeburn 3170: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3171: $filepath = 'tmp/helprequests/'.$now;
3172: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3173: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3174: '_'.$env{'user.domain'}.'/pending';
3175: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3176: my ($docuname,$docudom);
3177: if ($destudom) {
3178: $docudom = $destudom;
3179: } else {
3180: $docudom = $env{'user.domain'};
3181: }
3182: if ($destuname) {
3183: $docuname = $destuname;
3184: } else {
3185: $docuname = $env{'user.name'};
3186: }
3187: if (exists($env{'form.group'})) {
3188: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3189: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3190: }
3191: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3192: if ($context eq 'canceloverwrite') {
3193: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3194: if (-e $tempfile) {
3195: my @info = stat($tempfile);
3196: if ($info[9] eq $env{'form.timestamp'}) {
3197: unlink($tempfile);
3198: }
3199: }
3200: return;
1.523 raeburn 3201: }
3202: }
1.1090 raeburn 3203: # Create the directory if not present
1.741 raeburn 3204: my @parts=split(/\//,$filepath);
3205: my $fullpath = $perlvar{'lonDaemons'};
3206: for (my $i=0;$i<@parts;$i++) {
3207: $fullpath .= '/'.$parts[$i];
3208: if ((-e $fullpath)!=1) {
3209: mkdir($fullpath,0777);
3210: }
3211: }
3212: open(my $fh,'>'.$fullpath.'/'.$fname);
3213: print $fh $env{'form.'.$formname};
3214: close($fh);
1.1090 raeburn 3215: if ($context eq 'existingfile') {
3216: my @info = stat($fullpath.'/'.$fname);
3217: return ($fullpath.'/'.$fname,$info[9]);
3218: } else {
3219: return $fullpath.'/'.$fname;
3220: }
1.523 raeburn 3221: }
1.995 raeburn 3222: if ($subdir eq 'scantron') {
3223: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3224: } else {
1.995 raeburn 3225: $fname="$subdir/$fname";
3226: }
1.1090 raeburn 3227: if ($context eq 'coursedoc') {
1.638 albertel 3228: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3229: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3230: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3231: return &finishuserfileupload($docuname,$docudom,
3232: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3233: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3234: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3235: } else {
1.1172.2.21 raeburn 3236: if ($env{'form.folder'}) {
3237: $fname=$env{'form.folder'}.'/'.$fname;
3238: }
1.638 albertel 3239: return &process_coursefile('uploaddoc',$docuname,$docudom,
3240: $fname,$formname,$parser,
1.1095 raeburn 3241: $allfiles,$codebase,$mimetype);
1.481 raeburn 3242: }
1.719 banghart 3243: } elsif (defined($destuname)) {
3244: my $docuname=$destuname;
3245: my $docudom=$destudom;
1.860 raeburn 3246: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3247: $parser,$allfiles,$codebase,
1.1051 raeburn 3248: $thumbwidth,$thumbheight,
1.1095 raeburn 3249: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3250: } else {
1.638 albertel 3251: my $docuname=$env{'user.name'};
3252: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3253: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3254: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3255: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3256: }
1.860 raeburn 3257: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3258: $parser,$allfiles,$codebase,
1.1051 raeburn 3259: $thumbwidth,$thumbheight,
1.1095 raeburn 3260: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3261: }
1.271 www 3262: }
3263:
3264: sub finishuserfileupload {
1.860 raeburn 3265: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3266: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3267: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3268: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3269:
1.860 raeburn 3270: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3271: $file=$fname;
3272: if ($fname=~m|/|) {
3273: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3274: $path.=$fnamepath.'/';
3275: }
1.259 www 3276: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3277: my $count;
3278: for ($count=4;$count<=$#parts;$count++) {
3279: $filepath.="/$parts[$count]";
3280: if ((-e $filepath)!=1) {
3281: mkdir($filepath,0777);
3282: }
3283: }
1.984 neumanie 3284:
1.258 www 3285: # Save the file
3286: {
1.701 albertel 3287: if (!open(FH,'>'.$filepath.'/'.$file)) {
3288: &logthis('Failed to create '.$filepath.'/'.$file);
3289: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3290: return '/adm/notfound.html';
3291: }
1.1090 raeburn 3292: if ($context eq 'overwrite') {
1.1117 foxr 3293: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3294: my $target = $filepath.'/'.$file;
3295: if (-e $source) {
3296: my @info = stat($source);
3297: if ($info[9] eq $env{'form.timestamp'}) {
3298: unless (&File::Copy::move($source,$target)) {
3299: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3300: return "Moving from $source failed";
3301: }
3302: } else {
3303: return "Temporary file: $source had unexpected date/time for last modification";
3304: }
3305: } else {
3306: return "Temporary file: $source missing";
3307: }
3308: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3309: &logthis('Failed to write to '.$filepath.'/'.$file);
3310: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3311: return '/adm/notfound.html';
3312: }
1.570 albertel 3313: close(FH);
1.1051 raeburn 3314: if ($resizewidth && $resizeheight) {
3315: my $mm = new File::MMagic;
3316: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3317: if ($mime_type =~ m{^image/}) {
3318: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3319: }
1.977 amueller 3320: }
1.258 www 3321: }
1.1152 raeburn 3322: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3323: if (ref($mimetype)) {
3324: if ($$mimetype eq '') {
3325: my $mm = new File::MMagic;
3326: my $type = $mm->checktype_filename($filepath.'/'.$file);
3327: $$mimetype = $type;
3328: }
3329: }
3330: }
1.637 raeburn 3331: if ($parser eq 'parse') {
1.1152 raeburn 3332: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3333: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3334: $allfiles,$codebase);
3335: unless ($parse_result eq 'ok') {
3336: &logthis('Failed to parse '.$filepath.$file.
3337: ' for embedded media: '.$parse_result);
3338: }
1.637 raeburn 3339: }
3340: }
1.860 raeburn 3341: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3342: my $input = $filepath.'/'.$file;
3343: my $output = $filepath.'/'.'tn-'.$file;
3344: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3345: system("convert -sample $thumbsize $input $output");
3346: if (-e $filepath.'/'.'tn-'.$file) {
3347: $fetchthumb = 1;
3348: }
3349: }
1.858 raeburn 3350:
1.259 www 3351: # Notify homeserver to grep it
3352: #
1.984 neumanie 3353: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3354: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3355: if ($fetchresult eq 'ok') {
1.860 raeburn 3356: if ($fetchthumb) {
3357: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3358: if ($thumbresult ne 'ok') {
3359: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3360: $docuhome.': '.$thumbresult);
3361: }
3362: }
1.259 www 3363: #
1.258 www 3364: # Return the URL to it
1.494 albertel 3365: return '/uploaded/'.$path.$file;
1.263 www 3366: } else {
1.494 albertel 3367: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3368: ': '.$fetchresult);
1.263 www 3369: return '/adm/notfound.html';
1.858 raeburn 3370: }
1.493 albertel 3371: }
3372:
1.637 raeburn 3373: sub extract_embedded_items {
1.961 raeburn 3374: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3375: my @state = ();
1.1164 raeburn 3376: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3377: my %javafiles = (
3378: codebase => '',
3379: code => '',
3380: archive => ''
3381: );
3382: my %mediafiles = (
3383: src => '',
3384: movie => '',
3385: );
1.648 raeburn 3386: my $p;
3387: if ($content) {
3388: $p = HTML::LCParser->new($content);
3389: } else {
1.961 raeburn 3390: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3391: }
1.641 albertel 3392: while (my $t=$p->get_token()) {
1.640 albertel 3393: if ($t->[0] eq 'S') {
3394: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3395: push(@state, $tagname);
1.648 raeburn 3396: if (lc($tagname) eq 'allow') {
3397: &add_filetype($allfiles,$attr->{'src'},'src');
3398: }
1.640 albertel 3399: if (lc($tagname) eq 'img') {
3400: &add_filetype($allfiles,$attr->{'src'},'src');
3401: }
1.886 albertel 3402: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3403: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3404: &add_filetype($allfiles,$attr->{'href'},'href');
3405: }
1.886 albertel 3406: }
1.645 raeburn 3407: if (lc($tagname) eq 'script') {
1.1164 raeburn 3408: my $src;
1.645 raeburn 3409: if ($attr->{'archive'} =~ /\.jar$/i) {
3410: &add_filetype($allfiles,$attr->{'archive'},'archive');
3411: } else {
1.1164 raeburn 3412: if ($attr->{'src'} ne '') {
3413: $src = $attr->{'src'};
3414: &add_filetype($allfiles,$src,'src');
3415: }
3416: }
3417: my $text = $p->get_trimmed_text();
3418: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3419: my @swfargs = split(/,/,$1);
3420: foreach my $item (@swfargs) {
3421: $item =~ s/["']//g;
3422: $item =~ s/^\s+//;
3423: $item =~ s/\s+$//;
3424: }
3425: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3426: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3427: push(@{$related{$swfargs[0]}},$swfargs[2]);
3428: } else {
3429: $related{$swfargs[0]} = [$swfargs[2]];
3430: }
3431: }
1.645 raeburn 3432: }
3433: }
3434: if (lc($tagname) eq 'link') {
3435: if (lc($attr->{'rel'}) eq 'stylesheet') {
3436: &add_filetype($allfiles,$attr->{'href'},'href');
3437: }
3438: }
1.640 albertel 3439: if (lc($tagname) eq 'object' ||
3440: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3441: foreach my $item (keys(%javafiles)) {
3442: $javafiles{$item} = '';
3443: }
1.1164 raeburn 3444: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3445: $lastids{lc($tagname)} = $attr->{'id'};
3446: }
1.640 albertel 3447: }
3448: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3449: my $name = lc($attr->{'name'});
3450: foreach my $item (keys(%javafiles)) {
3451: if ($name eq $item) {
3452: $javafiles{$item} = $attr->{'value'};
3453: last;
3454: }
3455: }
1.1164 raeburn 3456: my $pathfrom;
1.640 albertel 3457: foreach my $item (keys(%mediafiles)) {
3458: if ($name eq $item) {
1.1164 raeburn 3459: $pathfrom = $attr->{'value'};
3460: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3461: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3462: last;
3463: }
3464: }
1.1164 raeburn 3465: if ($name eq 'flashvars') {
3466: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3467: }
3468: if ($pathfrom ne '') {
3469: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3470: $pathfrom);
3471: }
1.640 albertel 3472: }
3473: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3474: foreach my $item (keys(%javafiles)) {
3475: if ($attr->{$item}) {
3476: $javafiles{$item} = $attr->{$item};
3477: last;
3478: }
3479: }
3480: foreach my $item (keys(%mediafiles)) {
3481: if ($attr->{$item}) {
3482: &add_filetype($allfiles,$attr->{$item},$item);
3483: last;
3484: }
3485: }
1.1164 raeburn 3486: if (lc($tagname) eq 'embed') {
3487: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3488: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3489: $attr->{'src'});
3490: }
3491: }
1.640 albertel 3492: }
1.1164 raeburn 3493: if ($t->[4] =~ m{/>$}) {
3494: pop(@state);
3495: }
1.640 albertel 3496: } elsif ($t->[0] eq 'E') {
3497: my ($tagname) = ($t->[1]);
3498: if ($javafiles{'codebase'} ne '') {
3499: $javafiles{'codebase'} .= '/';
3500: }
3501: if (lc($tagname) eq 'applet' ||
3502: lc($tagname) eq 'object' ||
3503: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3504: ) {
3505: foreach my $item (keys(%javafiles)) {
3506: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3507: my $file=$javafiles{'codebase'}.$javafiles{$item};
3508: &add_filetype($allfiles,$file,$item);
3509: }
3510: }
3511: }
3512: pop @state;
3513: }
3514: }
1.1164 raeburn 3515: foreach my $id (sort(keys(%flashvars))) {
3516: if ($shockwave{$id} ne '') {
3517: my @pairs = split(/\&/,$flashvars{$id});
3518: foreach my $pair (@pairs) {
3519: my ($key,$value) = split(/\=/,$pair);
3520: if ($key eq 'thumb') {
3521: &add_filetype($allfiles,$value,$key);
3522: } elsif ($key eq 'content') {
3523: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3524: my ($ext) = ($value =~ /\.([^.]+)$/);
3525: if ($ext ne '') {
3526: &add_filetype($allfiles,$path.$value,$ext);
3527: }
3528: }
3529: }
3530: }
3531: }
1.637 raeburn 3532: return 'ok';
3533: }
3534:
1.639 albertel 3535: sub add_filetype {
3536: my ($allfiles,$file,$type)=@_;
3537: if (exists($allfiles->{$file})) {
3538: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3539: push(@{$allfiles->{$file}}, &escape($type));
3540: }
3541: } else {
3542: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3543: }
3544: }
3545:
1.1164 raeburn 3546: sub embedded_dependency {
3547: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3548: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3549: if (($identifier ne '') &&
3550: (ref($related->{$identifier}) eq 'ARRAY') &&
3551: ($pathfrom ne '')) {
3552: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3553: foreach my $dep (@{$related->{$identifier}}) {
3554: &add_filetype($allfiles,$path.$dep,'object');
3555: }
3556: }
3557: }
3558: return;
3559: }
3560:
1.493 albertel 3561: sub removeuploadedurl {
1.984 neumanie 3562: my ($url)=@_;
3563: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3564: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3565: }
3566:
3567: sub removeuserfile {
3568: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3569: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3570: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3571: if ($result eq 'ok') {
1.798 raeburn 3572: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3573: my $metafile = $fname.'.meta';
3574: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3575: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3576: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3577: my $sqlresult =
1.823 albertel 3578: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3579: 'portfolio_metadata',$group,
3580: 'delete');
1.798 raeburn 3581: }
3582: }
3583: return $result;
1.257 www 3584: }
1.15 www 3585:
1.530 albertel 3586: sub mkdiruserfile {
3587: my ($docuname,$docudom,$dir)=@_;
3588: my $home=&homeserver($docuname,$docudom);
3589: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3590: }
3591:
1.531 albertel 3592: sub renameuserfile {
3593: my ($docuname,$docudom,$old,$new)=@_;
3594: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3595: my $result = &reply("renameuserfile:$docudom:$docuname:".
3596: &escape("$old").':'.&escape("$new"),$home);
3597: if ($result eq 'ok') {
3598: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3599: my $oldmeta = $old.'.meta';
3600: my $newmeta = $new.'.meta';
3601: my $metaresult =
3602: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3603: my $url = "/uploaded/$docudom/$docuname/$old";
3604: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3605: my $sqlresult =
1.823 albertel 3606: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3607: 'portfolio_metadata',$group,
3608: 'delete');
1.798 raeburn 3609: }
3610: }
3611: return $result;
1.531 albertel 3612: }
3613:
1.14 www 3614: # ------------------------------------------------------------------------- Log
3615:
3616: sub log {
3617: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3618: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3619: }
3620:
3621: # ------------------------------------------------------------------ Course Log
1.352 www 3622: #
3623: # This routine flushes several buffers of non-mission-critical nature
3624: #
1.157 www 3625:
3626: sub flushcourselogs {
1.352 www 3627: &logthis('Flushing log buffers');
3628: #
3629: # course logs
3630: # This is a log of all transactions in a course, which can be used
3631: # for data mining purposes
3632: #
3633: # It also collects the courseid database, which lists last transaction
3634: # times and course titles for all courseids
3635: #
3636: my %courseidbuffer=();
1.921 raeburn 3637: foreach my $crsid (keys(%courselogs)) {
1.352 www 3638: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3639: &escape($courselogs{$crsid}),
3640: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3641: delete $courselogs{$crsid};
3642: } else {
3643: &logthis('Failed to flush log buffer for '.$crsid);
3644: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3645: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3646: " exceeded maximum size, deleting.</font>");
3647: delete $courselogs{$crsid};
3648: }
1.352 www 3649: }
1.920 raeburn 3650: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3651: 'description' => $coursedescrbuf{$crsid},
3652: 'inst_code' => $courseinstcodebuf{$crsid},
3653: 'type' => $coursetypebuf{$crsid},
3654: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3655: };
1.191 harris41 3656: }
1.352 www 3657: #
3658: # Write course id database (reverse lookup) to homeserver of courses
3659: # Is used in pickcourse
3660: #
1.840 albertel 3661: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3662: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3663: $courseidbuffer{$crs_home},
3664: $crs_home,'timeonly');
1.352 www 3665: }
3666: #
3667: # File accesses
3668: # Writes to the dynamic metadata of resources to get hit counts, etc.
3669: #
1.449 matthew 3670: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3671: if ($entry =~ /___count$/) {
3672: my ($dom,$name);
1.807 albertel 3673: ($dom,$name,undef)=
1.811 albertel 3674: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3675: if (! defined($dom) || $dom eq '' ||
3676: ! defined($name) || $name eq '') {
1.620 albertel 3677: my $cid = $env{'request.course.id'};
3678: $dom = $env{'request.'.$cid.'.domain'};
3679: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3680: }
1.450 matthew 3681: my $value = $accesshash{$entry};
3682: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3683: my %temphash=($url => $value);
1.449 matthew 3684: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3685: if ($result eq 'ok') {
3686: delete $accesshash{$entry};
3687: }
3688: } else {
1.811 albertel 3689: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3690: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3691: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3692: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3693: delete $accesshash{$entry};
3694: }
1.185 www 3695: }
1.191 harris41 3696: }
1.352 www 3697: #
3698: # Roles
3699: # Reverse lookup of user roles for course faculty/staff and co-authorship
3700: #
1.800 albertel 3701: foreach my $entry (keys(%userrolehash)) {
1.351 www 3702: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3703: split(/\:/,$entry);
3704: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3705: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3706: $rudom,$runame) eq 'ok') {
3707: delete $userrolehash{$entry};
3708: }
3709: }
1.662 raeburn 3710: #
3711: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3712: #
3713: my %domrolebuffer = ();
1.1000 raeburn 3714: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3715: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3716: if ($domrolebuffer{$rudom}) {
3717: $domrolebuffer{$rudom}.='&'.&escape($entry).
3718: '='.&escape($domainrolehash{$entry});
3719: } else {
3720: $domrolebuffer{$rudom}.=&escape($entry).
3721: '='.&escape($domainrolehash{$entry});
3722: }
3723: delete $domainrolehash{$entry};
3724: }
3725: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3726: my %servers = &get_servers($dom,'library');
3727: foreach my $tryserver (keys(%servers)) {
3728: unless (&reply('domroleput:'.$dom.':'.
3729: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3730: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3731: }
1.662 raeburn 3732: }
3733: }
1.186 www 3734: $dumpcount++;
1.157 www 3735: }
3736:
3737: sub courselog {
3738: my $what=shift;
1.158 www 3739: $what=time.':'.$what;
1.620 albertel 3740: unless ($env{'request.course.id'}) { return ''; }
3741: $coursedombuf{$env{'request.course.id'}}=
3742: $env{'course.'.$env{'request.course.id'}.'.domain'};
3743: $coursenumbuf{$env{'request.course.id'}}=
3744: $env{'course.'.$env{'request.course.id'}.'.num'};
3745: $coursehombuf{$env{'request.course.id'}}=
3746: $env{'course.'.$env{'request.course.id'}.'.home'};
3747: $coursedescrbuf{$env{'request.course.id'}}=
3748: $env{'course.'.$env{'request.course.id'}.'.description'};
3749: $courseinstcodebuf{$env{'request.course.id'}}=
3750: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3751: $courseownerbuf{$env{'request.course.id'}}=
3752: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3753: $coursetypebuf{$env{'request.course.id'}}=
3754: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3755: if (defined $courselogs{$env{'request.course.id'}}) {
3756: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3757: } else {
1.620 albertel 3758: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3759: }
1.620 albertel 3760: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3761: &flushcourselogs();
3762: }
1.158 www 3763: }
3764:
3765: sub courseacclog {
3766: my $fnsymb=shift;
1.620 albertel 3767: unless ($env{'request.course.id'}) { return ''; }
3768: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3769: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3770: $what.=':POST';
1.583 matthew 3771: # FIXME: Probably ought to escape things....
1.800 albertel 3772: foreach my $key (keys(%env)) {
3773: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3774: my $formitem = $1;
3775: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3776: $what.=':'.$formitem.'='.$env{$key};
3777: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3778: $what.=':'.$formitem.'='.$env{$key};
3779: }
1.158 www 3780: }
1.191 harris41 3781: }
1.583 matthew 3782: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3783: # FIXME: We should not be depending on a form parameter that someone
3784: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3785: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3786: $what.= ':POST';
3787: # FIXME: Probably ought to escape things....
3788: foreach my $element ('courseexp','crsfulltext','crsrelated',
3789: 'crsdiscuss') {
1.620 albertel 3790: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3791: }
3792: }
1.158 www 3793: }
3794: &courselog($what);
1.149 www 3795: }
3796:
1.185 www 3797: sub countacc {
3798: my $url=&declutter(shift);
1.458 matthew 3799: return if (! defined($url) || $url eq '');
1.620 albertel 3800: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3801: #
3802: # Mark that this url was used in this course
3803: #
1.620 albertel 3804: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3805: #
3806: # Increase the access count for this resource in this child process
3807: #
1.281 www 3808: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3809: $accesshash{$key}++;
1.185 www 3810: }
1.349 www 3811:
1.361 www 3812: sub linklog {
3813: my ($from,$to)=@_;
3814: $from=&declutter($from);
3815: $to=&declutter($to);
3816: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3817: $accesshash{$to.'___'.$from.'___goto'}=1;
3818: }
1.1160 www 3819:
3820: sub statslog {
3821: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3822: if ($users<2) { return; }
3823: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3824: 'course' => $env{'request.course.id'},
3825: 'sections' => '"all"',
3826: 'num_students' => $users,
3827: 'part' => $part,
3828: 'symb' => $symb,
3829: 'mean_tries' => $av_attempts,
3830: 'deg_of_diff' => $degdiff});
3831: foreach my $key (keys(%dynstore)) {
3832: $accesshash{$key}=$dynstore{$key};
3833: }
3834: }
1.361 www 3835:
1.349 www 3836: sub userrolelog {
3837: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3838: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3839: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3840: $userrolehash
3841: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3842: =$tend.':'.$tstart;
1.662 raeburn 3843: }
1.1169 droeschl 3844: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3845: $userrolehash
3846: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3847: =$tend.':'.$tstart;
3848: }
1.1169 droeschl 3849: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3850: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3851: $domainrolehash
3852: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3853: = $tend.':'.$tstart;
3854: }
1.351 www 3855: }
3856:
1.957 raeburn 3857: sub courserolelog {
3858: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3859: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3860: my $cdom = $1;
3861: my $cnum = $2;
3862: my $sec = $3;
3863: my $namespace = 'rolelog';
3864: my %storehash = (
3865: role => $trole,
3866: start => $tstart,
3867: end => $tend,
3868: selfenroll => $selfenroll,
3869: context => $context,
3870: );
3871: if ($trole eq 'gr') {
3872: $namespace = 'groupslog';
3873: $storehash{'group'} = $sec;
3874: } else {
3875: $storehash{'section'} = $sec;
3876: }
3877: &write_log('course',$namespace,\%storehash,$delflag,$username,
3878: $domain,$cnum,$cdom);
3879: if (($trole ne 'st') || ($sec ne '')) {
3880: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3881: }
3882: }
3883: return;
3884: }
3885:
1.1172.2.9 raeburn 3886: sub domainrolelog {
3887: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3888: if ($area =~ m{^/($match_domain)/$}) {
3889: my $cdom = $1;
3890: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3891: my $namespace = 'rolelog';
3892: my %storehash = (
3893: role => $trole,
3894: start => $tstart,
3895: end => $tend,
3896: context => $context,
3897: );
3898: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3899: $domain,$domconfiguser,$cdom);
3900: }
3901: return;
3902:
3903: }
3904:
3905: sub coauthorrolelog {
3906: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3907: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3908: my $audom = $1;
3909: my $auname = $2;
3910: my $namespace = 'rolelog';
3911: my %storehash = (
3912: role => $trole,
3913: start => $tstart,
3914: end => $tend,
3915: context => $context,
3916: );
3917: &write_log('author',$namespace,\%storehash,$delflag,$username,
3918: $domain,$auname,$audom);
3919: }
3920: return;
3921: }
3922:
1.351 www 3923: sub get_course_adv_roles {
1.948 raeburn 3924: my ($cid,$codes) = @_;
1.620 albertel 3925: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3926: my %coursehash=&coursedescription($cid);
1.988 raeburn 3927: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3928: my %nothide=();
1.800 albertel 3929: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3930: if ($user !~ /:/) {
3931: $nothide{join(':',split(/[\@]/,$user))}=1;
3932: } else {
3933: $nothide{$user}=1;
3934: }
1.470 www 3935: }
1.1172.2.23 raeburn 3936: my @possdoms = ($coursehash{'domain'});
3937: if ($coursehash{'checkforpriv'}) {
3938: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3939: }
1.351 www 3940: my %returnhash=();
3941: my %dumphash=
3942: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3943: my $now=time;
1.997 raeburn 3944: my %privileged;
1.1000 raeburn 3945: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3946: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3947: if (($tstart) && ($tstart<0)) { next; }
3948: if (($tend) && ($tend<$now)) { next; }
3949: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3950: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3951: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 3952: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 3953: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3954: if ($role eq 'cr') { next; }
1.948 raeburn 3955: if ($codes) {
3956: if ($section) { $role .= ':'.$section; }
3957: if ($returnhash{$role}) {
3958: $returnhash{$role}.=','.$username.':'.$domain;
3959: } else {
3960: $returnhash{$role}=$username.':'.$domain;
3961: }
1.351 www 3962: } else {
1.988 raeburn 3963: my $key=&plaintext($role,$crstype);
1.973 bisitz 3964: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3965: if ($returnhash{$key}) {
3966: $returnhash{$key}.=','.$username.':'.$domain;
3967: } else {
3968: $returnhash{$key}=$username.':'.$domain;
3969: }
1.351 www 3970: }
1.948 raeburn 3971: }
1.400 www 3972: return %returnhash;
3973: }
3974:
3975: sub get_my_roles {
1.937 raeburn 3976: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3977: unless (defined($uname)) { $uname=$env{'user.name'}; }
3978: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3979: my (%dumphash,%nothide);
1.1086 raeburn 3980: if ($context eq 'userroles') {
1.1166 raeburn 3981: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 3982: } else {
1.1172.2.23 raeburn 3983: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3984: if ($hidepriv) {
3985: my %coursehash=&coursedescription($udom.'_'.$uname);
3986: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3987: if ($user !~ /:/) {
3988: $nothide{join(':',split(/[\@]/,$user))} = 1;
3989: } else {
3990: $nothide{$user} = 1;
3991: }
3992: }
3993: }
1.858 raeburn 3994: }
1.400 www 3995: my %returnhash=();
3996: my $now=time;
1.999 raeburn 3997: my %privileged;
1.800 albertel 3998: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3999: my ($role,$tend,$tstart);
4000: if ($context eq 'userroles') {
1.1149 raeburn 4001: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4002: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4003: } else {
4004: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4005: }
1.400 www 4006: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4007: my $status = 'active';
1.939 raeburn 4008: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4009: $status = 'previous';
4010: }
4011: if (($tstart) && ($now<$tstart)) {
4012: $status = 'future';
4013: }
4014: if (ref($types) eq 'ARRAY') {
4015: if (!grep(/^\Q$status\E$/,@{$types})) {
4016: next;
4017: }
4018: } else {
4019: if ($status ne 'active') {
4020: next;
4021: }
4022: }
1.867 raeburn 4023: my ($rolecode,$username,$domain,$section,$area);
4024: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4025: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4026: (undef,$domain,$username,$section) = split(/\//,$area);
4027: } else {
4028: ($role,$username,$domain,$section) = split(/\:/,$entry);
4029: }
1.832 raeburn 4030: if (ref($roledoms) eq 'ARRAY') {
4031: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4032: next;
4033: }
4034: }
4035: if (ref($roles) eq 'ARRAY') {
4036: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4037: if ($role =~ /^cr\//) {
4038: if (!grep(/^cr$/,@{$roles})) {
4039: next;
4040: }
1.1104 raeburn 4041: } elsif ($role =~ /^gr\//) {
4042: if (!grep(/^gr$/,@{$roles})) {
4043: next;
4044: }
1.922 raeburn 4045: } else {
4046: next;
4047: }
1.832 raeburn 4048: }
1.867 raeburn 4049: }
1.937 raeburn 4050: if ($hidepriv) {
1.1172.2.23 raeburn 4051: my @privroles = ('dc','su');
1.999 raeburn 4052: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4053: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4054: } else {
1.1172.2.23 raeburn 4055: my $possdoms = [$domain];
4056: if (ref($roledoms) eq 'ARRAY') {
4057: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4058: }
1.1172.2.23 raeburn 4059: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4060: if (!$nothide{$username.':'.$domain}) {
4061: next;
4062: }
4063: }
1.937 raeburn 4064: }
4065: }
1.933 raeburn 4066: if ($withsec) {
4067: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4068: $tstart.':'.$tend;
4069: } else {
4070: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4071: }
1.832 raeburn 4072: }
1.373 www 4073: return %returnhash;
1.399 www 4074: }
4075:
4076: # ----------------------------------------------------- Frontpage Announcements
4077: #
4078: #
4079:
4080: sub postannounce {
4081: my ($server,$text)=@_;
1.844 albertel 4082: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4083: unless ($text=~/\w/) { $text=''; }
4084: return &reply('setannounce:'.&escape($text),$server);
4085: }
4086:
4087: sub getannounce {
1.448 albertel 4088:
4089: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4090: my $announcement='';
1.800 albertel 4091: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4092: close($fh);
1.399 www 4093: if ($announcement=~/\w/) {
4094: return
4095: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4096: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4097: } else {
4098: return '';
4099: }
4100: } else {
4101: return '';
4102: }
1.351 www 4103: }
1.353 www 4104:
4105: # ---------------------------------------------------------- Course ID routines
4106: # Deal with domain's nohist_courseid.db files
4107: #
4108:
4109: sub courseidput {
1.921 raeburn 4110: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4111: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4112: my $outcome;
4113: if ($caller eq 'timeonly') {
4114: my $cids = '';
4115: foreach my $item (keys(%$storehash)) {
4116: $cids.=&escape($item).'&';
4117: }
4118: $cids=~s/\&$//;
4119: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4120: $coursehome);
4121: } else {
4122: my $items = '';
4123: foreach my $item (keys(%$storehash)) {
4124: $items.= &escape($item).'='.
4125: &freeze_escape($$storehash{$item}).'&';
4126: }
4127: $items=~s/\&$//;
4128: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4129: $coursehome);
1.918 raeburn 4130: }
4131: if ($outcome eq 'unknown_cmd') {
4132: my $what;
4133: foreach my $cid (keys(%$storehash)) {
4134: $what .= &escape($cid).'=';
1.921 raeburn 4135: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4136: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4137: }
4138: $what =~ s/\:$/&/;
4139: }
4140: $what =~ s/\&$//;
4141: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4142: } else {
4143: return $outcome;
4144: }
1.353 www 4145: }
4146:
4147: sub courseiddump {
1.921 raeburn 4148: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4149: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4150: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 4151: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 4152: my $as_hash = 1;
4153: my %returnhash;
4154: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4155: my %libserv = &all_library();
4156: foreach my $tryserver (keys(%libserv)) {
4157: if ( ( $hostidflag == 1
4158: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4159: || (!defined($hostidflag)) ) {
4160:
1.918 raeburn 4161: if (($domfilter eq '') ||
4162: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4163: my $rep;
4164: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4165: $rep = &LONCAPA::Lond::dump_course_id_handler(
4166: join(":", (&host_domain($tryserver), $sincefilter,
4167: &escape($descfilter), &escape($instcodefilter),
4168: &escape($ownerfilter), &escape($coursefilter),
4169: &escape($typefilter), &escape($regexp_ok),
4170: $as_hash, &escape($selfenrollonly),
4171: &escape($catfilter), $showhidden, $caller,
4172: &escape($cloner), &escape($cc_clone), $cloneonly,
4173: &escape($createdbefore), &escape($createdafter),
4174: &escape($creationcontext), $domcloner)));
4175: } else {
4176: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4177: $sincefilter.':'.&escape($descfilter).':'.
4178: &escape($instcodefilter).':'.&escape($ownerfilter).
4179: ':'.&escape($coursefilter).':'.&escape($typefilter).
4180: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4181: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4182: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4183: &escape($cc_clone).':'.$cloneonly.':'.
4184: &escape($createdbefore).':'.&escape($createdafter).':'.
4185: &escape($creationcontext).':'.$domcloner,
4186: $tryserver);
4187: }
4188:
1.918 raeburn 4189: my @pairs=split(/\&/,$rep);
4190: foreach my $item (@pairs) {
4191: my ($key,$value)=split(/\=/,$item,2);
4192: $key = &unescape($key);
4193: next if ($key =~ /^error: 2 /);
4194: my $result = &thaw_unescape($value);
4195: if (ref($result) eq 'HASH') {
4196: $returnhash{$key}=$result;
4197: } else {
1.921 raeburn 4198: my @responses = split(/:/,$value);
4199: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4200: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4201: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4202: }
1.1008 raeburn 4203: }
1.353 www 4204: }
4205: }
4206: }
4207: }
4208: return %returnhash;
4209: }
4210:
1.1055 raeburn 4211: sub courselastaccess {
4212: my ($cdom,$cnum,$hostidref) = @_;
4213: my %returnhash;
4214: if ($cdom && $cnum) {
4215: my $chome = &homeserver($cnum,$cdom);
4216: if ($chome ne 'no_host') {
4217: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4218: &extract_lastaccess(\%returnhash,$rep);
4219: }
4220: } else {
4221: if (!$cdom) { $cdom=''; }
4222: my %libserv = &all_library();
4223: foreach my $tryserver (keys(%libserv)) {
4224: if (ref($hostidref) eq 'ARRAY') {
4225: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4226: }
4227: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4228: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4229: &extract_lastaccess(\%returnhash,$rep);
4230: }
4231: }
4232: }
4233: return %returnhash;
4234: }
4235:
4236: sub extract_lastaccess {
4237: my ($returnhash,$rep) = @_;
4238: if (ref($returnhash) eq 'HASH') {
4239: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4240: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4241: $rep eq '') {
4242: my @pairs=split(/\&/,$rep);
4243: foreach my $item (@pairs) {
4244: my ($key,$value)=split(/\=/,$item,2);
4245: $key = &unescape($key);
4246: next if ($key =~ /^error: 2 /);
4247: $returnhash->{$key} = &thaw_unescape($value);
4248: }
4249: }
4250: }
4251: return;
4252: }
4253:
1.658 raeburn 4254: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4255:
4256: sub dcmailput {
1.685 raeburn 4257: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4258: my $status = &Apache::lonnet::critical(
1.740 www 4259: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4260: &escape($message),$server);
1.662 raeburn 4261: return $status;
4262: }
4263:
1.658 raeburn 4264: sub dcmaildump {
4265: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4266: my %returnhash=();
1.846 albertel 4267:
4268: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4269: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4270: &escape($enddate).':';
4271: my @esc_senders=map { &escape($_)} @$senders;
4272: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4273: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4274: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4275: if (($key) && ($value)) {
4276: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4277: }
4278: }
4279: }
4280: return %returnhash;
4281: }
1.662 raeburn 4282: # ---------------------------------------------------------- Domain roles
4283:
4284: sub get_domain_roles {
4285: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4286: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4287: $startdate = '.';
4288: }
1.1018 raeburn 4289: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4290: $enddate = '.';
4291: }
1.922 raeburn 4292: my $rolelist;
4293: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4294: $rolelist = join('&',@{$roles});
1.922 raeburn 4295: }
1.662 raeburn 4296: my %personnel = ();
1.841 albertel 4297:
4298: my %servers = &get_servers($dom,'library');
4299: foreach my $tryserver (keys(%servers)) {
4300: %{$personnel{$tryserver}}=();
4301: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4302: &escape($startdate).':'.
4303: &escape($enddate).':'.
4304: &escape($rolelist), $tryserver))) {
4305: my ($key,$value) = split(/\=/,$line,2);
4306: if (($key) && ($value)) {
4307: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4308: }
4309: }
1.662 raeburn 4310: }
4311: return %personnel;
4312: }
1.658 raeburn 4313:
1.1057 www 4314: # ----------------------------------------------------------- Interval timing
1.149 www 4315:
1.1153 www 4316: {
4317: # Caches needed for speedup of navmaps
4318: # We don't want to cache this for very long at all (5 seconds at most)
4319: #
4320: # The user for whom we cache
4321: my $cachedkey='';
4322: # The cached times for this user
4323: my %cachedtimes=();
4324: # When this was last done
4325: my $cachedtime=();
4326:
4327: sub load_all_first_access {
1.1154 raeburn 4328: my ($uname,$udom)=@_;
1.1156 www 4329: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4330: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4331: return;
4332: }
4333: $cachedtime=time;
4334: $cachedkey=$uname.':'.$udom;
4335: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4336: }
4337:
1.504 albertel 4338: sub get_first_access {
1.1162 raeburn 4339: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4340: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4341: if ($argsymb) { $symb=$argsymb; }
4342: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4343: if ($argmap) { $map = $argmap; }
1.926 albertel 4344: if ($type eq 'course') {
4345: $res='course';
4346: } elsif ($type eq 'map') {
1.588 albertel 4347: $res=&symbread($map);
4348: } else {
4349: $res=$symb;
4350: }
1.1153 www 4351: &load_all_first_access($uname,$udom);
4352: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4353: }
4354:
4355: sub set_first_access {
1.1162 raeburn 4356: my ($type,$interval)=@_;
1.790 albertel 4357: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4358: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4359: if ($type eq 'course') {
4360: $res='course';
4361: } elsif ($type eq 'map') {
1.588 albertel 4362: $res=&symbread($map);
4363: } else {
4364: $res=$symb;
4365: }
1.1153 www 4366: $cachedkey='';
1.1162 raeburn 4367: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4368: if (!$firstaccess) {
1.1162 raeburn 4369: my $start = time;
4370: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4371: $udom,$uname);
4372: if ($putres eq 'ok') {
4373: &put('timerinterval',{"$courseid\0$res"=>$interval},
4374: $udom,$uname);
4375: &appenv(
4376: {
4377: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4378: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4379: }
4380: );
4381: }
4382: return $putres;
1.505 albertel 4383: }
4384: return 'already_set';
1.504 albertel 4385: }
1.1153 www 4386: }
1.110 www 4387: # --------------------------------------------- Set Expire Date for Spreadsheet
4388:
4389: sub expirespread {
4390: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4391: my $cid=$env{'request.course.id'};
1.110 www 4392: if ($cid) {
4393: my $now=time;
4394: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4395: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4396: $env{'course.'.$cid.'.num'}.
1.110 www 4397: ':nohist_expirationdates:'.
4398: &escape($key).'='.$now,
1.620 albertel 4399: $env{'course.'.$cid.'.home'})
1.110 www 4400: }
4401: return 'ok';
1.14 www 4402: }
4403:
1.109 www 4404: # ----------------------------------------------------- Devalidate Spreadsheets
4405:
4406: sub devalidate {
1.325 www 4407: my ($symb,$uname,$udom)=@_;
1.620 albertel 4408: my $cid=$env{'request.course.id'};
1.109 www 4409: if ($cid) {
1.391 matthew 4410: # delete the stored spreadsheets for
4411: # - the student level sheet of this user in course's homespace
4412: # - the assessment level sheet for this resource
4413: # for this user in user's homespace
1.553 albertel 4414: # - current conditional state info
1.325 www 4415: my $key=$uname.':'.$udom.':';
1.109 www 4416: my $status=
1.299 matthew 4417: &del('nohist_calculatedsheets',
1.391 matthew 4418: [$key.'studentcalc:'],
1.620 albertel 4419: $env{'course.'.$cid.'.domain'},
4420: $env{'course.'.$cid.'.num'})
1.133 albertel 4421: .' '.
4422: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4423: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4424: unless ($status eq 'ok ok') {
4425: &logthis('Could not devalidate spreadsheet '.
1.325 www 4426: $uname.' at '.$udom.' for '.
1.109 www 4427: $symb.': '.$status);
1.133 albertel 4428: }
1.553 albertel 4429: &delenv('user.state.'.$cid);
1.109 www 4430: }
4431: }
4432:
1.265 albertel 4433: sub get_scalar {
4434: my ($string,$end) = @_;
4435: my $value;
4436: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4437: $value = $1;
4438: } elsif ($$string =~ s/^([^&]*?)&//) {
4439: $value = $1;
4440: }
4441: return &unescape($value);
4442: }
4443:
4444: sub array2str {
4445: my (@array) = @_;
4446: my $result=&arrayref2str(\@array);
4447: $result=~s/^__ARRAY_REF__//;
4448: $result=~s/__END_ARRAY_REF__$//;
4449: return $result;
4450: }
4451:
1.204 albertel 4452: sub arrayref2str {
4453: my ($arrayref) = @_;
1.265 albertel 4454: my $result='__ARRAY_REF__';
1.204 albertel 4455: foreach my $elem (@$arrayref) {
1.265 albertel 4456: if(ref($elem) eq 'ARRAY') {
4457: $result.=&arrayref2str($elem).'&';
4458: } elsif(ref($elem) eq 'HASH') {
4459: $result.=&hashref2str($elem).'&';
4460: } elsif(ref($elem)) {
4461: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4462: } else {
4463: $result.=&escape($elem).'&';
4464: }
4465: }
4466: $result=~s/\&$//;
1.265 albertel 4467: $result .= '__END_ARRAY_REF__';
1.204 albertel 4468: return $result;
4469: }
4470:
1.168 albertel 4471: sub hash2str {
1.204 albertel 4472: my (%hash) = @_;
4473: my $result=&hashref2str(\%hash);
1.265 albertel 4474: $result=~s/^__HASH_REF__//;
4475: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4476: return $result;
4477: }
4478:
4479: sub hashref2str {
4480: my ($hashref)=@_;
1.265 albertel 4481: my $result='__HASH_REF__';
1.800 albertel 4482: foreach my $key (sort(keys(%$hashref))) {
4483: if (ref($key) eq 'ARRAY') {
4484: $result.=&arrayref2str($key).'=';
4485: } elsif (ref($key) eq 'HASH') {
4486: $result.=&hashref2str($key).'=';
4487: } elsif (ref($key)) {
1.265 albertel 4488: $result.='=';
1.800 albertel 4489: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4490: } else {
1.1132 raeburn 4491: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4492: }
4493:
1.800 albertel 4494: if(ref($hashref->{$key}) eq 'ARRAY') {
4495: $result.=&arrayref2str($hashref->{$key}).'&';
4496: } elsif(ref($hashref->{$key}) eq 'HASH') {
4497: $result.=&hashref2str($hashref->{$key}).'&';
4498: } elsif(ref($hashref->{$key})) {
1.265 albertel 4499: $result.='&';
1.800 albertel 4500: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4501: } else {
1.800 albertel 4502: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4503: }
4504: }
1.168 albertel 4505: $result=~s/\&$//;
1.265 albertel 4506: $result .= '__END_HASH_REF__';
1.168 albertel 4507: return $result;
4508: }
4509:
4510: sub str2hash {
1.265 albertel 4511: my ($string)=@_;
4512: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4513: return %$hash;
4514: }
4515:
4516: sub str2hashref {
1.168 albertel 4517: my ($string) = @_;
1.265 albertel 4518:
4519: my %hash;
4520:
4521: if($string !~ /^__HASH_REF__/) {
4522: if (! ($string eq '' || !defined($string))) {
4523: $hash{'error'}='Not hash reference';
4524: }
4525: return (\%hash, $string);
4526: }
4527:
4528: $string =~ s/^__HASH_REF__//;
4529:
4530: while($string !~ /^__END_HASH_REF__/) {
4531: #key
4532: my $key='';
4533: if($string =~ /^__HASH_REF__/) {
4534: ($key, $string)=&str2hashref($string);
4535: if(defined($key->{'error'})) {
4536: $hash{'error'}='Bad data';
4537: return (\%hash, $string);
4538: }
4539: } elsif($string =~ /^__ARRAY_REF__/) {
4540: ($key, $string)=&str2arrayref($string);
4541: if($key->[0] eq 'Array reference error') {
4542: $hash{'error'}='Bad data';
4543: return (\%hash, $string);
4544: }
4545: } else {
4546: $string =~ s/^(.*?)=//;
1.267 albertel 4547: $key=&unescape($1);
1.265 albertel 4548: }
4549: $string =~ s/^=//;
4550:
4551: #value
4552: my $value='';
4553: if($string =~ /^__HASH_REF__/) {
4554: ($value, $string)=&str2hashref($string);
4555: if(defined($value->{'error'})) {
4556: $hash{'error'}='Bad data';
4557: return (\%hash, $string);
4558: }
4559: } elsif($string =~ /^__ARRAY_REF__/) {
4560: ($value, $string)=&str2arrayref($string);
4561: if($value->[0] eq 'Array reference error') {
4562: $hash{'error'}='Bad data';
4563: return (\%hash, $string);
4564: }
4565: } else {
4566: $value=&get_scalar(\$string,'__END_HASH_REF__');
4567: }
4568: $string =~ s/^&//;
4569:
4570: $hash{$key}=$value;
1.204 albertel 4571: }
1.265 albertel 4572:
4573: $string =~ s/^__END_HASH_REF__//;
4574:
4575: return (\%hash, $string);
1.204 albertel 4576: }
4577:
4578: sub str2array {
1.265 albertel 4579: my ($string)=@_;
4580: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4581: return @$array;
4582: }
4583:
4584: sub str2arrayref {
1.204 albertel 4585: my ($string) = @_;
1.265 albertel 4586: my @array;
4587:
4588: if($string !~ /^__ARRAY_REF__/) {
4589: if (! ($string eq '' || !defined($string))) {
4590: $array[0]='Array reference error';
4591: }
4592: return (\@array, $string);
4593: }
4594:
4595: $string =~ s/^__ARRAY_REF__//;
4596:
4597: while($string !~ /^__END_ARRAY_REF__/) {
4598: my $value='';
4599: if($string =~ /^__HASH_REF__/) {
4600: ($value, $string)=&str2hashref($string);
4601: if(defined($value->{'error'})) {
4602: $array[0] ='Array reference error';
4603: return (\@array, $string);
4604: }
4605: } elsif($string =~ /^__ARRAY_REF__/) {
4606: ($value, $string)=&str2arrayref($string);
4607: if($value->[0] eq 'Array reference error') {
4608: $array[0] ='Array reference error';
4609: return (\@array, $string);
4610: }
4611: } else {
4612: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4613: }
4614: $string =~ s/^&//;
4615:
4616: push(@array, $value);
1.191 harris41 4617: }
1.265 albertel 4618:
4619: $string =~ s/^__END_ARRAY_REF__//;
4620:
4621: return (\@array, $string);
1.168 albertel 4622: }
4623:
1.167 albertel 4624: # -------------------------------------------------------------------Temp Store
4625:
1.168 albertel 4626: sub tmpreset {
4627: my ($symb,$namespace,$domain,$stuname) = @_;
4628: if (!$symb) {
4629: $symb=&symbread();
1.620 albertel 4630: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4631: }
4632: $symb=escape($symb);
4633:
1.620 albertel 4634: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4635: $namespace=~s/\//\_/g;
4636: $namespace=~s/\W//g;
4637:
1.620 albertel 4638: if (!$domain) { $domain=$env{'user.domain'}; }
4639: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4640: if ($domain eq 'public' && $stuname eq 'public') {
4641: $stuname=$ENV{'REMOTE_ADDR'};
4642: }
1.1117 foxr 4643: my $path=LONCAPA::tempdir();
1.168 albertel 4644: my %hash;
4645: if (tie(%hash,'GDBM_File',
4646: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4647: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4648: foreach my $key (keys(%hash)) {
1.180 albertel 4649: if ($key=~ /:$symb/) {
1.168 albertel 4650: delete($hash{$key});
4651: }
4652: }
4653: }
4654: }
4655:
1.167 albertel 4656: sub tmpstore {
1.168 albertel 4657: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4658:
4659: if (!$symb) {
4660: $symb=&symbread();
1.620 albertel 4661: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4662: }
4663: $symb=escape($symb);
4664:
4665: if (!$namespace) {
4666: # I don't think we would ever want to store this for a course.
4667: # it seems this will only be used if we don't have a course.
1.620 albertel 4668: #$namespace=$env{'request.course.id'};
1.168 albertel 4669: #if (!$namespace) {
1.620 albertel 4670: $namespace=$env{'request.state'};
1.168 albertel 4671: #}
4672: }
4673: $namespace=~s/\//\_/g;
4674: $namespace=~s/\W//g;
1.620 albertel 4675: if (!$domain) { $domain=$env{'user.domain'}; }
4676: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4677: if ($domain eq 'public' && $stuname eq 'public') {
4678: $stuname=$ENV{'REMOTE_ADDR'};
4679: }
1.168 albertel 4680: my $now=time;
4681: my %hash;
1.1117 foxr 4682: my $path=LONCAPA::tempdir();
1.168 albertel 4683: if (tie(%hash,'GDBM_File',
4684: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4685: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4686: $hash{"version:$symb"}++;
4687: my $version=$hash{"version:$symb"};
4688: my $allkeys='';
4689: foreach my $key (keys(%$storehash)) {
4690: $allkeys.=$key.':';
1.591 albertel 4691: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4692: }
4693: $hash{"$version:$symb:timestamp"}=$now;
4694: $allkeys.='timestamp';
4695: $hash{"$version:keys:$symb"}=$allkeys;
4696: if (untie(%hash)) {
4697: return 'ok';
4698: } else {
4699: return "error:$!";
4700: }
4701: } else {
4702: return "error:$!";
4703: }
4704: }
1.167 albertel 4705:
1.168 albertel 4706: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4707:
1.168 albertel 4708: sub tmprestore {
4709: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4710:
1.168 albertel 4711: if (!$symb) {
4712: $symb=&symbread();
1.620 albertel 4713: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4714: }
4715: $symb=escape($symb);
4716:
1.620 albertel 4717: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4718:
1.620 albertel 4719: if (!$domain) { $domain=$env{'user.domain'}; }
4720: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4721: if ($domain eq 'public' && $stuname eq 'public') {
4722: $stuname=$ENV{'REMOTE_ADDR'};
4723: }
1.168 albertel 4724: my %returnhash;
4725: $namespace=~s/\//\_/g;
4726: $namespace=~s/\W//g;
4727: my %hash;
1.1117 foxr 4728: my $path=LONCAPA::tempdir();
1.168 albertel 4729: if (tie(%hash,'GDBM_File',
4730: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4731: &GDBM_READER(),0640)) {
1.168 albertel 4732: my $version=$hash{"version:$symb"};
4733: $returnhash{'version'}=$version;
4734: my $scope;
4735: for ($scope=1;$scope<=$version;$scope++) {
4736: my $vkeys=$hash{"$scope:keys:$symb"};
4737: my @keys=split(/:/,$vkeys);
4738: my $key;
4739: $returnhash{"$scope:keys"}=$vkeys;
4740: foreach $key (@keys) {
1.591 albertel 4741: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4742: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4743: }
4744: }
1.168 albertel 4745: if (!(untie(%hash))) {
4746: return "error:$!";
4747: }
4748: } else {
4749: return "error:$!";
4750: }
4751: return %returnhash;
1.167 albertel 4752: }
4753:
1.9 www 4754: # ----------------------------------------------------------------------- Store
4755:
4756: sub store {
1.124 www 4757: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4758: my $home='';
4759:
1.168 albertel 4760: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4761:
1.213 www 4762: $symb=&symbclean($symb);
1.122 albertel 4763: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4764:
1.620 albertel 4765: if (!$domain) { $domain=$env{'user.domain'}; }
4766: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4767:
4768: &devalidate($symb,$stuname,$domain);
1.109 www 4769:
4770: $symb=escape($symb);
1.187 www 4771: if (!$namespace) {
1.620 albertel 4772: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4773: return '';
4774: }
4775: }
1.620 albertel 4776: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4777:
4778: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4779: $$storehash{'host'}=$perlvar{'lonHostID'};
4780:
1.12 www 4781: my $namevalue='';
1.800 albertel 4782: foreach my $key (keys(%$storehash)) {
4783: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4784: }
1.12 www 4785: $namevalue=~s/\&$//;
1.187 www 4786: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4787: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4788: }
4789:
1.47 www 4790: # -------------------------------------------------------------- Critical Store
4791:
4792: sub cstore {
1.124 www 4793: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4794: my $home='';
4795:
1.168 albertel 4796: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4797:
1.213 www 4798: $symb=&symbclean($symb);
1.122 albertel 4799: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4800:
1.620 albertel 4801: if (!$domain) { $domain=$env{'user.domain'}; }
4802: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4803:
4804: &devalidate($symb,$stuname,$domain);
1.109 www 4805:
4806: $symb=escape($symb);
1.187 www 4807: if (!$namespace) {
1.620 albertel 4808: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4809: return '';
4810: }
4811: }
1.620 albertel 4812: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4813:
4814: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4815: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4816:
1.47 www 4817: my $namevalue='';
1.800 albertel 4818: foreach my $key (keys(%$storehash)) {
4819: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4820: }
1.47 www 4821: $namevalue=~s/\&$//;
1.187 www 4822: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4823: return critical
4824: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4825: }
4826:
1.9 www 4827: # --------------------------------------------------------------------- Restore
4828:
4829: sub restore {
1.124 www 4830: my ($symb,$namespace,$domain,$stuname) = @_;
4831: my $home='';
4832:
1.168 albertel 4833: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4834:
1.122 albertel 4835: if (!$symb) {
1.1172.2.26 raeburn 4836: return if ($namespace eq 'courserequests');
4837: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4838: } else {
1.1172.2.26 raeburn 4839: unless ($namespace eq 'courserequests') {
4840: $symb=&escape(&symbclean($symb));
4841: }
1.122 albertel 4842: }
1.188 www 4843: if (!$namespace) {
1.620 albertel 4844: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4845: return '';
4846: }
4847: }
1.620 albertel 4848: if (!$domain) { $domain=$env{'user.domain'}; }
4849: if (!$stuname) { $stuname=$env{'user.name'}; }
4850: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4851: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4852:
1.12 www 4853: my %returnhash=();
1.800 albertel 4854: foreach my $line (split(/\&/,$answer)) {
4855: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4856: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4857: }
1.75 www 4858: my $version;
4859: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4860: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4861: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4862: }
1.75 www 4863: }
1.13 www 4864: return %returnhash;
1.34 www 4865: }
4866:
4867: # ---------------------------------------------------------- Course Description
1.1118 foxr 4868: #
4869: #
1.34 www 4870:
4871: sub coursedescription {
1.731 albertel 4872: my ($courseid,$args)=@_;
1.34 www 4873: $courseid=~s/^\///;
1.49 www 4874: $courseid=~s/\_/\//g;
1.34 www 4875: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4876: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4877: my $normalid=$cdomain.'_'.$cnum;
4878: # need to always cache even if we get errors otherwise we keep
4879: # trying and trying and trying to get the course description.
4880: my %envhash=();
4881: my %returnhash=();
1.731 albertel 4882:
4883: my $expiretime=600;
4884: if ($env{'request.course.id'} eq $normalid) {
4885: $expiretime=120;
4886: }
4887:
4888: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4889: if (!$args->{'freshen_cache'}
4890: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4891: foreach my $key (keys(%env)) {
4892: next if ($key !~ /^\Q$prefix\E(.*)/);
4893: my ($setting) = $1;
4894: $returnhash{$setting} = $env{$key};
4895: }
4896: return %returnhash;
4897: }
4898:
1.1118 foxr 4899: # get the data again
4900:
1.731 albertel 4901: if (!$args->{'one_time'}) {
4902: $envhash{'course.'.$normalid.'.last_cache'}=time;
4903: }
1.811 albertel 4904:
1.34 www 4905: if ($chome ne 'no_host') {
1.302 albertel 4906: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4907: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4908: my $username = $env{'user.name'}; # Defult username
4909: if(defined $args->{'user'}) {
4910: $username = $args->{'user'};
4911: }
1.129 albertel 4912: $returnhash{'home'}= $chome;
4913: $returnhash{'domain'} = $cdomain;
4914: $returnhash{'num'} = $cnum;
1.741 raeburn 4915: if (!defined($returnhash{'type'})) {
4916: $returnhash{'type'} = 'Course';
4917: }
1.130 albertel 4918: while (my ($name,$value) = each %returnhash) {
1.53 www 4919: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4920: }
1.270 www 4921: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4922: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4923: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4924: $envhash{'course.'.$normalid.'.home'}=$chome;
4925: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4926: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4927: }
4928: }
1.731 albertel 4929: if (!$args->{'one_time'}) {
1.949 raeburn 4930: &appenv(\%envhash);
1.731 albertel 4931: }
1.302 albertel 4932: return %returnhash;
1.461 www 4933: }
4934:
1.1080 raeburn 4935: sub update_released_required {
4936: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4937: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4938: $cid = $env{'request.course.id'};
4939: $cdom = $env{'course.'.$cid.'.domain'};
4940: $cnum = $env{'course.'.$cid.'.num'};
4941: $chome = $env{'course.'.$cid.'.home'};
4942: }
4943: if ($needsrelease) {
4944: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4945: my $needsupdate;
4946: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4947: $needsupdate = 1;
4948: } else {
4949: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4950: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4951: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4952: $needsupdate = 1;
4953: }
4954: }
4955: if ($needsupdate) {
4956: my %needshash = (
4957: 'internal.releaserequired' => $needsrelease,
4958: );
4959: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4960: if ($putresult eq 'ok') {
4961: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4962: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4963: if (ref($crsinfo{$cid}) eq 'HASH') {
4964: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4965: &courseidput($cdom,\%crsinfo,$chome,'notime');
4966: }
4967: }
4968: }
4969: }
4970: return;
4971: }
4972:
1.461 www 4973: # -------------------------------------------------See if a user is privileged
4974:
4975: sub privileged {
1.1172.2.23 raeburn 4976: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 4977: my $now = time;
1.1172.2.23 raeburn 4978: my $roles;
4979: if (ref($possroles) eq 'ARRAY') {
4980: $roles = $possroles;
4981: } else {
4982: $roles = ['dc','su'];
4983: }
4984: if (ref($possdomains) eq 'ARRAY') {
4985: my %privileged = &privileged_by_domain($possdomains,$roles);
4986: foreach my $dom (@{$possdomains}) {
4987: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
4988: (ref($privileged{$dom}) eq 'HASH')) {
4989: foreach my $role (@{$roles}) {
4990: if (ref($privileged{$dom}{$role}) eq 'HASH') {
4991: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
4992: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
4993: return 1 unless (($end && $end < $now) ||
4994: ($start && $start > $now));
4995: }
4996: }
4997: }
4998: }
4999: }
5000: } else {
5001: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5002: my $now = time;
1.1170 droeschl 5003:
1.1172.2.23 raeburn 5004: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5005: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5006: if (grep(/^\Q$trole\E$/,@{$roles})) {
5007: return 1 unless ($tend && $tend < $now)
5008: or ($tstart && $tstart > $now);
1.1170 droeschl 5009: }
1.1172.2.23 raeburn 5010: }
5011: }
1.461 www 5012: return 0;
1.9 www 5013: }
1.1 albertel 5014:
1.1172.2.23 raeburn 5015: sub privileged_by_domain {
5016: my ($domains,$roles) = @_;
5017: my %privileged = ();
5018: my $cachetime = 60*60*24;
5019: my $now = time;
5020: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5021: return %privileged;
5022: }
5023: foreach my $dom (@{$domains}) {
5024: next if (ref($privileged{$dom}) eq 'HASH');
5025: my $needroles;
5026: foreach my $role (@{$roles}) {
5027: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5028: if (defined($cached)) {
5029: if (ref($result) eq 'HASH') {
5030: $privileged{$dom}{$role} = $result;
5031: }
5032: } else {
5033: $needroles = 1;
5034: }
5035: }
5036: if ($needroles) {
5037: my %dompersonnel = &get_domain_roles($dom,$roles);
5038: $privileged{$dom} = {};
5039: foreach my $server (keys(%dompersonnel)) {
5040: if (ref($dompersonnel{$server}) eq 'HASH') {
5041: foreach my $item (keys(%{$dompersonnel{$server}})) {
5042: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5043: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5044: next if ($end && $end < $now);
5045: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5046: $dompersonnel{$server}{$item};
5047: }
5048: }
5049: }
5050: if (ref($privileged{$dom}) eq 'HASH') {
5051: foreach my $role (@{$roles}) {
5052: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5053: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5054: } else {
5055: my %hash = ();
5056: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5057: }
5058: }
5059: }
5060: }
5061: }
5062: return %privileged;
5063: }
5064:
1.103 harris41 5065: # -------------------------------------------------------- Get user privileges
1.11 www 5066:
5067: sub rolesinit {
1.1169 droeschl 5068: my ($domain, $username) = @_;
5069: my %userroles = ('user.login.time' => time);
5070: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5071:
5072: # firstaccess and timerinterval are related to timed maps/resources.
5073: # also, blocking can be triggered by an activating timer
5074: # it's saved in the user's %env.
5075: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5076: my %timerinterval = &dump('timerinterval', $domain, $username);
5077: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5078: %timerintchk, %timerintenv);
5079:
1.1162 raeburn 5080: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5081: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5082: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5083: }
1.1169 droeschl 5084:
1.1162 raeburn 5085: foreach my $key (keys(%timerinterval)) {
5086: my ($cid,$rest) = split(/\0/,$key);
5087: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5088: }
1.1169 droeschl 5089:
1.11 www 5090: my %allroles=();
1.1162 raeburn 5091: my %allgroups=();
1.11 www 5092:
1.1169 droeschl 5093: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5094: my $role = $rolesdump{$area};
5095: $area =~ s/\_\w\w$//;
5096:
5097: my ($trole, $tend, $tstart, $group_privs);
5098:
5099: if ($role =~ /^cr/) {
5100: # Custom role, defined by a user
5101: # e.g., user.role.cr/msu/smith/mynewrole
5102: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5103: $trole = $1;
5104: ($tend, $tstart) = split('_', $2);
5105: } else {
5106: $trole = $role;
5107: }
5108: } elsif ($role =~ m|^gr/|) {
5109: # Role of member in a group, defined within a course/community
5110: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5111: ($trole, $tend, $tstart) = split(/_/, $role);
5112: next if $tstart eq '-1';
5113: ($trole, $group_privs) = split(/\//, $trole);
5114: $group_privs = &unescape($group_privs);
5115: } else {
5116: # Just a normal role, defined in roles.tab
5117: ($trole, $tend, $tstart) = split(/_/,$role);
5118: }
5119:
5120: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5121: $username);
5122: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5123:
5124: # role expired or not available yet?
5125: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5126: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5127:
5128: next if $area eq '' or $trole eq '';
5129:
5130: my $spec = "$trole.$area";
5131: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5132:
5133: if ($trole =~ /^cr\//) {
5134: # Custom role, defined by a user
5135: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5136: } elsif ($trole eq 'gr') {
5137: # Role of a member in a group, defined within a course/community
5138: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5139: next;
5140: } else {
5141: # Normal role, defined in roles.tab
5142: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5143: }
5144:
5145: my $cid = $tdomain.'_'.$trest;
5146: unless ($firstaccchk{$cid}) {
5147: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5148: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5149: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5150: $coursetimerstarts{$cid}{$item};
5151: }
5152: }
5153: $firstaccchk{$cid} = 1;
5154: }
5155: unless ($timerintchk{$cid}) {
5156: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5157: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5158: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5159: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5160: }
1.12 www 5161: }
1.1169 droeschl 5162: $timerintchk{$cid} = 1;
1.191 harris41 5163: }
1.11 www 5164: }
1.1169 droeschl 5165:
5166: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5167: \%allroles, \%allgroups);
5168: $env{'user.adv'} = $userroles{'user.adv'};
5169:
1.1162 raeburn 5170: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5171: }
5172:
1.567 raeburn 5173: sub set_arearole {
1.1172.2.19 raeburn 5174: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5175: unless ($nolog) {
1.567 raeburn 5176: # log the associated role with the area
1.1172.2.19 raeburn 5177: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5178: }
1.743 albertel 5179: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5180: }
5181:
5182: sub custom_roleprivs {
5183: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5184: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5185: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 5186: if (&hostname($homsvr) ne '') {
1.567 raeburn 5187: my ($rdummy,$roledef)=
5188: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5189: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5190: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5191: if (defined($syspriv)) {
1.1043 raeburn 5192: if ($trest =~ /^$match_community$/) {
5193: $syspriv =~ s/bre\&S//;
5194: }
1.567 raeburn 5195: $$allroles{'cm./'}.=':'.$syspriv;
5196: $$allroles{$spec.'./'}.=':'.$syspriv;
5197: }
5198: if ($tdomain ne '') {
5199: if (defined($dompriv)) {
5200: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5201: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5202: }
5203: if (($trest ne '') && (defined($coursepriv))) {
5204: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5205: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5206: }
5207: }
5208: }
5209: }
5210: }
5211:
1.678 raeburn 5212: sub group_roleprivs {
5213: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5214: my $access = 1;
5215: my $now = time;
5216: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5217: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5218: if ($access) {
1.811 albertel 5219: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5220: $$allgroups{$course}{$group} .=':'.$group_privs;
5221: }
5222: }
1.567 raeburn 5223:
5224: sub standard_roleprivs {
5225: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5226: if (defined($pr{$trole.':s'})) {
5227: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5228: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5229: }
5230: if ($tdomain ne '') {
5231: if (defined($pr{$trole.':d'})) {
5232: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5233: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5234: }
5235: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5236: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5237: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5238: }
5239: }
5240: }
5241:
5242: sub set_userprivs {
1.1064 raeburn 5243: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5244: my $author=0;
5245: my $adv=0;
1.678 raeburn 5246: my %grouproles = ();
5247: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5248: my @groupkeys;
1.1000 raeburn 5249: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5250: push(@groupkeys,$role);
5251: }
5252: if (ref($groups_roles) eq 'HASH') {
5253: foreach my $key (keys(%{$groups_roles})) {
5254: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5255: push(@groupkeys,$key);
5256: }
5257: }
5258: }
5259: if (@groupkeys > 0) {
5260: foreach my $role (@groupkeys) {
5261: my ($trole,$area,$sec,$extendedarea);
5262: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5263: $trole = $1;
5264: $area = $2;
5265: $sec = $3;
5266: $extendedarea = $area.$sec;
5267: if (exists($$allgroups{$area})) {
5268: foreach my $group (keys(%{$$allgroups{$area}})) {
5269: my $spec = $trole.'.'.$extendedarea;
5270: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5271: $$allgroups{$area}{$group};
1.1064 raeburn 5272: }
1.678 raeburn 5273: }
5274: }
5275: }
5276: }
5277: }
1.800 albertel 5278: foreach my $group (keys(%grouproles)) {
5279: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5280: }
1.800 albertel 5281: foreach my $role (keys(%{$allroles})) {
5282: my %thesepriv;
1.941 raeburn 5283: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5284: foreach my $item (split(/:/,$$allroles{$role})) {
5285: if ($item ne '') {
5286: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5287: if ($restrictions eq '') {
5288: $thesepriv{$privilege}='F';
5289: } elsif ($thesepriv{$privilege} ne 'F') {
5290: $thesepriv{$privilege}.=$restrictions;
5291: }
5292: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5293: }
5294: }
5295: my $thesestr='';
1.1104 raeburn 5296: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5297: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5298: }
5299: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5300: }
5301: return ($author,$adv);
5302: }
5303:
1.994 raeburn 5304: sub role_status {
1.1104 raeburn 5305: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5306: my @pwhere = ();
5307: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5308: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5309: unless (!defined($$role) || $$role eq '') {
5310: $$where=join('.',@pwhere);
5311: $$trolecode=$$role.'.'.$$where;
5312: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5313: $$tstatus='is';
1.1104 raeburn 5314: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5315: $$tstatus='future';
1.1034 raeburn 5316: if ($$tstart<$now) {
5317: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5318: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5319: my (%allroles,%allgroups,$group_privs,
5320: %groups_roles,@rolecodes);
1.1002 raeburn 5321: my %userroles = (
5322: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5323: );
1.1064 raeburn 5324: @rolecodes = ('cm');
1.1002 raeburn 5325: my $spec=$$role.'.'.$$where;
5326: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5327: if ($$role =~ /^cr\//) {
5328: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5329: push(@rolecodes,'cr');
1.1002 raeburn 5330: } elsif ($$role eq 'gr') {
1.1064 raeburn 5331: push(@rolecodes,$$role);
1.1002 raeburn 5332: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5333: $env{'user.name'});
1.1064 raeburn 5334: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5335: (undef,my $group_privs) = split(/\//,$trole);
5336: $group_privs = &unescape($group_privs);
5337: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5338: 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 5339: &get_groups_roles($tdomain,$trest,
5340: \%course_roles,\@rolecodes,
5341: \%groups_roles);
1.1002 raeburn 5342: } else {
1.1064 raeburn 5343: push(@rolecodes,$$role);
1.1002 raeburn 5344: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5345: }
1.1064 raeburn 5346: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5347: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5348: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5349: }
5350: }
1.1034 raeburn 5351: $$tstatus = 'is';
1.1002 raeburn 5352: }
1.994 raeburn 5353: }
5354: if ($$tend) {
1.1104 raeburn 5355: if ($$tend<$update) {
1.994 raeburn 5356: $$tstatus='expired';
5357: } elsif ($$tend<$now) {
5358: $$tstatus='will_not';
5359: }
5360: }
5361: }
5362: }
5363: }
5364:
1.1104 raeburn 5365: sub get_groups_roles {
5366: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5367: return unless((ref($cdom_courseroles) eq 'HASH') &&
5368: (ref($rolecodes) eq 'ARRAY') &&
5369: (ref($groups_roles) eq 'HASH'));
5370: if (keys(%{$cdom_courseroles}) > 0) {
5371: my ($cnum) = ($rest =~ /^($match_courseid)/);
5372: if ($cdom ne '' && $cnum ne '') {
5373: foreach my $key (keys(%{$cdom_courseroles})) {
5374: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5375: my $crsrole = $1;
5376: my $crssec = $2;
5377: if ($crsrole =~ /^cr/) {
5378: unless (grep(/^cr$/,@{$rolecodes})) {
5379: push(@{$rolecodes},'cr');
5380: }
5381: } else {
5382: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5383: push(@{$rolecodes},$crsrole);
5384: }
5385: }
5386: my $rolekey = "$crsrole./$cdom/$cnum";
5387: if ($crssec ne '') {
5388: $rolekey .= "/$crssec";
5389: }
5390: $rolekey .= './';
5391: $groups_roles->{$rolekey} = $rolecodes;
5392: }
5393: }
5394: }
5395: }
5396: return;
5397: }
5398:
5399: sub delete_env_groupprivs {
5400: my ($where,$courseroles,$possroles) = @_;
5401: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5402: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5403: unless (ref($courseroles->{$udom}) eq 'HASH') {
5404: %{$courseroles->{$udom}} =
5405: &get_my_roles('','','userroles',['active'],
5406: $possroles,[$udom],1);
5407: }
5408: if (ref($courseroles->{$udom}) eq 'HASH') {
5409: foreach my $item (keys(%{$courseroles->{$udom}})) {
5410: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5411: my $area = '/'.$cdom.'/'.$cnum;
5412: my $privkey = "user.priv.$crsrole.$area";
5413: if ($crssec ne '') {
5414: $privkey .= '/'.$crssec;
5415: }
5416: $privkey .= ".$area/$group";
5417: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5418: }
5419: }
5420: return;
5421: }
5422:
1.994 raeburn 5423: sub check_adhoc_privs {
1.1104 raeburn 5424: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5425: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5426: my $setprivs;
1.994 raeburn 5427: if ($env{$cckey}) {
5428: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5429: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5430: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5431: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5432: $setprivs = 1;
1.994 raeburn 5433: }
5434: } else {
1.1088 raeburn 5435: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5436: $setprivs = 1;
1.994 raeburn 5437: }
1.1172.2.9 raeburn 5438: return $setprivs;
1.994 raeburn 5439: }
5440:
5441: sub set_adhoc_privileges {
5442: # role can be cc or ca
1.1088 raeburn 5443: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5444: my $area = '/'.$dcdom.'/'.$pickedcourse;
5445: my $spec = $role.'.'.$area;
5446: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5447: $env{'user.name'},1);
1.994 raeburn 5448: my %ccrole = ();
5449: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5450: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5451: &appenv(\%userroles,[$role,'cm']);
5452: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5453: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5454: &appenv( {'request.role' => $spec,
5455: 'request.role.domain' => $dcdom,
5456: 'request.course.sec' => ''
5457: }
5458: );
5459: my $tadv=0;
5460: if (&allowed('adv') eq 'F') { $tadv=1; }
5461: &appenv({'request.role.adv' => $tadv});
5462: }
1.994 raeburn 5463: }
5464:
1.12 www 5465: # --------------------------------------------------------------- get interface
5466:
5467: sub get {
1.131 albertel 5468: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5469: my $items='';
1.800 albertel 5470: foreach my $item (@$storearr) {
5471: $items.=&escape($item).'&';
1.191 harris41 5472: }
1.12 www 5473: $items=~s/\&$//;
1.620 albertel 5474: if (!$udomain) { $udomain=$env{'user.domain'}; }
5475: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5476: my $uhome=&homeserver($uname,$udomain);
5477:
1.133 albertel 5478: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5479: my @pairs=split(/\&/,$rep);
1.273 albertel 5480: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5481: return @pairs;
5482: }
1.15 www 5483: my %returnhash=();
1.42 www 5484: my $i=0;
1.800 albertel 5485: foreach my $item (@$storearr) {
5486: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5487: $i++;
1.191 harris41 5488: }
1.15 www 5489: return %returnhash;
1.27 www 5490: }
5491:
5492: # --------------------------------------------------------------- del interface
5493:
5494: sub del {
1.133 albertel 5495: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5496: my $items='';
1.800 albertel 5497: foreach my $item (@$storearr) {
5498: $items.=&escape($item).'&';
1.191 harris41 5499: }
1.984 neumanie 5500:
1.27 www 5501: $items=~s/\&$//;
1.620 albertel 5502: if (!$udomain) { $udomain=$env{'user.domain'}; }
5503: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5504: my $uhome=&homeserver($uname,$udomain);
5505: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5506: }
5507:
5508: # -------------------------------------------------------------- dump interface
5509:
1.1172.2.22 raeburn 5510: sub unserialize {
5511: my ($rep, $escapedkeys) = @_;
5512:
5513: return {} if $rep =~ /^error/;
5514:
5515: my %returnhash=();
5516: foreach my $item (split(/\&/,$rep)) {
5517: my ($key, $value) = split(/=/, $item, 2);
5518: $key = unescape($key) unless $escapedkeys;
5519: next if $key =~ /^error: 2 /;
5520: $returnhash{$key} = &thaw_unescape($value);
5521: }
5522: return \%returnhash;
5523: }
5524:
5525: # see Lond::dump_with_regexp
5526: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5527: sub dump {
1.1172.2.22 raeburn 5528: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5529: if (!$udomain) { $udomain=$env{'user.domain'}; }
5530: if (!$uname) { $uname=$env{'user.name'}; }
5531: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5532:
1.1172.2.22 raeburn 5533: my $reply;
5534: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5535: # user is hosted on this machine
5536: $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5537: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5538: return %{&unserialize($reply, $escapedkeys)};
5539: }
1.755 albertel 5540: if ($regexp) {
5541: $regexp=&escape($regexp);
5542: } else {
5543: $regexp='.';
5544: }
1.1166 raeburn 5545: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5546: my @pairs=split(/\&/,$rep);
5547: my %returnhash=();
1.1098 foxr 5548: if (!($rep =~ /^error/ )) {
5549: foreach my $item (@pairs) {
5550: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5551: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5552: next if ($key =~ /^error: 2 /);
5553: $returnhash{$key}=&thaw_unescape($value);
5554: }
1.755 albertel 5555: }
5556: return %returnhash;
1.407 www 5557: }
5558:
1.1098 foxr 5559:
1.717 albertel 5560: # --------------------------------------------------------- dumpstore interface
5561:
5562: sub dumpstore {
5563: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5564: # same as dump but keys must be escaped. They may contain colon separated
5565: # lists of values that may themself contain colons (e.g. symbs).
5566: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5567: }
5568:
1.407 www 5569: # -------------------------------------------------------------- keys interface
5570:
5571: sub getkeys {
5572: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5573: if (!$udomain) { $udomain=$env{'user.domain'}; }
5574: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5575: my $uhome=&homeserver($uname,$udomain);
5576: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5577: my @keyarray=();
1.800 albertel 5578: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5579: next if ($key =~ /^error: 2 /);
1.800 albertel 5580: push(@keyarray,&unescape($key));
1.407 www 5581: }
5582: return @keyarray;
1.318 matthew 5583: }
5584:
1.319 matthew 5585: # --------------------------------------------------------------- currentdump
5586: sub currentdump {
1.328 matthew 5587: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5588: $courseid = $env{'request.course.id'} if (! defined($courseid));
5589: $sdom = $env{'user.domain'} if (! defined($sdom));
5590: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5591: my $uhome = &homeserver($sname,$sdom);
5592: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5593: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5594: #
1.318 matthew 5595: my %returnhash=();
1.319 matthew 5596: #
5597: if ($rep eq "unknown_cmd") {
5598: # an old lond will not know currentdump
5599: # Do a dump and make it look like a currentdump
1.822 albertel 5600: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5601: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5602: my %hash = @tmp;
5603: @tmp=();
1.424 matthew 5604: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5605: } else {
5606: my @pairs=split(/\&/,$rep);
1.800 albertel 5607: foreach my $pair (@pairs) {
5608: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5609: my ($symb,$param) = split(/:/,$key);
5610: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5611: &thaw_unescape($value);
1.319 matthew 5612: }
1.191 harris41 5613: }
1.12 www 5614: return %returnhash;
1.424 matthew 5615: }
5616:
5617: sub convert_dump_to_currentdump{
5618: my %hash = %{shift()};
5619: my %returnhash;
5620: # Code ripped from lond, essentially. The only difference
5621: # here is the unescaping done by lonnet::dump(). Conceivably
5622: # we might run in to problems with parameter names =~ /^v\./
5623: while (my ($key,$value) = each(%hash)) {
5624: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5625: $symb = &unescape($symb);
5626: $param = &unescape($param);
1.424 matthew 5627: next if ($v eq 'version' || $symb eq 'keys');
5628: next if (exists($returnhash{$symb}) &&
5629: exists($returnhash{$symb}->{$param}) &&
5630: $returnhash{$symb}->{'v.'.$param} > $v);
5631: $returnhash{$symb}->{$param}=$value;
5632: $returnhash{$symb}->{'v.'.$param}=$v;
5633: }
5634: #
5635: # Remove all of the keys in the hashes which keep track of
5636: # the version of the parameter.
5637: while (my ($symb,$param_hash) = each(%returnhash)) {
5638: # use a foreach because we are going to delete from the hash.
5639: foreach my $key (keys(%$param_hash)) {
5640: delete($param_hash->{$key}) if ($key =~ /^v\./);
5641: }
5642: }
5643: return \%returnhash;
1.12 www 5644: }
5645:
1.627 albertel 5646: # ------------------------------------------------------ critical inc interface
5647:
5648: sub cinc {
5649: return &inc(@_,'critical');
5650: }
5651:
1.449 matthew 5652: # --------------------------------------------------------------- inc interface
5653:
5654: sub inc {
1.627 albertel 5655: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5656: if (!$udomain) { $udomain=$env{'user.domain'}; }
5657: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5658: my $uhome=&homeserver($uname,$udomain);
5659: my $items='';
5660: if (! ref($store)) {
5661: # got a single value, so use that instead
5662: $items = &escape($store).'=&';
5663: } elsif (ref($store) eq 'SCALAR') {
5664: $items = &escape($$store).'=&';
5665: } elsif (ref($store) eq 'ARRAY') {
5666: $items = join('=&',map {&escape($_);} @{$store});
5667: } elsif (ref($store) eq 'HASH') {
5668: while (my($key,$value) = each(%{$store})) {
5669: $items.= &escape($key).'='.&escape($value).'&';
5670: }
5671: }
5672: $items=~s/\&$//;
1.627 albertel 5673: if ($critical) {
5674: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5675: } else {
5676: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5677: }
1.449 matthew 5678: }
5679:
1.12 www 5680: # --------------------------------------------------------------- put interface
5681:
5682: sub put {
1.134 albertel 5683: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5684: if (!$udomain) { $udomain=$env{'user.domain'}; }
5685: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5686: my $uhome=&homeserver($uname,$udomain);
1.12 www 5687: my $items='';
1.800 albertel 5688: foreach my $item (keys(%$storehash)) {
5689: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5690: }
1.12 www 5691: $items=~s/\&$//;
1.134 albertel 5692: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5693: }
5694:
1.631 albertel 5695: # ------------------------------------------------------------ newput interface
5696:
5697: sub newput {
5698: my ($namespace,$storehash,$udomain,$uname)=@_;
5699: if (!$udomain) { $udomain=$env{'user.domain'}; }
5700: if (!$uname) { $uname=$env{'user.name'}; }
5701: my $uhome=&homeserver($uname,$udomain);
5702: my $items='';
5703: foreach my $key (keys(%$storehash)) {
5704: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5705: }
5706: $items=~s/\&$//;
5707: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5708: }
5709:
5710: # --------------------------------------------------------- putstore interface
5711:
1.524 raeburn 5712: sub putstore {
1.715 albertel 5713: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5714: if (!$udomain) { $udomain=$env{'user.domain'}; }
5715: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5716: my $uhome=&homeserver($uname,$udomain);
5717: my $items='';
1.715 albertel 5718: foreach my $key (keys(%$storehash)) {
5719: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5720: }
1.715 albertel 5721: $items=~s/\&$//;
1.716 albertel 5722: my $esc_symb=&escape($symb);
5723: my $esc_v=&escape($version);
1.715 albertel 5724: my $reply =
1.716 albertel 5725: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5726: $uhome);
5727: if ($reply eq 'unknown_cmd') {
1.716 albertel 5728: # gfall back to way things use to be done
1.715 albertel 5729: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5730: $uname);
1.524 raeburn 5731: }
1.715 albertel 5732: return $reply;
5733: }
5734:
5735: sub old_putstore {
1.716 albertel 5736: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5737: if (!$udomain) { $udomain=$env{'user.domain'}; }
5738: if (!$uname) { $uname=$env{'user.name'}; }
5739: my $uhome=&homeserver($uname,$udomain);
5740: my %newstorehash;
1.800 albertel 5741: foreach my $item (keys(%$storehash)) {
5742: my $key = $version.':'.&escape($symb).':'.$item;
5743: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5744: }
5745: my $items='';
5746: my %allitems = ();
1.800 albertel 5747: foreach my $item (keys(%newstorehash)) {
5748: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5749: my $key = $1.':keys:'.$2;
5750: $allitems{$key} .= $3.':';
5751: }
1.800 albertel 5752: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5753: }
1.800 albertel 5754: foreach my $item (keys(%allitems)) {
5755: $allitems{$item} =~ s/\:$//;
5756: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5757: }
5758: $items=~s/\&$//;
5759: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5760: }
5761:
1.47 www 5762: # ------------------------------------------------------ critical put interface
5763:
5764: sub cput {
1.134 albertel 5765: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5766: if (!$udomain) { $udomain=$env{'user.domain'}; }
5767: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5768: my $uhome=&homeserver($uname,$udomain);
1.47 www 5769: my $items='';
1.800 albertel 5770: foreach my $item (keys(%$storehash)) {
5771: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5772: }
1.47 www 5773: $items=~s/\&$//;
1.134 albertel 5774: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5775: }
5776:
5777: # -------------------------------------------------------------- eget interface
5778:
5779: sub eget {
1.133 albertel 5780: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5781: my $items='';
1.800 albertel 5782: foreach my $item (@$storearr) {
5783: $items.=&escape($item).'&';
1.191 harris41 5784: }
1.12 www 5785: $items=~s/\&$//;
1.620 albertel 5786: if (!$udomain) { $udomain=$env{'user.domain'}; }
5787: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5788: my $uhome=&homeserver($uname,$udomain);
5789: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5790: my @pairs=split(/\&/,$rep);
5791: my %returnhash=();
1.42 www 5792: my $i=0;
1.800 albertel 5793: foreach my $item (@$storearr) {
5794: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5795: $i++;
1.191 harris41 5796: }
1.12 www 5797: return %returnhash;
5798: }
5799:
1.667 albertel 5800: # ------------------------------------------------------------ tmpput interface
5801: sub tmpput {
1.802 raeburn 5802: my ($storehash,$server,$context)=@_;
1.667 albertel 5803: my $items='';
1.800 albertel 5804: foreach my $item (keys(%$storehash)) {
5805: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5806: }
5807: $items=~s/\&$//;
1.802 raeburn 5808: if (defined($context)) {
5809: $items .= ':'.&escape($context);
5810: }
1.667 albertel 5811: return &reply("tmpput:$items",$server);
5812: }
5813:
5814: # ------------------------------------------------------------ tmpget interface
5815: sub tmpget {
1.688 albertel 5816: my ($token,$server)=@_;
5817: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5818: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5819: my %returnhash;
5820: foreach my $item (split(/\&/,$rep)) {
5821: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5822: next if ($key =~ /^error: 2 /);
1.667 albertel 5823: $returnhash{&unescape($key)}=&thaw_unescape($value);
5824: }
5825: return %returnhash;
5826: }
5827:
1.1113 raeburn 5828: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5829: sub tmpdel {
5830: my ($token,$server)=@_;
5831: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5832: return &reply("tmpdel:$token",$server);
5833: }
5834:
1.1172.2.13 raeburn 5835: # ------------------------------------------------------------ get_timebased_id
5836:
5837: sub get_timebased_id {
5838: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5839: $maxtries) = @_;
5840: my ($newid,$error,$dellock);
5841: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5842: return ('','ok','invalid call to get suffix');
5843: }
5844:
5845: # set defaults for any optional args for which values were not supplied
5846: if ($who eq '') {
5847: $who = $env{'user.name'}.':'.$env{'user.domain'};
5848: }
5849: if (!$locktries) {
5850: $locktries = 3;
5851: }
5852: if (!$maxtries) {
5853: $maxtries = 10;
5854: }
5855:
5856: if (($cdom eq '') || ($cnum eq '')) {
5857: if ($env{'request.course.id'}) {
5858: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5859: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5860: }
5861: if (($cdom eq '') || ($cnum eq '')) {
5862: return ('','ok','call to get suffix not in course context');
5863: }
5864: }
5865:
5866: # construct locking item
5867: my $lockhash = {
5868: $prefix."\0".'locked_'.$keyid => $who,
5869: };
5870: my $tries = 0;
5871:
5872: # attempt to get lock on nohist_$namespace file
5873: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5874: while (($gotlock ne 'ok') && $tries <$locktries) {
5875: $tries ++;
5876: sleep 1;
5877: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5878: }
5879:
5880: # attempt to get unique identifier, based on current timestamp
5881: if ($gotlock eq 'ok') {
5882: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5883: my $id = time;
5884: $newid = $id;
5885: my $idtries = 0;
5886: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5887: if ($idtype eq 'concat') {
5888: $newid = $id.$idtries;
5889: } else {
5890: $newid ++;
5891: }
5892: $idtries ++;
5893: }
5894: if (!exists($inuse{$prefix."\0".$newid})) {
5895: my %new_item = (
5896: $prefix."\0".$newid => $who,
5897: );
5898: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5899: $cdom,$cnum);
5900: if ($putresult ne 'ok') {
5901: undef($newid);
5902: $error = 'error saving new item: '.$putresult;
5903: }
5904: } else {
5905: $error = ('error: no unique suffix available for the new item ');
5906: }
5907: # remove lock
5908: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5909: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5910: } else {
5911: $error = "error: could not obtain lockfile\n";
5912: $dellock = 'ok';
5913: }
5914: return ($newid,$dellock,$error);
5915: }
5916:
1.765 albertel 5917: # -------------------------------------------------- portfolio access checking
5918:
5919: sub portfolio_access {
1.766 albertel 5920: my ($requrl) = @_;
1.765 albertel 5921: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5922: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5923: if ($result) {
5924: my %setters;
5925: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5926: my ($startblock,$endblock) =
5927: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5928: if ($startblock && $endblock) {
5929: return 'B';
5930: }
5931: } else {
5932: my ($startblock,$endblock) =
5933: &Apache::loncommon::blockcheck(\%setters,'port');
5934: if ($startblock && $endblock) {
5935: return 'B';
5936: }
5937: }
5938: }
1.765 albertel 5939: if ($result eq 'ok') {
1.766 albertel 5940: return 'F';
1.765 albertel 5941: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5942: return 'A';
1.765 albertel 5943: }
1.766 albertel 5944: return '';
1.765 albertel 5945: }
5946:
5947: sub get_portfolio_access {
1.767 albertel 5948: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5949:
5950: if (!ref($access_hash)) {
5951: my $current_perms = &get_portfile_permissions($udom,$unum);
5952: my %access_controls = &get_access_controls($current_perms,$group,
5953: $file_name);
5954: $access_hash = $access_controls{$file_name};
5955: }
5956:
1.765 albertel 5957: my ($public,$guest,@domains,@users,@courses,@groups);
5958: my $now = time;
5959: if (ref($access_hash) eq 'HASH') {
5960: foreach my $key (keys(%{$access_hash})) {
5961: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5962: if ($start > $now) {
5963: next;
5964: }
5965: if ($end && $end<$now) {
5966: next;
5967: }
5968: if ($scope eq 'public') {
5969: $public = $key;
5970: last;
5971: } elsif ($scope eq 'guest') {
5972: $guest = $key;
5973: } elsif ($scope eq 'domains') {
5974: push(@domains,$key);
5975: } elsif ($scope eq 'users') {
5976: push(@users,$key);
5977: } elsif ($scope eq 'course') {
5978: push(@courses,$key);
5979: } elsif ($scope eq 'group') {
5980: push(@groups,$key);
5981: }
5982: }
5983: if ($public) {
5984: return 'ok';
5985: }
5986: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5987: if ($guest) {
5988: return $guest;
5989: }
5990: } else {
5991: if (@domains > 0) {
5992: foreach my $domkey (@domains) {
5993: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5994: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5995: return 'ok';
5996: }
5997: }
5998: }
5999: }
6000: if (@users > 0) {
6001: foreach my $userkey (@users) {
1.865 raeburn 6002: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6003: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6004: if (ref($item) eq 'HASH') {
6005: if (($item->{'uname'} eq $env{'user.name'}) &&
6006: ($item->{'udom'} eq $env{'user.domain'})) {
6007: return 'ok';
6008: }
6009: }
6010: }
6011: }
1.765 albertel 6012: }
6013: }
6014: my %roleshash;
6015: my @courses_and_groups = @courses;
6016: push(@courses_and_groups,@groups);
6017: if (@courses_and_groups > 0) {
6018: my (%allgroups,%allroles);
6019: my ($start,$end,$role,$sec,$group);
6020: foreach my $envkey (%env) {
1.1060 raeburn 6021: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6022: my $cid = $2.'_'.$3;
6023: if ($1 eq 'gr') {
6024: $group = $4;
6025: $allgroups{$cid}{$group} = $env{$envkey};
6026: } else {
6027: if ($4 eq '') {
6028: $sec = 'none';
6029: } else {
6030: $sec = $4;
6031: }
6032: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6033: }
1.811 albertel 6034: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6035: my $cid = $2.'_'.$3;
6036: if ($4 eq '') {
6037: $sec = 'none';
6038: } else {
6039: $sec = $4;
6040: }
6041: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6042: }
6043: }
6044: if (keys(%allroles) == 0) {
6045: return;
6046: }
6047: foreach my $key (@courses_and_groups) {
6048: my %content = %{$$access_hash{$key}};
6049: my $cnum = $content{'number'};
6050: my $cdom = $content{'domain'};
6051: my $cid = $cdom.'_'.$cnum;
6052: if (!exists($allroles{$cid})) {
6053: next;
6054: }
6055: foreach my $role_id (keys(%{$content{'roles'}})) {
6056: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6057: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6058: my @status = @{$content{'roles'}{$role_id}{'access'}};
6059: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6060: foreach my $role (keys(%{$allroles{$cid}})) {
6061: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6062: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6063: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6064: if (grep/^all$/,@sections) {
6065: return 'ok';
6066: } else {
6067: if (grep/^$sec$/,@sections) {
6068: return 'ok';
6069: }
6070: }
6071: }
6072: }
6073: if (keys(%{$allgroups{$cid}}) == 0) {
6074: if (grep/^none$/,@groups) {
6075: return 'ok';
6076: }
6077: } else {
6078: if (grep/^all$/,@groups) {
6079: return 'ok';
6080: }
6081: foreach my $group (keys(%{$allgroups{$cid}})) {
6082: if (grep/^$group$/,@groups) {
6083: return 'ok';
6084: }
6085: }
6086: }
6087: }
6088: }
6089: }
6090: }
6091: }
6092: if ($guest) {
6093: return $guest;
6094: }
6095: }
6096: }
6097: return;
6098: }
6099:
6100: sub course_group_datechecker {
6101: my ($dates,$now,$status) = @_;
6102: my ($start,$end) = split(/\./,$dates);
6103: if (!$start && !$end) {
6104: return 'ok';
6105: }
6106: if (grep/^active$/,@{$status}) {
6107: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6108: return 'ok';
6109: }
6110: }
6111: if (grep/^previous$/,@{$status}) {
6112: if ($end > $now ) {
6113: return 'ok';
6114: }
6115: }
6116: if (grep/^future$/,@{$status}) {
6117: if ($start > $now) {
6118: return 'ok';
6119: }
6120: }
6121: return;
6122: }
6123:
6124: sub parse_portfolio_url {
6125: my ($url) = @_;
6126:
6127: my ($type,$udom,$unum,$group,$file_name);
6128:
1.823 albertel 6129: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6130: $type = 1;
6131: $udom = $1;
6132: $unum = $2;
6133: $file_name = $3;
1.823 albertel 6134: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6135: $type = 2;
6136: $udom = $1;
6137: $unum = $2;
6138: $group = $3;
6139: $file_name = $3.'/'.$4;
6140: }
6141: if (wantarray) {
6142: return ($type,$udom,$unum,$file_name,$group);
6143: }
6144: return $type;
6145: }
6146:
6147: sub is_portfolio_url {
6148: my ($url) = @_;
6149: return scalar(&parse_portfolio_url($url));
6150: }
6151:
1.798 raeburn 6152: sub is_portfolio_file {
6153: my ($file) = @_;
1.820 raeburn 6154: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6155: return 1;
6156: }
6157: return;
6158: }
6159:
1.976 raeburn 6160: sub usertools_access {
1.1084 raeburn 6161: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6162: my ($access,%tools);
6163: if ($context eq '') {
6164: $context = 'tools';
6165: }
6166: if ($context eq 'requestcourses') {
6167: %tools = (
6168: official => 1,
6169: unofficial => 1,
1.1006 raeburn 6170: community => 1,
1.985 raeburn 6171: );
1.1172.2.9 raeburn 6172: } elsif ($context eq 'requestauthor') {
6173: %tools = (
6174: requestauthor => 1,
6175: );
1.985 raeburn 6176: } else {
6177: %tools = (
6178: aboutme => 1,
6179: blog => 1,
1.1172.2.6 raeburn 6180: webdav => 1,
1.985 raeburn 6181: portfolio => 1,
6182: );
6183: }
1.976 raeburn 6184: return if (!defined($tools{$tool}));
6185:
6186: if ((!defined($udom)) || (!defined($uname))) {
6187: $udom = $env{'user.domain'};
6188: $uname = $env{'user.name'};
6189: }
6190:
1.978 raeburn 6191: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6192: if ($action ne 'reload') {
1.985 raeburn 6193: if ($context eq 'requestcourses') {
6194: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6195: } elsif ($context eq 'requestauthor') {
6196: return $env{'environment.canrequest.author'};
1.985 raeburn 6197: } else {
6198: return $env{'environment.availabletools.'.$tool};
6199: }
6200: }
1.976 raeburn 6201: }
6202:
1.1172.2.9 raeburn 6203: my ($toolstatus,$inststatus,$envkey);
6204: if ($context eq 'requestauthor') {
6205: $envkey = $context;
6206: } else {
6207: $envkey = $context.'.'.$tool;
6208: }
1.976 raeburn 6209:
1.985 raeburn 6210: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6211: ($action ne 'reload')) {
1.1172.2.9 raeburn 6212: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6213: $inststatus = $env{'environment.inststatus'};
6214: } else {
1.1084 raeburn 6215: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6216: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6217: $inststatus = $userenvref->{'inststatus'};
6218: } else {
1.1172.2.9 raeburn 6219: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6220: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6221: $inststatus = $userenv{'inststatus'};
6222: }
1.976 raeburn 6223: }
6224:
6225: if ($toolstatus ne '') {
6226: if ($toolstatus) {
6227: $access = 1;
6228: } else {
6229: $access = 0;
6230: }
6231: return $access;
6232: }
6233:
1.1084 raeburn 6234: my ($is_adv,%domdef);
6235: if (ref($is_advref) eq 'HASH') {
6236: $is_adv = $is_advref->{'is_adv'};
6237: } else {
6238: $is_adv = &is_advanced_user($udom,$uname);
6239: }
6240: if (ref($domdefref) eq 'HASH') {
6241: %domdef = %{$domdefref};
6242: } else {
6243: %domdef = &get_domain_defaults($udom);
6244: }
1.976 raeburn 6245: if (ref($domdef{$tool}) eq 'HASH') {
6246: if ($is_adv) {
6247: if ($domdef{$tool}{'_LC_adv'} ne '') {
6248: if ($domdef{$tool}{'_LC_adv'}) {
6249: $access = 1;
6250: } else {
6251: $access = 0;
6252: }
6253: return $access;
6254: }
6255: }
6256: if ($inststatus ne '') {
6257: my ($hasaccess,$hasnoaccess);
6258: foreach my $affiliation (split(/:/,$inststatus)) {
6259: if ($domdef{$tool}{$affiliation} ne '') {
6260: if ($domdef{$tool}{$affiliation}) {
6261: $hasaccess = 1;
6262: } else {
6263: $hasnoaccess = 1;
6264: }
6265: }
6266: }
6267: if ($hasaccess || $hasnoaccess) {
6268: if ($hasaccess) {
6269: $access = 1;
6270: } elsif ($hasnoaccess) {
6271: $access = 0;
6272: }
6273: return $access;
6274: }
6275: } else {
6276: if ($domdef{$tool}{'default'} ne '') {
6277: if ($domdef{$tool}{'default'}) {
6278: $access = 1;
6279: } elsif ($domdef{$tool}{'default'} == 0) {
6280: $access = 0;
6281: }
6282: return $access;
6283: }
6284: }
6285: } else {
1.1172.2.6 raeburn 6286: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6287: $access = 1;
6288: } else {
6289: $access = 0;
6290: }
1.976 raeburn 6291: return $access;
6292: }
6293: }
6294:
1.1050 raeburn 6295: sub is_course_owner {
6296: my ($cdom,$cnum,$udom,$uname) = @_;
6297: if (($udom eq '') || ($uname eq '')) {
6298: $udom = $env{'user.domain'};
6299: $uname = $env{'user.name'};
6300: }
6301: unless (($udom eq '') || ($uname eq '')) {
6302: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6303: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6304: return 1;
6305: } else {
6306: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6307: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6308: return 1;
6309: }
6310: }
6311: }
6312: }
6313: return;
6314: }
6315:
1.976 raeburn 6316: sub is_advanced_user {
6317: my ($udom,$uname) = @_;
1.1085 raeburn 6318: if ($udom ne '' && $uname ne '') {
6319: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6320: if (wantarray) {
6321: return ($env{'user.adv'},$env{'user.author'});
6322: } else {
6323: return $env{'user.adv'};
6324: }
1.1085 raeburn 6325: }
6326: }
1.976 raeburn 6327: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6328: my %allroles;
1.1128 raeburn 6329: my ($is_adv,$is_author);
1.976 raeburn 6330: foreach my $role (keys(%roleshash)) {
6331: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6332: my $area = '/'.$tdomain.'/'.$trest;
6333: if ($sec ne '') {
6334: $area .= '/'.$sec;
6335: }
6336: if (($area ne '') && ($trole ne '')) {
6337: my $spec=$trole.'.'.$area;
6338: if ($trole =~ /^cr\//) {
6339: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6340: } elsif ($trole ne 'gr') {
6341: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6342: }
1.1128 raeburn 6343: if ($trole eq 'au') {
6344: $is_author = 1;
6345: }
1.976 raeburn 6346: }
6347: }
6348: foreach my $role (keys(%allroles)) {
6349: last if ($is_adv);
6350: foreach my $item (split(/:/,$allroles{$role})) {
6351: if ($item ne '') {
6352: my ($privilege,$restrictions)=split(/&/,$item);
6353: if ($privilege eq 'adv') {
6354: $is_adv = 1;
6355: last;
6356: }
6357: }
6358: }
6359: }
1.1128 raeburn 6360: if (wantarray) {
6361: return ($is_adv,$is_author);
6362: }
1.976 raeburn 6363: return $is_adv;
6364: }
1.798 raeburn 6365:
1.1035 raeburn 6366: sub check_can_request {
1.1036 raeburn 6367: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6368: my $canreq = 0;
6369: my ($types,$typename) = &Apache::loncommon::course_types();
6370: my @options = ('approval','validate','autolimit');
6371: my $optregex = join('|',@options);
6372: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6373: foreach my $type (@{$types}) {
6374: if (&usertools_access($env{'user.name'},
6375: $env{'user.domain'},
6376: $type,undef,'requestcourses')) {
6377: $canreq ++;
1.1036 raeburn 6378: if (ref($request_domains) eq 'HASH') {
6379: push(@{$request_domains->{$type}},$env{'user.domain'});
6380: }
1.1035 raeburn 6381: if ($dom eq $env{'user.domain'}) {
6382: $can_request->{$type} = 1;
6383: }
6384: }
6385: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6386: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6387: if (@curr > 0) {
1.1036 raeburn 6388: foreach my $item (@curr) {
6389: if (ref($request_domains) eq 'HASH') {
6390: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6391: if ($otherdom ne '') {
6392: if (ref($request_domains->{$type}) eq 'ARRAY') {
6393: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6394: push(@{$request_domains->{$type}},$otherdom);
6395: }
6396: } else {
6397: push(@{$request_domains->{$type}},$otherdom);
6398: }
6399: }
6400: }
6401: }
6402: unless($dom eq $env{'user.domain'}) {
6403: $canreq ++;
1.1035 raeburn 6404: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6405: $can_request->{$type} = 1;
6406: }
6407: }
6408: }
6409: }
6410: }
6411: }
6412: return $canreq;
6413: }
6414:
1.341 www 6415: # ---------------------------------------------- Custom access rule evaluation
6416:
6417: sub customaccess {
6418: my ($priv,$uri)=@_;
1.807 albertel 6419: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6420: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6421: $udom = &LONCAPA::clean_domain($udom);
6422: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6423: my $access=0;
1.800 albertel 6424: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6425: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6426: if ($type eq 'user') {
6427: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6428: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6429: if ($tdom) {
6430: if ($tdom ne $env{'user.domain'}) { next; }
6431: }
1.896 albertel 6432: if ($tuname) {
6433: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6434: }
6435: $access=($effect eq 'allow');
6436: last;
6437: }
6438: } else {
6439: if ($role) {
6440: if ($role ne $urole) { next; }
6441: }
6442: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6443: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6444: if ($tdom) {
6445: if ($tdom ne $udom) { next; }
6446: }
6447: if ($tcrs) {
6448: if ($tcrs ne $ucrs) { next; }
6449: }
6450: if ($tsec) {
6451: if ($tsec ne $usec) { next; }
6452: }
6453: $access=($effect eq 'allow');
6454: last;
6455: }
6456: if ($realm eq '' && $role eq '') {
6457: $access=($effect eq 'allow');
6458: }
1.402 bowersj2 6459: }
1.341 www 6460: }
6461: return $access;
6462: }
6463:
1.103 harris41 6464: # ------------------------------------------------- Check for a user privilege
1.12 www 6465:
6466: sub allowed {
1.810 raeburn 6467: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6468: my $ver_orguri=$uri;
1.439 www 6469: $uri=&deversion($uri);
1.152 www 6470: my $orguri=$uri;
1.52 www 6471: $uri=&declutter($uri);
1.809 raeburn 6472:
1.810 raeburn 6473: if ($priv eq 'evb') {
6474: # Evade communication block restrictions for specified role in a course
6475: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6476: return $1;
6477: } else {
6478: return;
6479: }
6480: }
6481:
1.620 albertel 6482: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6483: # Free bre access to adm and meta resources
1.775 albertel 6484: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6485: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6486: && ($priv eq 'bre')) {
1.14 www 6487: return 'F';
1.159 www 6488: }
6489:
1.545 banghart 6490: # Free bre access to user's own portfolio contents
1.714 raeburn 6491: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6492: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6493: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6494: my %setters;
6495: my ($startblock,$endblock) =
6496: &Apache::loncommon::blockcheck(\%setters,'port');
6497: if ($startblock && $endblock) {
6498: return 'B';
6499: } else {
6500: return 'F';
6501: }
1.545 banghart 6502: }
6503:
1.762 raeburn 6504: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6505: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6506: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6507: if (exists($env{'request.course.id'})) {
6508: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6509: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6510: if (($domain eq $cdom) && ($name eq $cnum)) {
6511: my $courseprivid=$env{'request.course.id'};
6512: $courseprivid=~s/\_/\//;
6513: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6514: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6515: return $1;
1.762 raeburn 6516: } else {
6517: if ($env{'request.course.sec'}) {
6518: $courseprivid.='/'.$env{'request.course.sec'};
6519: }
6520: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6521: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6522: return $2;
6523: }
1.714 raeburn 6524: }
6525: }
6526: }
6527: }
6528:
1.159 www 6529: # Free bre to public access
6530:
6531: if ($priv eq 'bre') {
1.238 www 6532: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6533: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6534: return 'F';
6535: }
1.238 www 6536: if ($copyright eq 'priv') {
6537: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6538: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6539: return '';
6540: }
6541: }
6542: if ($copyright eq 'domain') {
6543: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6544: unless (($env{'user.domain'} eq $1) ||
6545: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6546: return '';
6547: }
1.262 matthew 6548: }
1.620 albertel 6549: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6550: # Library role, so allow browsing of resources in this domain.
6551: return 'F';
1.238 www 6552: }
1.341 www 6553: if ($copyright eq 'custom') {
6554: unless (&customaccess($priv,$uri)) { return ''; }
6555: }
1.14 www 6556: }
1.264 matthew 6557: # Domain coordinator is trying to create a course
1.620 albertel 6558: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6559: # uri is the requested domain in this case.
6560: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6561: # a role of dc for the domain in question.
1.620 albertel 6562: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6563: }
1.29 www 6564:
1.52 www 6565: my $thisallowed='';
6566: my $statecond=0;
6567: my $courseprivid='';
6568:
1.1039 raeburn 6569: my $ownaccess;
1.1043 raeburn 6570: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6571: if (($priv eq 'bro') && ($env{'user.author'})) {
6572: if ($uri eq '') {
6573: $ownaccess = 1;
6574: } else {
6575: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6576: my $udom = $env{'user.domain'};
6577: my $uname = $env{'user.name'};
6578: if ($uri =~ m{^\Q$udom\E/?$}) {
6579: $ownaccess = 1;
1.1040 raeburn 6580: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6581: unless ($uri =~ m{\.\./}) {
6582: $ownaccess = 1;
6583: }
6584: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6585: my $now = time;
6586: if ($uri =~ m{^([^/]+)/?$}) {
6587: my $adom = $1;
6588: foreach my $key (keys(%env)) {
1.1042 raeburn 6589: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6590: my ($start,$end) = split('.',$env{$key});
6591: if (($now >= $start) && (!$end || $end < $now)) {
6592: $ownaccess = 1;
6593: last;
6594: }
6595: }
6596: }
6597: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6598: my $adom = $1;
6599: my $aname = $2;
1.1042 raeburn 6600: foreach my $role ('ca','aa') {
6601: if ($env{"user.role.$role./$adom/$aname"}) {
6602: my ($start,$end) =
6603: split('.',$env{"user.role.$role./$adom/$aname"});
6604: if (($now >= $start) && (!$end || $end < $now)) {
6605: $ownaccess = 1;
6606: last;
6607: }
1.1039 raeburn 6608: }
6609: }
6610: }
6611: }
6612: }
6613: }
6614: }
6615:
1.52 www 6616: # Course
6617:
1.620 albertel 6618: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6619: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6620: $thisallowed.=$1;
6621: }
1.52 www 6622: }
1.29 www 6623:
1.52 www 6624: # Domain
6625:
1.620 albertel 6626: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6627: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6628: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6629: $thisallowed.=$1;
6630: }
1.12 www 6631: }
1.52 www 6632:
1.1141 raeburn 6633: # User who is not author or co-author might still be able to edit
6634: # resource of an author in the domain (e.g., if Domain Coordinator).
6635: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6636: (&allowed('mdc',$env{'request.course.id'}))) {
6637: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6638: $thisallowed.=$1;
6639: }
6640: }
6641:
1.52 www 6642: # Course: uri itself is a course
1.66 www 6643: my $courseuri=$uri;
6644: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6645: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6646:
1.620 albertel 6647: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6648: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6649: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6650: $thisallowed.=$1;
6651: }
1.12 www 6652: }
1.29 www 6653:
1.665 albertel 6654: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6655: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6656: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6657: $thisallowed='';
1.671 raeburn 6658: my ($match)=&is_on_map($uri);
6659: if ($match) {
6660: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6661: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6662: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6663: if (@blockers > 0) {
6664: $thisallowed = 'B';
6665: } else {
6666: $thisallowed.=$1;
6667: }
1.671 raeburn 6668: }
6669: } else {
1.705 albertel 6670: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6671: if ($refuri) {
6672: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6673: $thisallowed='F';
1.671 raeburn 6674: } else {
6675: $refuri=&declutter($refuri);
6676: my ($match) = &is_on_map($refuri);
6677: if ($match) {
1.1162 raeburn 6678: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6679: if (@blockers > 0) {
6680: $thisallowed = 'B';
6681: } else {
6682: $thisallowed='F';
6683: }
1.671 raeburn 6684: }
1.669 raeburn 6685: }
1.671 raeburn 6686: }
6687: }
1.314 www 6688: }
1.492 albertel 6689:
1.766 albertel 6690: if ($priv eq 'bre'
6691: && $thisallowed ne 'F'
6692: && $thisallowed ne '2'
6693: && &is_portfolio_url($uri)) {
6694: $thisallowed = &portfolio_access($uri);
6695: }
6696:
1.52 www 6697: # Full access at system, domain or course-wide level? Exit.
1.29 www 6698: if ($thisallowed=~/F/) {
6699: return 'F';
6700: }
6701:
1.52 www 6702: # If this is generating or modifying users, exit with special codes
1.29 www 6703:
1.643 www 6704: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6705: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6706: my ($audom,$auname)=split('/',$uri);
1.643 www 6707: # no author name given, so this just checks on the general right to make a co-author in this domain
6708: unless ($auname) { return $thisallowed; }
6709: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6710: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6711: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6712: ($audom ne $env{'request.role.domain'}))) { return ''; }
6713: }
1.52 www 6714: return $thisallowed;
6715: }
6716: #
1.103 harris41 6717: # Gathered so far: system, domain and course wide privileges
1.52 www 6718: #
6719: # Course: See if uri or referer is an individual resource that is part of
6720: # the course
6721:
1.620 albertel 6722: if ($env{'request.course.id'}) {
1.232 www 6723:
1.620 albertel 6724: $courseprivid=$env{'request.course.id'};
6725: if ($env{'request.course.sec'}) {
6726: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6727: }
6728: $courseprivid=~s/\_/\//;
6729: my $checkreferer=1;
1.232 www 6730: my ($match,$cond)=&is_on_map($uri);
6731: if ($match) {
6732: $statecond=$cond;
1.620 albertel 6733: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6734: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6735: my $value = $1;
6736: if ($priv eq 'bre') {
6737: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6738: if (@blockers > 0) {
6739: $thisallowed = 'B';
6740: } else {
6741: $thisallowed.=$value;
6742: }
6743: } else {
6744: $thisallowed.=$value;
6745: }
1.52 www 6746: $checkreferer=0;
6747: }
1.29 www 6748: }
1.83 www 6749:
1.148 www 6750: if ($checkreferer) {
1.620 albertel 6751: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6752: unless ($refuri) {
1.800 albertel 6753: foreach my $key (keys(%env)) {
6754: if ($key=~/^httpref\..*\*/) {
6755: my $pattern=$key;
1.156 www 6756: $pattern=~s/^httpref\.\/res\///;
1.148 www 6757: $pattern=~s/\*/\[\^\/\]\+/g;
6758: $pattern=~s/\//\\\//g;
1.152 www 6759: if ($orguri=~/$pattern/) {
1.800 albertel 6760: $refuri=$env{$key};
1.148 www 6761: }
6762: }
1.191 harris41 6763: }
1.148 www 6764: }
1.232 www 6765:
1.148 www 6766: if ($refuri) {
1.152 www 6767: $refuri=&declutter($refuri);
1.232 www 6768: my ($match,$cond)=&is_on_map($refuri);
6769: if ($match) {
6770: my $refstatecond=$cond;
1.620 albertel 6771: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6772: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6773: my $value = $1;
6774: if ($priv eq 'bre') {
6775: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6776: if (@blockers > 0) {
6777: $thisallowed = 'B';
6778: } else {
6779: $thisallowed.=$value;
6780: }
6781: } else {
6782: $thisallowed.=$value;
6783: }
1.53 www 6784: $uri=$refuri;
6785: $statecond=$refstatecond;
1.52 www 6786: }
6787: }
1.148 www 6788: }
1.29 www 6789: }
1.52 www 6790: }
1.29 www 6791:
1.52 www 6792: #
1.103 harris41 6793: # Gathered now: all privileges that could apply, and condition number
1.52 www 6794: #
6795: #
6796: # Full or no access?
6797: #
1.29 www 6798:
1.52 www 6799: if ($thisallowed=~/F/) {
6800: return 'F';
6801: }
1.29 www 6802:
1.52 www 6803: unless ($thisallowed) {
6804: return '';
6805: }
1.29 www 6806:
1.52 www 6807: # Restrictions exist, deal with them
6808: #
6809: # C:according to course preferences
6810: # R:according to resource settings
6811: # L:unless locked
6812: # X:according to user session state
6813: #
6814:
6815: # Possibly locked functionality, check all courses
1.54 www 6816: # Locks might take effect only after 10 minutes cache expiration for other
6817: # courses, and 2 minutes for current course
1.52 www 6818:
6819: my $envkey;
6820: if ($thisallowed=~/L/) {
1.1000 raeburn 6821: foreach $envkey (keys(%env)) {
1.54 www 6822: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6823: my $courseid=$2;
6824: my $roleid=$1.'.'.$2;
1.92 www 6825: $courseid=~s/^\///;
1.54 www 6826: my $expiretime=600;
1.620 albertel 6827: if ($env{'request.role'} eq $roleid) {
1.54 www 6828: $expiretime=120;
6829: }
6830: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6831: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6832: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6833: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6834: }
1.620 albertel 6835: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6836: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6837: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6838: &log($env{'user.domain'},$env{'user.name'},
6839: $env{'user.home'},
1.57 www 6840: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6841: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6842: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6843: return '';
6844: }
6845: }
1.620 albertel 6846: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6847: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6848: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6849: &log($env{'user.domain'},$env{'user.name'},
6850: $env{'user.home'},
1.57 www 6851: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6852: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6853: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6854: return '';
6855: }
6856: }
6857: }
1.29 www 6858: }
1.52 www 6859: }
6860:
6861: #
6862: # Rest of the restrictions depend on selected course
6863: #
6864:
1.620 albertel 6865: unless ($env{'request.course.id'}) {
1.766 albertel 6866: if ($thisallowed eq 'A') {
6867: return 'A';
1.814 raeburn 6868: } elsif ($thisallowed eq 'B') {
6869: return 'B';
1.766 albertel 6870: } else {
6871: return '1';
6872: }
1.52 www 6873: }
1.29 www 6874:
1.52 www 6875: #
6876: # Now user is definitely in a course
6877: #
1.53 www 6878:
6879:
6880: # Course preferences
6881:
6882: if ($thisallowed=~/C/) {
1.620 albertel 6883: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6884: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6885: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6886: =~/\Q$rolecode\E/) {
1.1103 raeburn 6887: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6888: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6889: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6890: $env{'request.course.id'});
6891: }
1.237 www 6892: return '';
6893: }
6894:
1.620 albertel 6895: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6896: =~/\Q$unamedom\E/) {
1.1103 raeburn 6897: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6898: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6899: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6900: $env{'request.course.id'});
6901: }
1.54 www 6902: return '';
6903: }
1.53 www 6904: }
6905:
6906: # Resource preferences
6907:
6908: if ($thisallowed=~/R/) {
1.620 albertel 6909: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6910: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6911: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6912: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6913: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6914: }
6915: return '';
1.54 www 6916: }
1.53 www 6917: }
1.30 www 6918:
1.246 www 6919: # Restricted by state or randomout?
1.30 www 6920:
1.52 www 6921: if ($thisallowed=~/X/) {
1.620 albertel 6922: if ($env{'acc.randomout'}) {
1.579 albertel 6923: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6924: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6925: return '';
6926: }
1.247 www 6927: }
6928: if (&condval($statecond)) {
1.52 www 6929: return '2';
6930: } else {
6931: return '';
6932: }
6933: }
1.30 www 6934:
1.766 albertel 6935: if ($thisallowed eq 'A') {
6936: return 'A';
1.814 raeburn 6937: } elsif ($thisallowed eq 'B') {
6938: return 'B';
1.766 albertel 6939: }
1.52 www 6940: return 'F';
1.232 www 6941: }
1.1162 raeburn 6942:
1.1172.2.13 raeburn 6943: # ------------------------------------------- Check construction space access
6944:
6945: sub constructaccess {
6946: my ($url,$setpriv)=@_;
6947:
6948: # We do not allow editing of previous versions of files
6949: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
6950:
6951: # Get username and domain from URL
6952: my ($ownername,$ownerdomain,$ownerhome);
6953:
6954: ($ownerdomain,$ownername) =
6955: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
6956:
6957: # The URL does not really point to any authorspace, forget it
6958: unless (($ownername) && ($ownerdomain)) { return ''; }
6959:
6960: # Now we need to see if the user has access to the authorspace of
6961: # $ownername at $ownerdomain
6962:
6963: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
6964: # Real author for this?
6965: $ownerhome = $env{'user.home'};
6966: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
6967: return ($ownername,$ownerdomain,$ownerhome);
6968: }
6969: } else {
6970: # Co-author for this?
6971: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
6972: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
6973: $ownerhome = &homeserver($ownername,$ownerdomain);
6974: return ($ownername,$ownerdomain,$ownerhome);
6975: }
6976: }
6977:
6978: # We don't have any access right now. If we are not possibly going to do anything about this,
6979: # we might as well leave
6980: unless ($setpriv) { return ''; }
6981:
6982: # Backdoor access?
6983: my $allowed=&allowed('eco',$ownerdomain);
6984: # Nope
6985: unless ($allowed) { return ''; }
6986: # Looks like we may have access, but could be locked by the owner of the construction space
6987: if ($allowed eq 'U') {
6988: my %blocked=&get('environment',['domcoord.author'],
6989: $ownerdomain,$ownername);
6990: # Is blocked by owner
6991: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
6992: }
6993: if (($allowed eq 'F') || ($allowed eq 'U')) {
6994: # Grant temporary access
6995: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 6996: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 6997: if (!$update) { $update = $then; }
6998: my $refresh=$env{'user.refresh.time'};
6999: if (!$refresh) { $refresh = $update; }
7000: my $now = time;
7001: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7002: $now,'ca','constructaccess');
7003: $ownerhome = &homeserver($ownername,$ownerdomain);
7004: return($ownername,$ownerdomain,$ownerhome);
7005: }
7006: # No business here
7007: return '';
7008: }
7009:
1.1162 raeburn 7010: sub get_comm_blocks {
7011: my ($cdom,$cnum) = @_;
7012: if ($cdom eq '' || $cnum eq '') {
7013: return unless ($env{'request.course.id'});
7014: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7015: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7016: }
7017: my %commblocks;
7018: my $hashid=$cdom.'_'.$cnum;
7019: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7020: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7021: %commblocks = %{$blocksref};
7022: } else {
7023: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7024: my $cachetime = 600;
7025: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7026: }
7027: return %commblocks;
7028: }
7029:
7030: sub has_comm_blocking {
7031: my ($priv,$symb,$uri,$blocks) = @_;
7032: return unless ($env{'request.course.id'});
7033: return unless ($priv eq 'bre');
7034: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7035: my %commblocks;
7036: if (ref($blocks) eq 'HASH') {
7037: %commblocks = %{$blocks};
7038: } else {
7039: %commblocks = &get_comm_blocks();
7040: }
7041: return unless (keys(%commblocks) > 0);
7042: if (!$symb) { $symb=&symbread($uri,1); }
7043: my ($map,$resid,undef)=&decode_symb($symb);
7044: my %tocheck = (
7045: maps => $map,
7046: resources => $symb,
7047: );
7048: my @blockers;
7049: my $now = time;
1.1163 raeburn 7050: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7051: foreach my $block (keys(%commblocks)) {
7052: if ($block =~ /^(\d+)____(\d+)$/) {
7053: my ($start,$end) = ($1,$2);
7054: if ($start <= $now && $end >= $now) {
7055: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7056: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7057: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7058: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7059: unless (grep(/^\Q$block\E$/,@blockers)) {
7060: push(@blockers,$block);
7061: }
7062: }
7063: }
7064: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7065: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7066: unless (grep(/^\Q$block\E$/,@blockers)) {
7067: push(@blockers,$block);
7068: }
7069: }
7070: }
7071: }
7072: }
7073: }
7074: } elsif ($block =~ /^firstaccess____(.+)$/) {
7075: my $item = $1;
1.1163 raeburn 7076: my @to_test;
1.1162 raeburn 7077: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7078: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7079: my $check_interval;
7080: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7081: my @interval;
7082: my $type = 'map';
7083: if ($item eq 'course') {
7084: $type = 'course';
7085: @interval=&EXT("resource.0.interval");
7086: } else {
7087: if ($item =~ /___\d+___/) {
7088: $type = 'resource';
7089: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7090: if (ref($navmap)) {
7091: my $res = $navmap->getBySymb($item);
7092: push(@to_test,$res);
7093: }
1.1162 raeburn 7094: } else {
7095: my $mapsymb = &symbread($item,1);
7096: if ($mapsymb) {
7097: if (ref($navmap)) {
7098: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7099: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7100: foreach my $res (@to_test) {
1.1162 raeburn 7101: my $symb = $res->symb();
7102: next if ($symb eq $mapsymb);
7103: if ($symb ne '') {
7104: @interval=&EXT("resource.0.interval",$symb);
7105: last;
7106: }
7107: }
7108: }
7109: }
7110: }
7111: }
7112: if ($interval[0] =~ /\d+/) {
7113: my $first_access;
7114: if ($type eq 'resource') {
7115: $first_access=&get_first_access($interval[1],$item);
7116: } elsif ($type eq 'map') {
7117: $first_access=&get_first_access($interval[1],undef,$item);
7118: } else {
7119: $first_access=&get_first_access($interval[1]);
7120: }
7121: if ($first_access) {
7122: my $timesup = $first_access+$interval[0];
7123: if ($timesup > $now) {
1.1163 raeburn 7124: foreach my $res (@to_test) {
7125: if ($res->is_problem()) {
7126: if ($res->completable()) {
7127: unless (grep(/^\Q$block\E$/,@blockers)) {
7128: push(@blockers,$block);
7129: }
7130: last;
7131: }
7132: }
1.1162 raeburn 7133: }
7134: }
7135: }
7136: }
7137: }
7138: }
7139: }
7140: }
7141: }
7142: return @blockers;
7143: }
7144:
7145: sub check_docs_block {
7146: my ($docsblock,$tocheck) =@_;
7147: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7148: return;
7149: }
7150: if (ref($docsblock->{'maps'}) eq 'HASH') {
7151: if ($tocheck->{'maps'}) {
7152: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7153: return 1;
7154: }
7155: }
7156: }
7157: if (ref($docsblock->{'resources'}) eq 'HASH') {
7158: if ($tocheck->{'resources'}) {
7159: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7160: return 1;
7161: }
7162: }
7163: }
7164: return;
7165: }
7166:
1.1133 foxr 7167: #
7168: # Removes the versino from a URI and
7169: # splits it in to its filename and path to the filename.
7170: # Seems like File::Basename could have done this more clearly.
7171: # Parameters:
7172: # $uri - input URI
7173: # Returns:
7174: # Two element list consisting of
7175: # $pathname - the URI up to and excluding the trailing /
7176: # $filename - The part of the URI following the last /
7177: # NOTE:
7178: # Another realization of this is simply:
7179: # use File::Basename;
7180: # ...
7181: # $uri = shift;
7182: # $filename = basename($uri);
7183: # $path = dirname($uri);
7184: # return ($filename, $path);
7185: #
7186: # The implementation below is probably faster however.
7187: #
1.710 albertel 7188: sub split_uri_for_cond {
7189: my $uri=&deversion(&declutter(shift));
7190: my @uriparts=split(/\//,$uri);
7191: my $filename=pop(@uriparts);
7192: my $pathname=join('/',@uriparts);
7193: return ($pathname,$filename);
7194: }
1.232 www 7195: # --------------------------------------------------- Is a resource on the map?
7196:
7197: sub is_on_map {
1.710 albertel 7198: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7199: #Trying to find the conditional for the file
1.620 albertel 7200: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7201: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7202: if ($match) {
1.289 bowersj2 7203: return (1,$1);
7204: } else {
1.434 www 7205: return (0,0);
1.289 bowersj2 7206: }
1.12 www 7207: }
7208:
1.427 www 7209: # --------------------------------------------------------- Get symb from alias
7210:
7211: sub get_symb_from_alias {
7212: my $symb=shift;
7213: my ($map,$resid,$url)=&decode_symb($symb);
7214: # Already is a symb
7215: if ($url) { return $symb; }
7216: # Must be an alias
7217: my $aliassymb='';
7218: my %bighash;
1.620 albertel 7219: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7220: &GDBM_READER(),0640)) {
7221: my $rid=$bighash{'mapalias_'.$symb};
7222: if ($rid) {
7223: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7224: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7225: $resid,$bighash{'src_'.$rid});
1.427 www 7226: }
7227: untie %bighash;
7228: }
7229: return $aliassymb;
7230: }
7231:
1.12 www 7232: # ----------------------------------------------------------------- Define Role
7233:
7234: sub definerole {
7235: if (allowed('mcr','/')) {
7236: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7237: foreach my $role (split(':',$sysrole)) {
7238: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7239: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7240: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7241: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7242: return "refused:s:$crole&$cqual";
7243: }
7244: }
1.191 harris41 7245: }
1.800 albertel 7246: foreach my $role (split(':',$domrole)) {
7247: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7248: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7249: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7250: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7251: return "refused:d:$crole&$cqual";
7252: }
7253: }
1.191 harris41 7254: }
1.800 albertel 7255: foreach my $role (split(':',$courole)) {
7256: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7257: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7258: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7259: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7260: return "refused:c:$crole&$cqual";
7261: }
7262: }
1.191 harris41 7263: }
1.620 albertel 7264: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7265: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7266: "rolesdef_$rolename=".
7267: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7268: return reply($command,$env{'user.home'});
1.12 www 7269: } else {
7270: return 'refused';
7271: }
1.105 harris41 7272: }
7273:
7274: # ---------------- Make a metadata query against the network of library servers
7275:
7276: sub metadata_query {
1.244 matthew 7277: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 7278: my %rhash;
1.845 albertel 7279: my %libserv = &all_library();
1.244 matthew 7280: my @server_list = (defined($server_array) ? @$server_array
7281: : keys(%libserv) );
7282: for my $server (@server_list) {
1.118 harris41 7283: unless ($custom or $customshow) {
7284: my $reply=&reply("querysend:".&escape($query),$server);
7285: $rhash{$server}=$reply;
7286: }
7287: else {
7288: my $reply=&reply("querysend:".&escape($query).':'.
7289: &escape($custom).':'.&escape($customshow),
7290: $server);
7291: $rhash{$server}=$reply;
7292: }
1.112 harris41 7293: }
1.118 harris41 7294: return \%rhash;
1.240 www 7295: }
7296:
7297: # ----------------------------------------- Send log queries and wait for reply
7298:
7299: sub log_query {
7300: my ($uname,$udom,$query,%filters)=@_;
7301: my $uhome=&homeserver($uname,$udom);
7302: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7303: my $uhost=&hostname($uhome);
1.800 albertel 7304: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7305: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7306: $uhome);
1.479 albertel 7307: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7308: return get_query_reply($queryid);
7309: }
7310:
1.818 raeburn 7311: # -------------------------- Update MySQL table for portfolio file
7312:
7313: sub update_portfolio_table {
1.821 raeburn 7314: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7315: if ($group ne '') {
7316: $file_name =~s /^\Q$group\E//;
7317: }
1.818 raeburn 7318: my $homeserver = &homeserver($uname,$udom);
7319: my $queryid=
1.821 raeburn 7320: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7321: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7322: my $reply = &get_query_reply($queryid);
7323: return $reply;
7324: }
7325:
1.899 raeburn 7326: # -------------------------- Update MySQL allusers table
7327:
7328: sub update_allusers_table {
7329: my ($uname,$udom,$names) = @_;
7330: my $homeserver = &homeserver($uname,$udom);
7331: my $queryid=
7332: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7333: 'lastname='.&escape($names->{'lastname'}).'%%'.
7334: 'firstname='.&escape($names->{'firstname'}).'%%'.
7335: 'middlename='.&escape($names->{'middlename'}).'%%'.
7336: 'generation='.&escape($names->{'generation'}).'%%'.
7337: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7338: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7339: return;
1.899 raeburn 7340: }
7341:
1.508 raeburn 7342: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7343:
7344: sub fetch_enrollment_query {
1.511 raeburn 7345: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7346: my $homeserver;
1.547 raeburn 7347: my $maxtries = 1;
1.508 raeburn 7348: if ($context eq 'automated') {
7349: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7350: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7351: } else {
7352: $homeserver = &homeserver($cnum,$dom);
7353: }
1.838 albertel 7354: my $host=&hostname($homeserver);
1.506 raeburn 7355: my $cmd = '';
1.1000 raeburn 7356: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7357: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7358: }
7359: $cmd =~ s/%%$//;
7360: $cmd = &escape($cmd);
7361: my $query = 'fetchenrollment';
1.620 albertel 7362: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7363: unless ($queryid=~/^\Q$host\E\_/) {
7364: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7365: return 'error: '.$queryid;
7366: }
1.506 raeburn 7367: my $reply = &get_query_reply($queryid);
1.547 raeburn 7368: my $tries = 1;
7369: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7370: $reply = &get_query_reply($queryid);
7371: $tries ++;
7372: }
1.526 raeburn 7373: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7374: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7375: } else {
1.901 albertel 7376: my @responses = split(/:/,$reply);
1.515 raeburn 7377: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7378: foreach my $line (@responses) {
7379: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7380: $$replyref{$key} = $value;
7381: }
7382: } else {
1.1117 foxr 7383: my $pathname = LONCAPA::tempdir();
1.800 albertel 7384: foreach my $line (@responses) {
7385: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7386: $$replyref{$key} = $value;
7387: if ($value > 0) {
1.800 albertel 7388: foreach my $item (@{$$affiliatesref{$key}}) {
7389: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7390: my $destname = $pathname.'/'.$filename;
7391: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7392: if ($xml_classlist =~ /^error/) {
7393: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7394: } else {
1.506 raeburn 7395: if ( open(FILE,">$destname") ) {
7396: print FILE &unescape($xml_classlist);
7397: close(FILE);
1.526 raeburn 7398: } else {
7399: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7400: }
7401: }
7402: }
7403: }
7404: }
7405: }
7406: return 'ok';
7407: }
7408: return 'error';
7409: }
7410:
1.242 www 7411: sub get_query_reply {
7412: my $queryid=shift;
1.1117 foxr 7413: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7414: my $reply='';
7415: for (1..100) {
7416: sleep 2;
7417: if (-e $replyfile.'.end') {
1.448 albertel 7418: if (open(my $fh,$replyfile)) {
1.904 albertel 7419: $reply = join('',<$fh>);
7420: close($fh);
1.240 www 7421: } else { return 'error: reply_file_error'; }
1.242 www 7422: return &unescape($reply);
7423: }
1.240 www 7424: }
1.242 www 7425: return 'timeout:'.$queryid;
1.240 www 7426: }
7427:
7428: sub courselog_query {
1.241 www 7429: #
7430: # possible filters:
7431: # url: url or symb
7432: # username
7433: # domain
7434: # action: view, submit, grade
7435: # start: timestamp
7436: # end: timestamp
7437: #
1.240 www 7438: my (%filters)=@_;
1.620 albertel 7439: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7440: if ($filters{'url'}) {
7441: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7442: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7443: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7444: }
1.620 albertel 7445: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7446: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7447: return &log_query($cname,$cdom,'courselog',%filters);
7448: }
7449:
7450: sub userlog_query {
1.858 raeburn 7451: #
7452: # possible filters:
7453: # action: log check role
7454: # start: timestamp
7455: # end: timestamp
7456: #
1.240 www 7457: my ($uname,$udom,%filters)=@_;
7458: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7459: }
7460:
1.506 raeburn 7461: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7462:
7463: sub auto_run {
1.508 raeburn 7464: my ($cnum,$cdom) = @_;
1.876 raeburn 7465: my $response = 0;
7466: my $settings;
7467: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7468: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7469: $settings = $domconfig{'autoenroll'};
7470: if ($settings->{'run'} eq '1') {
7471: $response = 1;
7472: }
7473: } else {
1.934 raeburn 7474: my $homeserver;
7475: if (&is_course($cdom,$cnum)) {
7476: $homeserver = &homeserver($cnum,$cdom);
7477: } else {
7478: $homeserver = &domain($cdom,'primary');
7479: }
7480: if ($homeserver ne 'no_host') {
7481: $response = &reply('autorun:'.$cdom,$homeserver);
7482: }
1.876 raeburn 7483: }
1.506 raeburn 7484: return $response;
7485: }
1.776 albertel 7486:
1.506 raeburn 7487: sub auto_get_sections {
1.508 raeburn 7488: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7489: my $homeserver;
7490: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7491: $homeserver = &homeserver($cnum,$cdom);
7492: }
7493: if (!defined($homeserver)) {
7494: if ($cdom =~ /^$match_domain$/) {
7495: $homeserver = &domain($cdom,'primary');
7496: }
7497: }
7498: my @secs;
7499: if (defined($homeserver)) {
7500: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7501: unless ($response eq 'refused') {
7502: @secs = split(/:/,$response);
7503: }
1.506 raeburn 7504: }
7505: return @secs;
7506: }
1.776 albertel 7507:
1.506 raeburn 7508: sub auto_new_course {
1.1099 raeburn 7509: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7510: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7511: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7512: return $response;
7513: }
1.776 albertel 7514:
1.506 raeburn 7515: sub auto_validate_courseID {
1.508 raeburn 7516: my ($cnum,$cdom,$inst_course_id) = @_;
7517: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7518: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7519: return $response;
7520: }
1.776 albertel 7521:
1.1007 raeburn 7522: sub auto_validate_instcode {
1.1020 raeburn 7523: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7524: my ($homeserver,$response);
7525: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7526: $homeserver = &homeserver($cnum,$cdom);
7527: }
7528: if (!defined($homeserver)) {
7529: if ($cdom =~ /^$match_domain$/) {
7530: $homeserver = &domain($cdom,'primary');
7531: }
7532: }
1.1065 raeburn 7533: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7534: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7535: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7536: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7537: }
7538:
1.506 raeburn 7539: sub auto_create_password {
1.873 raeburn 7540: my ($cnum,$cdom,$authparam,$udom) = @_;
7541: my ($homeserver,$response);
1.506 raeburn 7542: my $create_passwd = 0;
7543: my $authchk = '';
1.873 raeburn 7544: if ($udom =~ /^$match_domain$/) {
7545: $homeserver = &domain($udom,'primary');
7546: }
7547: if ($homeserver eq '') {
7548: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7549: $homeserver = &homeserver($cnum,$cdom);
7550: }
7551: }
7552: if ($homeserver eq '') {
7553: $authchk = 'nodomain';
1.506 raeburn 7554: } else {
1.873 raeburn 7555: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7556: if ($response eq 'refused') {
7557: $authchk = 'refused';
7558: } else {
1.901 albertel 7559: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7560: }
1.506 raeburn 7561: }
7562: return ($authparam,$create_passwd,$authchk);
7563: }
7564:
1.706 raeburn 7565: sub auto_photo_permission {
7566: my ($cnum,$cdom,$students) = @_;
7567: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7568: my ($outcome,$perm_reqd,$conditions) =
7569: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7570: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7571: return (undef,undef);
7572: }
1.706 raeburn 7573: return ($outcome,$perm_reqd,$conditions);
7574: }
7575:
7576: sub auto_checkphotos {
7577: my ($uname,$udom,$pid) = @_;
7578: my $homeserver = &homeserver($uname,$udom);
7579: my ($result,$resulttype);
7580: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7581: &escape($uname).':'.&escape($pid),
7582: $homeserver));
1.709 albertel 7583: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7584: return (undef,undef);
7585: }
1.706 raeburn 7586: if ($outcome) {
7587: ($result,$resulttype) = split(/:/,$outcome);
7588: }
7589: return ($result,$resulttype);
7590: }
7591:
7592: sub auto_photochoice {
7593: my ($cnum,$cdom) = @_;
7594: my $homeserver = &homeserver($cnum,$cdom);
7595: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7596: &escape($cdom),
7597: $homeserver)));
1.709 albertel 7598: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7599: return (undef,undef);
7600: }
1.706 raeburn 7601: return ($update,$comment);
7602: }
7603:
7604: sub auto_photoupdate {
7605: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7606: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7607: my $host=&hostname($homeserver);
1.706 raeburn 7608: my $cmd = '';
7609: my $maxtries = 1;
1.800 albertel 7610: foreach my $affiliate (keys(%{$affiliatesref})) {
7611: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7612: }
7613: $cmd =~ s/%%$//;
7614: $cmd = &escape($cmd);
7615: my $query = 'institutionalphotos';
7616: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7617: unless ($queryid=~/^\Q$host\E\_/) {
7618: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7619: return 'error: '.$queryid;
7620: }
7621: my $reply = &get_query_reply($queryid);
7622: my $tries = 1;
7623: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7624: $reply = &get_query_reply($queryid);
7625: $tries ++;
7626: }
7627: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7628: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7629: } else {
7630: my @responses = split(/:/,$reply);
7631: my $outcome = shift(@responses);
7632: foreach my $item (@responses) {
7633: my ($key,$value) = split(/=/,$item);
7634: $$photo{$key} = $value;
7635: }
7636: return $outcome;
7637: }
7638: return 'error';
7639: }
7640:
1.521 raeburn 7641: sub auto_instcode_format {
1.793 albertel 7642: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7643: $cat_order) = @_;
1.521 raeburn 7644: my $courses = '';
1.772 raeburn 7645: my @homeservers;
1.521 raeburn 7646: if ($caller eq 'global') {
1.841 albertel 7647: my %servers = &get_servers($codedom,'library');
7648: foreach my $tryserver (keys(%servers)) {
7649: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7650: push(@homeservers,$tryserver);
7651: }
1.584 raeburn 7652: }
1.1022 raeburn 7653: } elsif ($caller eq 'requests') {
7654: if ($codedom =~ /^$match_domain$/) {
7655: my $chome = &domain($codedom,'primary');
7656: unless ($chome eq 'no_host') {
7657: push(@homeservers,$chome);
7658: }
7659: }
1.521 raeburn 7660: } else {
1.772 raeburn 7661: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7662: }
1.793 albertel 7663: foreach my $code (keys(%{$instcodes})) {
7664: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7665: }
7666: chop($courses);
1.772 raeburn 7667: my $ok_response = 0;
7668: my $response;
7669: while (@homeservers > 0 && $ok_response == 0) {
7670: my $server = shift(@homeservers);
7671: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7672: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7673: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7674: split(/:/,$response);
1.772 raeburn 7675: %{$codes} = (%{$codes},&str2hash($codes_str));
7676: push(@{$codetitles},&str2array($codetitles_str));
7677: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7678: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7679: $ok_response = 1;
7680: }
7681: }
7682: if ($ok_response) {
1.521 raeburn 7683: return 'ok';
1.772 raeburn 7684: } else {
7685: return $response;
1.521 raeburn 7686: }
7687: }
7688:
1.792 raeburn 7689: sub auto_instcode_defaults {
7690: my ($domain,$returnhash,$code_order) = @_;
7691: my @homeservers;
1.841 albertel 7692:
7693: my %servers = &get_servers($domain,'library');
7694: foreach my $tryserver (keys(%servers)) {
7695: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7696: push(@homeservers,$tryserver);
7697: }
1.792 raeburn 7698: }
1.841 albertel 7699:
1.792 raeburn 7700: my $response;
1.841 albertel 7701: foreach my $server (@homeservers) {
1.792 raeburn 7702: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7703: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7704:
7705: foreach my $pair (split(/\&/,$response)) {
7706: my ($name,$value)=split(/\=/,$pair);
7707: if ($name eq 'code_order') {
7708: @{$code_order} = split(/\&/,&unescape($value));
7709: } else {
7710: $returnhash->{&unescape($name)}=&unescape($value);
7711: }
7712: }
7713: return 'ok';
1.792 raeburn 7714: }
1.841 albertel 7715:
7716: return $response;
1.1003 raeburn 7717: }
7718:
7719: sub auto_possible_instcodes {
1.1007 raeburn 7720: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7721: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7722: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7723: return;
7724: }
1.1003 raeburn 7725: my (@homeservers,$uhome);
7726: if (defined(&domain($domain,'primary'))) {
7727: $uhome=&domain($domain,'primary');
7728: push(@homeservers,&domain($domain,'primary'));
7729: } else {
7730: my %servers = &get_servers($domain,'library');
7731: foreach my $tryserver (keys(%servers)) {
7732: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7733: push(@homeservers,$tryserver);
7734: }
7735: }
7736: }
7737: my $response;
7738: foreach my $server (@homeservers) {
7739: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7740: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7741: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7742: split(':',$response);
7743: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7744: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7745: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7746: my ($name,$value)=split('=',$item);
7747: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7748: }
7749: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7750: my ($name,$value)=split('=',$item);
7751: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7752: }
7753: return 'ok';
7754: }
7755: return $response;
7756: }
1.792 raeburn 7757:
1.1010 raeburn 7758: sub auto_courserequest_checks {
7759: my ($dom) = @_;
1.1020 raeburn 7760: my ($homeserver,%validations);
7761: if ($dom =~ /^$match_domain$/) {
7762: $homeserver = &domain($dom,'primary');
7763: }
7764: unless ($homeserver eq 'no_host') {
7765: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7766: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7767: my @items = split(/&/,$response);
7768: foreach my $item (@items) {
7769: my ($key,$value) = split('=',$item);
7770: $validations{&unescape($key)} = &thaw_unescape($value);
7771: }
7772: }
7773: }
1.1010 raeburn 7774: return %validations;
7775: }
7776:
1.1020 raeburn 7777: sub auto_courserequest_validation {
7778: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7779: my ($homeserver,$response);
7780: if ($dom =~ /^$match_domain$/) {
7781: $homeserver = &domain($dom,'primary');
7782: }
7783: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7784:
1.1020 raeburn 7785: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7786: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7787: ':'.&escape($instcode).':'.&escape($instseclist),
7788: $homeserver));
7789: }
7790: return $response;
7791: }
7792:
1.777 albertel 7793: sub auto_validate_class_sec {
1.918 raeburn 7794: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7795: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7796: my $ownerlist;
7797: if (ref($owners) eq 'ARRAY') {
7798: $ownerlist = join(',',@{$owners});
7799: } else {
7800: $ownerlist = $owners;
7801: }
1.773 raeburn 7802: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7803: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7804: return $response;
7805: }
7806:
1.679 raeburn 7807: # ------------------------------------------------------- Course Group routines
7808:
7809: sub get_coursegroups {
1.809 raeburn 7810: my ($cdom,$cnum,$group,$namespace) = @_;
7811: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7812: }
7813:
1.679 raeburn 7814: sub modify_coursegroup {
7815: my ($cdom,$cnum,$groupsettings) = @_;
7816: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7817: }
7818:
1.809 raeburn 7819: sub toggle_coursegroup_status {
7820: my ($cdom,$cnum,$group,$action) = @_;
7821: my ($from_namespace,$to_namespace);
7822: if ($action eq 'delete') {
7823: $from_namespace = 'coursegroups';
7824: $to_namespace = 'deleted_groups';
7825: } else {
7826: $from_namespace = 'deleted_groups';
7827: $to_namespace = 'coursegroups';
7828: }
7829: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7830: if (my $tmp = &error(%curr_group)) {
7831: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7832: return ('read error',$tmp);
7833: } else {
7834: my %savedsettings = %curr_group;
1.809 raeburn 7835: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7836: my $deloutcome;
7837: if ($result eq 'ok') {
1.809 raeburn 7838: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7839: } else {
7840: return ('write error',$result);
7841: }
7842: if ($deloutcome eq 'ok') {
7843: return 'ok';
7844: } else {
7845: return ('delete error',$deloutcome);
7846: }
7847: }
7848: }
7849:
1.679 raeburn 7850: sub modify_group_roles {
1.957 raeburn 7851: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7852: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7853: my $role = 'gr/'.&escape($userprivs);
7854: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7855: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7856: if ($result eq 'ok') {
7857: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7858: }
1.679 raeburn 7859: return $result;
7860: }
7861:
7862: sub modify_coursegroup_membership {
7863: my ($cdom,$cnum,$membership) = @_;
7864: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7865: return $result;
7866: }
7867:
1.682 raeburn 7868: sub get_active_groups {
7869: my ($udom,$uname,$cdom,$cnum) = @_;
7870: my $now = time;
7871: my %groups = ();
7872: foreach my $key (keys(%env)) {
1.811 albertel 7873: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7874: my ($start,$end) = split(/\./,$env{$key});
7875: if (($end!=0) && ($end<$now)) { next; }
7876: if (($start!=0) && ($start>$now)) { next; }
7877: if ($1 eq $cdom && $2 eq $cnum) {
7878: $groups{$3} = $env{$key} ;
7879: }
7880: }
7881: }
7882: return %groups;
7883: }
7884:
1.683 raeburn 7885: sub get_group_membership {
7886: my ($cdom,$cnum,$group) = @_;
7887: return(&dump('groupmembership',$cdom,$cnum,$group));
7888: }
7889:
7890: sub get_users_groups {
7891: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7892: my @usersgroups;
1.683 raeburn 7893: my $cachetime=1800;
7894:
7895: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7896: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7897: if (defined($cached)) {
1.734 albertel 7898: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7899: } else {
7900: $grouplist = '';
1.816 raeburn 7901: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7902: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7903: my $access_end = $env{'course.'.$courseid.
7904: '.default_enrollment_end_date'};
7905: my $now = time;
7906: foreach my $key (keys(%roleshash)) {
7907: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7908: my $group = $1;
7909: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7910: my $start = $2;
7911: my $end = $1;
7912: if ($start == -1) { next; } # deleted from group
7913: if (($start!=0) && ($start>$now)) { next; }
7914: if (($end!=0) && ($end<$now)) {
7915: if ($access_end && $access_end < $now) {
7916: if ($access_end - $end < 86400) {
7917: push(@usersgroups,$group);
1.733 raeburn 7918: }
7919: }
1.817 raeburn 7920: next;
1.733 raeburn 7921: }
1.817 raeburn 7922: push(@usersgroups,$group);
1.683 raeburn 7923: }
7924: }
7925: }
1.817 raeburn 7926: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7927: $grouplist = join(':',@usersgroups);
7928: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7929: }
1.733 raeburn 7930: return @usersgroups;
1.683 raeburn 7931: }
7932:
7933: sub devalidate_getgroups_cache {
7934: my ($udom,$uname,$cdom,$cnum)=@_;
7935: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7936:
1.683 raeburn 7937: my $hashid="$udom:$uname:$courseid";
7938: &devalidate_cache_new('getgroups',$hashid);
7939: }
7940:
1.12 www 7941: # ------------------------------------------------------------------ Plain Text
7942:
7943: sub plaintext {
1.988 raeburn 7944: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7945: if ($short =~ m{^cr/}) {
1.758 albertel 7946: return (split('/',$short))[-1];
7947: }
1.742 raeburn 7948: if (!defined($cid)) {
7949: $cid = $env{'request.course.id'};
7950: }
7951: my %rolenames = (
1.1008 raeburn 7952: Course => 'std',
7953: Community => 'alt1',
1.742 raeburn 7954: );
1.1037 raeburn 7955: if ($cid ne '') {
7956: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7957: unless ($forcedefault) {
7958: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7959: &Apache::lonlocal::mt_escape(\$roletext);
7960: return &Apache::lonlocal::mt($roletext);
7961: }
7962: }
7963: }
7964: if ((defined($type)) && (defined($rolenames{$type})) &&
7965: (defined($rolenames{$type})) &&
7966: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7967: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7968: } elsif ($cid ne '') {
7969: my $crstype = $env{'course.'.$cid.'.type'};
7970: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7971: (defined($prp{$short}{$rolenames{$crstype}}))) {
7972: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7973: }
1.742 raeburn 7974: }
1.1037 raeburn 7975: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7976: }
7977:
7978: # ----------------------------------------------------------------- Assign Role
7979:
7980: sub assignrole {
1.957 raeburn 7981: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7982: $context)=@_;
1.21 www 7983: my $mrole;
7984: if ($role =~ /^cr\//) {
1.393 www 7985: my $cwosec=$url;
1.811 albertel 7986: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7987: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7988: my $refused = 1;
7989: if ($context eq 'requestcourses') {
7990: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7991: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7992: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7993: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7994: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7995: if ($crsenv{'internal.courseowner'} eq
7996: $env{'user.name'}.':'.$env{'user.domain'}) {
7997: $refused = '';
7998: }
7999: }
8000: }
8001: }
8002: }
8003: if ($refused) {
8004: &logthis('Refused custom assignrole: '.
8005: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8006: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8007: return 'refused';
8008: }
1.104 www 8009: }
1.21 www 8010: $mrole='cr';
1.678 raeburn 8011: } elsif ($role =~ /^gr\//) {
8012: my $cwogrp=$url;
1.811 albertel 8013: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8014: unless (&allowed('mdg',$cwogrp)) {
8015: &logthis('Refused group assignrole: '.
8016: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8017: $env{'user.name'}.' at '.$env{'user.domain'});
8018: return 'refused';
8019: }
8020: $mrole='gr';
1.21 www 8021: } else {
1.82 www 8022: my $cwosec=$url;
1.811 albertel 8023: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8024: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8025: my $refused;
8026: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8027: if (!(&allowed('c'.$role,$url))) {
8028: $refused = 1;
8029: }
8030: } else {
8031: $refused = 1;
8032: }
1.947 raeburn 8033: if ($refused) {
1.1045 raeburn 8034: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8035: if (!$selfenroll && $context eq 'course') {
8036: my %crsenv;
8037: if ($role eq 'cc' || $role eq 'co') {
8038: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8039: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8040: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8041: if ($crsenv{'internal.courseowner'} eq
8042: $env{'user.name'}.':'.$env{'user.domain'}) {
8043: $refused = '';
8044: }
8045: }
8046: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8047: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8048: if ($crsenv{'internal.courseowner'} eq
8049: $env{'user.name'}.':'.$env{'user.domain'}) {
8050: $refused = '';
8051: }
8052: }
8053: }
8054: }
8055: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8056: $refused = '';
1.1017 raeburn 8057: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8058: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8059: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8060: my $wrongcc;
8061: if ($cnum =~ /^$match_community$/) {
8062: $wrongcc = 1 if ($role eq 'cc');
8063: } else {
8064: $wrongcc = 1 if ($role eq 'co');
8065: }
8066: unless ($wrongcc) {
8067: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8068: if ($crsenv{'internal.courseowner'} eq
8069: $env{'user.name'}.':'.$env{'user.domain'}) {
8070: $refused = '';
8071: }
1.1017 raeburn 8072: }
8073: }
1.1172.2.9 raeburn 8074: } elsif ($context eq 'requestauthor') {
8075: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8076: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8077: if ($env{'environment.requestauthor'} eq 'automatic') {
8078: $refused = '';
8079: } else {
8080: my %domdefaults = &get_domain_defaults($udom);
8081: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8082: my $checkbystatus;
8083: if ($env{'user.adv'}) {
8084: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8085: if ($disposition eq 'automatic') {
8086: $refused = '';
8087: } elsif ($disposition eq '') {
8088: $checkbystatus = 1;
8089: }
8090: } else {
8091: $checkbystatus = 1;
8092: }
8093: if ($checkbystatus) {
8094: if ($env{'environment.inststatus'}) {
8095: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8096: foreach my $type (@inststatuses) {
8097: if (($type ne '') &&
8098: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8099: $refused = '';
8100: }
8101: }
8102: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8103: $refused = '';
8104: }
8105: }
8106: }
8107: }
8108: }
1.1017 raeburn 8109: }
8110: if ($refused) {
1.947 raeburn 8111: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8112: ' '.$role.' '.$end.' '.$start.' by '.
8113: $env{'user.name'}.' at '.$env{'user.domain'});
8114: return 'refused';
8115: }
1.932 raeburn 8116: }
1.1131 raeburn 8117: } elsif ($role eq 'au') {
8118: if ($url ne '/'.$udom.'/') {
8119: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8120: ' to assign author role for '.$uname.':'.$udom.
8121: ' in domain: '.$url.' refused (wrong domain).');
8122: return 'refused';
8123: }
1.104 www 8124: }
1.21 www 8125: $mrole=$role;
8126: }
1.620 albertel 8127: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8128: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8129: if ($end) { $command.='_'.$end; }
1.21 www 8130: if ($start) {
8131: if ($end) {
1.81 www 8132: $command.='_'.$start;
1.21 www 8133: } else {
1.81 www 8134: $command.='_0_'.$start;
1.21 www 8135: }
8136: }
1.739 raeburn 8137: my $origstart = $start;
8138: my $origend = $end;
1.957 raeburn 8139: my $delflag;
1.357 www 8140: # actually delete
8141: if ($deleteflag) {
1.373 www 8142: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8143: # modify command to delete the role
1.620 albertel 8144: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8145: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8146: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8147: # set start and finish to negative values for userrolelog
8148: $start=-1;
8149: $end=-1;
1.957 raeburn 8150: $delflag = 1;
1.357 www 8151: }
8152: }
8153: # send command
1.349 www 8154: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8155: # log new user role if status is ok
1.349 www 8156: if ($answer eq 'ok') {
1.663 raeburn 8157: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8158: if (($role eq 'cc') || ($role eq 'in') ||
8159: ($role eq 'ep') || ($role eq 'ad') ||
8160: ($role eq 'ta') || ($role eq 'st') ||
8161: ($role=~/^cr/) || ($role eq 'gr') ||
8162: ($role eq 'co')) {
1.1172.2.13 raeburn 8163: # for course roles, perform group memberships changes triggered by role change.
8164: unless ($role =~ /^gr/) {
8165: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8166: $origstart,$selfenroll,$context);
8167: }
1.1172.2.9 raeburn 8168: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8169: $selfenroll,$context);
8170: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8171: ($role eq 'au') || ($role eq 'dc')) {
8172: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8173: $context);
8174: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8175: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8176: $context);
8177: }
1.1053 raeburn 8178: if ($role eq 'cc') {
8179: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8180: }
1.349 www 8181: }
8182: return $answer;
1.169 harris41 8183: }
8184:
1.1053 raeburn 8185: sub autoupdate_coowners {
8186: my ($url,$end,$start,$uname,$udom) = @_;
8187: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8188: if (($cdom ne '') && ($cnum ne '')) {
8189: my $now = time;
8190: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8191: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8192: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8193: my $instcode = $coursehash{'internal.coursecode'};
8194: if ($instcode ne '') {
1.1056 raeburn 8195: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8196: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8197: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8198: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8199: if ($result eq 'valid') {
8200: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8201: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8202: push(@newcoowners,$coowner);
8203: }
8204: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8205: push(@newcoowners,$uname.':'.$udom);
8206: }
8207: @newcoowners = sort(@newcoowners);
8208: } else {
8209: push(@newcoowners,$uname.':'.$udom);
8210: }
8211: } else {
8212: if ($coursehash{'internal.co-owners'}) {
8213: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8214: unless ($coowner eq $uname.':'.$udom) {
8215: push(@newcoowners,$coowner);
8216: }
8217: }
8218: unless (@newcoowners > 0) {
8219: $delcoowners = 1;
8220: $coowners = '';
8221: }
8222: }
8223: }
8224: if (@newcoowners || $delcoowners) {
8225: &store_coowners($cdom,$cnum,$coursehash{'home'},
8226: $delcoowners,@newcoowners);
8227: }
8228: }
8229: }
8230: }
8231: }
8232: }
8233: }
8234:
8235: sub store_coowners {
8236: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8237: my $cid = $cdom.'_'.$cnum;
8238: my ($coowners,$delresult,$putresult);
8239: if (@newcoowners) {
8240: $coowners = join(',',@newcoowners);
8241: my %coownershash = (
8242: 'internal.co-owners' => $coowners,
8243: );
8244: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8245: if ($putresult eq 'ok') {
8246: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8247: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8248: }
8249: }
8250: }
8251: if ($delcoowners) {
8252: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8253: if ($delresult eq 'ok') {
8254: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8255: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8256: }
8257: }
8258: }
8259: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8260: my %crsinfo =
8261: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8262: if (ref($crsinfo{$cid}) eq 'HASH') {
8263: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8264: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8265: }
8266: }
8267: }
8268:
1.169 harris41 8269: # -------------------------------------------------- Modify user authentication
1.197 www 8270: # Overrides without validation
8271:
1.169 harris41 8272: sub modifyuserauth {
8273: my ($udom,$uname,$umode,$upass)=@_;
8274: my $uhome=&homeserver($uname,$udom);
1.197 www 8275: unless (&allowed('mau',$udom)) { return 'refused'; }
8276: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8277: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8278: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8279: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8280: &escape($upass),$uhome);
1.620 albertel 8281: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8282: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8283: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8284: &log($udom,,$uname,$uhome,
1.620 albertel 8285: 'Authentication changed by '.$env{'user.domain'}.', '.
8286: $env{'user.name'}.', '.$umode.
1.197 www 8287: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8288: unless ($reply eq 'ok') {
1.197 www 8289: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8290: return 'error: '.$reply;
8291: }
1.170 harris41 8292: return 'ok';
1.80 www 8293: }
8294:
1.81 www 8295: # --------------------------------------------------------------- Modify a user
1.80 www 8296:
1.81 www 8297: sub modifyuser {
1.206 matthew 8298: my ($udom, $uname, $uid,
8299: $umode, $upass, $first,
8300: $middle, $last, $gene,
1.1058 raeburn 8301: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8302: $udom= &LONCAPA::clean_domain($udom);
8303: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8304: my $showcandelete = 'none';
8305: if (ref($candelete) eq 'ARRAY') {
8306: if (@{$candelete} > 0) {
8307: $showcandelete = join(', ',@{$candelete});
8308: }
8309: }
1.81 www 8310: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8311: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8312: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8313: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8314: ' desiredhome not specified').
1.620 albertel 8315: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8316: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8317: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8318: my $newuser;
8319: if ($uhome eq 'no_host') {
8320: $newuser = 1;
8321: }
1.80 www 8322: # ----------------------------------------------------------------- Create User
1.406 albertel 8323: if (($uhome eq 'no_host') &&
8324: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8325: my $unhome='';
1.844 albertel 8326: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8327: $unhome = $desiredhome;
1.620 albertel 8328: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8329: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8330: } else { # load balancing routine for determining $unhome
1.81 www 8331: my $loadm=10000000;
1.841 albertel 8332: my %servers = &get_servers($udom,'library');
8333: foreach my $tryserver (keys(%servers)) {
8334: my $answer=reply('load',$tryserver);
8335: if (($answer=~/\d+/) && ($answer<$loadm)) {
8336: $loadm=$answer;
8337: $unhome=$tryserver;
8338: }
1.80 www 8339: }
8340: }
8341: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8342: return 'error: unable to find a home server for '.$uname.
8343: ' in domain '.$udom;
1.80 www 8344: }
8345: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8346: &escape($upass),$unhome);
8347: unless ($reply eq 'ok') {
8348: return 'error: '.$reply;
8349: }
1.230 stredwic 8350: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8351: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8352: return 'error: unable verify users home machine.';
1.80 www 8353: }
1.209 matthew 8354: } # End of creation of new user
1.80 www 8355: # ---------------------------------------------------------------------- Add ID
8356: if ($uid) {
8357: $uid=~tr/A-Z/a-z/;
8358: my %uidhash=&idrget($udom,$uname);
1.196 www 8359: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8360: && (!$forceid)) {
1.80 www 8361: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8362: return 'error: user id "'.$uid.'" does not match '.
8363: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8364: }
8365: } else {
8366: &idput($udom,($uname => $uid));
8367: }
8368: }
8369: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8370: my @tmp=&get('environment',
1.899 raeburn 8371: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8372: 'permanentemail','inststatus'],
1.134 albertel 8373: $udom,$uname);
1.1075 raeburn 8374: my (%names,%oldnames);
1.313 matthew 8375: if ($tmp[0] =~ m/^error:.*/) {
8376: %names=();
8377: } else {
8378: %names = @tmp;
1.1075 raeburn 8379: %oldnames = %names;
1.313 matthew 8380: }
1.388 www 8381: #
1.1058 raeburn 8382: # If name, email and/or uid are blank (e.g., because an uploaded file
8383: # of users did not contain them), do not overwrite existing values
8384: # unless field is in $candelete array ref.
8385: #
8386:
8387: my @fields = ('firstname','middlename','lastname','generation',
8388: 'permanentemail','id');
8389: my %newvalues;
8390: if (ref($candelete) eq 'ARRAY') {
8391: foreach my $field (@fields) {
8392: if (grep(/^\Q$field\E$/,@{$candelete})) {
8393: if ($field eq 'firstname') {
8394: $names{$field} = $first;
8395: } elsif ($field eq 'middlename') {
8396: $names{$field} = $middle;
8397: } elsif ($field eq 'lastname') {
8398: $names{$field} = $last;
8399: } elsif ($field eq 'generation') {
8400: $names{$field} = $gene;
8401: } elsif ($field eq 'permanentemail') {
8402: $names{$field} = $email;
8403: } elsif ($field eq 'id') {
8404: $names{$field} = $uid;
8405: }
8406: }
8407: }
8408: }
1.388 www 8409: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8410: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8411: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8412: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8413: if ($email) {
8414: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8415: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8416: }
1.899 raeburn 8417: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8418: if (defined($inststatus)) {
8419: $names{'inststatus'} = '';
8420: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8421: if (ref($usertypes) eq 'HASH') {
8422: my @okstatuses;
8423: foreach my $item (split(/:/,$inststatus)) {
8424: if (defined($usertypes->{$item})) {
8425: push(@okstatuses,$item);
8426: }
8427: }
8428: if (@okstatuses) {
8429: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8430: }
8431: }
8432: }
1.1075 raeburn 8433: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8434: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8435: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8436: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8437: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8438: } else {
8439: $logmsg .= ' during self creation';
8440: }
1.1075 raeburn 8441: my $changed;
8442: if ($newuser) {
8443: $changed = 1;
8444: } else {
8445: foreach my $field (@fields) {
8446: if ($names{$field} ne $oldnames{$field}) {
8447: $changed = 1;
8448: last;
8449: }
8450: }
8451: }
8452: unless ($changed) {
8453: $logmsg = 'No changes in user information needed for: '.$logmsg;
8454: &logthis($logmsg);
8455: return 'ok';
8456: }
8457: my $reply = &put('environment', \%names, $udom,$uname);
8458: if ($reply ne 'ok') {
8459: return 'error: '.$reply;
8460: }
1.1087 raeburn 8461: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8462: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8463: }
1.1075 raeburn 8464: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8465: &devalidate_cache_new('namescache',$uname.':'.$udom);
8466: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8467: &logthis($logmsg);
1.134 albertel 8468: return 'ok';
1.80 www 8469: }
8470:
1.81 www 8471: # -------------------------------------------------------------- Modify student
1.80 www 8472:
1.81 www 8473: sub modifystudent {
8474: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8475: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8476: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8477: if (!$cid) {
1.620 albertel 8478: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8479: return 'not_in_class';
8480: }
1.80 www 8481: }
8482: # --------------------------------------------------------------- Make the user
1.81 www 8483: my $reply=&modifyuser
1.209 matthew 8484: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8485: $desiredhome,$email,$inststatus);
1.80 www 8486: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8487: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31! raeburn 8488: # student's environment
1.297 matthew 8489: $uid = undef if (!$forceid);
1.455 albertel 8490: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8491: $gene,$usec,$end,$start,$type,$locktype,
8492: $cid,$selfenroll,$context,$credits);
1.297 matthew 8493: return $reply;
8494: }
8495:
8496: sub modify_student_enrollment {
1.1172.2.23 raeburn 8497: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8498: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8499: my ($cdom,$cnum,$chome);
8500: if (!$cid) {
1.620 albertel 8501: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8502: return 'not_in_class';
8503: }
1.620 albertel 8504: $cdom=$env{'course.'.$cid.'.domain'};
8505: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8506: } else {
8507: ($cdom,$cnum)=split(/_/,$cid);
8508: }
1.620 albertel 8509: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8510: if (!$chome) {
1.457 raeburn 8511: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8512: }
1.455 albertel 8513: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8514: # Make sure the user exists
1.81 www 8515: my $uhome=&homeserver($uname,$udom);
8516: if (($uhome eq '') || ($uhome eq 'no_host')) {
8517: return 'error: no such user';
8518: }
1.297 matthew 8519: # Get student data if we were not given enough information
8520: if (!defined($first) || $first eq '' ||
8521: !defined($last) || $last eq '' ||
8522: !defined($uid) || $uid eq '' ||
8523: !defined($middle) || $middle eq '' ||
8524: !defined($gene) || $gene eq '') {
1.294 matthew 8525: # They did not supply us with enough data to enroll the student, so
8526: # we need to pick up more information.
1.297 matthew 8527: my %tmp = &get('environment',
1.294 matthew 8528: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8529: ,$udom,$uname);
8530:
1.800 albertel 8531: #foreach my $key (keys(%tmp)) {
8532: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8533: #}
1.294 matthew 8534: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8535: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8536: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8537: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8538: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8539: }
1.556 albertel 8540: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8541: my $user = "$uname:$udom";
8542: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8543: my $reply=cput('classlist',
1.1148 raeburn 8544: {$user =>
1.1172.2.19 raeburn 8545: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8546: $cdom,$cnum);
1.1148 raeburn 8547: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8548: &devalidate_getsection_cache($udom,$uname,$cid);
8549: } else {
1.81 www 8550: return 'error: '.$reply;
8551: }
1.297 matthew 8552: # Add student role to user
1.83 www 8553: my $uurl='/'.$cid;
1.81 www 8554: $uurl=~s/\_/\//g;
8555: if ($usec) {
8556: $uurl.='/'.$usec;
8557: }
1.1148 raeburn 8558: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8559: $selfenroll,$context);
8560: if ($result ne 'ok') {
8561: if ($old_entry{$user} ne '') {
8562: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8563: } else {
8564: $reply = &del('classlist',[$user],$cdom,$cnum);
8565: }
8566: }
8567: return $result;
1.21 www 8568: }
8569:
1.556 albertel 8570: sub format_name {
8571: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8572: my $name;
8573: if ($first ne 'lastname') {
8574: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8575: } else {
8576: if ($lastname=~/\S/) {
8577: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8578: $name=~s/\s+,/,/;
8579: } else {
8580: $name.= $firstname.' '.$middlename.' '.$generation;
8581: }
8582: }
8583: $name=~s/^\s+//;
8584: $name=~s/\s+$//;
8585: $name=~s/\s+/ /g;
8586: return $name;
8587: }
8588:
1.84 www 8589: # ------------------------------------------------- Write to course preferences
8590:
8591: sub writecoursepref {
8592: my ($courseid,%prefs)=@_;
8593: $courseid=~s/^\///;
8594: $courseid=~s/\_/\//g;
8595: my ($cdomain,$cnum)=split(/\//,$courseid);
8596: my $chome=homeserver($cnum,$cdomain);
8597: if (($chome eq '') || ($chome eq 'no_host')) {
8598: return 'error: no such course';
8599: }
8600: my $cstring='';
1.800 albertel 8601: foreach my $pref (keys(%prefs)) {
8602: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8603: }
1.84 www 8604: $cstring=~s/\&$//;
8605: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8606: }
8607:
8608: # ---------------------------------------------------------- Make/modify course
8609:
8610: sub createcourse {
1.741 raeburn 8611: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8612: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8613: $url=&declutter($url);
8614: my $cid='';
1.1028 raeburn 8615: if ($context eq 'requestcourses') {
8616: my $can_create = 0;
8617: my ($ownername,$ownerdom) = split(':',$course_owner);
8618: if ($udom eq $ownerdom) {
8619: if (&usertools_access($ownername,$ownerdom,$category,undef,
8620: $context)) {
8621: $can_create = 1;
8622: }
8623: } else {
8624: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8625: $category);
8626: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8627: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8628: if (@curr > 0) {
8629: my @options = qw(approval validate autolimit);
8630: my $optregex = join('|',@options);
8631: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8632: $can_create = 1;
8633: }
8634: }
8635: }
8636: }
8637: if ($can_create) {
8638: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8639: unless (&allowed('ccc',$udom)) {
8640: return 'refused';
8641: }
1.1017 raeburn 8642: }
8643: } else {
8644: return 'refused';
8645: }
1.1028 raeburn 8646: } elsif (!&allowed('ccc',$udom)) {
8647: return 'refused';
1.84 www 8648: }
1.1011 raeburn 8649: # --------------------------------------------------------------- Get Unique ID
8650: my $uname;
8651: if ($cnum =~ /^$match_courseid$/) {
8652: my $chome=&homeserver($cnum,$udom,'true');
8653: if (($chome eq '') || ($chome eq 'no_host')) {
8654: $uname = $cnum;
8655: } else {
1.1038 raeburn 8656: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8657: }
8658: } else {
1.1038 raeburn 8659: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8660: }
8661: return $uname if ($uname =~ /^error/);
8662: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8663: if (!defined($course_server)) {
8664: if (defined(&domain($udom,'primary'))) {
8665: $course_server = &domain($udom,'primary');
8666: } else {
8667: $course_server = $env{'user.home'};
8668: }
8669: }
8670: my %host_servers =
8671: &Apache::lonnet::get_servers($udom,'library');
8672: unless ($host_servers{$course_server}) {
8673: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8674: }
1.84 www 8675: # ------------------------------------------------------------- Make the course
8676: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8677: $course_server);
1.84 www 8678: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8679: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8680: if (($uhome eq '') || ($uhome eq 'no_host')) {
8681: return 'error: no such course';
8682: }
1.271 www 8683: # ----------------------------------------------------------------- Course made
1.516 raeburn 8684: # log existence
1.1029 raeburn 8685: my $now = time;
1.918 raeburn 8686: my $newcourse = {
8687: $udom.'_'.$uname => {
1.921 raeburn 8688: description => $description,
8689: inst_code => $inst_code,
8690: owner => $course_owner,
8691: type => $crstype,
1.1029 raeburn 8692: creator => $env{'user.name'}.':'.
8693: $env{'user.domain'},
8694: created => $now,
8695: context => $context,
1.918 raeburn 8696: },
8697: };
1.921 raeburn 8698: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8699: # set toplevel url
1.271 www 8700: my $topurl=$url;
8701: unless ($nonstandard) {
8702: # ------------------------------------------ For standard courses, make top url
8703: my $mapurl=&clutter($url);
1.278 www 8704: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8705: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8706: <map>
8707: <resource id="1" type="start"></resource>
8708: <resource id="2" src="$mapurl"></resource>
8709: <resource id="3" type="finish"></resource>
8710: <link index="1" from="1" to="2"></link>
8711: <link index="2" from="2" to="3"></link>
8712: </map>
8713: ENDINITMAP
8714: $topurl=&declutter(
1.638 albertel 8715: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8716: );
8717: }
8718: # ----------------------------------------------------------- Write preferences
1.84 www 8719: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8720: ('description' => $description,
8721: 'url' => $topurl,
8722: 'internal.creator' => $env{'user.name'}.':'.
8723: $env{'user.domain'},
8724: 'internal.created' => $now,
8725: 'internal.creationcontext' => $context)
8726: );
1.84 www 8727: return '/'.$udom.'/'.$uname;
8728: }
8729:
1.1011 raeburn 8730: # ------------------------------------------------------------------- Create ID
8731: sub generate_coursenum {
1.1038 raeburn 8732: my ($udom,$crstype) = @_;
1.1011 raeburn 8733: my $domdesc = &domain($udom);
8734: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8735: my $first;
8736: if ($crstype eq 'Community') {
8737: $first = '0';
8738: } else {
8739: $first = int(1+rand(9));
8740: }
8741: my $uname=$first.
1.1011 raeburn 8742: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8743: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8744: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8745: # ----------------------------------------------- Make sure that does not exist
8746: my $uhome=&homeserver($uname,$udom,'true');
8747: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8748: if ($crstype eq 'Community') {
8749: $first = '0';
8750: } else {
8751: $first = int(1+rand(9));
8752: }
8753: $uname=$first.
1.1011 raeburn 8754: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8755: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8756: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8757: $uhome=&homeserver($uname,$udom,'true');
8758: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8759: return 'error: unable to generate unique course-ID';
8760: }
8761: }
8762: return $uname;
8763: }
8764:
1.813 albertel 8765: sub is_course {
1.1167 droeschl 8766: my ($cdom, $cnum) = scalar(@_) == 1 ?
8767: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8768:
8769: return unless $cdom and $cnum;
8770:
8771: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8772: '.');
8773:
1.1172.2.23 raeburn 8774: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8775: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8776: }
8777:
1.1015 raeburn 8778: sub store_userdata {
8779: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8780: my $result;
1.1016 raeburn 8781: if ($datakey ne '') {
1.1013 raeburn 8782: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8783: if ($udom eq '' || $uname eq '') {
8784: $udom = $env{'user.domain'};
8785: $uname = $env{'user.name'};
8786: }
8787: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8788: if (($uhome eq '') || ($uhome eq 'no_host')) {
8789: $result = 'error: no_host';
8790: } else {
8791: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8792: $storehash->{'host'} = $perlvar{'lonHostID'};
8793:
8794: my $namevalue='';
8795: foreach my $key (keys(%{$storehash})) {
8796: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8797: }
8798: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 8799: unless ($namespace eq 'courserequests') {
8800: $datakey = &escape($datakey);
8801: }
1.1105 raeburn 8802: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8803: $namevalue,$uhome);
1.1013 raeburn 8804: }
8805: } else {
8806: $result = 'error: data to store was not a hash reference';
8807: }
8808: } else {
8809: $result= 'error: invalid requestkey';
8810: }
8811: return $result;
8812: }
8813:
1.21 www 8814: # ---------------------------------------------------------- Assign Custom Role
8815:
8816: sub assigncustomrole {
1.957 raeburn 8817: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8818: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8819: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8820: }
8821:
8822: # ----------------------------------------------------------------- Revoke Role
8823:
8824: sub revokerole {
1.957 raeburn 8825: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8826: my $now=time;
1.965 raeburn 8827: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8828: }
8829:
8830: # ---------------------------------------------------------- Revoke Custom Role
8831:
8832: sub revokecustomrole {
1.957 raeburn 8833: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8834: my $now=time;
1.357 www 8835: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8836: $deleteflag,$selfenroll,$context);
1.17 www 8837: }
8838:
1.533 banghart 8839: # ------------------------------------------------------------ Disk usage
1.535 albertel 8840: sub diskusage {
1.955 raeburn 8841: my ($udom,$uname,$directorypath,$getpropath)=@_;
8842: $directorypath =~ s/\/$//;
8843: my $listing=&reply('du2:'.&escape($directorypath).':'
8844: .&escape($getpropath).':'.&escape($uname).':'
8845: .&escape($udom),homeserver($uname,$udom));
8846: if ($listing eq 'unknown_cmd') {
8847: if ($getpropath) {
8848: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8849: }
8850: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8851: }
1.514 albertel 8852: return $listing;
1.512 banghart 8853: }
8854:
1.566 banghart 8855: sub is_locked {
1.1096 raeburn 8856: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8857: my @check;
8858: my $is_locked;
1.1093 raeburn 8859: push (@check,$file_name);
1.613 albertel 8860: my %locked = &get('file_permissions',\@check,
1.620 albertel 8861: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8862: my ($tmp)=keys(%locked);
8863: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8864:
1.566 banghart 8865: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8866: $is_locked = 'false';
8867: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8868: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8869: $is_locked = 'true';
1.1096 raeburn 8870: if (ref($which) eq 'ARRAY') {
8871: push(@{$which},$entry);
8872: } else {
8873: last;
8874: }
1.745 raeburn 8875: }
8876: }
1.566 banghart 8877: } else {
8878: $is_locked = 'false';
8879: }
1.1093 raeburn 8880: return $is_locked;
1.566 banghart 8881: }
8882:
1.759 albertel 8883: sub declutter_portfile {
8884: my ($file) = @_;
1.833 albertel 8885: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8886: return $file;
8887: }
8888:
1.559 banghart 8889: # ------------------------------------------------------------- Mark as Read Only
8890:
8891: sub mark_as_readonly {
8892: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8893: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8894: my ($tmp)=keys(%current_permissions);
8895: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8896: foreach my $file (@{$files}) {
1.759 albertel 8897: $file = &declutter_portfile($file);
1.561 banghart 8898: push(@{$current_permissions{$file}},$what);
1.559 banghart 8899: }
1.613 albertel 8900: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8901: return;
8902: }
8903:
1.572 banghart 8904: # ------------------------------------------------------------Save Selected Files
8905:
8906: sub save_selected_files {
8907: my ($user, $path, @files) = @_;
8908: my $filename = $user."savedfiles";
1.573 banghart 8909: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8910: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8911: foreach my $file (@files) {
1.620 albertel 8912: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8913: }
8914: foreach my $file (@other_files) {
1.574 banghart 8915: print (OUT $file."\n");
1.572 banghart 8916: }
1.574 banghart 8917: close (OUT);
1.572 banghart 8918: return 'ok';
8919: }
8920:
1.574 banghart 8921: sub clear_selected_files {
8922: my ($user) = @_;
8923: my $filename = $user."savedfiles";
1.1117 foxr 8924: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8925: print (OUT undef);
8926: close (OUT);
8927: return ("ok");
8928: }
8929:
1.572 banghart 8930: sub files_in_path {
8931: my ($user, $path) = @_;
8932: my $filename = $user."savedfiles";
8933: my %return_files;
1.1117 foxr 8934: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8935: while (my $line_in = <IN>) {
1.574 banghart 8936: chomp ($line_in);
8937: my @paths_and_file = split (m!/!, $line_in);
8938: my $file_part = pop (@paths_and_file);
8939: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8940: $path_part.='/';
8941: my $path_and_file = $path_part.$file_part;
8942: if ($path_part eq $path) {
8943: $return_files{$file_part}= 'selected';
8944: }
8945: }
1.574 banghart 8946: close (IN);
8947: return (\%return_files);
1.572 banghart 8948: }
8949:
8950: # called in portfolio select mode, to show files selected NOT in current directory
8951: sub files_not_in_path {
8952: my ($user, $path) = @_;
8953: my $filename = $user."savedfiles";
8954: my @return_files;
8955: my $path_part;
1.1117 foxr 8956: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8957: while (my $line = <IN>) {
1.572 banghart 8958: #ok, I know it's clunky, but I want it to work
1.800 albertel 8959: my @paths_and_file = split(m|/|, $line);
8960: my $file_part = pop(@paths_and_file);
8961: chomp($file_part);
8962: my $path_part = join('/', @paths_and_file);
1.572 banghart 8963: $path_part .= '/';
8964: my $path_and_file = $path_part.$file_part;
8965: if ($path_part ne $path) {
1.800 albertel 8966: push(@return_files, ($path_and_file));
1.572 banghart 8967: }
8968: }
1.800 albertel 8969: close(OUT);
1.574 banghart 8970: return (@return_files);
1.572 banghart 8971: }
8972:
1.745 raeburn 8973: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8974:
1.745 raeburn 8975: sub get_portfile_permissions {
8976: my ($domain,$user) = @_;
1.613 albertel 8977: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8978: my ($tmp)=keys(%current_permissions);
8979: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8980: return \%current_permissions;
8981: }
8982:
8983: #---------------------------------------------Get portfolio file access controls
8984:
1.749 raeburn 8985: sub get_access_controls {
1.745 raeburn 8986: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8987: my %access;
8988: my $real_file = $file;
8989: $file =~ s/\.meta$//;
1.745 raeburn 8990: if (defined($file)) {
1.749 raeburn 8991: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8992: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8993: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8994: }
8995: }
1.745 raeburn 8996: } else {
1.749 raeburn 8997: foreach my $key (keys(%{$current_permissions})) {
8998: if ($key =~ /\0accesscontrol$/) {
8999: if (defined($group)) {
9000: if ($key !~ m-^\Q$group\E/-) {
9001: next;
9002: }
9003: }
9004: my ($fullpath) = split(/\0/,$key);
9005: if (ref($$current_permissions{$key}) eq 'HASH') {
9006: foreach my $control (keys(%{$$current_permissions{$key}})) {
9007: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9008: }
9009: }
9010: }
9011: }
9012: }
9013: return %access;
9014: }
9015:
9016: sub modify_access_controls {
9017: my ($file_name,$changes,$domain,$user)=@_;
9018: my ($outcome,$deloutcome);
9019: my %store_permissions;
9020: my %new_values;
9021: my %new_control;
9022: my %translation;
9023: my @deletions = ();
9024: my $now = time;
9025: if (exists($$changes{'activate'})) {
9026: if (ref($$changes{'activate'}) eq 'HASH') {
9027: my @newitems = sort(keys(%{$$changes{'activate'}}));
9028: my $numnew = scalar(@newitems);
9029: for (my $i=0; $i<$numnew; $i++) {
9030: my $newkey = $newitems[$i];
9031: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9032: if ($newkey =~ /^\d+:/) {
9033: $newkey =~ s/^(\d+)/$newid/;
9034: $translation{$1} = $newid;
9035: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9036: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9037: $translation{$1} = $newid;
9038: }
1.749 raeburn 9039: $new_values{$file_name."\0".$newkey} =
9040: $$changes{'activate'}{$newitems[$i]};
9041: $new_control{$newkey} = $now;
9042: }
9043: }
9044: }
9045: my %todelete;
9046: my %changed_items;
9047: foreach my $action ('delete','update') {
9048: if (exists($$changes{$action})) {
9049: if (ref($$changes{$action}) eq 'HASH') {
9050: foreach my $key (keys(%{$$changes{$action}})) {
9051: my ($itemnum) = ($key =~ /^([^:]+):/);
9052: if ($action eq 'delete') {
9053: $todelete{$itemnum} = 1;
9054: } else {
9055: $changed_items{$itemnum} = $key;
9056: }
9057: }
1.745 raeburn 9058: }
9059: }
1.749 raeburn 9060: }
9061: # get lock on access controls for file.
9062: my $lockhash = {
9063: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9064: ':'.$env{'user.domain'},
9065: };
9066: my $tries = 0;
9067: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9068:
9069: while (($gotlock ne 'ok') && $tries <3) {
9070: $tries ++;
9071: sleep 1;
9072: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9073: }
9074: if ($gotlock eq 'ok') {
9075: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9076: my ($tmp)=keys(%curr_permissions);
9077: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9078: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9079: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9080: if (ref($curr_controls) eq 'HASH') {
9081: foreach my $control_item (keys(%{$curr_controls})) {
9082: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9083: if (defined($todelete{$itemnum})) {
9084: push(@deletions,$file_name."\0".$control_item);
9085: } else {
9086: if (defined($changed_items{$itemnum})) {
9087: $new_control{$changed_items{$itemnum}} = $now;
9088: push(@deletions,$file_name."\0".$control_item);
9089: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9090: } else {
9091: $new_control{$control_item} = $$curr_controls{$control_item};
9092: }
9093: }
1.745 raeburn 9094: }
9095: }
9096: }
1.970 raeburn 9097: my ($group);
9098: if (&is_course($domain,$user)) {
9099: ($group,my $file) = split(/\//,$file_name,2);
9100: }
1.749 raeburn 9101: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9102: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9103: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9104: # remove lock
9105: my @del_lock = ($file_name."\0".'locked_access_records');
9106: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9107: my $sqlresult =
1.970 raeburn 9108: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9109: $group);
1.749 raeburn 9110: } else {
9111: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9112: }
1.749 raeburn 9113: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9114: }
9115:
1.827 raeburn 9116: sub make_public_indefinitely {
9117: my ($requrl) = @_;
9118: my $now = time;
9119: my $action = 'activate';
9120: my $aclnum = 0;
9121: if (&is_portfolio_url($requrl)) {
9122: my (undef,$udom,$unum,$file_name,$group) =
9123: &parse_portfolio_url($requrl);
9124: my $current_perms = &get_portfile_permissions($udom,$unum);
9125: my %access_controls = &get_access_controls($current_perms,
9126: $group,$file_name);
9127: foreach my $key (keys(%{$access_controls{$file_name}})) {
9128: my ($num,$scope,$end,$start) =
9129: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9130: if ($scope eq 'public') {
9131: if ($start <= $now && $end == 0) {
9132: $action = 'none';
9133: } else {
9134: $action = 'update';
9135: $aclnum = $num;
9136: }
9137: last;
9138: }
9139: }
9140: if ($action eq 'none') {
9141: return 'ok';
9142: } else {
9143: my %changes;
9144: my $newend = 0;
9145: my $newstart = $now;
9146: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9147: $changes{$action}{$newkey} = {
9148: type => 'public',
9149: time => {
9150: start => $newstart,
9151: end => $newend,
9152: },
9153: };
9154: my ($outcome,$deloutcome,$new_values,$translation) =
9155: &modify_access_controls($file_name,\%changes,$udom,$unum);
9156: return $outcome;
9157: }
9158: } else {
9159: return 'invalid';
9160: }
9161: }
9162:
1.745 raeburn 9163: #------------------------------------------------------Get Marked as Read Only
9164:
9165: sub get_marked_as_readonly {
9166: my ($domain,$user,$what,$group) = @_;
9167: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9168: my @readonly_files;
1.629 banghart 9169: my $cmp1=$what;
9170: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9171: while (my ($file_name,$value) = each(%{$current_permissions})) {
9172: if (defined($group)) {
9173: if ($file_name !~ m-^\Q$group\E/-) {
9174: next;
9175: }
9176: }
1.561 banghart 9177: if (ref($value) eq "ARRAY"){
9178: foreach my $stored_what (@{$value}) {
1.629 banghart 9179: my $cmp2=$stored_what;
1.759 albertel 9180: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9181: $cmp2=join('',@{$stored_what});
1.745 raeburn 9182: }
1.629 banghart 9183: if ($cmp1 eq $cmp2) {
1.561 banghart 9184: push(@readonly_files, $file_name);
1.745 raeburn 9185: last;
1.563 banghart 9186: } elsif (!defined($what)) {
9187: push(@readonly_files, $file_name);
1.745 raeburn 9188: last;
1.561 banghart 9189: }
9190: }
1.745 raeburn 9191: }
1.561 banghart 9192: }
9193: return @readonly_files;
9194: }
1.577 banghart 9195: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9196:
1.577 banghart 9197: sub get_marked_as_readonly_hash {
1.745 raeburn 9198: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9199: my %readonly_files;
1.745 raeburn 9200: while (my ($file_name,$value) = each(%{$current_permissions})) {
9201: if (defined($group)) {
9202: if ($file_name !~ m-^\Q$group\E/-) {
9203: next;
9204: }
9205: }
1.577 banghart 9206: if (ref($value) eq "ARRAY"){
9207: foreach my $stored_what (@{$value}) {
1.745 raeburn 9208: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9209: foreach my $lock_descriptor(@{$stored_what}) {
9210: if ($lock_descriptor eq 'graded') {
9211: $readonly_files{$file_name} = 'graded';
9212: } elsif ($lock_descriptor eq 'handback') {
9213: $readonly_files{$file_name} = 'handback';
9214: } else {
9215: if (!exists($readonly_files{$file_name})) {
9216: $readonly_files{$file_name} = 'locked';
9217: }
9218: }
1.745 raeburn 9219: }
1.750 banghart 9220: }
1.577 banghart 9221: }
9222: }
9223: }
9224: return %readonly_files;
9225: }
1.559 banghart 9226: # ------------------------------------------------------------ Unmark as Read Only
9227:
9228: sub unmark_as_readonly {
1.629 banghart 9229: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9230: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9231: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9232: $file_name = &declutter_portfile($file_name);
1.634 albertel 9233: my $symb_crs = $what;
9234: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9235: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9236: my ($tmp)=keys(%current_permissions);
9237: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9238: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9239: foreach my $file (@readonly_files) {
1.759 albertel 9240: my $clean_file = &declutter_portfile($file);
9241: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9242: my $current_locks = $current_permissions{$file};
1.563 banghart 9243: my @new_locks;
9244: my @del_keys;
9245: if (ref($current_locks) eq "ARRAY"){
9246: foreach my $locker (@{$current_locks}) {
1.632 albertel 9247: my $compare=$locker;
1.749 raeburn 9248: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9249: $compare=join('',@{$locker});
1.746 raeburn 9250: if ($compare ne $symb_crs) {
9251: push(@new_locks, $locker);
9252: }
1.563 banghart 9253: }
9254: }
1.650 albertel 9255: if (scalar(@new_locks) > 0) {
1.563 banghart 9256: $current_permissions{$file} = \@new_locks;
9257: } else {
9258: push(@del_keys, $file);
1.613 albertel 9259: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9260: delete($current_permissions{$file});
1.563 banghart 9261: }
9262: }
1.561 banghart 9263: }
1.613 albertel 9264: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9265: return;
9266: }
1.512 banghart 9267:
1.17 www 9268: # ------------------------------------------------------------ Directory lister
9269:
9270: sub dirlist {
1.955 raeburn 9271: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9272: $uri=~s/^\///;
9273: $uri=~s/\/$//;
1.253 stredwic 9274: my ($udom, $uname);
1.955 raeburn 9275: if ($getuserdir) {
1.253 stredwic 9276: $udom = $userdomain;
9277: $uname = $username;
1.955 raeburn 9278: } else {
9279: (undef,$udom,$uname)=split(/\//,$uri);
9280: if(defined($userdomain)) {
9281: $udom = $userdomain;
9282: }
9283: if(defined($username)) {
9284: $uname = $username;
9285: }
1.253 stredwic 9286: }
1.955 raeburn 9287: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9288:
1.955 raeburn 9289: $dirRoot = $perlvar{'lonDocRoot'};
9290: if (defined($getpropath)) {
9291: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9292: $dirRoot =~ s/\/$//;
1.955 raeburn 9293: } elsif (defined($getuserdir)) {
9294: my $subdir=$uname.'__';
9295: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9296: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9297: ."/$udom/$subdir/$uname";
9298: } elsif (defined($alternateRoot)) {
9299: $dirRoot = $alternateRoot;
1.751 banghart 9300: }
1.253 stredwic 9301:
9302: if($udom) {
9303: if($uname) {
1.1135 raeburn 9304: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9305: if ($uhome eq 'no_host') {
9306: return ([],'no_host');
9307: }
1.955 raeburn 9308: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9309: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9310: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9311: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9312: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9313: } else {
9314: @listing_results = map { &unescape($_); } split(/:/,$listing);
9315: }
1.605 matthew 9316: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9317: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9318: @listing_results = split(/:/,$listing);
9319: } else {
9320: @listing_results = map { &unescape($_); } split(/:/,$listing);
9321: }
1.1135 raeburn 9322: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9323: ($listing eq 'rejected') || ($listing eq 'refused') ||
9324: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9325: return ([],$listing);
9326: } else {
9327: return (\@listing_results);
1.1135 raeburn 9328: }
1.955 raeburn 9329: } elsif(!$alternateRoot) {
1.1136 raeburn 9330: my (%allusers,%listerror);
1.841 albertel 9331: my %servers = &get_servers($udom,'library');
1.955 raeburn 9332: foreach my $tryserver (keys(%servers)) {
9333: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9334: &escape($udom),$tryserver);
9335: if ($listing eq 'unknown_cmd') {
9336: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9337: $udom, $tryserver);
9338: } else {
9339: @listing_results = map { &unescape($_); } split(/:/,$listing);
9340: }
1.841 albertel 9341: if ($listing eq 'unknown_cmd') {
9342: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9343: $udom, $tryserver);
9344: @listing_results = split(/:/,$listing);
9345: } else {
9346: @listing_results =
9347: map { &unescape($_); } split(/:/,$listing);
9348: }
1.1136 raeburn 9349: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9350: ($listing eq 'rejected') || ($listing eq 'refused') ||
9351: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9352: $listerror{$tryserver} = $listing;
9353: } else {
1.841 albertel 9354: foreach my $line (@listing_results) {
9355: my ($entry) = split(/&/,$line,2);
9356: $allusers{$entry} = 1;
9357: }
9358: }
1.253 stredwic 9359: }
1.1136 raeburn 9360: my @alluserslist=();
1.800 albertel 9361: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9362: push(@alluserslist,$user.'&user');
1.253 stredwic 9363: }
1.1136 raeburn 9364: return (\@alluserslist);
1.253 stredwic 9365: } else {
1.1136 raeburn 9366: return ([],'missing username');
1.253 stredwic 9367: }
1.955 raeburn 9368: } elsif(!defined($getpropath)) {
1.1136 raeburn 9369: my $path = $perlvar{'lonDocRoot'}.'/res/';
9370: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9371: return (\@all_domains);
1.955 raeburn 9372: } else {
1.1136 raeburn 9373: return ([],'missing domain');
1.275 stredwic 9374: }
9375: }
9376:
9377: # --------------------------------------------- GetFileTimestamp
9378: # This function utilizes dirlist and returns the date stamp for
9379: # when it was last modified. It will also return an error of -1
9380: # if an error occurs
9381:
9382: sub GetFileTimestamp {
1.955 raeburn 9383: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9384: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9385: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9386: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9387: undef,$getuserdir);
9388: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9389: return -1;
9390: }
9391: if (ref($fileref) eq 'ARRAY') {
9392: my @stats = split('&',$fileref->[0]);
1.375 matthew 9393: # @stats contains first the filename, then the stat output
9394: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9395: } else {
9396: return -1;
1.253 stredwic 9397: }
1.26 www 9398: }
9399:
1.712 albertel 9400: sub stat_file {
9401: my ($uri) = @_;
1.787 albertel 9402: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9403:
1.955 raeburn 9404: my ($udom,$uname,$file);
1.712 albertel 9405: if ($uri =~ m-^/(uploaded|editupload)/-) {
9406: ($udom,$uname,$file) =
1.811 albertel 9407: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9408: $file = 'userfiles/'.$file;
9409: }
9410: if ($uri =~ m-^/res/-) {
9411: ($udom,$uname) =
1.807 albertel 9412: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9413: $file = $uri;
9414: }
9415:
9416: if (!$udom || !$uname || !$file) {
9417: # unable to handle the uri
9418: return ();
9419: }
1.956 raeburn 9420: my $getpropath;
9421: if ($file =~ /^userfiles\//) {
9422: $getpropath = 1;
9423: }
1.1136 raeburn 9424: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9425: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9426: return ();
9427: } else {
9428: if (ref($listref) eq 'ARRAY') {
9429: my @stats = split('&',$listref->[0]);
9430: shift(@stats); #filename is first
9431: return @stats;
9432: }
1.712 albertel 9433: }
9434: return ();
9435: }
9436:
1.26 www 9437: # -------------------------------------------------------- Value of a Condition
9438:
1.713 albertel 9439: # gets the value of a specific preevaluated condition
9440: # stored in the string $env{user.state.<cid>}
9441: # or looks up a condition reference in the bighash and if if hasn't
9442: # already been evaluated recurses into docondval to get the value of
9443: # the condition, then memoizing it to
9444: # $env{user.state.<cid>.<condition>}
1.40 www 9445: sub directcondval {
9446: my $number=shift;
1.620 albertel 9447: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9448: &Apache::lonuserstate::evalstate();
9449: }
1.713 albertel 9450: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9451: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9452: } elsif ($number =~ /^_/) {
9453: my $sub_condition;
9454: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9455: &GDBM_READER(),0640)) {
9456: $sub_condition=$bighash{'conditions'.$number};
9457: untie(%bighash);
9458: }
9459: my $value = &docondval($sub_condition);
1.949 raeburn 9460: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9461: return $value;
9462: }
1.620 albertel 9463: if ($env{'user.state.'.$env{'request.course.id'}}) {
9464: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9465: } else {
9466: return 2;
9467: }
9468: }
9469:
1.713 albertel 9470: # get the collection of conditions for this resource
1.26 www 9471: sub condval {
9472: my $condidx=shift;
1.54 www 9473: my $allpathcond='';
1.713 albertel 9474: foreach my $cond (split(/\|/,$condidx)) {
9475: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9476: $allpathcond.=
9477: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9478: }
1.191 harris41 9479: }
1.54 www 9480: $allpathcond=~s/\|$//;
1.713 albertel 9481: return &docondval($allpathcond);
9482: }
9483:
9484: #evaluates an expression of conditions
9485: sub docondval {
9486: my ($allpathcond) = @_;
9487: my $result=0;
9488: if ($env{'request.course.id'}
9489: && defined($allpathcond)) {
9490: my $operand='|';
9491: my @stack;
9492: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9493: if ($chunk eq '(') {
9494: push @stack,($operand,$result);
9495: } elsif ($chunk eq ')') {
9496: my $before=pop @stack;
9497: if (pop @stack eq '&') {
9498: $result=$result>$before?$before:$result;
9499: } else {
9500: $result=$result>$before?$result:$before;
9501: }
9502: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9503: $operand=$chunk;
9504: } else {
9505: my $new=directcondval($chunk);
9506: if ($operand eq '&') {
9507: $result=$result>$new?$new:$result;
9508: } else {
9509: $result=$result>$new?$result:$new;
9510: }
9511: }
9512: }
1.26 www 9513: }
9514: return $result;
1.421 albertel 9515: }
9516:
9517: # ---------------------------------------------------- Devalidate courseresdata
9518:
9519: sub devalidatecourseresdata {
9520: my ($coursenum,$coursedomain)=@_;
9521: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9522: &devalidate_cache_new('courseres',$hashid);
1.28 www 9523: }
9524:
1.763 www 9525:
1.200 www 9526: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9527: #
9528: # Parameters:
9529: # $coursenum - Number of the course.
9530: # $coursedomain - Domain at which the course was created.
9531: # Returns:
9532: # A hash of the course parameters along (I think) with timestamps
9533: # and version info.
1.877 foxr 9534:
1.624 albertel 9535: sub get_courseresdata {
9536: my ($coursenum,$coursedomain)=@_;
1.200 www 9537: my $coursehom=&homeserver($coursenum,$coursedomain);
9538: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9539: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9540: my %dumpreply;
1.417 albertel 9541: unless (defined($cached)) {
1.624 albertel 9542: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9543: $result=\%dumpreply;
1.251 albertel 9544: my ($tmp) = keys(%dumpreply);
9545: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9546: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9547: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9548: return $tmp;
1.416 albertel 9549: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9550: $result=undef;
1.599 albertel 9551: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9552: }
9553: }
1.624 albertel 9554: return $result;
9555: }
9556:
1.633 albertel 9557: sub devalidateuserresdata {
9558: my ($uname,$udom)=@_;
9559: my $hashid="$udom:$uname";
9560: &devalidate_cache_new('userres',$hashid);
9561: }
9562:
1.624 albertel 9563: sub get_userresdata {
9564: my ($uname,$udom)=@_;
9565: #most student don\'t have any data set, check if there is some data
9566: if (&EXT_cache_status($udom,$uname)) { return undef; }
9567:
9568: my $hashid="$udom:$uname";
9569: my ($result,$cached)=&is_cached_new('userres',$hashid);
9570: if (!defined($cached)) {
9571: my %resourcedata=&dump('resourcedata',$udom,$uname);
9572: $result=\%resourcedata;
9573: &do_cache_new('userres',$hashid,$result,600);
9574: }
9575: my ($tmp)=keys(%$result);
9576: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9577: return $result;
9578: }
9579: #error 2 occurs when the .db doesn't exist
9580: if ($tmp!~/error: 2 /) {
1.672 albertel 9581: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9582: " Trying to get resource data for ".
9583: $uname." at ".$udom.": ".
9584: $tmp."</font>");
9585: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9586: #&EXT_cache_set($udom,$uname);
9587: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9588: undef($tmp); # not really an error so don't send it back
1.624 albertel 9589: }
9590: return $tmp;
9591: }
1.879 foxr 9592: #----------------------------------------------- resdata - return resource data
9593: # Purpose:
9594: # Return resource data for either users or for a course.
9595: # Parameters:
9596: # $name - Course/user name.
9597: # $domain - Name of the domain the user/course is registered on.
9598: # $type - Type of thing $name is (must be 'course' or 'user'
9599: # @which - Array of names of resources desired.
9600: # Returns:
9601: # The value of the first reasource in @which that is found in the
9602: # resource hash.
9603: # Exceptional Conditions:
9604: # If the $type passed in is not valid (not the string 'course' or
9605: # 'user', an undefined reference is returned.
9606: # If none of the resources are found, an undef is returned
1.624 albertel 9607: sub resdata {
9608: my ($name,$domain,$type,@which)=@_;
9609: my $result;
9610: if ($type eq 'course') {
9611: $result=&get_courseresdata($name,$domain);
9612: } elsif ($type eq 'user') {
9613: $result=&get_userresdata($name,$domain);
9614: }
9615: if (!ref($result)) { return $result; }
1.251 albertel 9616: foreach my $item (@which) {
1.927 albertel 9617: if (defined($result->{$item->[0]})) {
9618: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9619: }
1.250 albertel 9620: }
1.291 albertel 9621: return undef;
1.200 www 9622: }
9623:
1.1172.2.31! raeburn 9624: sub get_numsuppfiles {
! 9625: my ($cnum,$cdom,$ignorecache)=@_;
! 9626: my $hashid=$cnum.':'.$cdom;
! 9627: my ($suppcount,$cached);
! 9628: unless ($ignorecache) {
! 9629: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
! 9630: }
! 9631: unless (defined($cached)) {
! 9632: my $chome=&homeserver($cnum,$cdom);
! 9633: unless ($chome eq 'no_host') {
! 9634: ($suppcount,my $errors) = (0,0);
! 9635: my $suppmap = 'supplemental.sequence';
! 9636: ($suppcount,$errors) =
! 9637: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
! 9638: }
! 9639: &do_cache_new('suppcount',$hashid,$suppcount,600);
! 9640: }
! 9641: return $suppcount;
! 9642: }
! 9643:
1.379 matthew 9644: #
9645: # EXT resource caching routines
9646: #
9647:
9648: sub clear_EXT_cache_status {
1.383 albertel 9649: &delenv('cache.EXT.');
1.379 matthew 9650: }
9651:
9652: sub EXT_cache_status {
9653: my ($target_domain,$target_user) = @_;
1.383 albertel 9654: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9655: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9656: # We know already the user has no data
9657: return 1;
9658: } else {
9659: return 0;
9660: }
9661: }
9662:
9663: sub EXT_cache_set {
9664: my ($target_domain,$target_user) = @_;
1.383 albertel 9665: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9666: #&appenv({$cachename => time});
1.379 matthew 9667: }
9668:
1.28 www 9669: # --------------------------------------------------------- Value of a Variable
1.58 www 9670: sub EXT {
1.715 albertel 9671:
1.1172.2.28 raeburn 9672: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9673: unless ($varname) { return ''; }
1.218 albertel 9674: #get real user name/domain, courseid and symb
9675: my $courseid;
1.359 albertel 9676: my $publicuser;
1.427 www 9677: if ($symbparm) {
9678: $symbparm=&get_symb_from_alias($symbparm);
9679: }
1.218 albertel 9680: if (!($uname && $udom)) {
1.790 albertel 9681: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9682: if (!$symbparm) { $symbparm=$cursymb; }
9683: } else {
1.620 albertel 9684: $courseid=$env{'request.course.id'};
1.218 albertel 9685: }
1.48 www 9686: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9687: my $rest;
1.320 albertel 9688: if (defined($therest[0])) {
1.48 www 9689: $rest=join('.',@therest);
9690: } else {
9691: $rest='';
9692: }
1.320 albertel 9693:
1.57 www 9694: my $qualifierrest=$qualifier;
9695: if ($rest) { $qualifierrest.='.'.$rest; }
9696: my $spacequalifierrest=$space;
9697: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9698: if ($realm eq 'user') {
1.48 www 9699: # --------------------------------------------------------------- user.resource
9700: if ($space eq 'resource') {
1.651 albertel 9701: if ( (defined($Apache::lonhomework::parsing_a_problem)
9702: || defined($Apache::lonhomework::parsing_a_task))
9703: &&
1.744 albertel 9704: ($symbparm eq &symbread()) ) {
9705: # if we are in the middle of processing the resource the
9706: # get the value we are planning on committing
9707: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9708: return $Apache::lonhomework::results{$qualifierrest};
9709: } else {
9710: return $Apache::lonhomework::history{$qualifierrest};
9711: }
1.335 albertel 9712: } else {
1.359 albertel 9713: my %restored;
1.620 albertel 9714: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9715: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9716: } else {
9717: %restored=&restore($symbparm,$courseid,$udom,$uname);
9718: }
1.335 albertel 9719: return $restored{$qualifierrest};
9720: }
1.48 www 9721: # ----------------------------------------------------------------- user.access
9722: } elsif ($space eq 'access') {
1.218 albertel 9723: # FIXME - not supporting calls for a specific user
1.48 www 9724: return &allowed($qualifier,$rest);
9725: # ------------------------------------------ user.preferences, user.environment
9726: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9727: if (($uname eq $env{'user.name'}) &&
9728: ($udom eq $env{'user.domain'})) {
9729: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9730: } else {
1.359 albertel 9731: my %returnhash;
9732: if (!$publicuser) {
9733: %returnhash=&userenvironment($udom,$uname,
9734: $qualifierrest);
9735: }
1.218 albertel 9736: return $returnhash{$qualifierrest};
9737: }
1.48 www 9738: # ----------------------------------------------------------------- user.course
9739: } elsif ($space eq 'course') {
1.218 albertel 9740: # FIXME - not supporting calls for a specific user
1.620 albertel 9741: return $env{join('.',('request.course',$qualifier))};
1.48 www 9742: # ------------------------------------------------------------------- user.role
9743: } elsif ($space eq 'role') {
1.218 albertel 9744: # FIXME - not supporting calls for a specific user
1.620 albertel 9745: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9746: if ($qualifier eq 'value') {
9747: return $role;
9748: } elsif ($qualifier eq 'extent') {
9749: return $where;
9750: }
9751: # ----------------------------------------------------------------- user.domain
9752: } elsif ($space eq 'domain') {
1.218 albertel 9753: return $udom;
1.48 www 9754: # ------------------------------------------------------------------- user.name
9755: } elsif ($space eq 'name') {
1.218 albertel 9756: return $uname;
1.48 www 9757: # ---------------------------------------------------- Any other user namespace
1.29 www 9758: } else {
1.359 albertel 9759: my %reply;
9760: if (!$publicuser) {
9761: %reply=&get($space,[$qualifierrest],$udom,$uname);
9762: }
9763: return $reply{$qualifierrest};
1.48 www 9764: }
1.236 www 9765: } elsif ($realm eq 'query') {
9766: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9767: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9768: [$spacequalifierrest]);
1.620 albertel 9769: return $env{'form.'.$spacequalifierrest};
1.236 www 9770: } elsif ($realm eq 'request') {
1.48 www 9771: # ------------------------------------------------------------- request.browser
9772: if ($space eq 'browser') {
1.1145 bisitz 9773: return $env{'browser.'.$qualifier};
1.57 www 9774: # ------------------------------------------------------------ request.filename
9775: } else {
1.620 albertel 9776: return $env{'request.'.$spacequalifierrest};
1.29 www 9777: }
1.28 www 9778: } elsif ($realm eq 'course') {
1.48 www 9779: # ---------------------------------------------------------- course.description
1.620 albertel 9780: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9781: } elsif ($realm eq 'resource') {
1.165 www 9782:
1.620 albertel 9783: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9784: if (!$symbparm) { $symbparm=&symbread(); }
9785: }
1.693 albertel 9786:
1.1172.2.30 raeburn 9787: if ($qualifier eq '') {
9788: if ($space eq 'title') {
9789: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9790: return &gettitle($symbparm);
9791: }
1.693 albertel 9792:
1.1172.2.30 raeburn 9793: if ($space eq 'map') {
9794: my ($map) = &decode_symb($symbparm);
9795: return &symbread($map);
9796: }
9797: if ($space eq 'maptitle') {
9798: my ($map) = &decode_symb($symbparm);
9799: return &gettitle($map);
9800: }
9801: if ($space eq 'filename') {
9802: if ($symbparm) {
9803: return &clutter((&decode_symb($symbparm))[2]);
9804: }
9805: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9806: }
1.1172.2.30 raeburn 9807:
9808: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9809: if ($space eq 'visibleparts') {
9810: my $navmap = Apache::lonnavmaps::navmap->new();
9811: my $item;
9812: if (ref($navmap)) {
9813: my $res = $navmap->getBySymb($symbparm);
9814: my $parts = $res->parts();
9815: if (ref($parts) eq 'ARRAY') {
9816: $item = join(',',@{$parts});
9817: }
9818: undef($navmap);
9819: }
9820: return $item;
9821: }
9822: }
9823: }
1.693 albertel 9824:
9825: my ($section, $group, @groups);
1.593 albertel 9826: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 9827: if (($courseid eq '') && ($cid)) {
9828: $courseid = $cid;
9829: }
9830: if (($symbparm && $courseid) &&
9831: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9832:
1.218 albertel 9833: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9834:
1.60 www 9835: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9836: my $symbp=$symbparm;
1.735 albertel 9837: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9838:
9839: my $symbparm=$symbp.'.'.$spacequalifierrest;
9840: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9841:
1.620 albertel 9842: if (($env{'user.name'} eq $uname) &&
9843: ($env{'user.domain'} eq $udom)) {
9844: $section=$env{'request.course.sec'};
1.733 raeburn 9845: @groups = split(/:/,$env{'request.course.groups'});
9846: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9847: } else {
1.539 albertel 9848: if (! defined($usection)) {
1.551 albertel 9849: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9850: } else {
9851: $section = $usection;
9852: }
1.733 raeburn 9853: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9854: }
9855:
9856: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9857: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9858: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9859:
1.593 albertel 9860: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9861: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9862: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9863:
1.60 www 9864: # ----------------------------------------------------------- first, check user
1.624 albertel 9865:
9866: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9867: ([$courselevelr,'resource'],
9868: [$courselevelm,'map' ],
9869: [$courselevel, 'course' ]));
1.931 albertel 9870: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9871:
1.594 albertel 9872: # ------------------------------------------------ second, check some of course
1.684 raeburn 9873: my $coursereply;
1.691 raeburn 9874: if (@groups > 0) {
9875: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9876: $mapparm,$spacequalifierrest);
1.927 albertel 9877: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9878: }
1.96 www 9879:
1.684 raeburn 9880: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9881: $env{'course.'.$courseid.'.domain'},
9882: 'course',
9883: ([$seclevelr, 'resource'],
9884: [$seclevelm, 'map' ],
9885: [$seclevel, 'course' ],
9886: [$courselevelr,'resource']));
9887: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9888:
1.60 www 9889: # ------------------------------------------------------ third, check map parms
1.218 albertel 9890: my %parmhash=();
9891: my $thisparm='';
9892: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9893: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9894: &GDBM_READER(),0640)) {
1.218 albertel 9895: $thisparm=$parmhash{$symbparm};
9896: untie(%parmhash);
9897: }
1.927 albertel 9898: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9899: }
1.594 albertel 9900: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9901:
1.218 albertel 9902: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9903: my $filename;
9904: if (!$symbparm) { $symbparm=&symbread(); }
9905: if ($symbparm) {
1.409 www 9906: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9907: } else {
1.620 albertel 9908: $filename=$env{'request.filename'};
1.282 albertel 9909: }
9910: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9911: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9912: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9913: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9914:
1.927 albertel 9915: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9916: if ($symbparm && defined($courseid) &&
1.620 albertel 9917: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9918: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9919: $env{'course.'.$courseid.'.domain'},
9920: 'course',
1.927 albertel 9921: ([$courselevelm,'map' ],
9922: [$courselevel, 'course']));
9923: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9924: }
1.145 www 9925: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9926: unless ($space eq '0') {
1.336 albertel 9927: my @parts=split(/_/,$space);
9928: my $id=pop(@parts);
9929: my $part=join('_',@parts);
9930: if ($part eq '') { $part='0'; }
1.927 albertel 9931: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9932: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9933: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9934: }
1.395 albertel 9935: if ($recurse) { return undef; }
9936: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9937: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9938: # ---------------------------------------------------- Any other user namespace
9939: } elsif ($realm eq 'environment') {
9940: # ----------------------------------------------------------------- environment
1.620 albertel 9941: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9942: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9943: } else {
1.770 albertel 9944: if ($uname eq 'anonymous' && $udom eq '') {
9945: return '';
9946: }
1.219 albertel 9947: my %returnhash=&userenvironment($udom,$uname,
9948: $spacequalifierrest);
9949: return $returnhash{$spacequalifierrest};
9950: }
1.28 www 9951: } elsif ($realm eq 'system') {
1.48 www 9952: # ----------------------------------------------------------------- system.time
9953: if ($space eq 'time') {
9954: return time;
9955: }
1.696 albertel 9956: } elsif ($realm eq 'server') {
9957: # ----------------------------------------------------------------- system.time
9958: if ($space eq 'name') {
9959: return $ENV{'SERVER_NAME'};
9960: }
1.28 www 9961: }
1.48 www 9962: return '';
1.61 www 9963: }
9964:
1.927 albertel 9965: sub get_reply {
9966: my ($reply_value) = @_;
1.940 raeburn 9967: if (ref($reply_value) eq 'ARRAY') {
9968: if (wantarray) {
9969: return @$reply_value;
9970: }
9971: return $reply_value->[0];
9972: } else {
9973: return $reply_value;
1.927 albertel 9974: }
9975: }
9976:
1.691 raeburn 9977: sub check_group_parms {
9978: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9979: my @groupitems = ();
9980: my $resultitem;
1.927 albertel 9981: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9982: foreach my $group (@{$groups}) {
9983: foreach my $level (@levels) {
1.927 albertel 9984: my $item = $courseid.'.['.$group.'].'.$level->[0];
9985: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9986: }
9987: }
9988: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9989: $env{'course.'.$courseid.'.domain'},
9990: 'course',@groupitems);
9991: return $coursereply;
9992: }
9993:
9994: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9995: my ($courseid,@groups) = @_;
9996: @groups = sort(@groups);
1.691 raeburn 9997: return @groups;
9998: }
9999:
1.395 albertel 10000: sub packages_tab_default {
10001: my ($uri,$varname)=@_;
10002: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10003:
10004: my (@extension,@specifics,$do_default);
10005: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10006: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10007: if ($pack_type eq 'default') {
10008: $do_default=1;
10009: } elsif ($pack_type eq 'extension') {
10010: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10011: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10012: # only look at packages defaults for packages that this id is
1.738 albertel 10013: push(@specifics,[$package,$pack_type,$pack_part]);
10014: }
10015: }
10016: # first look for a package that matches the requested part id
10017: foreach my $package (@specifics) {
10018: my (undef,$pack_type,$pack_part)=@{$package};
10019: next if ($pack_part ne $part);
10020: if (defined($packagetab{"$pack_type&$name&default"})) {
10021: return $packagetab{"$pack_type&$name&default"};
10022: }
10023: }
10024: # look for any possible matching non extension_ package
10025: foreach my $package (@specifics) {
10026: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10027: if (defined($packagetab{"$pack_type&$name&default"})) {
10028: return $packagetab{"$pack_type&$name&default"};
10029: }
1.585 albertel 10030: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10031: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10032: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10033: }
10034: }
1.738 albertel 10035: # look for any posible extension_ match
10036: foreach my $package (@extension) {
10037: my ($package,$pack_type)=@{$package};
10038: if (defined($packagetab{"$pack_type&$name&default"})) {
10039: return $packagetab{"$pack_type&$name&default"};
10040: }
10041: if (defined($packagetab{$package."&$name&default"})) {
10042: return $packagetab{$package."&$name&default"};
10043: }
10044: }
10045: # look for a global default setting
10046: if ($do_default && defined($packagetab{"default&$name&default"})) {
10047: return $packagetab{"default&$name&default"};
10048: }
1.395 albertel 10049: return undef;
10050: }
10051:
1.334 albertel 10052: sub add_prefix_and_part {
10053: my ($prefix,$part)=@_;
10054: my $keyroot;
10055: if (defined($prefix) && $prefix !~ /^__/) {
10056: # prefix that has a part already
10057: $keyroot=$prefix;
10058: } elsif (defined($prefix)) {
10059: # prefix that is missing a part
10060: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10061: } else {
10062: # no prefix at all
10063: if (defined($part)) { $keyroot='_'.$part; }
10064: }
10065: return $keyroot;
10066: }
10067:
1.71 www 10068: # ---------------------------------------------------------------- Get metadata
10069:
1.599 albertel 10070: my %metaentry;
1.1070 www 10071: my %importedpartids;
1.71 www 10072: sub metadata {
1.176 www 10073: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10074: $uri=&declutter($uri);
1.288 albertel 10075: # if it is a non metadata possible uri return quickly
1.529 albertel 10076: if (($uri eq '') ||
10077: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10078: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10079: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10080: return undef;
10081: }
1.1140 www 10082: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10083: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10084: return undef;
1.288 albertel 10085: }
1.73 www 10086: my $filename=$uri;
10087: $uri=~s/\.meta$//;
1.172 www 10088: #
10089: # Is the metadata already cached?
1.177 www 10090: # Look at timestamp of caching
1.172 www 10091: # Everything is cached by the main uri, libraries are never directly cached
10092: #
1.428 albertel 10093: if (!defined($liburi)) {
1.599 albertel 10094: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10095: if (defined($cached)) { return $result->{':'.$what}; }
10096: }
10097: {
1.1069 www 10098: # Imported parts would go here
1.1070 www 10099: my %importedids=();
10100: my @origfileimportpartids=();
1.1069 www 10101: my $importedparts=0;
1.172 www 10102: #
10103: # Is this a recursive call for a library?
10104: #
1.599 albertel 10105: # if (! exists($metacache{$uri})) {
10106: # $metacache{$uri}={};
10107: # }
1.924 albertel 10108: my $cachetime = 60*60;
1.171 www 10109: if ($liburi) {
10110: $liburi=&declutter($liburi);
10111: $filename=$liburi;
1.401 bowersj2 10112: } else {
1.599 albertel 10113: &devalidate_cache_new('meta',$uri);
10114: undef(%metaentry);
1.401 bowersj2 10115: }
1.140 www 10116: my %metathesekeys=();
1.73 www 10117: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10118: my $metastring;
1.1140 www 10119: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10120: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10121: $metastring =
1.929 albertel 10122: &Apache::lonnet::ssi_body($which,
1.924 albertel 10123: ('grade_target' => 'meta'));
10124: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10125: } elsif (($uri !~ m -^(editupload)/-) &&
10126: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10127: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10128: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10129: $metastring=&getfile($file);
1.489 albertel 10130: }
1.208 albertel 10131: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10132: my $token;
1.140 www 10133: undef %metathesekeys;
1.71 www 10134: while ($token=$parser->get_token) {
1.339 albertel 10135: if ($token->[0] eq 'S') {
10136: if (defined($token->[2]->{'package'})) {
1.172 www 10137: #
10138: # This is a package - get package info
10139: #
1.339 albertel 10140: my $package=$token->[2]->{'package'};
10141: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10142: if (defined($token->[2]->{'id'})) {
10143: $keyroot.='_'.$token->[2]->{'id'};
10144: }
1.599 albertel 10145: if ($metaentry{':packages'}) {
10146: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10147: } else {
1.599 albertel 10148: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10149: }
1.736 albertel 10150: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10151: my $part=$keyroot;
10152: $part=~s/^\_//;
1.736 albertel 10153: if ($pack_entry=~/^\Q$package\E\&/ ||
10154: $pack_entry=~/^\Q$package\E_0\&/) {
10155: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10156: # ignore package.tab specified default values
10157: # here &package_tab_default() will fetch those
10158: if ($subp eq 'default') { next; }
1.736 albertel 10159: my $value=$packagetab{$pack_entry};
1.432 albertel 10160: my $unikey;
10161: if ($pack =~ /_0$/) {
10162: $unikey='parameter_0_'.$name;
10163: $part=0;
10164: } else {
10165: $unikey='parameter'.$keyroot.'_'.$name;
10166: }
1.339 albertel 10167: if ($subp eq 'display') {
10168: $value.=' [Part: '.$part.']';
10169: }
1.599 albertel 10170: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10171: $metathesekeys{$unikey}=1;
1.599 albertel 10172: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10173: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10174: }
1.599 albertel 10175: if (defined($metaentry{':'.$unikey.'.default'})) {
10176: $metaentry{':'.$unikey}=
10177: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10178: }
1.339 albertel 10179: }
10180: }
10181: } else {
1.172 www 10182: #
10183: # This is not a package - some other kind of start tag
1.339 albertel 10184: #
10185: my $entry=$token->[1];
1.1068 www 10186: my $unikey='';
1.175 www 10187:
1.339 albertel 10188: if ($entry eq 'import') {
1.175 www 10189: #
10190: # Importing a library here
1.339 albertel 10191: #
1.1067 www 10192: my $location=$parser->get_text('/import');
10193: my $dir=$filename;
10194: $dir=~s|[^/]*$||;
10195: $location=&filelocation($dir,$location);
1.1069 www 10196:
1.1068 www 10197: my $importmode=$token->[2]->{'importmode'};
10198: if ($importmode eq 'problem') {
1.1069 www 10199: # Import as problem/response
1.1068 www 10200: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10201: } elsif ($importmode eq 'part') {
10202: # Import as part(s)
1.1069 www 10203: $importedparts=1;
10204: # We need to get the original file and the imported file to get the part order correct
10205: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10206: # Load and inspect original file
1.1070 www 10207: if ($#origfileimportpartids<0) {
10208: undef(%importedpartids);
10209: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10210: my $origfile=&getfile($origfilelocation);
10211: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10212: }
10213:
1.1069 www 10214: # Load and inspect imported file
10215: my $impfile=&getfile($location);
10216: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10217: if ($#impfilepartids>=0) {
10218: # This problem had parts
1.1070 www 10219: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10220: } else {
10221: # Importing by turning a single problem into a problem part
10222: # It gets the import-tags ID as part-ID
10223: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10224: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10225: }
1.1068 www 10226: } else {
10227: # Normal import
10228: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10229: if (defined($token->[2]->{'id'})) {
10230: $unikey.='_'.$token->[2]->{'id'};
10231: }
1.1067 www 10232: }
10233:
1.339 albertel 10234: if ($depthcount<20) {
1.736 albertel 10235: my $metadata =
10236: &metadata($uri,'keys', $location,$unikey,
10237: $depthcount+1);
10238: foreach my $meta (split(',',$metadata)) {
10239: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10240: $metathesekeys{$meta}=1;
1.339 albertel 10241: }
1.1068 www 10242:
10243: }
1.1067 www 10244: } else {
10245: #
10246: # Not importing, some other kind of non-package, non-library start tag
10247: #
10248: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10249: if (defined($token->[2]->{'id'})) {
10250: $unikey.='_'.$token->[2]->{'id'};
10251: }
1.339 albertel 10252: if (defined($token->[2]->{'name'})) {
10253: $unikey.='_'.$token->[2]->{'name'};
10254: }
10255: $metathesekeys{$unikey}=1;
1.736 albertel 10256: foreach my $param (@{$token->[3]}) {
10257: $metaentry{':'.$unikey.'.'.$param} =
10258: $token->[2]->{$param};
1.339 albertel 10259: }
10260: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10261: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10262: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10263: # only ws inside the tag, and not in default, so use default
10264: # as value
1.599 albertel 10265: $metaentry{':'.$unikey}=$default;
1.908 albertel 10266: } elsif ( $internaltext =~ /\S/ ) {
10267: # something interesting inside the tag
10268: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10269: } else {
1.908 albertel 10270: # no interesting values, don't set a default
1.339 albertel 10271: }
1.172 www 10272: # end of not-a-package not-a-library import
1.339 albertel 10273: }
1.172 www 10274: # end of not-a-package start tag
1.339 albertel 10275: }
1.172 www 10276: # the next is the end of "start tag"
1.339 albertel 10277: }
10278: }
1.483 albertel 10279: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10280: $extension = lc($extension);
10281: if ($extension eq 'htm') { $extension='html'; }
10282:
1.737 albertel 10283: foreach my $key (keys(%packagetab)) {
1.483 albertel 10284: #no specific packages #how's our extension
10285: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10286: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10287: \%metathesekeys);
10288: }
1.883 albertel 10289:
10290: if (!exists($metaentry{':packages'})
10291: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10292: foreach my $key (keys(%packagetab)) {
1.483 albertel 10293: #no specific packages well let's get default then
10294: if ($key!~/^default&/) { next; }
1.488 albertel 10295: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10296: \%metathesekeys);
10297: }
10298: }
1.338 www 10299: # are there custom rights to evaluate
1.599 albertel 10300: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10301:
1.338 www 10302: #
10303: # Importing a rights file here
1.339 albertel 10304: #
10305: unless ($depthcount) {
1.599 albertel 10306: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10307: my $dir=$filename;
10308: $dir=~s|[^/]*$||;
10309: $location=&filelocation($dir,$location);
1.736 albertel 10310: my $rights_metadata =
10311: &metadata($uri,'keys',$location,'_rights',
10312: $depthcount+1);
10313: foreach my $rights (split(',',$rights_metadata)) {
10314: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10315: $metathesekeys{$rights}=1;
1.339 albertel 10316: }
10317: }
10318: }
1.737 albertel 10319: # uniqifiy package listing
10320: my %seen;
10321: my @uniq_packages =
10322: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10323: $metaentry{':packages'} = join(',',@uniq_packages);
10324:
1.1070 www 10325: if ($importedparts) {
10326: # We had imported parts and need to rebuild partorder
10327: $metaentry{':partorder'}='';
10328: $metathesekeys{'partorder'}=1;
10329: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10330: if ($origfileimportpartids[$index] eq 'part') {
10331: # original part, part of the problem
10332: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10333: } else {
10334: # we have imported parts at this position
10335: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10336: }
10337: }
10338: $metaentry{':partorder'}=~s/^\,//;
10339: }
10340:
1.737 albertel 10341: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10342: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10343: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10344: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10345: # this is the end of "was not already recently cached
1.71 www 10346: }
1.599 albertel 10347: return $metaentry{':'.$what};
1.261 albertel 10348: }
10349:
1.488 albertel 10350: sub metadata_create_package_def {
1.483 albertel 10351: my ($uri,$key,$package,$metathesekeys)=@_;
10352: my ($pack,$name,$subp)=split(/\&/,$key);
10353: if ($subp eq 'default') { next; }
10354:
1.599 albertel 10355: if (defined($metaentry{':packages'})) {
10356: $metaentry{':packages'}.=','.$package;
1.483 albertel 10357: } else {
1.599 albertel 10358: $metaentry{':packages'}=$package;
1.483 albertel 10359: }
10360: my $value=$packagetab{$key};
10361: my $unikey;
10362: $unikey='parameter_0_'.$name;
1.599 albertel 10363: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10364: $$metathesekeys{$unikey}=1;
1.599 albertel 10365: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10366: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10367: }
1.599 albertel 10368: if (defined($metaentry{':'.$unikey.'.default'})) {
10369: $metaentry{':'.$unikey}=
10370: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10371: }
10372: }
10373:
1.261 albertel 10374: sub metadata_generate_part0 {
10375: my ($metadata,$metacache,$uri) = @_;
10376: my %allnames;
1.737 albertel 10377: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10378: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10379: my $part=$$metacache{':'.$metakey.'.part'};
10380: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10381: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10382: $allnames{$name}=$part;
10383: }
10384: }
10385: }
10386: foreach my $name (keys(%allnames)) {
10387: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10388: my $key=":parameter_0_$name";
1.261 albertel 10389: $$metacache{"$key.part"}='0';
10390: $$metacache{"$key.name"}=$name;
1.428 albertel 10391: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10392: $allnames{$name}.'_'.$name.
10393: '.type'};
1.428 albertel 10394: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10395: '.display'};
1.644 www 10396: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10397: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10398: $$metacache{"$key.display"}=$olddis;
10399: }
1.71 www 10400: }
10401:
1.764 albertel 10402: # ------------------------------------------------------ Devalidate title cache
10403:
10404: sub devalidate_title_cache {
10405: my ($url)=@_;
10406: if (!$env{'request.course.id'}) { return; }
10407: my $symb=&symbread($url);
10408: if (!$symb) { return; }
10409: my $key=$env{'request.course.id'}."\0".$symb;
10410: &devalidate_cache_new('title',$key);
10411: }
10412:
1.1014 droeschl 10413: # ------------------------------------------------- Get the title of a course
10414:
10415: sub current_course_title {
10416: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10417: }
1.301 www 10418: # ------------------------------------------------- Get the title of a resource
10419:
10420: sub gettitle {
10421: my $urlsymb=shift;
10422: my $symb=&symbread($urlsymb);
1.534 albertel 10423: if ($symb) {
1.620 albertel 10424: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10425: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10426: if (defined($cached)) {
10427: return $result;
10428: }
1.534 albertel 10429: my ($map,$resid,$url)=&decode_symb($symb);
10430: my $title='';
1.907 albertel 10431: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10432: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10433: } else {
10434: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10435: &GDBM_READER(),0640)) {
10436: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10437: $title=$bighash{'title_'.$mapid.'.'.$resid};
10438: untie(%bighash);
10439: }
1.534 albertel 10440: }
10441: $title=~s/\&colon\;/\:/gs;
10442: if ($title) {
1.1159 www 10443: # Remember both $symb and $title for dynamic metadata
10444: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10445: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10446: # Cache this title and then return it
1.599 albertel 10447: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10448: }
10449: $urlsymb=$url;
10450: }
10451: my $title=&metadata($urlsymb,'title');
10452: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10453: return $title;
1.301 www 10454: }
1.613 albertel 10455:
1.614 albertel 10456: sub get_slot {
10457: my ($which,$cnum,$cdom)=@_;
10458: if (!$cnum || !$cdom) {
1.790 albertel 10459: (undef,my $courseid)=&whichuser();
1.620 albertel 10460: $cdom=$env{'course.'.$courseid.'.domain'};
10461: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10462: }
1.703 albertel 10463: my $key=join("\0",'slots',$cdom,$cnum,$which);
10464: my %slotinfo;
10465: if (exists($remembered{$key})) {
10466: $slotinfo{$which} = $remembered{$key};
10467: } else {
10468: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10469: &Apache::lonhomework::showhash(%slotinfo);
10470: my ($tmp)=keys(%slotinfo);
10471: if ($tmp=~/^error:/) { return (); }
10472: $remembered{$key} = $slotinfo{$which};
10473: }
1.616 albertel 10474: if (ref($slotinfo{$which}) eq 'HASH') {
10475: return %{$slotinfo{$which}};
10476: }
10477: return $slotinfo{$which};
1.614 albertel 10478: }
1.1150 raeburn 10479:
10480: sub get_reservable_slots {
10481: my ($cnum,$cdom,$uname,$udom) = @_;
10482: my $now = time;
10483: my $reservable_info;
10484: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10485: if (exists($remembered{$key})) {
10486: $reservable_info = $remembered{$key};
10487: } else {
10488: my %resv;
10489: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10490: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10491: $reservable_info = \%resv;
10492: $remembered{$key} = $reservable_info;
10493: }
10494: return $reservable_info;
10495: }
10496:
10497: sub get_course_slots {
10498: my ($cnum,$cdom) = @_;
10499: my $hashid=$cnum.':'.$cdom;
10500: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10501: if (defined($cached)) {
10502: if (ref($result) eq 'HASH') {
10503: return %{$result};
10504: }
10505: } else {
10506: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10507: my ($tmp) = keys(%slots);
10508: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10509: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10510: return %slots;
10511: }
10512: }
10513: return;
10514: }
10515:
10516: sub devalidate_slots_cache {
10517: my ($cnum,$cdom)=@_;
10518: my $hashid=$cnum.':'.$cdom;
10519: &devalidate_cache_new('allslots',$hashid);
10520: }
10521:
1.1172.2.8 raeburn 10522: sub get_coursechange {
10523: my ($cdom,$cnum) = @_;
10524: if ($cdom eq '' || $cnum eq '') {
10525: return unless ($env{'request.course.id'});
10526: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10527: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10528: }
10529: my $hashid=$cdom.'_'.$cnum;
10530: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10531: if ((defined($cached)) && ($change ne '')) {
10532: return $change;
10533: } else {
10534: my %crshash;
10535: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10536: if ($crshash{'internal.contentchange'} eq '') {
10537: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10538: if ($change eq '') {
10539: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10540: $change = $crshash{'internal.created'};
10541: }
10542: } else {
10543: $change = $crshash{'internal.contentchange'};
10544: }
10545: my $cachetime = 600;
10546: &do_cache_new('crschange',$hashid,$change,$cachetime);
10547: }
10548: return $change;
10549: }
10550:
10551: sub devalidate_coursechange_cache {
10552: my ($cnum,$cdom)=@_;
10553: my $hashid=$cnum.':'.$cdom;
10554: &devalidate_cache_new('crschange',$hashid);
10555: }
10556:
1.31 www 10557: # ------------------------------------------------- Update symbolic store links
10558:
10559: sub symblist {
10560: my ($mapname,%newhash)=@_;
1.438 www 10561: $mapname=&deversion(&declutter($mapname));
1.31 www 10562: my %hash;
1.620 albertel 10563: if (($env{'request.course.fn'}) && (%newhash)) {
10564: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10565: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10566: foreach my $url (keys(%newhash)) {
1.711 albertel 10567: next if ($url eq 'last_known'
10568: && $env{'form.no_update_last_known'});
10569: $hash{declutter($url)}=&encode_symb($mapname,
10570: $newhash{$url}->[1],
10571: $newhash{$url}->[0]);
1.191 harris41 10572: }
1.31 www 10573: if (untie(%hash)) {
10574: return 'ok';
10575: }
10576: }
10577: }
10578: return 'error';
1.212 www 10579: }
10580:
10581: # --------------------------------------------------------------- Verify a symb
10582:
10583: sub symbverify {
1.1172.2.11 raeburn 10584: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10585: my $thisfn=$thisurl;
1.439 www 10586: $thisfn=&declutter($thisfn);
1.215 www 10587: # direct jump to resource in page or to a sequence - will construct own symbs
10588: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10589: # check URL part
1.409 www 10590: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10591:
1.431 www 10592: unless ($url eq $thisfn) { return 0; }
1.213 www 10593:
1.216 www 10594: $symb=&symbclean($symb);
1.510 www 10595: $thisurl=&deversion($thisurl);
1.439 www 10596: $thisfn=&deversion($thisfn);
1.213 www 10597:
10598: my %bighash;
10599: my $okay=0;
1.431 www 10600:
1.620 albertel 10601: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10602: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10603: my $noclutter;
1.1032 raeburn 10604: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10605: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10606: if ($map =~ m{^uploaded/.+\.page$}) {
10607: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10608: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10609: $noclutter = 1;
10610: }
10611: }
10612: my $ids;
10613: if ($noclutter) {
10614: $ids=$bighash{'ids_'.$thisurl};
10615: } else {
10616: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10617: }
1.1102 raeburn 10618: unless ($ids) {
1.1172.2.13 raeburn 10619: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10620: $ids=$bighash{$idkey};
1.216 www 10621: }
10622: if ($ids) {
10623: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10624: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10625: $symb =~ s/\?.+$//;
10626: }
1.800 albertel 10627: foreach my $id (split(/\,/,$ids)) {
10628: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10629: if (
10630: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10631: eq $symb) {
1.1172.2.11 raeburn 10632: if (ref($encstate)) {
10633: $$encstate = $bighash{'encrypted_'.$id};
10634: }
1.1172.2.13 raeburn 10635: if (($env{'request.role.adv'}) ||
10636: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10637: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10638: $okay=1;
10639: last;
10640: }
10641: }
10642: }
1.216 www 10643: }
1.213 www 10644: untie(%bighash);
10645: }
10646: return $okay;
1.31 www 10647: }
10648:
1.210 www 10649: # --------------------------------------------------------------- Clean-up symb
10650:
10651: sub symbclean {
10652: my $symb=shift;
1.568 albertel 10653: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10654: # remove version from map
10655: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10656:
1.210 www 10657: # remove version from URL
10658: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10659:
1.507 www 10660: # remove wrapper
10661:
1.510 www 10662: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10663: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10664: return $symb;
1.409 www 10665: }
10666:
10667: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10668:
10669: sub encode_symb {
10670: my ($map,$resid,$url)=@_;
10671: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10672: }
1.409 www 10673:
10674: sub decode_symb {
1.568 albertel 10675: my $symb=shift;
10676: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10677: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10678: return (&fixversion($map),$resid,&fixversion($url));
10679: }
10680:
10681: sub fixversion {
10682: my $fn=shift;
1.609 banghart 10683: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10684: my %bighash;
10685: my $uri=&clutter($fn);
1.620 albertel 10686: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10687: # is this cached?
1.599 albertel 10688: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10689: if (defined($cached)) { return $result; }
10690: # unfortunately not cached, or expired
1.620 albertel 10691: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10692: &GDBM_READER(),0640)) {
10693: if ($bighash{'version_'.$uri}) {
10694: my $version=$bighash{'version_'.$uri};
1.444 www 10695: unless (($version eq 'mostrecent') ||
10696: ($version==&getversion($uri))) {
1.440 www 10697: $uri=~s/\.(\w+)$/\.$version\.$1/;
10698: }
10699: }
10700: untie %bighash;
1.413 www 10701: }
1.599 albertel 10702: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10703: }
10704:
10705: sub deversion {
10706: my $url=shift;
10707: $url=~s/\.\d+\.(\w+)$/\.$1/;
10708: return $url;
1.210 www 10709: }
10710:
1.31 www 10711: # ------------------------------------------------------ Return symb list entry
10712:
10713: sub symbread {
1.249 www 10714: my ($thisfn,$donotrecurse)=@_;
1.1172.2.13 raeburn 10715: my $cache_str;
10716: if ($thisfn ne '') {
10717: $cache_str='request.symbread.cached.'.$thisfn;
10718: if ($env{$cache_str} ne '') {
1.1172.2.8 raeburn 10719: return $env{$cache_str};
10720: }
1.1172.2.13 raeburn 10721: } else {
1.242 www 10722: # no filename provided? try from environment
1.620 albertel 10723: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10724: return $env{$cache_str}=&symbclean($env{'request.symb'});
10725: }
10726: $thisfn=$env{'request.filename'};
1.44 www 10727: }
1.569 albertel 10728: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10729: # is that filename actually a symb? Verify, clean, and return
10730: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10731: if (&symbverify($thisfn,$1)) {
1.620 albertel 10732: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10733: }
1.242 www 10734: }
1.44 www 10735: $thisfn=declutter($thisfn);
1.31 www 10736: my %hash;
1.37 www 10737: my %bighash;
10738: my $syval='';
1.620 albertel 10739: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10740: my $targetfn = $thisfn;
1.609 banghart 10741: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10742: $targetfn = 'adm/wrapper/'.$thisfn;
10743: }
1.687 albertel 10744: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10745: $targetfn=$1;
10746: }
1.620 albertel 10747: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10748: &GDBM_READER(),0640)) {
1.481 raeburn 10749: $syval=$hash{$targetfn};
1.37 www 10750: untie(%hash);
10751: }
10752: # ---------------------------------------------------------- There was an entry
10753: if ($syval) {
1.601 albertel 10754: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10755: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10756: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10757: #return $env{$cache_str}='';
1.601 albertel 10758: #}
10759: #$syval.=$1;
10760: #}
1.37 www 10761: } else {
10762: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10763: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10764: &GDBM_READER(),0640)) {
1.37 www 10765: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10766: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10767: unless ($ids) {
10768: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10769: }
10770: unless ($ids) {
10771: # alias?
10772: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10773: }
1.37 www 10774: if ($ids) {
10775: # ------------------------------------------------------------------- Has ID(s)
10776: my @possibilities=split(/\,/,$ids);
1.39 www 10777: if ($#possibilities==0) {
10778: # ----------------------------------------------- There is only one possibility
1.37 www 10779: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10780: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10781: $resid,$thisfn);
1.249 www 10782: } elsif (!$donotrecurse) {
1.39 www 10783: # ------------------------------------------ There is more than one possibility
10784: my $realpossible=0;
1.800 albertel 10785: foreach my $id (@possibilities) {
10786: my $file=$bighash{'src_'.$id};
1.39 www 10787: if (&allowed('bre',$file)) {
1.800 albertel 10788: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10789: if ($bighash{'map_type_'.$mapid} ne 'page') {
10790: $realpossible++;
1.626 albertel 10791: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10792: $resid,$thisfn);
1.39 www 10793: }
10794: }
1.191 harris41 10795: }
1.39 www 10796: if ($realpossible!=1) { $syval=''; }
1.249 www 10797: } else {
10798: $syval='';
1.37 www 10799: }
10800: }
10801: untie(%bighash)
1.481 raeburn 10802: }
1.31 www 10803: }
1.62 www 10804: if ($syval) {
1.620 albertel 10805: return $env{$cache_str}=$syval;
1.62 www 10806: }
1.31 www 10807: }
1.949 raeburn 10808: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10809: return $env{$cache_str}='';
1.31 www 10810: }
10811:
10812: # ---------------------------------------------------------- Return random seed
10813:
1.32 www 10814: sub numval {
10815: my $txt=shift;
10816: $txt=~tr/A-J/0-9/;
10817: $txt=~tr/a-j/0-9/;
10818: $txt=~tr/K-T/0-9/;
10819: $txt=~tr/k-t/0-9/;
10820: $txt=~tr/U-Z/0-5/;
10821: $txt=~tr/u-z/0-5/;
10822: $txt=~s/\D//g;
1.564 albertel 10823: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10824: return int($txt);
1.368 albertel 10825: }
10826:
1.484 albertel 10827: sub numval2 {
10828: my $txt=shift;
10829: $txt=~tr/A-J/0-9/;
10830: $txt=~tr/a-j/0-9/;
10831: $txt=~tr/K-T/0-9/;
10832: $txt=~tr/k-t/0-9/;
10833: $txt=~tr/U-Z/0-5/;
10834: $txt=~tr/u-z/0-5/;
10835: $txt=~s/\D//g;
10836: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10837: my $total;
10838: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10839: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10840: return int($total);
10841: }
10842:
1.575 albertel 10843: sub numval3 {
10844: use integer;
10845: my $txt=shift;
10846: $txt=~tr/A-J/0-9/;
10847: $txt=~tr/a-j/0-9/;
10848: $txt=~tr/K-T/0-9/;
10849: $txt=~tr/k-t/0-9/;
10850: $txt=~tr/U-Z/0-5/;
10851: $txt=~tr/u-z/0-5/;
10852: $txt=~s/\D//g;
10853: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10854: my $total;
10855: foreach my $val (@txts) { $total+=$val; }
10856: if ($_64bit) { $total=(($total<<32)>>32); }
10857: return $total;
10858: }
10859:
1.675 albertel 10860: sub digest {
10861: my ($data)=@_;
10862: my $digest=&Digest::MD5::md5($data);
10863: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10864: my ($e,$f);
10865: {
10866: use integer;
10867: $e=($a+$b);
10868: $f=($c+$d);
10869: if ($_64bit) {
10870: $e=(($e<<32)>>32);
10871: $f=(($f<<32)>>32);
10872: }
10873: }
10874: if (wantarray) {
10875: return ($e,$f);
10876: } else {
10877: my $g;
10878: {
10879: use integer;
10880: $g=($e+$f);
10881: if ($_64bit) {
10882: $g=(($g<<32)>>32);
10883: }
10884: }
10885: return $g;
10886: }
10887: }
10888:
1.368 albertel 10889: sub latest_rnd_algorithm_id {
1.675 albertel 10890: return '64bit5';
1.366 albertel 10891: }
1.32 www 10892:
1.503 albertel 10893: sub get_rand_alg {
10894: my ($courseid)=@_;
1.790 albertel 10895: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10896: if ($courseid) {
1.620 albertel 10897: return $env{"course.$courseid.rndseed"};
1.503 albertel 10898: }
10899: return &latest_rnd_algorithm_id();
10900: }
10901:
1.562 albertel 10902: sub validCODE {
10903: my ($CODE)=@_;
10904: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10905: return 0;
10906: }
10907:
1.491 albertel 10908: sub getCODE {
1.620 albertel 10909: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10910: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10911: defined($Apache::lonhomework::parsing_a_task) ) &&
10912: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10913: return $Apache::lonhomework::history{'resource.CODE'};
10914: }
10915: return undef;
10916: }
1.1133 foxr 10917: #
10918: # Determines the random seed for a specific context:
10919: #
10920: # parameters:
10921: # symb - in course context the symb for the seed.
10922: # course_id - The course id of the form domain_coursenum.
10923: # domain - Domain for the user.
10924: # course - Course for the user.
10925: # cenv - environment of the course.
10926: #
10927: # NOTE:
10928: # All parameters are picked out of the environment if missing
10929: # or not defined.
10930: # If a symb cannot be determined the current time is used instead.
10931: #
10932: # For a given well defined symb, courside, domain, username,
10933: # and course environment, the seed is reproducible.
10934: #
1.31 www 10935: sub rndseed {
1.1133 foxr 10936: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10937: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10938: if (!defined($symb)) {
1.366 albertel 10939: unless ($symb=$wsymb) { return time; }
10940: }
1.1146 foxr 10941: if (!defined $courseid) {
10942: $courseid=$wcourseid;
10943: }
10944: if (!defined $domain) { $domain=$wdomain; }
10945: if (!defined $username) { $username=$wusername }
1.1133 foxr 10946:
10947: my $which;
10948: if (defined($cenv->{'rndseed'})) {
10949: $which = $cenv->{'rndseed'};
10950: } else {
10951: $which =&get_rand_alg($courseid);
10952: }
1.491 albertel 10953: if (defined(&getCODE())) {
1.675 albertel 10954: if ($which eq '64bit5') {
10955: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10956: } elsif ($which eq '64bit4') {
1.575 albertel 10957: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10958: } else {
10959: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10960: }
1.675 albertel 10961: } elsif ($which eq '64bit5') {
10962: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10963: } elsif ($which eq '64bit4') {
10964: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10965: } elsif ($which eq '64bit3') {
10966: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10967: } elsif ($which eq '64bit2') {
10968: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10969: } elsif ($which eq '64bit') {
10970: return &rndseed_64bit($symb,$courseid,$domain,$username);
10971: }
10972: return &rndseed_32bit($symb,$courseid,$domain,$username);
10973: }
10974:
10975: sub rndseed_32bit {
10976: my ($symb,$courseid,$domain,$username)=@_;
10977: {
10978: use integer;
10979: my $symbchck=unpack("%32C*",$symb) << 27;
10980: my $symbseed=numval($symb) << 22;
10981: my $namechck=unpack("%32C*",$username) << 17;
10982: my $nameseed=numval($username) << 12;
10983: my $domainseed=unpack("%32C*",$domain) << 7;
10984: my $courseseed=unpack("%32C*",$courseid);
10985: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10986: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10987: #&logthis("rndseed :$num:$symb");
1.564 albertel 10988: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10989: return $num;
10990: }
10991: }
10992:
10993: sub rndseed_64bit {
10994: my ($symb,$courseid,$domain,$username)=@_;
10995: {
10996: use integer;
10997: my $symbchck=unpack("%32S*",$symb) << 21;
10998: my $symbseed=numval($symb) << 10;
10999: my $namechck=unpack("%32S*",$username);
11000:
11001: my $nameseed=numval($username) << 21;
11002: my $domainseed=unpack("%32S*",$domain) << 10;
11003: my $courseseed=unpack("%32S*",$courseid);
11004:
11005: my $num1=$symbchck+$symbseed+$namechck;
11006: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11007: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11008: #&logthis("rndseed :$num:$symb");
1.564 albertel 11009: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11010: return "$num1,$num2";
1.155 albertel 11011: }
1.366 albertel 11012: }
11013:
1.443 albertel 11014: sub rndseed_64bit2 {
11015: my ($symb,$courseid,$domain,$username)=@_;
11016: {
11017: use integer;
11018: # strings need to be an even # of cahracters long, it it is odd the
11019: # last characters gets thrown away
11020: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11021: my $symbseed=numval($symb) << 10;
11022: my $namechck=unpack("%32S*",$username.' ');
11023:
11024: my $nameseed=numval($username) << 21;
1.501 albertel 11025: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11026: my $courseseed=unpack("%32S*",$courseid.' ');
11027:
11028: my $num1=$symbchck+$symbseed+$namechck;
11029: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11030: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11031: #&logthis("rndseed :$num:$symb");
1.803 albertel 11032: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11033: return "$num1,$num2";
11034: }
11035: }
11036:
11037: sub rndseed_64bit3 {
11038: my ($symb,$courseid,$domain,$username)=@_;
11039: {
11040: use integer;
11041: # strings need to be an even # of cahracters long, it it is odd the
11042: # last characters gets thrown away
11043: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11044: my $symbseed=numval2($symb) << 10;
11045: my $namechck=unpack("%32S*",$username.' ');
11046:
11047: my $nameseed=numval2($username) << 21;
1.443 albertel 11048: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11049: my $courseseed=unpack("%32S*",$courseid.' ');
11050:
11051: my $num1=$symbchck+$symbseed+$namechck;
11052: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11053: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11054: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11055: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11056:
1.503 albertel 11057: return "$num1:$num2";
1.443 albertel 11058: }
11059: }
11060:
1.575 albertel 11061: sub rndseed_64bit4 {
11062: my ($symb,$courseid,$domain,$username)=@_;
11063: {
11064: use integer;
11065: # strings need to be an even # of cahracters long, it it is odd the
11066: # last characters gets thrown away
11067: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11068: my $symbseed=numval3($symb) << 10;
11069: my $namechck=unpack("%32S*",$username.' ');
11070:
11071: my $nameseed=numval3($username) << 21;
11072: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11073: my $courseseed=unpack("%32S*",$courseid.' ');
11074:
11075: my $num1=$symbchck+$symbseed+$namechck;
11076: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11077: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11078: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11079: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11080:
1.575 albertel 11081: return "$num1:$num2";
11082: }
11083: }
11084:
1.675 albertel 11085: sub rndseed_64bit5 {
11086: my ($symb,$courseid,$domain,$username)=@_;
11087: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11088: return "$num1:$num2";
11089: }
11090:
1.366 albertel 11091: sub rndseed_CODE_64bit {
11092: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11093: {
1.366 albertel 11094: use integer;
1.443 albertel 11095: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11096: my $symbseed=numval2($symb);
1.491 albertel 11097: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11098: my $CODEseed=numval(&getCODE());
1.443 albertel 11099: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11100: my $num1=$symbseed+$CODEchck;
11101: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11102: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11103: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11104: if ($_64bit) { $num1=(($num1<<32)>>32); }
11105: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11106: return "$num1:$num2";
1.366 albertel 11107: }
11108: }
11109:
1.575 albertel 11110: sub rndseed_CODE_64bit4 {
11111: my ($symb,$courseid,$domain,$username)=@_;
11112: {
11113: use integer;
11114: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11115: my $symbseed=numval3($symb);
11116: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11117: my $CODEseed=numval3(&getCODE());
11118: my $courseseed=unpack("%32S*",$courseid.' ');
11119: my $num1=$symbseed+$CODEchck;
11120: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11121: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11122: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11123: if ($_64bit) { $num1=(($num1<<32)>>32); }
11124: if ($_64bit) { $num2=(($num2<<32)>>32); }
11125: return "$num1:$num2";
11126: }
11127: }
11128:
1.675 albertel 11129: sub rndseed_CODE_64bit5 {
11130: my ($symb,$courseid,$domain,$username)=@_;
11131: my $code = &getCODE();
11132: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11133: return "$num1:$num2";
11134: }
11135:
1.366 albertel 11136: sub setup_random_from_rndseed {
11137: my ($rndseed)=@_;
1.503 albertel 11138: if ($rndseed =~/([,:])/) {
11139: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11140: &Math::Random::random_set_seed(abs($num1),abs($num2));
11141: } else {
11142: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11143: }
1.36 albertel 11144: }
11145:
1.474 albertel 11146: sub latest_receipt_algorithm_id {
1.835 albertel 11147: return 'receipt3';
1.474 albertel 11148: }
11149:
1.480 www 11150: sub recunique {
11151: my $fucourseid=shift;
11152: my $unique;
1.835 albertel 11153: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11154: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11155: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11156: } else {
11157: $unique=$perlvar{'lonReceipt'};
11158: }
11159: return unpack("%32C*",$unique);
11160: }
11161:
11162: sub recprefix {
11163: my $fucourseid=shift;
11164: my $prefix;
1.835 albertel 11165: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11166: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11167: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11168: } else {
11169: $prefix=$perlvar{'lonHostID'};
11170: }
11171: return unpack("%32C*",$prefix);
11172: }
11173:
1.76 www 11174: sub ireceipt {
1.474 albertel 11175: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11176:
11177: my $return =&recprefix($fucourseid).'-';
11178:
11179: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11180: $env{'request.state'} eq 'construct') {
11181: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11182: return $return;
11183: }
11184:
1.76 www 11185: my $cuname=unpack("%32C*",$funame);
11186: my $cudom=unpack("%32C*",$fudom);
11187: my $cucourseid=unpack("%32C*",$fucourseid);
11188: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11189: my $cunique=&recunique($fucourseid);
1.474 albertel 11190: my $cpart=unpack("%32S*",$part);
1.835 albertel 11191: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11192:
1.790 albertel 11193: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11194:
11195: $return.= ($cunique%$cuname+
11196: $cunique%$cudom+
11197: $cusymb%$cuname+
11198: $cusymb%$cudom+
11199: $cucourseid%$cuname+
11200: $cucourseid%$cudom+
11201: $cpart%$cuname+
11202: $cpart%$cudom);
11203: } else {
11204: $return.= ($cunique%$cuname+
11205: $cunique%$cudom+
11206: $cusymb%$cuname+
11207: $cusymb%$cudom+
11208: $cucourseid%$cuname+
11209: $cucourseid%$cudom);
11210: }
11211: return $return;
1.76 www 11212: }
11213:
11214: sub receipt {
1.474 albertel 11215: my ($part)=@_;
1.790 albertel 11216: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11217: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11218: }
1.260 ng 11219:
1.790 albertel 11220: sub whichuser {
11221: my ($passedsymb)=@_;
11222: my ($symb,$courseid,$domain,$name,$publicuser);
11223: if (defined($env{'form.grade_symb'})) {
11224: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11225: my $allowed=&allowed('vgr',$tmp_courseid);
11226: if (!$allowed &&
11227: exists($env{'request.course.sec'}) &&
11228: $env{'request.course.sec'} !~ /^\s*$/) {
11229: $allowed=&allowed('vgr',$tmp_courseid.
11230: '/'.$env{'request.course.sec'});
11231: }
11232: if ($allowed) {
11233: ($symb)=&get_env_multiple('form.grade_symb');
11234: $courseid=$tmp_courseid;
11235: ($domain)=&get_env_multiple('form.grade_domain');
11236: ($name)=&get_env_multiple('form.grade_username');
11237: return ($symb,$courseid,$domain,$name,$publicuser);
11238: }
11239: }
11240: if (!$passedsymb) {
11241: $symb=&symbread();
11242: } else {
11243: $symb=$passedsymb;
11244: }
11245: $courseid=$env{'request.course.id'};
11246: $domain=$env{'user.domain'};
11247: $name=$env{'user.name'};
11248: if ($name eq 'public' && $domain eq 'public') {
11249: if (!defined($env{'form.username'})) {
11250: $env{'form.username'}.=time.rand(10000000);
11251: }
11252: $name.=$env{'form.username'};
11253: }
11254: return ($symb,$courseid,$domain,$name,$publicuser);
11255:
11256: }
11257:
1.36 albertel 11258: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11259: # returns either the contents of the file or
11260: # -1 if the file doesn't exist
1.481 raeburn 11261: #
11262: # if the target is a file that was uploaded via DOCS,
11263: # a check will be made to see if a current copy exists on the local server,
11264: # if it does this will be served, otherwise a copy will be retrieved from
11265: # the home server for the course and stored in /home/httpd/html/userfiles on
11266: # the local server.
1.472 albertel 11267:
1.36 albertel 11268: sub getfile {
1.538 albertel 11269: my ($file) = @_;
1.609 banghart 11270: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11271: &repcopy($file);
11272: return &readfile($file);
11273: }
11274:
11275: sub repcopy_userfile {
11276: my ($file)=@_;
1.1142 raeburn 11277: my $londocroot = $perlvar{'lonDocRoot'};
11278: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11279: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11280: my ($cdom,$cnum,$filename) =
1.811 albertel 11281: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11282: my $uri="/uploaded/$cdom/$cnum/$filename";
11283: if (-e "$file") {
1.828 www 11284: # we already have a local copy, check it out
1.538 albertel 11285: my @fileinfo = stat($file);
1.828 www 11286: my $rtncode;
11287: my $info;
1.538 albertel 11288: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11289: if ($lwpresp ne 'ok') {
1.828 www 11290: # there is no such file anymore, even though we had a local copy
1.482 albertel 11291: if ($rtncode eq '404') {
1.538 albertel 11292: unlink($file);
1.482 albertel 11293: }
11294: return -1;
11295: }
11296: if ($info < $fileinfo[9]) {
1.828 www 11297: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11298: return 'ok';
1.828 www 11299: } else {
11300: # the file is outdated, get rid of it
11301: unlink($file);
1.482 albertel 11302: }
1.828 www 11303: }
11304: # one way or the other, at this point, we don't have the file
11305: # construct the correct path for the file
11306: my @parts = ($cdom,$cnum);
11307: if ($filename =~ m|^(.+)/[^/]+$|) {
11308: push @parts, split(/\//,$1);
11309: }
11310: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11311: foreach my $part (@parts) {
11312: $path .= '/'.$part;
11313: if (!-e $path) {
11314: mkdir($path,0770);
1.482 albertel 11315: }
11316: }
1.828 www 11317: # now the path exists for sure
11318: # get a user agent
11319: my $ua=new LWP::UserAgent;
11320: my $transferfile=$file.'.in.transfer';
11321: # FIXME: this should flock
11322: if (-e $transferfile) { return 'ok'; }
11323: my $request;
11324: $uri=~s/^\///;
1.980 raeburn 11325: my $homeserver = &homeserver($cnum,$cdom);
11326: my $protocol = $protocol{$homeserver};
11327: $protocol = 'http' if ($protocol ne 'https');
11328: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11329: my $response=$ua->request($request,$transferfile);
11330: # did it work?
11331: if ($response->is_error()) {
11332: unlink($transferfile);
11333: &logthis("Userfile repcopy failed for $uri");
11334: return -1;
11335: }
11336: # worked, rename the transfer file
11337: rename($transferfile,$file);
1.607 raeburn 11338: return 'ok';
1.481 raeburn 11339: }
11340:
1.517 albertel 11341: sub tokenwrapper {
11342: my $uri=shift;
1.980 raeburn 11343: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11344: $uri=~s|^/||;
1.620 albertel 11345: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11346: my $token=$1;
1.552 albertel 11347: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11348: if ($udom && $uname && $file) {
11349: $file=~s|(\?\.*)*$||;
1.949 raeburn 11350: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11351: my $homeserver = &homeserver($uname,$udom);
11352: my $protocol = $protocol{$homeserver};
11353: $protocol = 'http' if ($protocol ne 'https');
11354: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11355: (($uri=~/\?/)?'&':'?').'token='.$token.
11356: '&tokenissued='.$perlvar{'lonHostID'};
11357: } else {
11358: return '/adm/notfound.html';
11359: }
11360: }
11361:
1.828 www 11362: # call with reqtype HEAD: get last modification time
11363: # call with reqtype GET: get the file contents
11364: # Do not call this with reqtype GET for large files! It loads everything into memory
11365: #
1.481 raeburn 11366: sub getuploaded {
11367: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11368: $uri=~s/^\///;
1.980 raeburn 11369: my $homeserver = &homeserver($cnum,$cdom);
11370: my $protocol = $protocol{$homeserver};
11371: $protocol = 'http' if ($protocol ne 'https');
11372: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11373: my $ua=new LWP::UserAgent;
11374: my $request=new HTTP::Request($reqtype,$uri);
11375: my $response=$ua->request($request);
11376: $$rtncode = $response->code;
1.482 albertel 11377: if (! $response->is_success()) {
11378: return 'failed';
11379: }
11380: if ($reqtype eq 'HEAD') {
1.486 www 11381: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11382: } elsif ($reqtype eq 'GET') {
11383: $$info = $response->content;
1.472 albertel 11384: }
1.482 albertel 11385: return 'ok';
1.36 albertel 11386: }
11387:
1.481 raeburn 11388: sub readfile {
11389: my $file = shift;
11390: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11391: my $fh;
11392: open($fh,"<$file");
11393: my $a='';
1.800 albertel 11394: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11395: return $a;
11396: }
11397:
1.36 albertel 11398: sub filelocation {
1.590 banghart 11399: my ($dir,$file) = @_;
11400: my $location;
11401: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11402:
11403: if ($file =~ m-^/adm/-) {
11404: $file=~s-^/adm/wrapper/-/-;
11405: $file=~s-^/adm/coursedocs/showdoc/-/-;
11406: }
1.882 albertel 11407:
1.1139 www 11408: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11409: $location = $file;
1.609 banghart 11410: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11411: my ($udom,$uname,$filename)=
1.811 albertel 11412: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11413: my $home=&homeserver($uname,$udom);
11414: my $is_me=0;
11415: my @ids=¤t_machine_ids();
11416: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11417: if ($is_me) {
1.1117 foxr 11418: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11419: } else {
11420: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11421: $udom.'/'.$uname.'/'.$filename;
11422: }
1.882 albertel 11423: } elsif ($file =~ m-^/adm/-) {
11424: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11425: } else {
11426: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11427: $file=~s:^/(res|priv)/:/:;
11428: my $space=$1;
1.590 banghart 11429: if ( !( $file =~ m:^/:) ) {
11430: $location = $dir. '/'.$file;
11431: } else {
1.1142 raeburn 11432: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11433: }
1.59 albertel 11434: }
1.590 banghart 11435: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11436: while ($location=~m{/\.\./}) {
11437: if ($location =~ m{/[^/]+/\.\./}) {
11438: $location=~ s{/[^/]+/\.\./}{/}g;
11439: } else {
11440: $location=~ s{/\.\./}{/}g;
11441: }
11442: } #remove dir/..
1.590 banghart 11443: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11444: return $location;
1.46 www 11445: }
1.36 albertel 11446:
1.46 www 11447: sub hreflocation {
11448: my ($dir,$file)=@_;
1.980 raeburn 11449: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11450: $file=filelocation($dir,$file);
1.700 albertel 11451: } elsif ($file=~m-^/adm/-) {
11452: $file=~s-^/adm/wrapper/-/-;
11453: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11454: }
11455: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11456: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11457: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11458: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11459: {/uploaded/$1/$2/}x;
1.46 www 11460: }
1.913 albertel 11461: if ($file=~ m{^/userfiles/}) {
11462: $file =~ s{^/userfiles/}{/uploaded/};
11463: }
1.462 albertel 11464: return $file;
1.465 albertel 11465: }
11466:
1.1139 www 11467:
11468:
11469:
11470:
1.465 albertel 11471: sub current_machine_domains {
1.853 albertel 11472: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11473: }
11474:
11475: sub machine_domains {
11476: my ($hostname) = @_;
1.465 albertel 11477: my @domains;
1.838 albertel 11478: my %hostname = &all_hostnames();
1.465 albertel 11479: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11480: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11481: if ($hostname eq $name) {
1.844 albertel 11482: push(@domains,&host_domain($id));
1.465 albertel 11483: }
11484: }
11485: return @domains;
11486: }
11487:
11488: sub current_machine_ids {
1.853 albertel 11489: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11490: }
11491:
11492: sub machine_ids {
11493: my ($hostname) = @_;
11494: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11495: my @ids;
1.888 albertel 11496: my %name_to_host = &all_names();
1.889 albertel 11497: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11498: return @{ $name_to_host{$hostname} };
11499: }
11500: return;
1.31 www 11501: }
11502:
1.824 raeburn 11503: sub additional_machine_domains {
11504: my @domains;
11505: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11506: while( my $line = <$fh>) {
11507: $line =~ s/\s//g;
11508: push(@domains,$line);
11509: }
11510: return @domains;
11511: }
11512:
11513: sub default_login_domain {
11514: my $domain = $perlvar{'lonDefDomain'};
11515: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11516: foreach my $posdom (¤t_machine_domains(),
11517: &additional_machine_domains()) {
11518: if (lc($posdom) eq lc($testdomain)) {
11519: $domain=$posdom;
11520: last;
11521: }
11522: }
11523: return $domain;
11524: }
11525:
1.31 www 11526: # ------------------------------------------------------------- Declutters URLs
11527:
11528: sub declutter {
11529: my $thisfn=shift;
1.569 albertel 11530: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11531: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11532: $thisfn=~s/^\///;
1.697 albertel 11533: $thisfn=~s|^adm/wrapper/||;
11534: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11535: $thisfn=~s/^res\///;
1.1172 bisitz 11536: $thisfn=~s/^priv\///;
1.1032 raeburn 11537: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11538: $thisfn=~s/\?.+$//;
11539: }
1.268 www 11540: return $thisfn;
11541: }
11542:
11543: # ------------------------------------------------------------- Clutter up URLs
11544:
11545: sub clutter {
11546: my $thisfn='/'.&declutter(shift);
1.887 albertel 11547: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11548: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11549: $thisfn='/res'.$thisfn;
11550: }
1.1031 raeburn 11551: if ($thisfn !~m|^/adm|) {
11552: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11553: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11554: } else {
11555: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11556: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11557: if ($embstyle eq 'ssi'
11558: || ($embstyle eq 'hdn')
11559: || ($embstyle eq 'rat')
11560: || ($embstyle eq 'prv')
11561: || ($embstyle eq 'ign')) {
11562: #do nothing with these
11563: } elsif (($embstyle eq 'img')
1.695 albertel 11564: || ($embstyle eq 'emb')
11565: || ($embstyle eq 'wrp')) {
11566: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11567: } elsif ($embstyle eq 'unk'
11568: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11569: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11570: } else {
1.718 www 11571: # &logthis("Got a blank emb style");
1.695 albertel 11572: }
1.694 albertel 11573: }
11574: }
1.31 www 11575: return $thisfn;
1.12 www 11576: }
11577:
1.787 albertel 11578: sub clutter_with_no_wrapper {
11579: my $uri = &clutter(shift);
11580: if ($uri =~ m-^/adm/-) {
11581: $uri =~ s-^/adm/wrapper/-/-;
11582: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11583: }
11584: return $uri;
11585: }
11586:
1.557 albertel 11587: sub freeze_escape {
11588: my ($value)=@_;
11589: if (ref($value)) {
11590: $value=&nfreeze($value);
11591: return '__FROZEN__'.&escape($value);
11592: }
11593: return &escape($value);
11594: }
11595:
1.11 www 11596:
1.557 albertel 11597: sub thaw_unescape {
11598: my ($value)=@_;
11599: if ($value =~ /^__FROZEN__/) {
11600: substr($value,0,10,undef);
11601: $value=&unescape($value);
11602: return &thaw($value);
11603: }
11604: return &unescape($value);
11605: }
11606:
1.436 albertel 11607: sub correct_line_ends {
11608: my ($result)=@_;
11609: $$result =~s/\r\n/\n/mg;
11610: $$result =~s/\r/\n/mg;
1.415 albertel 11611: }
1.1 albertel 11612: # ================================================================ Main Program
11613:
1.184 www 11614: sub goodbye {
1.204 albertel 11615: &logthis("Starting Shut down");
1.443 albertel 11616: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11617: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11618: #converted
1.599 albertel 11619: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11620: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11621: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11622: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11623: #1.1 only
1.870 albertel 11624: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11625: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11626: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11627: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11628: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11629: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11630: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11631: &flushcourselogs();
11632: &logthis("Shutting down");
11633: }
11634:
1.852 albertel 11635: sub get_dns {
1.1172.2.17 raeburn 11636: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11637: if (!$ignore_cache) {
11638: my ($content,$cached)=
11639: &Apache::lonnet::is_cached_new('dns',$url);
11640: if ($cached) {
1.1172.2.17 raeburn 11641: &$func($content,$hashref);
1.869 albertel 11642: return;
11643: }
11644: }
11645:
11646: my %alldns;
1.852 albertel 11647: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11648: foreach my $dns (<$config>) {
11649: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11650: my $line = $1;
11651: my ($host,$protocol) = split(/:/,$line);
11652: if ($protocol ne 'https') {
11653: $protocol = 'http';
11654: }
11655: $alldns{$host} = $protocol;
1.869 albertel 11656: }
11657: while (%alldns) {
11658: my ($dns) = keys(%alldns);
1.852 albertel 11659: my $ua=new LWP::UserAgent;
1.1134 raeburn 11660: $ua->timeout(30);
1.979 raeburn 11661: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11662: my $response=$ua->request($request);
1.979 raeburn 11663: delete($alldns{$dns});
1.852 albertel 11664: next if ($response->is_error());
11665: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11666: unless ($nocache) {
1.1172.2.23 raeburn 11667: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11668: }
11669: &$func(\@content,$hashref);
1.869 albertel 11670: return;
1.852 albertel 11671: }
11672: close($config);
1.871 albertel 11673: my $which = (split('/',$url))[3];
11674: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11675: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11676: my @content = <$config>;
1.1172.2.17 raeburn 11677: &$func(\@content,$hashref);
11678: return;
11679: }
11680:
11681: # ------------------------------------------------------Get DNS checksums file
11682: sub parse_dns_checksums_tab {
11683: my ($lines,$hashref) = @_;
11684: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11685: my $loncaparev = &get_server_loncaparev($machine_dom);
11686: my ($release,$timestamp) = split(/\-/,$loncaparev);
11687: my (%chksum,%revnum);
11688: if (ref($lines) eq 'ARRAY') {
11689: chomp(@{$lines});
11690: my $versions = shift(@{$lines});
11691: my %supported;
11692: if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
11693: my $releaseslist = $1;
11694: if ($releaseslist =~ /,/) {
11695: map { $supported{$_} = 1; } split(/,/,$releaseslist);
11696: } elsif ($releaseslist) {
11697: $supported{$releaseslist} = 1;
11698: }
11699: }
11700: if ($supported{$release}) {
11701: my $matchthis = 0;
11702: foreach my $line (@{$lines}) {
11703: if ($line =~ /^(\d[\w\.]+)$/) {
11704: if ($matchthis) {
11705: last;
11706: } elsif ($1 eq $release) {
11707: $matchthis = 1;
11708: }
11709: } elsif ($matchthis) {
11710: my ($file,$version,$shasum) = split(/,/,$line);
11711: $chksum{$file} = $shasum;
11712: $revnum{$file} = $version;
11713: }
11714: }
11715: if (ref($hashref) eq 'HASH') {
11716: %{$hashref} = (
11717: sums => \%chksum,
11718: versions => \%revnum,
11719: );
11720: }
11721: }
11722: }
1.869 albertel 11723: return;
1.852 albertel 11724: }
1.1172.2.17 raeburn 11725:
11726: sub fetch_dns_checksums {
11727: my %checksums;
11728: &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
11729: \%checksums);
11730: return \%checksums;
11731: }
11732:
1.327 albertel 11733: # ------------------------------------------------------------ Read domain file
11734: {
1.852 albertel 11735: my $loaded;
1.846 albertel 11736: my %domain;
11737:
1.852 albertel 11738: sub parse_domain_tab {
11739: my ($lines) = @_;
11740: foreach my $line (@$lines) {
11741: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11742:
1.846 albertel 11743: chomp($line);
1.852 albertel 11744: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11745: my %this_domain;
11746: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11747: 'lang_def', 'city', 'longi', 'lati',
11748: 'primary') {
11749: $this_domain{$field} = shift(@elements);
11750: }
11751: $domain{$name} = \%this_domain;
1.852 albertel 11752: }
11753: }
1.864 albertel 11754:
11755: sub reset_domain_info {
11756: undef($loaded);
11757: undef(%domain);
11758: }
11759:
1.852 albertel 11760: sub load_domain_tab {
1.869 albertel 11761: my ($ignore_cache) = @_;
11762: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11763: my $fh;
11764: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11765: my @lines = <$fh>;
11766: &parse_domain_tab(\@lines);
1.448 albertel 11767: }
1.852 albertel 11768: close($fh);
11769: $loaded = 1;
1.327 albertel 11770: }
1.846 albertel 11771:
11772: sub domain {
1.852 albertel 11773: &load_domain_tab() if (!$loaded);
11774:
1.846 albertel 11775: my ($name,$what) = @_;
11776: return if ( !exists($domain{$name}) );
11777:
11778: if (!$what) {
11779: return $domain{$name}{'description'};
11780: }
11781: return $domain{$name}{$what};
11782: }
1.974 raeburn 11783:
11784: sub domain_info {
11785: &load_domain_tab() if (!$loaded);
11786: return %domain;
11787: }
11788:
1.327 albertel 11789: }
11790:
11791:
1.1 albertel 11792: # ------------------------------------------------------------- Read hosts file
11793: {
1.838 albertel 11794: my %hostname;
1.844 albertel 11795: my %hostdom;
1.845 albertel 11796: my %libserv;
1.852 albertel 11797: my $loaded;
1.888 albertel 11798: my %name_to_host;
1.1074 raeburn 11799: my %internetdom;
1.1107 raeburn 11800: my %LC_dns_serv;
1.852 albertel 11801:
11802: sub parse_hosts_tab {
11803: my ($file) = @_;
11804: foreach my $configline (@$file) {
11805: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11806: chomp($configline);
11807: if ($configline =~ /^\^/) {
11808: if ($configline =~ /^\^([\w.\-]+)/) {
11809: $LC_dns_serv{$1} = 1;
11810: }
11811: next;
11812: }
1.1074 raeburn 11813: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11814: $name=~s/\s//g;
11815: if ($id && $domain && $role && $name) {
11816: $hostname{$id}=$name;
1.888 albertel 11817: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11818: $hostdom{$id}=$domain;
11819: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11820: if (defined($protocol)) {
11821: if ($protocol eq 'https') {
11822: $protocol{$id} = $protocol;
11823: } else {
11824: $protocol{$id} = 'http';
11825: }
1.968 raeburn 11826: } else {
1.969 raeburn 11827: $protocol{$id} = 'http';
1.968 raeburn 11828: }
1.1074 raeburn 11829: if (defined($intdom)) {
11830: $internetdom{$id} = $intdom;
11831: }
1.852 albertel 11832: }
11833: }
11834: }
1.864 albertel 11835:
11836: sub reset_hosts_info {
1.897 albertel 11837: &purge_remembered();
1.864 albertel 11838: &reset_domain_info();
11839: &reset_hosts_ip_info();
1.892 albertel 11840: undef(%name_to_host);
1.864 albertel 11841: undef(%hostname);
11842: undef(%hostdom);
11843: undef(%libserv);
11844: undef($loaded);
11845: }
1.1 albertel 11846:
1.852 albertel 11847: sub load_hosts_tab {
1.869 albertel 11848: my ($ignore_cache) = @_;
11849: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11850: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11851: my @config = <$config>;
11852: &parse_hosts_tab(\@config);
11853: close($config);
11854: $loaded=1;
1.1 albertel 11855: }
1.852 albertel 11856:
1.838 albertel 11857: sub hostname {
1.852 albertel 11858: &load_hosts_tab() if (!$loaded);
11859:
1.838 albertel 11860: my ($lonid) = @_;
11861: return $hostname{$lonid};
11862: }
1.845 albertel 11863:
1.838 albertel 11864: sub all_hostnames {
1.852 albertel 11865: &load_hosts_tab() if (!$loaded);
11866:
1.838 albertel 11867: return %hostname;
11868: }
1.845 albertel 11869:
1.888 albertel 11870: sub all_names {
11871: &load_hosts_tab() if (!$loaded);
11872:
11873: return %name_to_host;
11874: }
11875:
1.974 raeburn 11876: sub all_host_domain {
11877: &load_hosts_tab() if (!$loaded);
11878: return %hostdom;
11879: }
11880:
1.845 albertel 11881: sub is_library {
1.852 albertel 11882: &load_hosts_tab() if (!$loaded);
11883:
1.845 albertel 11884: return exists($libserv{$_[0]});
11885: }
11886:
11887: sub all_library {
1.852 albertel 11888: &load_hosts_tab() if (!$loaded);
11889:
1.845 albertel 11890: return %libserv;
11891: }
11892:
1.1062 droeschl 11893: sub unique_library {
11894: #2x reverse removes all hostnames that appear more than once
11895: my %unique = reverse &all_library();
11896: return reverse %unique;
11897: }
11898:
1.841 albertel 11899: sub get_servers {
1.852 albertel 11900: &load_hosts_tab() if (!$loaded);
11901:
1.841 albertel 11902: my ($domain,$type) = @_;
11903: my %possible_hosts = ($type eq 'library') ? %libserv
11904: : %hostname;
11905: my %result;
1.842 albertel 11906: if (ref($domain) eq 'ARRAY') {
11907: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11908: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11909: $result{$host} = $hostname;
11910: }
11911: }
11912: } else {
11913: while ( my ($host,$hostname) = each(%possible_hosts)) {
11914: if ($hostdom{$host} eq $domain) {
11915: $result{$host} = $hostname;
11916: }
1.841 albertel 11917: }
11918: }
11919: return %result;
11920: }
1.845 albertel 11921:
1.1062 droeschl 11922: sub get_unique_servers {
11923: my %unique = reverse &get_servers(@_);
11924: return reverse %unique;
11925: }
11926:
1.844 albertel 11927: sub host_domain {
1.852 albertel 11928: &load_hosts_tab() if (!$loaded);
11929:
1.844 albertel 11930: my ($lonid) = @_;
11931: return $hostdom{$lonid};
11932: }
11933:
1.841 albertel 11934: sub all_domains {
1.852 albertel 11935: &load_hosts_tab() if (!$loaded);
11936:
1.841 albertel 11937: my %seen;
11938: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11939: return @uniq;
11940: }
1.1074 raeburn 11941:
11942: sub internet_dom {
11943: &load_hosts_tab() if (!$loaded);
11944:
11945: my ($lonid) = @_;
11946: return $internetdom{$lonid};
11947: }
1.1107 raeburn 11948:
11949: sub is_LC_dns {
11950: &load_hosts_tab() if (!$loaded);
11951:
11952: my ($hostname) = @_;
11953: return exists($LC_dns_serv{$hostname});
11954: }
11955:
1.1 albertel 11956: }
11957:
1.847 albertel 11958: {
11959: my %iphost;
1.856 albertel 11960: my %name_to_ip;
11961: my %lonid_to_ip;
1.869 albertel 11962:
1.847 albertel 11963: sub get_hosts_from_ip {
11964: my ($ip) = @_;
11965: my %iphosts = &get_iphost();
11966: if (ref($iphosts{$ip})) {
11967: return @{$iphosts{$ip}};
11968: }
11969: return;
1.839 albertel 11970: }
1.864 albertel 11971:
11972: sub reset_hosts_ip_info {
11973: undef(%iphost);
11974: undef(%name_to_ip);
11975: undef(%lonid_to_ip);
11976: }
1.856 albertel 11977:
11978: sub get_host_ip {
11979: my ($lonid) = @_;
11980: if (exists($lonid_to_ip{$lonid})) {
11981: return $lonid_to_ip{$lonid};
11982: }
11983: my $name=&hostname($lonid);
11984: my $ip = gethostbyname($name);
11985: return if (!$ip || length($ip) ne 4);
11986: $ip=inet_ntoa($ip);
11987: $name_to_ip{$name} = $ip;
11988: $lonid_to_ip{$lonid} = $ip;
11989: return $ip;
11990: }
1.847 albertel 11991:
11992: sub get_iphost {
1.869 albertel 11993: my ($ignore_cache) = @_;
1.894 albertel 11994:
1.869 albertel 11995: if (!$ignore_cache) {
11996: if (%iphost) {
11997: return %iphost;
11998: }
11999: my ($ip_info,$cached)=
12000: &Apache::lonnet::is_cached_new('iphost','iphost');
12001: if ($cached) {
12002: %iphost = %{$ip_info->[0]};
12003: %name_to_ip = %{$ip_info->[1]};
12004: %lonid_to_ip = %{$ip_info->[2]};
12005: return %iphost;
12006: }
12007: }
1.894 albertel 12008:
12009: # get yesterday's info for fallback
12010: my %old_name_to_ip;
12011: my ($ip_info,$cached)=
12012: &Apache::lonnet::is_cached_new('iphost','iphost');
12013: if ($cached) {
12014: %old_name_to_ip = %{$ip_info->[1]};
12015: }
12016:
1.888 albertel 12017: my %name_to_host = &all_names();
12018: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12019: my $ip;
12020: if (!exists($name_to_ip{$name})) {
12021: $ip = gethostbyname($name);
12022: if (!$ip || length($ip) ne 4) {
1.894 albertel 12023: if (defined($old_name_to_ip{$name})) {
12024: $ip = $old_name_to_ip{$name};
12025: &logthis("Can't find $name defaulting to old $ip");
12026: } else {
12027: &logthis("Name $name no IP found");
12028: next;
12029: }
12030: } else {
12031: $ip=inet_ntoa($ip);
1.847 albertel 12032: }
12033: $name_to_ip{$name} = $ip;
12034: } else {
12035: $ip = $name_to_ip{$name};
1.653 albertel 12036: }
1.888 albertel 12037: foreach my $id (@{ $name_to_host{$name} }) {
12038: $lonid_to_ip{$id} = $ip;
12039: }
12040: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12041: }
1.1172.2.23 raeburn 12042: &do_cache_new('iphost','iphost',
12043: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12044: 48*60*60);
1.869 albertel 12045:
1.847 albertel 12046: return %iphost;
1.598 albertel 12047: }
12048:
1.992 raeburn 12049: #
12050: # Given a DNS returns the loncapa host name for that DNS
12051: #
12052: sub host_from_dns {
12053: my ($dns) = @_;
12054: my @hosts;
12055: my $ip;
12056:
1.993 raeburn 12057: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12058: $ip = $name_to_ip{$dns};
12059: }
12060: if (!$ip) {
12061: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12062: if (length($ip) == 4) {
12063: $ip = &IO::Socket::inet_ntoa($ip);
12064: }
12065: }
12066: if ($ip) {
12067: @hosts = get_hosts_from_ip($ip);
12068: return $hosts[0];
12069: }
12070: return undef;
1.986 foxr 12071: }
1.992 raeburn 12072:
1.1074 raeburn 12073: sub get_internet_names {
12074: my ($lonid) = @_;
12075: return if ($lonid eq '');
12076: my ($idnref,$cached)=
12077: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12078: if ($cached) {
12079: return $idnref;
12080: }
12081: my $ip = &get_host_ip($lonid);
12082: my @hosts = &get_hosts_from_ip($ip);
12083: my %iphost = &get_iphost();
12084: my (@idns,%seen);
12085: foreach my $id (@hosts) {
12086: my $dom = &host_domain($id);
12087: my $prim_id = &domain($dom,'primary');
12088: my $prim_ip = &get_host_ip($prim_id);
12089: next if ($seen{$prim_ip});
12090: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12091: foreach my $id (@{$iphost{$prim_ip}}) {
12092: my $intdom = &internet_dom($id);
12093: unless (grep(/^\Q$intdom\E$/,@idns)) {
12094: push(@idns,$intdom);
12095: }
12096: }
12097: }
12098: $seen{$prim_ip} = 1;
12099: }
1.1172.2.23 raeburn 12100: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12101: }
12102:
1.986 foxr 12103: }
12104:
1.1079 raeburn 12105: sub all_loncaparevs {
12106: 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);
12107: }
12108:
1.1172.2.27 raeburn 12109: # ------------------------------------------------------- Read loncaparev table
12110: {
12111: sub load_loncaparevs {
12112: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12113: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12114: while (my $configline=<$config>) {
12115: chomp($configline);
12116: my ($hostid,$loncaparev)=split(/:/,$configline);
12117: $loncaparevs{$hostid}=$loncaparev;
12118: }
12119: close($config);
12120: }
12121: }
12122: }
12123: }
12124:
12125: # ----------------------------------------------------- Read serverhostID table
12126: {
12127: sub load_serverhomeIDs {
12128: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12129: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12130: while (my $configline=<$config>) {
12131: chomp($configline);
12132: my ($name,$id)=split(/:/,$configline);
12133: $serverhomeIDs{$name}=$id;
12134: }
12135: close($config);
12136: }
12137: }
12138: }
12139: }
12140:
12141:
1.862 albertel 12142: BEGIN {
12143:
12144: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12145: unless ($readit) {
12146: {
12147: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12148: %perlvar = (%perlvar,%{$configvars});
12149: }
12150:
12151:
1.1 albertel 12152: # ------------------------------------------------------ Read spare server file
12153: {
1.448 albertel 12154: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12155:
12156: while (my $configline=<$config>) {
12157: chomp($configline);
1.284 matthew 12158: if ($configline) {
1.784 albertel 12159: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12160: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12161: push(@{ $spareid{$type} }, $host);
1.1 albertel 12162: }
12163: }
1.448 albertel 12164: close($config);
1.1 albertel 12165: }
1.11 www 12166: # ------------------------------------------------------------ Read permissions
12167: {
1.448 albertel 12168: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12169:
12170: while (my $configline=<$config>) {
1.448 albertel 12171: chomp($configline);
12172: if ($configline) {
12173: my ($role,$perm)=split(/ /,$configline);
12174: if ($perm ne '') { $pr{$role}=$perm; }
12175: }
1.11 www 12176: }
1.448 albertel 12177: close($config);
1.11 www 12178: }
12179:
12180: # -------------------------------------------- Read plain texts for permissions
12181: {
1.448 albertel 12182: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12183:
12184: while (my $configline=<$config>) {
1.448 albertel 12185: chomp($configline);
12186: if ($configline) {
1.742 raeburn 12187: my ($short,@plain)=split(/:/,$configline);
12188: %{$prp{$short}} = ();
12189: if (@plain > 0) {
12190: $prp{$short}{'std'} = $plain[0];
12191: for (my $i=1; $i<@plain; $i++) {
12192: $prp{$short}{'alt'.$i} = $plain[$i];
12193: }
12194: }
1.448 albertel 12195: }
1.135 www 12196: }
1.448 albertel 12197: close($config);
1.135 www 12198: }
12199:
12200: # ---------------------------------------------------------- Read package table
12201: {
1.448 albertel 12202: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12203:
12204: while (my $configline=<$config>) {
1.483 albertel 12205: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12206: chomp($configline);
12207: my ($short,$plain)=split(/:/,$configline);
12208: my ($pack,$name)=split(/\&/,$short);
12209: if ($plain ne '') {
12210: $packagetab{$pack.'&'.$name.'&name'}=$name;
12211: $packagetab{$short}=$plain;
12212: }
1.11 www 12213: }
1.448 albertel 12214: close($config);
1.329 matthew 12215: }
12216:
1.1172.2.27 raeburn 12217: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12218:
1.1172.2.27 raeburn 12219: &load_loncaparevs();
12220:
12221: # ------------------------------------------------------- Read serverhostID table
12222:
12223: &load_serverhomeIDs();
1.1074 raeburn 12224:
1.1172.2.27 raeburn 12225: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12226: {
12227: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12228: if (-e $file) {
12229: my $parser = HTML::LCParser->new($file);
12230: while (my $token = $parser->get_token()) {
12231: if ($token->[0] eq 'S') {
12232: my $item = $token->[1];
12233: my $name = $token->[2]{'name'};
12234: my $value = $token->[2]{'value'};
12235: if ($item ne '' && $name ne '' && $value ne '') {
12236: my $release = $parser->get_text();
12237: $release =~ s/(^\s*|\s*$ )//gx;
12238: $needsrelease{$item.':'.$name.':'.$value} = $release;
12239: }
12240: }
12241: }
12242: }
1.1073 raeburn 12243: }
12244:
1.1138 raeburn 12245: # ---------------------------------------------------------- Read managers table
12246: {
12247: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12248: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12249: while (my $configline=<$config>) {
12250: chomp($configline);
12251: next if ($configline =~ /^\#/);
12252: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12253: $managerstab{$configline} = 1;
12254: }
12255: }
12256: close($config);
12257: }
12258: }
12259: }
12260:
1.329 matthew 12261: # ------------- set up temporary directory
12262: {
1.1117 foxr 12263: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12264:
1.11 www 12265: }
12266:
1.794 albertel 12267: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12268: 'compress_threshold'=> 20_000,
12269: });
1.185 www 12270:
1.281 www 12271: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12272: $dumpcount=0;
1.958 www 12273: $locknum=0;
1.22 www 12274:
1.163 harris41 12275: &logtouch();
1.672 albertel 12276: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12277: $readit=1;
1.564 albertel 12278: {
12279: use integer;
12280: my $test=(2**32)+1;
1.568 albertel 12281: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12282: &logthis(" Detected 64bit platform ($_64bit)");
12283: }
1.1172.2.18 raeburn 12284:
12285: {
12286: eval {
12287: ($apache) =
12288: (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12289: };
12290: if ($@) {
12291: $apache = 1.3;
12292: }
12293: }
12294:
1.195 www 12295: }
1.1 albertel 12296: }
1.179 www 12297:
1.1 albertel 12298: 1;
1.191 harris41 12299: __END__
12300:
1.243 albertel 12301: =pod
12302:
1.191 harris41 12303: =head1 NAME
12304:
1.243 albertel 12305: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12306:
12307: =head1 SYNOPSIS
12308:
1.243 albertel 12309: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12310:
12311: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12312:
1.243 albertel 12313: Common parameters:
12314:
12315: =over 4
12316:
12317: =item *
12318:
12319: $uname : an internal username (if $cname expecting a course Id specifically)
12320:
12321: =item *
12322:
12323: $udom : a domain (if $cdom expecting a course's domain specifically)
12324:
12325: =item *
12326:
12327: $symb : a resource instance identifier
12328:
12329: =item *
12330:
12331: $namespace : the name of a .db file that contains the data needed or
12332: being set.
12333:
12334: =back
12335:
1.394 bowersj2 12336: =head1 OVERVIEW
1.191 harris41 12337:
1.394 bowersj2 12338: lonnet provides subroutines which interact with the
12339: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12340: about classes, users, and resources.
1.243 albertel 12341:
12342: For many of these objects you can also use this to store data about
12343: them or modify them in various ways.
1.191 harris41 12344:
1.394 bowersj2 12345: =head2 Symbs
1.191 harris41 12346:
1.394 bowersj2 12347: To identify a specific instance of a resource, LON-CAPA uses symbols
12348: or "symbs"X<symb>. These identifiers are built from the URL of the
12349: map, the resource number of the resource in the map, and the URL of
12350: the resource itself. The latter is somewhat redundant, but might help
12351: if maps change.
12352:
12353: An example is
12354:
12355: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12356:
12357: The respective map entry is
12358:
12359: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12360: title="Problem 2">
12361: </resource>
12362:
12363: Symbs are used by the random number generator, as well as to store and
12364: restore data specific to a certain instance of for example a problem.
12365:
12366: =head2 Storing And Retrieving Data
12367:
12368: X<store()>X<cstore()>X<restore()>Three of the most important functions
12369: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12370: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12371: is is the non-critical message twin of cstore. These functions are for
12372: handlers to store a perl hash to a user's permanent data space in an
12373: easy manner, and to retrieve it again on another call. It is expected
12374: that a handler would use this once at the beginning to retrieve data,
12375: and then again once at the end to send only the new data back.
12376:
12377: The data is stored in the user's data directory on the user's
12378: homeserver under the ID of the course.
12379:
12380: The hash that is returned by restore will have all of the previous
12381: value for all of the elements of the hash.
12382:
12383: Example:
12384:
12385: #creating a hash
12386: my %hash;
12387: $hash{'foo'}='bar';
12388:
12389: #storing it
12390: &Apache::lonnet::cstore(\%hash);
12391:
12392: #changing a value
12393: $hash{'foo'}='notbar';
12394:
12395: #adding a new value
12396: $hash{'bar'}='foo';
12397: &Apache::lonnet::cstore(\%hash);
12398:
12399: #retrieving the hash
12400: my %history=&Apache::lonnet::restore();
12401:
12402: #print the hash
12403: foreach my $key (sort(keys(%history))) {
12404: print("\%history{$key} = $history{$key}");
12405: }
12406:
12407: Will print out:
1.191 harris41 12408:
1.394 bowersj2 12409: %history{1:foo} = bar
12410: %history{1:keys} = foo:timestamp
12411: %history{1:timestamp} = 990455579
12412: %history{2:bar} = foo
12413: %history{2:foo} = notbar
12414: %history{2:keys} = foo:bar:timestamp
12415: %history{2:timestamp} = 990455580
12416: %history{bar} = foo
12417: %history{foo} = notbar
12418: %history{timestamp} = 990455580
12419: %history{version} = 2
12420:
12421: Note that the special hash entries C<keys>, C<version> and
12422: C<timestamp> were added to the hash. C<version> will be equal to the
12423: total number of versions of the data that have been stored. The
12424: C<timestamp> attribute will be the UNIX time the hash was
12425: stored. C<keys> is available in every historical section to list which
12426: keys were added or changed at a specific historical revision of a
12427: hash.
12428:
12429: B<Warning>: do not store the hash that restore returns directly. This
12430: will cause a mess since it will restore the historical keys as if the
12431: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12432:
1.394 bowersj2 12433: Calling convention:
1.191 harris41 12434:
1.1172.2.27 raeburn 12435: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12436: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12437:
1.394 bowersj2 12438: For more detailed information, see lonnet specific documentation.
1.191 harris41 12439:
1.394 bowersj2 12440: =head1 RETURN MESSAGES
1.191 harris41 12441:
1.394 bowersj2 12442: =over 4
1.191 harris41 12443:
1.394 bowersj2 12444: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12445:
1.394 bowersj2 12446: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12447: when the connection is brought back up
1.191 harris41 12448:
1.394 bowersj2 12449: =item * B<con_failed>: unable to contact remote host and unable to save message
12450: for later delivery
1.191 harris41 12451:
1.967 bisitz 12452: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12453:
1.394 bowersj2 12454: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12455: that was requested
1.191 harris41 12456:
1.243 albertel 12457: =back
1.191 harris41 12458:
1.243 albertel 12459: =head1 PUBLIC SUBROUTINES
1.191 harris41 12460:
1.243 albertel 12461: =head2 Session Environment Functions
1.191 harris41 12462:
1.243 albertel 12463: =over 4
1.191 harris41 12464:
1.394 bowersj2 12465: =item *
12466: X<appenv()>
1.949 raeburn 12467: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12468: the user envirnoment file, and will be restored for each access this
1.620 albertel 12469: user makes during this session, also modifies the %env for the current
1.949 raeburn 12470: process. Optional rolesarrayref - if defined contains a reference to an array
12471: of roles which are exempt from the restriction on modifying user.role entries
12472: in the user's environment.db and in %env.
1.191 harris41 12473:
12474: =item *
1.394 bowersj2 12475: X<delenv()>
1.987 raeburn 12476: B<delenv($delthis,$regexp)>: removes all items from the session
12477: environment file that begin with $delthis. If the
12478: optional second arg - $regexp - is true, $delthis is treated as a
12479: regular expression, otherwise \Q$delthis\E is used.
12480: The values are also deleted from the current processes %env.
1.191 harris41 12481:
1.795 albertel 12482: =item * get_env_multiple($name)
12483:
12484: gets $name from the %env hash, it seemlessly handles the cases where multiple
12485: values may be defined and end up as an array ref.
12486:
12487: returns an array of values
12488:
1.243 albertel 12489: =back
12490:
12491: =head2 User Information
1.191 harris41 12492:
1.243 albertel 12493: =over 4
1.191 harris41 12494:
12495: =item *
1.394 bowersj2 12496: X<queryauthenticate()>
12497: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12498: authentication scheme
12499:
12500: =item *
1.394 bowersj2 12501: X<authenticate()>
1.1073 raeburn 12502: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12503: authenticate user from domain's lib servers (first use the current
12504: one). C<$upass> should be the users password.
1.1073 raeburn 12505: $checkdefauth is optional (value is 1 if a check should be made to
12506: authenticate user using default authentication method, and allow
12507: account creation if username does not have account in the domain).
12508: $clientcancheckhost is optional (value is 1 if checking whether the
12509: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12510:
12511: =item *
1.394 bowersj2 12512: X<homeserver()>
12513: B<homeserver($uname,$udom)>: find the server which has
12514: the user's directory and files (there must be only one), this caches
12515: the answer, and also caches if there is a borken connection.
1.191 harris41 12516:
12517: =item *
1.394 bowersj2 12518: X<idget()>
12519: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12520: (IDs are a unique resource in a domain, there must be only 1 ID per
12521: username, and only 1 username per ID in a specific domain) (returns
12522: hash: id=>name,id=>name)
1.191 harris41 12523:
12524: =item *
1.394 bowersj2 12525: X<idrget()>
12526: B<idrget($udom,@unames)>: find the IDs behind a list of
12527: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12528:
12529: =item *
1.394 bowersj2 12530: X<idput()>
12531: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12532:
12533: =item *
1.394 bowersj2 12534: X<rolesinit()>
1.1169 droeschl 12535: B<rolesinit($udom,$username)>: get user privileges.
12536: returns user role, first access and timer interval hashes
1.243 albertel 12537:
12538: =item *
1.1171 droeschl 12539: X<privileged()>
12540: B<privileged($username,$domain)>: returns a true if user has a
12541: privileged and active role (i.e. su or dc), false otherwise.
12542:
12543: =item *
1.551 albertel 12544: X<getsection()>
12545: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12546: course $cname, return section name/number or '' for "not in course"
12547: and '-1' for "no section"
12548:
12549: =item *
1.394 bowersj2 12550: X<userenvironment()>
12551: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12552: passed in @what from the requested user's environment, returns a hash
12553:
1.858 raeburn 12554: =item *
12555: X<userlog_query()>
1.859 albertel 12556: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12557: activity.log file. %filters defines filters applied when parsing the
12558: log file. These can be start or end timestamps, or the type of action
12559: - log to look for Login or Logout events, check for Checkin or
12560: Checkout, role for role selection. The response is in the form
12561: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12562: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12563:
1.243 albertel 12564: =back
12565:
12566: =head2 User Roles
12567:
12568: =over 4
12569:
12570: =item *
12571:
1.810 raeburn 12572: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12573: F: full access
12574: U,I,K: authentication modes (cxx only)
12575: '': forbidden
12576: 1: user needs to choose course
12577: 2: browse allowed
1.766 albertel 12578: A: passphrase authentication needed
1.243 albertel 12579:
12580: =item *
12581:
1.1172.2.13 raeburn 12582: constructaccess($url,$setpriv) : check for access to construction space URL
12583:
12584: See if the owner domain and name in the URL match those in the
12585: expected environment. If so, return three element list
12586: ($ownername,$ownerdomain,$ownerhome).
12587:
12588: Otherwise return the null string.
12589:
12590: If second argument 'setpriv' is true, it assigns the privileges,
12591: and returns the same three element list, unless the owner has
12592: blocked "ad hoc" Domain Coordinator access to the Author Space,
12593: in which case the null string is returned.
12594:
12595: =item *
12596:
1.243 albertel 12597: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12598: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12599: and course level
12600:
12601: =item *
12602:
1.988 raeburn 12603: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12604: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12605: $type is Course (default) or Community.
1.988 raeburn 12606: If $forcedefault evaluates to true, text returned will be default
12607: text for $type. Otherwise, if this is a course, the text returned
12608: will be a custom name for the role (if defined in the course's
12609: environment). If no custom name is defined the default is returned.
12610:
1.832 raeburn 12611: =item *
12612:
1.1172.2.23 raeburn 12613: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12614: All arguments are optional. Returns a hash of a roles, either for
12615: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12616: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12617: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12618: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12619: For each key, value is set to colon-separated start and end times for
12620: the role. If no username and domain are specified, will default to
1.934 raeburn 12621: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12622: of role statuses (active, future or previous), roles
12623: (e.g., cc,in, st etc.) and domains of the roles which can be used
12624: to restrict the list of roles reported. If no array ref is
12625: provided for types, will default to return only active roles.
1.834 albertel 12626:
1.1172.2.13 raeburn 12627: =item *
12628:
12629: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12630: user: $uname:$udom has a role in the course: $cdom_$cnum.
12631:
12632: Additional optional arguments are: $type (if role checking is to be restricted
12633: to certain user status types -- previous (expired roles), active (currently
12634: available roles) or future (roles available in the future), and
12635: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12636: have active Domain Coordinator role in course's domain or in additional
12637: domains (specified in 'Domains to check for privileged users' in course
12638: environment -- set via: Course Settings -> Classlists and staff listing).
12639:
12640: =item *
12641:
12642: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12643: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12644: $possdomains and $possroles are optional array refs -- to domains to check and
12645: roles to check. If $possdomains is not specified, a dump will be done of the
12646: users' roles.db to check for a dc or su role in any domain. This can be
12647: time consuming if &privileged is called repeatedly (e.g., when displaying a
12648: classlist), so in such cases, supplying a $possdomains array is preferred, as
12649: this then allows &privileged_by_domain() to be used, which caches the identity
12650: of privileged users, eliminating the need for repeated calls to &dump().
12651:
12652: =item *
12653:
12654: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12655: where the outer hash keys are domains specified in the $possdomains array ref,
12656: next inner hash keys are privileged roles specified in the $roles array ref,
12657: and the innermost hash contains key = value pairs for username:domain = end:start
12658: for active or future "privileged" users with that role in that domain. To avoid
12659: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12660: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12661:
1.243 albertel 12662: =back
12663:
12664: =head2 User Modification
12665:
12666: =over 4
12667:
12668: =item *
12669:
1.957 raeburn 12670: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12671: user for the level given by URL. Optional start and end dates (leave empty
12672: string or zero for "no date")
1.191 harris41 12673:
12674: =item *
12675:
1.243 albertel 12676: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12677: change a users, password, possible return values are: ok,
12678: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12679: refused
1.191 harris41 12680:
12681: =item *
12682:
1.243 albertel 12683: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12684:
12685: =item *
12686:
1.1058 raeburn 12687: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12688: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12689:
12690: will update user information (firstname,middlename,lastname,generation,
12691: permanentemail), and if forceid is true, student/employee ID also.
12692: A user's institutional affiliation(s) can also be updated.
12693: User information fields will not be overwritten with empty entries
12694: unless the field is included in the $candelete array reference.
12695: This array is included when a single user is modified via "Manage Users",
12696: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12697:
12698: =item *
12699:
1.286 matthew 12700: modifystudent
12701:
1.957 raeburn 12702: modify a student's enrollment and identification information.
1.1172.2.31! raeburn 12703: The course id is resolved based on the current user's environment.
! 12704: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12705: associated with a course.
12706:
1.297 matthew 12707: This call is essentially a wrapper for lonnet::modifyuser and
12708: lonnet::modify_student_enrollment
1.286 matthew 12709:
12710: Inputs:
12711:
12712: =over 4
12713:
1.957 raeburn 12714: =item B<$udom> Student's loncapa domain
1.286 matthew 12715:
1.957 raeburn 12716: =item B<$uname> Student's loncapa login name
1.286 matthew 12717:
1.964 bisitz 12718: =item B<$uid> Student/Employee ID
1.286 matthew 12719:
1.957 raeburn 12720: =item B<$umode> Student's authentication mode
1.286 matthew 12721:
1.957 raeburn 12722: =item B<$upass> Student's password
1.286 matthew 12723:
1.957 raeburn 12724: =item B<$first> Student's first name
1.286 matthew 12725:
1.957 raeburn 12726: =item B<$middle> Student's middle name
1.286 matthew 12727:
1.957 raeburn 12728: =item B<$last> Student's last name
1.286 matthew 12729:
1.957 raeburn 12730: =item B<$gene> Student's generation
1.286 matthew 12731:
1.957 raeburn 12732: =item B<$usec> Student's section in course
1.286 matthew 12733:
12734: =item B<$end> Unix time of the roles expiration
12735:
12736: =item B<$start> Unix time of the roles start date
12737:
12738: =item B<$forceid> If defined, allow $uid to be changed
12739:
12740: =item B<$desiredhome> server to use as home server for student
12741:
1.957 raeburn 12742: =item B<$email> Student's permanent e-mail address
12743:
12744: =item B<$type> Type of enrollment (auto or manual)
12745:
1.963 raeburn 12746: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12747:
12748: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12749:
1.963 raeburn 12750: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12751:
1.963 raeburn 12752: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12753:
1.1172.2.19 raeburn 12754: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12755:
12756: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957 raeburn 12757:
1.286 matthew 12758: =back
1.297 matthew 12759:
12760: =item *
12761:
12762: modify_student_enrollment
12763:
1.1172.2.31! raeburn 12764: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12765: 'role.request.course' must be defined for this function to proceed.
12766:
12767: Inputs:
12768:
12769: =over 4
12770:
1.1172.2.31! raeburn 12771: =item $udom, student's domain
1.297 matthew 12772:
1.1172.2.31! raeburn 12773: =item $uname, student's name
1.297 matthew 12774:
1.1172.2.31! raeburn 12775: =item $uid, student's user id
1.297 matthew 12776:
1.1172.2.31! raeburn 12777: =item $first, student's first name
1.297 matthew 12778:
12779: =item $middle
12780:
12781: =item $last
12782:
12783: =item $gene
12784:
12785: =item $usec
12786:
12787: =item $end
12788:
12789: =item $start
12790:
1.957 raeburn 12791: =item $type
12792:
12793: =item $locktype
12794:
12795: =item $cid
12796:
12797: =item $selfenroll
12798:
12799: =item $context
12800:
1.1172.2.19 raeburn 12801: =item $credits, number of credits student will earn from this class
12802:
1.297 matthew 12803: =back
12804:
1.191 harris41 12805:
12806: =item *
12807:
1.243 albertel 12808: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12809: custom role; give a custom role to a user for the level given by URL. Specify
12810: name and domain of role author, and role name
1.191 harris41 12811:
12812: =item *
12813:
1.243 albertel 12814: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12815:
12816: =item *
12817:
1.243 albertel 12818: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12819:
12820: =back
12821:
12822: =head2 Course Infomation
12823:
12824: =over 4
1.191 harris41 12825:
12826: =item *
12827:
1.1118 foxr 12828: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12829: specified course id, including all environment settings for the
12830: course, the description of the course will be in the hash under the
12831: key 'description'
1.191 harris41 12832:
1.1118 foxr 12833: $options is an optional parameter that if supplied is a hash reference that controls
12834: what how this function works. It has the following key/values:
12835:
12836: =over 4
12837:
12838: =item freshen_cache
12839:
12840: If defined, and the environment cache for the course is valid, it is
12841: returned in the returned hash.
12842:
12843: =item one_time
12844:
12845: If defined, the last cache time is set to _now_
12846:
12847: =item user
12848:
12849: If defined, the supplied username is used instead of the current user.
12850:
12851:
12852: =back
12853:
1.191 harris41 12854: =item *
12855:
1.624 albertel 12856: resdata($name,$domain,$type,@which) : request for current parameter
12857: setting for a specific $type, where $type is either 'course' or 'user',
12858: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31! raeburn 12859: answers for 10 minutes.
1.243 albertel 12860:
1.877 foxr 12861: =item *
12862:
12863: get_courseresdata($courseid, $domain) : dump the entire course resource
12864: data base, returning a hash that is keyed by the resource name and has
12865: values that are the resource value. I believe that the timestamps and
12866: versions are also returned.
12867:
1.1172.2.31! raeburn 12868: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
! 12869: supplemental content area. This routine caches the number of files for
! 12870: 10 minutes.
! 12871:
1.243 albertel 12872: =back
12873:
12874: =head2 Course Modification
12875:
12876: =over 4
1.191 harris41 12877:
12878: =item *
12879:
1.243 albertel 12880: writecoursepref($courseid,%prefs) : write preferences (environment
12881: database) for a course
1.191 harris41 12882:
12883: =item *
12884:
1.1011 raeburn 12885: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12886:
12887: =item *
12888:
1.1038 raeburn 12889: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12890:
1.1167 droeschl 12891: =item *
12892:
12893: is_course($courseid), is_course($cdom, $cnum)
12894:
12895: Accepts either a combined $courseid (in the form of domain_courseid) or the
12896: two component version $cdom, $cnum. It checks if the specified course exists.
12897:
12898: Returns:
12899: undef if the course doesn't exist, otherwise
12900: in scalar context the combined courseid.
12901: in list context the two components of the course identifier, domain and
12902: courseid.
12903:
1.243 albertel 12904: =back
12905:
12906: =head2 Resource Subroutines
12907:
12908: =over 4
1.191 harris41 12909:
12910: =item *
12911:
1.243 albertel 12912: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12913:
12914: =item *
12915:
1.243 albertel 12916: repcopy($filename) : subscribes to the requested file, and attempts to
12917: replicate from the owning library server, Might return
1.607 raeburn 12918: 'unavailable', 'not_found', 'forbidden', 'ok', or
12919: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12920: resource. Expects the local filesystem pathname
12921: (/home/httpd/html/res/....)
12922:
12923: =back
12924:
12925: =head2 Resource Information
12926:
12927: =over 4
1.191 harris41 12928:
12929: =item *
12930:
1.1172.2.28 raeburn 12931: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
12932: and returns the value of a variety of different possible values,
12933: $varname should be a request string, and the other parameters can be
12934: used to specify who and what one is asking about. Ordinarily, $cid
12935: does not need to be specified, as it is retrived from
12936: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12937: within lonuserstate::loadmap() when initializing a course, before
12938: $env{'request.course.id'} has been set, so it needs to be provided
12939: in that one case.
1.243 albertel 12940:
12941: Possible values for $varname are environment.lastname (or other item
12942: from the envirnment hash), user.name (or someother aspect about the
12943: user), resource.0.maxtries (or some other part and parameter of a
12944: resource)
1.204 albertel 12945:
12946: =item *
12947:
1.243 albertel 12948: directcondval($number) : get current value of a condition; reads from a state
12949: string
1.204 albertel 12950:
12951: =item *
12952:
1.243 albertel 12953: condval($condidx) : value of condition index based on state
1.204 albertel 12954:
12955: =item *
12956:
1.243 albertel 12957: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12958: resource's metadata, $what should be either a specific key, or either
12959: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12960: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12961:
12962: this function automatically caches all requests
1.191 harris41 12963:
12964: =item *
12965:
1.243 albertel 12966: metadata_query($query,$custom,$customshow) : make a metadata query against the
12967: network of library servers; returns file handle of where SQL and regex results
12968: will be stored for query
1.191 harris41 12969:
12970: =item *
12971:
1.243 albertel 12972: symbread($filename) : return symbolic list entry (filename argument optional);
12973: returns the data handle
1.191 harris41 12974:
12975: =item *
12976:
1.1172.2.17 raeburn 12977: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 12978: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 12979: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 12980: on failure, user must be in a course, as it assumes the existence of
12981: the course initial hash, and uses $env('request.course.id'}. The third
12982: arg is an optional reference to a scalar. If this arg is passed in the
12983: call to symbverify, it will be set to 1 if the symb has been set to be
12984: encrypted; otherwise it will be null.
1.243 albertel 12985:
1.191 harris41 12986: =item *
12987:
1.243 albertel 12988: symbclean($symb) : removes versions numbers from a symb, returns the
12989: cleaned symb
1.191 harris41 12990:
12991: =item *
12992:
1.243 albertel 12993: is_on_map($uri) : checks if the $uri is somewhere on the current
12994: course map, user must be in a course for it to work.
1.191 harris41 12995:
12996: =item *
12997:
1.243 albertel 12998: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 12999:
13000: =item *
13001:
1.243 albertel 13002: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13003: a random seed, all arguments are optional, if they aren't sent it uses the
13004: environment to derive them. Note: if symb isn't sent and it can't get one
13005: from &symbread it will use the current time as its return value
1.191 harris41 13006:
13007: =item *
13008:
1.243 albertel 13009: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13010: unfakeable, receipt
1.191 harris41 13011:
13012: =item *
13013:
1.620 albertel 13014: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13015:
13016: =item *
13017:
1.243 albertel 13018: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13019:
13020: =item *
13021:
1.243 albertel 13022: 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 13023:
13024: =item *
13025:
1.243 albertel 13026: 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 13027:
13028: =item *
13029:
1.243 albertel 13030: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13031:
13032: =item *
13033:
1.243 albertel 13034: devalidate($symb) : devalidate temporary spreadsheet calculations,
13035: forcing spreadsheet to reevaluate the resource scores next time.
13036:
1.1172.2.13 raeburn 13037: =item *
13038:
13039: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13040: when viewing in course context.
13041:
13042: input: six args -- filename (decluttered), course number, course domain,
13043: url, symb (if registered) and group (if this is a
13044: group item -- e.g., bulletin board, group page etc.).
13045:
13046: output: array of five scalars --
13047: $cfile -- url for file editing if editable on current server
13048: $home -- homeserver of resource (i.e., for author if published,
13049: or course if uploaded.).
13050: $switchserver -- 1 if server switch will be needed.
13051: $forceedit -- 1 if icon/link should be to go to edit mode
13052: $forceview -- 1 if icon/link should be to go to view mode
13053:
13054: =item *
13055:
13056: is_course_upload($file,$cnum,$cdom)
13057:
13058: Used in course context to determine if current file was uploaded to
13059: the course (i.e., would be found in /userfiles/docs on the course's
13060: homeserver.
13061:
13062: input: 3 args -- filename (decluttered), course number and course domain.
13063: output: boolean -- 1 if file was uploaded.
13064:
1.243 albertel 13065: =back
13066:
13067: =head2 Storing/Retreiving Data
13068:
13069: =over 4
1.191 harris41 13070:
13071: =item *
13072:
1.243 albertel 13073: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13074: for this url; hashref needs to be given and should be a \%hashname; the
13075: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13076: be derived from the env
1.191 harris41 13077:
13078: =item *
13079:
1.243 albertel 13080: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13081: uses critical subroutine
1.191 harris41 13082:
13083: =item *
13084:
1.243 albertel 13085: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13086: all args are optional
1.191 harris41 13087:
13088: =item *
13089:
1.717 albertel 13090: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13091: dumps the complete (or key matching regexp) namespace into a hash
13092: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13093: normally &store()ed into
13094:
13095: $range should be either an integer '100' (give me the first 100
13096: matching records)
13097: or be two integers sperated by a - with no spaces
13098: '30-50' (give me the 30th through the 50th matching
13099: records)
13100:
13101:
13102: =item *
13103:
13104: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13105: replaces a &store() version of data with a replacement set of data
13106: for a particular resource in a namespace passed in the $storehash hash
13107: reference
13108:
13109: =item *
13110:
1.243 albertel 13111: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13112: works very similar to store/cstore, but all data is stored in a
13113: temporary location and can be reset using tmpreset, $storehash should
13114: be a hash reference, returns nothing on success
1.191 harris41 13115:
13116: =item *
13117:
1.243 albertel 13118: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13119: similar to restore, but all data is stored in a temporary location and
13120: can be reset using tmpreset. Returns a hash of values on success,
13121: error string otherwise.
1.191 harris41 13122:
13123: =item *
13124:
1.243 albertel 13125: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13126: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13127:
13128: =item *
13129:
1.243 albertel 13130: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13131: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13132:
13133: =item *
13134:
1.243 albertel 13135: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13136: namesp ($udom and $uname are optional)
1.191 harris41 13137:
13138: =item *
13139:
1.702 albertel 13140: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13141: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13142: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13143:
1.702 albertel 13144: $range should be either an integer '100' (give me the first 100
13145: matching records)
13146: or be two integers sperated by a - with no spaces
13147: '30-50' (give me the 30th through the 50th matching
13148: records)
1.449 matthew 13149: =item *
13150:
13151: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13152: $store can be a scalar, an array reference, or if the amount to be
13153: incremented is > 1, a hash reference.
13154:
13155: ($udom and $uname are optional)
1.191 harris41 13156:
13157: =item *
13158:
1.243 albertel 13159: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13160: ($udom and $uname are optional)
1.191 harris41 13161:
13162: =item *
13163:
1.243 albertel 13164: cput($namespace,$storehash,$udom,$uname) : critical put
13165: ($udom and $uname are optional)
1.191 harris41 13166:
13167: =item *
13168:
1.748 albertel 13169: newput($namespace,$storehash,$udom,$uname) :
13170:
13171: Attempts to store the items in the $storehash, but only if they don't
13172: currently exist, if this succeeds you can be certain that you have
13173: successfully created a new key value pair in the $namespace db.
13174:
13175:
13176: Args:
13177: $namespace: name of database to store values to
13178: $storehash: hashref to store to the db
13179: $udom: (optional) domain of user containing the db
13180: $uname: (optional) name of user caontaining the db
13181:
13182: Returns:
13183: 'ok' -> succeeded in storing all keys of $storehash
13184: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13185: least <key> already existed in the db (other
13186: requested keys may also already exist)
1.967 bisitz 13187: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13188: 'con_lost' -> unable to contact request server
13189: 'refused' -> action was not allowed by remote machine
13190:
13191:
13192: =item *
13193:
1.243 albertel 13194: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13195: reference filled in from namesp (encrypts the return communication)
13196: ($udom and $uname are optional)
1.191 harris41 13197:
13198: =item *
13199:
1.243 albertel 13200: log($udom,$name,$home,$message) : write to permanent log for user; use
13201: critical subroutine
13202:
1.806 raeburn 13203: =item *
13204:
1.860 raeburn 13205: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13206: array reference filled in from namespace found in domain level on either
13207: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13208:
13209: =item *
13210:
1.860 raeburn 13211: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13212: domain level either on specified domain server ($uhome) or primary domain
13213: server ($udom and $uhome are optional)
1.806 raeburn 13214:
1.943 raeburn 13215: =item *
13216:
13217: get_domain_defaults($target_domain) : returns hash with defaults for
13218: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13219: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13220: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13221: Values are retrieved from cache (if current), or from domain's configuration.db
13222: (if available), or lastly from values in lonTabs/dns_domain,tab,
13223: or lonTabs/domain.tab.
13224:
13225: %domdefaults = &get_auth_defaults($target_domain);
13226:
1.243 albertel 13227: =back
13228:
13229: =head2 Network Status Functions
13230:
13231: =over 4
1.191 harris41 13232:
13233: =item *
13234:
1.1137 raeburn 13235: dirlist() : return directory list based on URI (first arg).
13236:
13237: Inputs: 1 required, 5 optional.
13238:
13239: =over
13240:
13241: =item
13242: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13243:
13244: =item
13245: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13246:
13247: =item
13248: $username - username of user/course to be listed. Extracted from $uri if absent.
13249:
13250: =item
13251: $getpropath - boolean: 1 if prepend path using &propath().
13252:
13253: =item
13254: $getuserdir - boolean: 1 if prepend path for "userfiles".
13255:
13256: =item
13257: $alternateRoot - path to prepend in place of path from $uri.
13258:
13259: =back
13260:
13261: Returns: Array of up to two items.
13262:
13263: =over
13264:
13265: a reference to an array of files/subdirectories
13266:
13267: =over
13268:
13269: Each element in the array of files/subdirectories is a & separated list of
13270: item name and the result of running stat on the item. If dirlist was requested
13271: for a file instead of a directory, the item name will be ''. For a directory
13272: listing, if the item is a metadata file, the element will end &N&M
13273: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13274: default copyright set (1).
13275:
13276: =back
13277:
13278: a scalar containing error condition (if encountered).
13279:
13280: =over
13281:
13282: =item
13283: no_host (no homeserver identified for $username:$domain).
13284:
13285: =item
13286: no_such_host (server contacted for listing not identified as valid host).
13287:
13288: =item
13289: con_lost (connection to remote server failed).
13290:
13291: =item
13292: refused (invalid $username:$domain received on lond side).
13293:
13294: =item
13295: no_such_dir (directory at specified path on lond side does not exist).
13296:
13297: =item
13298: empty (directory at specified path on lond side is empty).
13299:
13300: =over
13301:
13302: This is currently not encountered because the &ls3, &ls2,
13303: &ls (_handler) routines on the lond side do not filter out
13304: . and .. from a directory listing.
13305:
13306: =back
13307:
13308: =back
13309:
13310: =back
1.191 harris41 13311:
13312: =item *
13313:
1.243 albertel 13314: spareserver() : find server with least workload from spare.tab
13315:
1.986 foxr 13316:
13317: =item *
13318:
13319: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13320: if there is no corresponding loncapa host.
13321:
1.243 albertel 13322: =back
13323:
1.986 foxr 13324:
1.243 albertel 13325: =head2 Apache Request
13326:
13327: =over 4
1.191 harris41 13328:
13329: =item *
13330:
1.243 albertel 13331: ssi($url,%hash) : server side include, does a complete request cycle on url to
13332: localhost, posts hash
13333:
13334: =back
13335:
13336: =head2 Data to String to Data
13337:
13338: =over 4
1.191 harris41 13339:
13340: =item *
13341:
1.243 albertel 13342: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13343: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13344:
13345: =item *
13346:
1.243 albertel 13347: hashref2str($hashref) : convert a hashref into a string complete with
13348: escaping and '=' and '&' separators, supports elements that are
13349: arrayrefs and hashrefs
1.191 harris41 13350:
13351: =item *
13352:
1.243 albertel 13353: arrayref2str($arrayref) : convert an arrayref into a string complete
13354: with escaping and '&' separators, supports elements that are arrayrefs
13355: and hashrefs
1.191 harris41 13356:
13357: =item *
13358:
1.243 albertel 13359: str2hash($string) : convert string to hash using unescaping and
13360: splitting on '=' and '&', supports elements that are arrayrefs and
13361: hashrefs
1.191 harris41 13362:
13363: =item *
13364:
1.243 albertel 13365: str2array($string) : convert string to hash using unescaping and
13366: splitting on '&', supports elements that are arrayrefs and hashrefs
13367:
13368: =back
13369:
13370: =head2 Logging Routines
13371:
13372:
13373: These routines allow one to make log messages in the lonnet.log and
13374: lonnet.perm logfiles.
1.191 harris41 13375:
1.1119 foxr 13376: =over 4
13377:
1.191 harris41 13378: =item *
13379:
1.243 albertel 13380: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13381:
13382: =item *
13383:
1.243 albertel 13384: logthis() : append message to the normal lonnet.log file, it gets
13385: preiodically rolled over and deleted.
1.191 harris41 13386:
13387: =item *
13388:
1.243 albertel 13389: logperm() : append a permanent message to lonnet.perm.log, this log
13390: file never gets deleted by any automated portion of the system, only
13391: messages of critical importance should go in here.
13392:
1.1119 foxr 13393:
1.243 albertel 13394: =back
13395:
13396: =head2 General File Helper Routines
13397:
13398: =over 4
1.191 harris41 13399:
13400: =item *
13401:
1.481 raeburn 13402: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13403: (a) files in /uploaded
13404: (i) If a local copy of the file exists -
13405: compares modification date of local copy with last-modified date for
13406: definitive version stored on home server for course. If local copy is
13407: stale, requests a new version from the home server and stores it.
13408: If the original has been removed from the home server, then local copy
13409: is unlinked.
13410: (ii) If local copy does not exist -
13411: requests the file from the home server and stores it.
13412:
13413: If $caller is 'uploadrep':
13414: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13415: for request for files originally uploaded via DOCS.
13416: - returns 'ok' if fresh local copy now available, -1 otherwise.
13417:
13418: Otherwise:
13419: This indicates a call from the content generation phase of the request.
13420: - returns the entire contents of the file or -1.
13421:
13422: (b) files in /res
13423: - returns the entire contents of a file or -1;
13424: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13425:
1.712 albertel 13426:
13427: =item *
13428:
13429: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13430: reference
13431:
13432: returns either a stat() list of data about the file or an empty list
13433: if the file doesn't exist or couldn't find out about it (connection
13434: problems or user unknown)
13435:
1.191 harris41 13436: =item *
13437:
1.243 albertel 13438: filelocation($dir,$file) : returns file system location of a file
13439: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13440: directory that relative $file lookups are to looked in ($dir of /a/dir
13441: and a file of ../bob will become /a/bob)
1.191 harris41 13442:
13443: =item *
13444:
13445: hreflocation($dir,$file) : returns file system location or a URL; same as
13446: filelocation except for hrefs
13447:
13448: =item *
13449:
13450: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13451:
1.243 albertel 13452: =back
13453:
1.608 albertel 13454: =head2 Usererfile file routines (/uploaded*)
13455:
13456: =over 4
13457:
13458: =item *
13459:
13460: userfileupload(): main rotine for putting a file in a user or course's
13461: filespace, arguments are,
13462:
1.620 albertel 13463: formname - required - this is the name of the element in $env where the
1.608 albertel 13464: filename, and the contents of the file to create/modifed exist
1.620 albertel 13465: the filename is in $env{'form.'.$formname.'.filename'} and the
13466: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13467: context - if coursedoc, store the file in the course of the active role
13468: of the current user;
13469: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13470: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13471: subdir - required - subdirectory to put the file in under ../userfiles/
13472: if undefined, it will be placed in "unknown"
13473:
13474: (This routine calls clean_filename() to remove any dangerous
13475: characters from the filename, and then calls finuserfileupload() to
13476: complete the transaction)
13477:
13478: returns either the url of the uploaded file (/uploaded/....) if successful
13479: and /adm/notfound.html if unsuccessful
13480:
13481: =item *
13482:
13483: clean_filename(): routine for cleaing a filename up for storage in
13484: userfile space, argument is:
13485:
13486: filename - proposed filename
13487:
13488: returns: the new clean filename
13489:
13490: =item *
13491:
1.1090 raeburn 13492: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13493: userspace, probably shouldn't be called directly
13494:
13495: docuname: username or courseid of destination for the file
13496: docudom: domain of user/course of destination for the file
13497: formname: same as for userfileupload()
1.1090 raeburn 13498: fname: filename (including subdirectories) for the file
13499: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13500: allfiles: reference to hash used to store objects found by parser
13501: codebase: reference to hash used for codebases of java objects found by parser
13502: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13503: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13504: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13505: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13506: context: if 'overwrite', will move the uploaded file from its temporary location to
13507: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13508: mimetype: reference to scalar to accommodate mime type determined
13509: from File::MMagic if $parser = parse.
1.608 albertel 13510:
13511: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13512: and /adm/notfound.html if unsuccessful (or an error message if context
13513: was 'overwrite').
13514:
1.608 albertel 13515:
13516: =item *
13517:
13518: renameuserfile(): renames an existing userfile to a new name
13519:
13520: Args:
13521: docuname: username or courseid of destination for the file
13522: docudom: domain of user/course of destination for the file
13523: old: current file name (including any subdirs under userfiles)
13524: new: desired file name (including any subdirs under userfiles)
13525:
13526: =item *
13527:
13528: mkdiruserfile(): creates a directory is a userfiles dir
13529:
13530: Args:
13531: docuname: username or courseid of destination for the file
13532: docudom: domain of user/course of destination for the file
13533: dir: dir to create (including any subdirs under userfiles)
13534:
13535: =item *
13536:
13537: removeuserfile(): removes a file that exists in userfiles
13538:
13539: Args:
13540: docuname: username or courseid of destination for the file
13541: docudom: domain of user/course of destination for the file
13542: fname: filname to delete (including any subdirs under userfiles)
13543:
13544: =item *
13545:
13546: removeuploadedurl(): convience function for removeuserfile()
13547:
13548: Args:
13549: url: a full /uploaded/... url to delete
13550:
1.747 albertel 13551: =item *
13552:
13553: get_portfile_permissions():
13554: Args:
13555: domain: domain of user or course contain the portfolio files
13556: user: name of user or num of course contain the portfolio files
13557: Returns:
13558: hashref of a dump of the proper file_permissions.db
13559:
13560:
13561: =item *
13562:
13563: get_access_controls():
13564:
13565: Args:
13566: current_permissions: the hash ref returned from get_portfile_permissions()
13567: group: (optional) the group you want the files associated with
13568: file: (optional) the file you want access info on
13569:
13570: Returns:
1.749 raeburn 13571: a hash (keys are file names) of hashes containing
13572: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13573: values are XML containing access control settings (see below)
1.747 albertel 13574:
13575: Internal notes:
13576:
1.749 raeburn 13577: access controls are stored in file_permissions.db as key=value pairs.
13578: key -> path to file/file_name\0uniqueID:scope_end_start
13579: where scope -> public,guest,course,group,domains or users.
13580: end -> UNIX time for end of access (0 -> no end date)
13581: start -> UNIX time for start of access
13582:
13583: value -> XML description of access control
13584: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13585: <start></start>
13586: <end></end>
13587:
13588: <password></password> for scope type = guest
13589:
13590: <domain></domain> for scope type = course or group
13591: <number></number>
13592: <roles id="">
13593: <role></role>
13594: <access></access>
13595: <section></section>
13596: <group></group>
13597: </roles>
13598:
13599: <dom></dom> for scope type = domains
13600:
13601: <users> for scope type = users
13602: <user>
13603: <uname></uname>
13604: <udom></udom>
13605: </user>
13606: </users>
13607: </scope>
13608:
13609: Access data is also aggregated for each file in an additional key=value pair:
13610: key -> path to file/file_name\0accesscontrol
13611: value -> reference to hash
13612: hash contains key = value pairs
13613: where key = uniqueID:scope_end_start
13614: value = UNIX time record was last updated
13615:
13616: Used to improve speed of look-ups of access controls for each file.
13617:
13618: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13619:
1.1172.2.13 raeburn 13620: =item *
13621:
1.749 raeburn 13622: modify_access_controls():
13623:
13624: Modifies access controls for a portfolio file
13625: Args
13626: 1. file name
13627: 2. reference to hash of required changes,
13628: 3. domain
13629: 4. username
13630: where domain,username are the domain of the portfolio owner
13631: (either a user or a course)
13632:
13633: Returns:
13634: 1. result of additions or updates ('ok' or 'error', with error message).
13635: 2. result of deletions ('ok' or 'error', with error message).
13636: 3. reference to hash of any new or updated access controls.
13637: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13638: key = integer (inbound ID)
1.1172.2.13 raeburn 13639: value = uniqueID
13640:
13641: =item *
13642:
13643: get_timebased_id():
13644:
13645: Attempts to get a unique timestamp-based suffix for use with items added to a
13646: course via the Course Editor (e.g., folders, composite pages,
13647: group bulletin boards).
13648:
13649: Args: (first three required; six others optional)
13650:
13651: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13652: docssequence, or name of group
13653:
13654: 2. keyid (alphanumeric): name of temporary locking key in hash,
13655: e.g., num, boardids
13656:
13657: 3. namespace: name of gdbm file used to store suffixes already assigned;
13658: file will be named nohist_namespace.db
13659:
13660: 4. cdom: domain of course; default is current course domain from %env
13661:
13662: 5. cnum: course number; default is current course number from %env
13663:
13664: 6. idtype: set to concat if an additional digit is to be appended to the
13665: unix timestamp to form the suffix, if the plain timestamp is already
13666: in use. Default is to not do this, but simply increment the unix
13667: timestamp by 1 until a unique key is obtained.
13668:
13669: 7. who: holder of locking key; defaults to user:domain for user.
13670:
13671: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13672: retrying); default is 3.
13673:
13674: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13675:
13676: Returns:
13677:
13678: 1. suffix obtained (numeric)
13679:
13680: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13681:
13682: 3. error: contains (localized) error message if an error occurred.
13683:
1.747 albertel 13684:
1.608 albertel 13685: =back
13686:
1.243 albertel 13687: =head2 HTTP Helper Routines
13688:
13689: =over 4
13690:
1.191 harris41 13691: =item *
13692:
13693: escape() : unpack non-word characters into CGI-compatible hex codes
13694:
13695: =item *
13696:
13697: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13698:
1.243 albertel 13699: =back
13700:
13701: =head1 PRIVATE SUBROUTINES
13702:
13703: =head2 Underlying communication routines (Shouldn't call)
13704:
13705: =over 4
13706:
13707: =item *
13708:
13709: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13710:
13711: =item *
13712:
13713: reply() : uses subreply to send a message to remote machine, logs all failures
13714:
13715: =item *
13716:
13717: critical() : passes a critical message to another server; if cannot
13718: get through then place message in connection buffer directory and
13719: returns con_delayed, if incapable of saving message, returns
13720: con_failed
13721:
13722: =item *
13723:
13724: reconlonc() : tries to reconnect lonc client processes.
13725:
13726: =back
13727:
13728: =head2 Resource Access Logging
13729:
13730: =over 4
13731:
13732: =item *
13733:
13734: flushcourselogs() : flush (save) buffer logs and access logs
13735:
13736: =item *
13737:
13738: courselog($what) : save message for course in hash
13739:
13740: =item *
13741:
13742: courseacclog($what) : save message for course using &courselog(). Perform
13743: special processing for specific resource types (problems, exams, quizzes, etc).
13744:
1.191 harris41 13745: =item *
13746:
13747: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13748: as a PerlChildExitHandler
1.243 albertel 13749:
13750: =back
13751:
13752: =head2 Other
13753:
13754: =over 4
13755:
13756: =item *
13757:
13758: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13759:
13760: =back
13761:
13762: =cut
1.877 foxr 13763:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>