Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.29
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.29! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.28 2013/06/27 18:34:21 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.1023 raeburn 1579: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1580: sub dump_dom {
1.1165 droeschl 1581: my ($namespace, $udom, $regexp) = @_;
1582:
1583: $udom ||= $env{'user.domain'};
1584:
1585: return () unless $udom;
1586:
1587: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1588: }
1589:
1.1023 raeburn 1590: # ------------------------------------------ get items from domain db files
1.806 raeburn 1591:
1592: sub get_dom {
1.860 raeburn 1593: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1594: my $items='';
1595: foreach my $item (@$storearr) {
1596: $items.=&escape($item).'&';
1597: }
1598: $items=~s/\&$//;
1.860 raeburn 1599: if (!$udom) {
1600: $udom=$env{'user.domain'};
1601: if (defined(&domain($udom,'primary'))) {
1602: $uhome=&domain($udom,'primary');
1603: } else {
1.874 albertel 1604: undef($uhome);
1.860 raeburn 1605: }
1606: } else {
1607: if (!$uhome) {
1608: if (defined(&domain($udom,'primary'))) {
1609: $uhome=&domain($udom,'primary');
1610: }
1611: }
1612: }
1613: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1614: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1615: my %returnhash;
1.875 albertel 1616: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1617: return %returnhash;
1618: }
1.806 raeburn 1619: my @pairs=split(/\&/,$rep);
1620: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1621: return @pairs;
1622: }
1623: my $i=0;
1624: foreach my $item (@$storearr) {
1625: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1626: $i++;
1627: }
1628: return %returnhash;
1629: } else {
1.880 banghart 1630: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1631: }
1632: }
1633:
1634: # -------------------------------------------- put items in domain db files
1635:
1636: sub put_dom {
1.860 raeburn 1637: my ($namespace,$storehash,$udom,$uhome)=@_;
1638: if (!$udom) {
1639: $udom=$env{'user.domain'};
1640: if (defined(&domain($udom,'primary'))) {
1641: $uhome=&domain($udom,'primary');
1642: } else {
1.874 albertel 1643: undef($uhome);
1.860 raeburn 1644: }
1645: } else {
1646: if (!$uhome) {
1647: if (defined(&domain($udom,'primary'))) {
1648: $uhome=&domain($udom,'primary');
1649: }
1650: }
1651: }
1652: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1653: my $items='';
1654: foreach my $item (keys(%$storehash)) {
1655: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1656: }
1657: $items=~s/\&$//;
1658: return &reply("putdom:$udom:$namespace:$items",$uhome);
1659: } else {
1.860 raeburn 1660: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1661: }
1662: }
1663:
1.1023 raeburn 1664: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1665: sub newput_dom {
1.1023 raeburn 1666: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1667: my $result;
1668: if (!$udom) {
1669: $udom=$env{'user.domain'};
1670: }
1.1023 raeburn 1671: if ($udom) {
1672: my $uname = &get_domainconfiguser($udom);
1673: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1674: }
1675: return $result;
1676: }
1677:
1.1023 raeburn 1678: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1679: sub del_dom {
1.1023 raeburn 1680: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1681: if (ref($storearr) eq 'ARRAY') {
1682: if (!$udom) {
1683: $udom=$env{'user.domain'};
1684: }
1.1023 raeburn 1685: if ($udom) {
1686: my $uname = &get_domainconfiguser($udom);
1687: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1688: }
1689: }
1690: }
1691:
1.1023 raeburn 1692: # ----------------------------------construct domainconfig user for a domain
1693: sub get_domainconfiguser {
1694: my ($udom) = @_;
1695: return $udom.'-domainconfig';
1696: }
1697:
1.837 raeburn 1698: sub retrieve_inst_usertypes {
1699: my ($udom) = @_;
1700: my (%returnhash,@order);
1.989 raeburn 1701: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1702: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1703: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1704: %returnhash = %{$domdefs{'inststatustypes'}};
1705: @order = @{$domdefs{'inststatusorder'}};
1706: } else {
1707: if (defined(&domain($udom,'primary'))) {
1708: my $uhome=&domain($udom,'primary');
1709: my $rep=&reply("inst_usertypes:$udom",$uhome);
1710: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1711: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1712: return (\%returnhash,\@order);
1713: }
1714: my ($hashitems,$orderitems) = split(/:/,$rep);
1715: my @pairs=split(/\&/,$hashitems);
1716: foreach my $item (@pairs) {
1717: my ($key,$value)=split(/=/,$item,2);
1718: $key = &unescape($key);
1719: next if ($key =~ /^error: 2 /);
1720: $returnhash{$key}=&thaw_unescape($value);
1721: }
1722: my @esc_order = split(/\&/,$orderitems);
1723: foreach my $item (@esc_order) {
1724: push(@order,&unescape($item));
1725: }
1726: } else {
1727: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1728: }
1729: }
1730: return (\%returnhash,\@order);
1731: }
1732:
1.868 raeburn 1733: sub is_domainimage {
1734: my ($url) = @_;
1735: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1736: if (&domain($1) ne '') {
1737: return '1';
1738: }
1739: }
1740: return;
1741: }
1742:
1.899 raeburn 1743: sub inst_directory_query {
1744: my ($srch) = @_;
1745: my $udom = $srch->{'srchdomain'};
1746: my %results;
1747: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1748: my $outcome;
1.899 raeburn 1749: if ($homeserver ne '') {
1.904 albertel 1750: my $queryid=&reply("querysend:instdirsearch:".
1751: &escape($srch->{'srchby'}).':'.
1752: &escape($srch->{'srchterm'}).':'.
1753: &escape($srch->{'srchtype'}),$homeserver);
1754: my $host=&hostname($homeserver);
1755: if ($queryid !~/^\Q$host\E\_/) {
1756: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1757: return;
1758: }
1759: my $response = &get_query_reply($queryid);
1760: my $maxtries = 5;
1761: my $tries = 1;
1762: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1763: $response = &get_query_reply($queryid);
1764: $tries ++;
1765: }
1766:
1767: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1768: if ($response eq 'unavailable') {
1769: $outcome = $response;
1770: } else {
1771: $outcome = 'ok';
1772: my @matches = split(/\n/,$response);
1773: foreach my $match (@matches) {
1774: my ($key,$value) = split(/=/,$match);
1775: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1776: }
1.899 raeburn 1777: }
1778: }
1779: }
1.909 raeburn 1780: return ($outcome,%results);
1.899 raeburn 1781: }
1782:
1783: sub usersearch {
1784: my ($srch) = @_;
1785: my $dom = $srch->{'srchdomain'};
1786: my %results;
1787: my %libserv = &all_library();
1788: my $query = 'usersearch';
1789: foreach my $tryserver (keys(%libserv)) {
1790: if (&host_domain($tryserver) eq $dom) {
1791: my $host=&hostname($tryserver);
1792: my $queryid=
1.911 raeburn 1793: &reply("querysend:".&escape($query).':'.
1794: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1795: &escape($srch->{'srchtype'}).':'.
1796: &escape($srch->{'srchterm'}),$tryserver);
1797: if ($queryid !~/^\Q$host\E\_/) {
1798: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1799: next;
1.899 raeburn 1800: }
1801: my $reply = &get_query_reply($queryid);
1802: my $maxtries = 1;
1803: my $tries = 1;
1804: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1805: $reply = &get_query_reply($queryid);
1806: $tries ++;
1807: }
1808: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1809: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1810: } else {
1.911 raeburn 1811: my @matches;
1812: if ($reply =~ /\n/) {
1813: @matches = split(/\n/,$reply);
1814: } else {
1815: @matches = split(/\&/,$reply);
1816: }
1.899 raeburn 1817: foreach my $match (@matches) {
1818: my ($uname,$udom,%userhash);
1.911 raeburn 1819: foreach my $entry (split(/:/,$match)) {
1820: my ($key,$value) =
1821: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1822: $userhash{$key} = $value;
1823: if ($key eq 'username') {
1824: $uname = $value;
1825: } elsif ($key eq 'domain') {
1826: $udom = $value;
1.911 raeburn 1827: }
1.899 raeburn 1828: }
1829: $results{$uname.':'.$udom} = \%userhash;
1830: }
1831: }
1832: }
1833: }
1834: return %results;
1835: }
1836:
1.912 raeburn 1837: sub get_instuser {
1838: my ($udom,$uname,$id) = @_;
1839: my $homeserver = &domain($udom,'primary');
1840: my ($outcome,%results);
1841: if ($homeserver ne '') {
1842: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1843: &escape($id).':'.&escape($udom),$homeserver);
1844: my $host=&hostname($homeserver);
1845: if ($queryid !~/^\Q$host\E\_/) {
1846: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1847: return;
1848: }
1849: my $response = &get_query_reply($queryid);
1850: my $maxtries = 5;
1851: my $tries = 1;
1852: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1853: $response = &get_query_reply($queryid);
1854: $tries ++;
1855: }
1856: if (!&error($response) && $response ne 'refused') {
1857: if ($response eq 'unavailable') {
1858: $outcome = $response;
1859: } else {
1860: $outcome = 'ok';
1861: my @matches = split(/\n/,$response);
1862: foreach my $match (@matches) {
1863: my ($key,$value) = split(/=/,$match);
1864: $results{&unescape($key)} = &thaw_unescape($value);
1865: }
1866: }
1867: }
1868: }
1869: my %userinfo;
1870: if (ref($results{$uname}) eq 'HASH') {
1871: %userinfo = %{$results{$uname}};
1872: }
1873: return ($outcome,%userinfo);
1874: }
1875:
1876: sub inst_rulecheck {
1.923 raeburn 1877: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1878: my %returnhash;
1879: if ($udom ne '') {
1880: if (ref($rules) eq 'ARRAY') {
1881: @{$rules} = map {&escape($_);} (@{$rules});
1882: my $rulestr = join(':',@{$rules});
1883: my $homeserver=&domain($udom,'primary');
1884: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1885: my $response;
1886: if ($item eq 'username') {
1887: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1888: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1889: $homeserver));
1.923 raeburn 1890: } elsif ($item eq 'id') {
1891: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1892: ':'.&escape($id).':'.$rulestr,
1893: $homeserver));
1.945 raeburn 1894: } elsif ($item eq 'selfcreate') {
1895: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1896: &escape($udom).':'.&escape($uname).
1897: ':'.$rulestr,$homeserver));
1.923 raeburn 1898: }
1.912 raeburn 1899: if ($response ne 'refused') {
1900: my @pairs=split(/\&/,$response);
1901: foreach my $item (@pairs) {
1902: my ($key,$value)=split(/=/,$item,2);
1903: $key = &unescape($key);
1904: next if ($key =~ /^error: 2 /);
1905: $returnhash{$key}=&thaw_unescape($value);
1906: }
1907: }
1908: }
1909: }
1910: }
1911: return %returnhash;
1912: }
1913:
1914: sub inst_userrules {
1.923 raeburn 1915: my ($udom,$check) = @_;
1.912 raeburn 1916: my (%ruleshash,@ruleorder);
1917: if ($udom ne '') {
1918: my $homeserver=&domain($udom,'primary');
1919: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1920: my $response;
1921: if ($check eq 'id') {
1922: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1923: $homeserver);
1.943 raeburn 1924: } elsif ($check eq 'email') {
1925: $response=&reply('instemailrules:'.&escape($udom),
1926: $homeserver);
1.923 raeburn 1927: } else {
1928: $response=&reply('instuserrules:'.&escape($udom),
1929: $homeserver);
1930: }
1.912 raeburn 1931: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1932: ($response ne 'unknown_cmd') &&
1.912 raeburn 1933: ($response ne 'no_such_host')) {
1934: my ($hashitems,$orderitems) = split(/:/,$response);
1935: my @pairs=split(/\&/,$hashitems);
1936: foreach my $item (@pairs) {
1937: my ($key,$value)=split(/=/,$item,2);
1938: $key = &unescape($key);
1939: next if ($key =~ /^error: 2 /);
1940: $ruleshash{$key}=&thaw_unescape($value);
1941: }
1942: my @esc_order = split(/\&/,$orderitems);
1943: foreach my $item (@esc_order) {
1944: push(@ruleorder,&unescape($item));
1945: }
1946: }
1947: }
1948: }
1949: return (\%ruleshash,\@ruleorder);
1950: }
1951:
1.976 raeburn 1952: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1953:
1954: sub get_domain_defaults {
1955: my ($domain) = @_;
1956: my $cachetime = 60*60*24;
1957: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1958: if (defined($cached)) {
1959: if (ref($result) eq 'HASH') {
1960: return %{$result};
1961: }
1962: }
1963: my %domdefaults;
1964: my %domconfig =
1.989 raeburn 1965: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1966: 'requestcourses','inststatus',
1.1172.2.9 raeburn 1967: 'coursedefaults','usersessions',
1968: 'requestauthor'],$domain);
1.943 raeburn 1969: if (ref($domconfig{'defaults'}) eq 'HASH') {
1970: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1971: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1972: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1973: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1974: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1975: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1976: } else {
1977: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1978: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1979: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1980: }
1.976 raeburn 1981: if (ref($domconfig{'quotas'}) eq 'HASH') {
1982: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1983: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1984: } else {
1985: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29! raeburn 1986: }
1.1172.2.6 raeburn 1987: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 1988: foreach my $item (@usertools) {
1989: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1990: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1991: }
1992: }
1.1172.2.29! raeburn 1993: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
! 1994: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
! 1995: }
1.976 raeburn 1996: }
1.985 raeburn 1997: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1998: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1999: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2000: }
2001: }
1.1172.2.9 raeburn 2002: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2003: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2004: }
1.989 raeburn 2005: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2006: foreach my $item ('inststatustypes','inststatusorder') {
2007: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2008: }
2009: }
1.1047 raeburn 2010: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19 raeburn 2011: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2012: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2013: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1047 raeburn 2014: }
2015: }
1.1073 raeburn 2016: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2017: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2018: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2019: }
2020: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2021: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2022: }
2023: }
1.1172.2.23 raeburn 2024: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2025: return %domdefaults;
2026: }
2027:
1.344 www 2028: # --------------------------------------------------- Assign a key to a student
2029:
2030: sub assign_access_key {
1.364 www 2031: #
2032: # a valid key looks like uname:udom#comments
2033: # comments are being appended
2034: #
1.498 www 2035: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2036: $kdom=
1.620 albertel 2037: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2038: $knum=
1.620 albertel 2039: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2040: $cdom=
1.620 albertel 2041: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2042: $cnum=
1.620 albertel 2043: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2044: $udom=$env{'user.name'} unless (defined($udom));
2045: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2046: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2047: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2048: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2049: # assigned to this person
2050: # - this should not happen,
1.345 www 2051: # unless something went wrong
2052: # the first time around
2053: # ready to assign
1.364 www 2054: $logentry=$1.'; '.$logentry;
1.496 www 2055: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2056: $kdom,$knum) eq 'ok') {
1.345 www 2057: # key now belongs to user
1.346 www 2058: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2059: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2060: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2061: return 'ok';
2062: } else {
2063: return
2064: 'error: Count not permanently assign key, will need to be re-entered later.';
2065: }
2066: } else {
2067: return 'error: Could not assign key, try again later.';
2068: }
1.364 www 2069: } elsif (!$existing{$ckey}) {
1.345 www 2070: # the key does not exist
2071: return 'error: The key does not exist';
2072: } else {
2073: # the key is somebody else's
2074: return 'error: The key is already in use';
2075: }
1.344 www 2076: }
2077:
1.364 www 2078: # ------------------------------------------ put an additional comment on a key
2079:
2080: sub comment_access_key {
2081: #
2082: # a valid key looks like uname:udom#comments
2083: # comments are being appended
2084: #
2085: my ($ckey,$cdom,$cnum,$logentry)=@_;
2086: $cdom=
1.620 albertel 2087: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2088: $cnum=
1.620 albertel 2089: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2090: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2091: if ($existing{$ckey}) {
2092: $existing{$ckey}.='; '.$logentry;
2093: # ready to assign
1.367 www 2094: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2095: $cdom,$cnum) eq 'ok') {
2096: return 'ok';
2097: } else {
2098: return 'error: Count not store comment.';
2099: }
2100: } else {
2101: # the key does not exist
2102: return 'error: The key does not exist';
2103: }
2104: }
2105:
1.344 www 2106: # ------------------------------------------------------ Generate a set of keys
2107:
2108: sub generate_access_keys {
1.364 www 2109: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2110: $cdom=
1.620 albertel 2111: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2112: $cnum=
1.620 albertel 2113: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2114: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2115: unless (($cdom) && ($cnum)) { return 0; }
2116: if ($number>10000) { return 0; }
2117: sleep(2); # make sure don't get same seed twice
2118: srand(time()^($$+($$<<15))); # from "Programming Perl"
2119: my $total=0;
2120: for (my $i=1;$i<=$number;$i++) {
2121: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2122: sprintf("%lx",int(100000*rand)).'-'.
2123: sprintf("%lx",int(100000*rand));
2124: $newkey=~s/1/g/g; # folks mix up 1 and l
2125: $newkey=~s/0/h/g; # and also 0 and O
2126: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2127: if ($existing{$newkey}) {
2128: $i--;
2129: } else {
1.364 www 2130: if (&put('accesskeys',
2131: { $newkey => '# generated '.localtime().
1.620 albertel 2132: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2133: '; '.$logentry },
2134: $cdom,$cnum) eq 'ok') {
1.344 www 2135: $total++;
2136: }
2137: }
2138: }
1.620 albertel 2139: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2140: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2141: return $total;
2142: }
2143:
2144: # ------------------------------------------------------- Validate an accesskey
2145:
2146: sub validate_access_key {
2147: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2148: $cdom=
1.620 albertel 2149: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2150: $cnum=
1.620 albertel 2151: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2152: $udom=$env{'user.domain'} unless (defined($udom));
2153: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2154: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2155: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2156: }
2157:
2158: # ------------------------------------- Find the section of student in a course
1.652 albertel 2159: sub devalidate_getsection_cache {
2160: my ($udom,$unam,$courseid)=@_;
2161: my $hashid="$udom:$unam:$courseid";
2162: &devalidate_cache_new('getsection',$hashid);
2163: }
1.298 matthew 2164:
1.815 albertel 2165: sub courseid_to_courseurl {
2166: my ($courseid) = @_;
2167: #already url style courseid
2168: return $courseid if ($courseid =~ m{^/});
2169:
2170: if (exists($env{'course.'.$courseid.'.num'})) {
2171: my $cnum = $env{'course.'.$courseid.'.num'};
2172: my $cdom = $env{'course.'.$courseid.'.domain'};
2173: return "/$cdom/$cnum";
2174: }
2175:
2176: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2177: if (exists($courseinfo{'num'})) {
2178: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2179: }
2180:
2181: return undef;
2182: }
2183:
1.298 matthew 2184: sub getsection {
2185: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2186: my $cachetime=1800;
1.551 albertel 2187:
2188: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2189: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2190: if (defined($cached)) { return $result; }
2191:
1.298 matthew 2192: my %Pending;
2193: my %Expired;
2194: #
2195: # Each role can either have not started yet (pending), be active,
2196: # or have expired.
2197: #
2198: # If there is an active role, we are done.
2199: #
2200: # If there is more than one role which has not started yet,
2201: # choose the one which will start sooner
2202: # If there is one role which has not started yet, return it.
2203: #
2204: # If there is more than one expired role, choose the one which ended last.
2205: # If there is a role which has expired, return it.
2206: #
1.815 albertel 2207: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2208: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2209: foreach my $key (keys(%roleshash)) {
1.479 albertel 2210: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2211: my $section=$1;
2212: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2213: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2214: my $now=time;
1.548 albertel 2215: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2216: $Expired{$end}=$section;
2217: next;
2218: }
1.548 albertel 2219: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2220: $Pending{$start}=$section;
2221: next;
2222: }
1.599 albertel 2223: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2224: }
2225: #
2226: # Presumedly there will be few matching roles from the above
2227: # loop and the sorting time will be negligible.
2228: if (scalar(keys(%Pending))) {
2229: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2230: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2231: }
2232: if (scalar(keys(%Expired))) {
2233: my @sorted = sort {$a <=> $b} keys(%Expired);
2234: my $time = pop(@sorted);
1.599 albertel 2235: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2236: }
1.599 albertel 2237: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2238: }
1.70 www 2239:
1.599 albertel 2240: sub save_cache {
2241: &purge_remembered();
1.722 albertel 2242: #&Apache::loncommon::validate_page();
1.620 albertel 2243: undef(%env);
1.780 albertel 2244: undef($env_loaded);
1.599 albertel 2245: }
1.452 albertel 2246:
1.599 albertel 2247: my $to_remember=-1;
2248: my %remembered;
2249: my %accessed;
2250: my $kicks=0;
2251: my $hits=0;
1.849 albertel 2252: sub make_key {
2253: my ($name,$id) = @_;
1.872 albertel 2254: if (length($id) > 65
2255: && length(&escape($id)) > 200) {
2256: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2257: }
1.849 albertel 2258: return &escape($name.':'.$id);
2259: }
2260:
1.599 albertel 2261: sub devalidate_cache_new {
2262: my ($name,$id,$debug) = @_;
2263: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2264: $id=&make_key($name,$id);
1.599 albertel 2265: $memcache->delete($id);
2266: delete($remembered{$id});
2267: delete($accessed{$id});
2268: }
2269:
2270: sub is_cached_new {
2271: my ($name,$id,$debug) = @_;
1.849 albertel 2272: $id=&make_key($name,$id);
1.599 albertel 2273: if (exists($remembered{$id})) {
1.1133 foxr 2274: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2275: $accessed{$id}=[&gettimeofday()];
2276: $hits++;
2277: return ($remembered{$id},1);
2278: }
2279: my $value = $memcache->get($id);
2280: if (!(defined($value))) {
2281: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2282: return (undef,undef);
1.416 albertel 2283: }
1.599 albertel 2284: if ($value eq '__undef__') {
2285: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2286: $value=undef;
2287: }
2288: &make_room($id,$value,$debug);
2289: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2290: return ($value,1);
2291: }
2292:
2293: sub do_cache_new {
2294: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2295: $id=&make_key($name,$id);
1.599 albertel 2296: my $setvalue=$value;
2297: if (!defined($setvalue)) {
2298: $setvalue='__undef__';
2299: }
1.623 albertel 2300: if (!defined($time) ) {
2301: $time=600;
2302: }
1.599 albertel 2303: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2304: my $result = $memcache->set($id,$setvalue,$time);
2305: if (! $result) {
1.872 albertel 2306: &logthis("caching of id -> $id failed");
1.910 albertel 2307: $memcache->disconnect_all();
1.872 albertel 2308: }
1.600 albertel 2309: # need to make a copy of $value
1.919 albertel 2310: &make_room($id,$value,$debug);
1.599 albertel 2311: return $value;
2312: }
2313:
2314: sub make_room {
2315: my ($id,$value,$debug)=@_;
1.919 albertel 2316:
2317: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2318: : $value;
1.599 albertel 2319: if ($to_remember<0) { return; }
2320: $accessed{$id}=[&gettimeofday()];
2321: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2322: my $to_kick;
2323: my $max_time=0;
2324: foreach my $other (keys(%accessed)) {
2325: if (&tv_interval($accessed{$other}) > $max_time) {
2326: $to_kick=$other;
2327: $max_time=&tv_interval($accessed{$other});
2328: }
2329: }
2330: delete($remembered{$to_kick});
2331: delete($accessed{$to_kick});
2332: $kicks++;
2333: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2334: return;
2335: }
2336:
1.599 albertel 2337: sub purge_remembered {
1.604 albertel 2338: #&logthis("Tossing ".scalar(keys(%remembered)));
2339: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2340: undef(%remembered);
2341: undef(%accessed);
1.428 albertel 2342: }
1.70 www 2343: # ------------------------------------- Read an entry from a user's environment
2344:
2345: sub userenvironment {
2346: my ($udom,$unam,@what)=@_;
1.976 raeburn 2347: my $items;
2348: foreach my $item (@what) {
2349: $items.=&escape($item).'&';
2350: }
2351: $items=~s/\&$//;
1.70 www 2352: my %returnhash=();
1.1009 raeburn 2353: my $uhome = &homeserver($unam,$udom);
2354: unless ($uhome eq 'no_host') {
2355: my @answer=split(/\&/,
2356: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2357: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2358: return %returnhash;
2359: }
1.1009 raeburn 2360: my $i;
2361: for ($i=0;$i<=$#what;$i++) {
2362: $returnhash{$what[$i]}=&unescape($answer[$i]);
2363: }
1.70 www 2364: }
2365: return %returnhash;
1.1 albertel 2366: }
2367:
1.617 albertel 2368: # ---------------------------------------------------------- Get a studentphoto
2369: sub studentphoto {
2370: my ($udom,$unam,$ext) = @_;
2371: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2372: if (defined($env{'request.course.id'})) {
1.708 raeburn 2373: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2374: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2375: return(&retrievestudentphoto($udom,$unam,$ext));
2376: } else {
2377: my ($result,$perm_reqd)=
1.707 albertel 2378: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2379: if ($result eq 'ok') {
2380: if (!($perm_reqd eq 'yes')) {
2381: return(&retrievestudentphoto($udom,$unam,$ext));
2382: }
2383: }
2384: }
2385: }
2386: } else {
2387: my ($result,$perm_reqd) =
1.707 albertel 2388: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2389: if ($result eq 'ok') {
2390: if (!($perm_reqd eq 'yes')) {
2391: return(&retrievestudentphoto($udom,$unam,$ext));
2392: }
2393: }
2394: }
2395: return '/adm/lonKaputt/lonlogo_broken.gif';
2396: }
2397:
2398: sub retrievestudentphoto {
2399: my ($udom,$unam,$ext,$type) = @_;
2400: my $home=&Apache::lonnet::homeserver($unam,$udom);
2401: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2402: if ($ret eq 'ok') {
2403: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2404: if ($type eq 'thumbnail') {
2405: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2406: }
2407: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2408: return $tokenurl;
2409: } else {
2410: if ($type eq 'thumbnail') {
2411: return '/adm/lonKaputt/genericstudent_tn.gif';
2412: } else {
2413: return '/adm/lonKaputt/lonlogo_broken.gif';
2414: }
1.617 albertel 2415: }
2416: }
2417:
1.263 www 2418: # -------------------------------------------------------------------- New chat
2419:
2420: sub chatsend {
1.724 raeburn 2421: my ($newentry,$anon,$group)=@_;
1.620 albertel 2422: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2423: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2424: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2425: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2426: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2427: &escape($newentry)).':'.$group,$chome);
1.292 www 2428: }
2429:
2430: # ------------------------------------------ Find current version of a resource
2431:
2432: sub getversion {
2433: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2434: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2435: return ¤tversion(&filelocation('',$fname));
2436: }
2437:
2438: sub currentversion {
2439: my $fname=shift;
2440: my $author=$fname;
2441: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2442: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2443: my $home=&homeserver($uname,$udom);
1.292 www 2444: if ($home eq 'no_host') {
2445: return -1;
2446: }
1.1112 www 2447: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2448: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2449: return -1;
2450: }
1.1112 www 2451: return $answer;
1.263 www 2452: }
2453:
1.1111 www 2454: #
2455: # Return special version number of resource if set by override, empty otherwise
2456: #
2457: sub usedversion {
2458: my $fname=shift;
2459: unless ($fname) { $fname=$env{'request.uri'}; }
2460: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2461: if ($urlversion) { return $urlversion; }
2462: return '';
2463: }
2464:
1.1 albertel 2465: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2466:
1.1 albertel 2467: sub subscribe {
2468: my $fname=shift;
1.761 raeburn 2469: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2470: $fname=~s/[\n\r]//g;
1.1 albertel 2471: my $author=$fname;
2472: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2473: my ($udom,$uname)=split(/\//,$author);
2474: my $home=homeserver($uname,$udom);
1.335 albertel 2475: if ($home eq 'no_host') {
2476: return 'not_found';
1.1 albertel 2477: }
2478: my $answer=reply("sub:$fname",$home);
1.64 www 2479: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2480: $answer.=' by '.$home;
2481: }
1.1 albertel 2482: return $answer;
2483: }
2484:
1.8 www 2485: # -------------------------------------------------------------- Replicate file
2486:
2487: sub repcopy {
2488: my $filename=shift;
1.23 www 2489: $filename=~s/\/+/\//g;
1.1142 raeburn 2490: my $londocroot = $perlvar{'lonDocRoot'};
2491: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2492: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2493: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2494: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2495: return &repcopy_userfile($filename);
2496: }
1.532 albertel 2497: $filename=~s/[\n\r]//g;
1.8 www 2498: my $transname="$filename.in.transfer";
1.828 www 2499: # FIXME: this should flock
1.607 raeburn 2500: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2501: my $remoteurl=subscribe($filename);
1.64 www 2502: if ($remoteurl =~ /^con_lost by/) {
2503: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2504: return 'unavailable';
1.8 www 2505: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2506: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2507: return 'not_found';
1.64 www 2508: } elsif ($remoteurl =~ /^rejected by/) {
2509: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2510: return 'forbidden';
1.20 www 2511: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2512: return 'ok';
1.8 www 2513: } else {
1.290 www 2514: my $author=$filename;
2515: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2516: my ($udom,$uname)=split(/\//,$author);
2517: my $home=homeserver($uname,$udom);
2518: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2519: my @parts=split(/\//,$filename);
2520: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2521: if ($path ne "$londocroot/res") {
1.8 www 2522: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2523: return 'bad_request';
1.8 www 2524: }
2525: my $count;
2526: for ($count=5;$count<$#parts;$count++) {
2527: $path.="/$parts[$count]";
2528: if ((-e $path)!=1) {
2529: mkdir($path,0777);
2530: }
2531: }
2532: my $ua=new LWP::UserAgent;
2533: my $request=new HTTP::Request('GET',"$remoteurl");
2534: my $response=$ua->request($request,$transname);
2535: if ($response->is_error()) {
2536: unlink($transname);
2537: my $message=$response->status_line;
1.672 albertel 2538: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2539: ." LWP get: $message: $filename</font>");
1.607 raeburn 2540: return 'unavailable';
1.8 www 2541: } else {
1.16 www 2542: if ($remoteurl!~/\.meta$/) {
2543: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2544: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2545: if ($mresponse->is_error()) {
2546: unlink($filename.'.meta');
2547: &logthis(
1.672 albertel 2548: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2549: }
2550: }
1.8 www 2551: rename($transname,$filename);
1.607 raeburn 2552: return 'ok';
1.8 www 2553: }
1.290 www 2554: }
1.8 www 2555: }
1.330 www 2556: }
2557:
2558: # ------------------------------------------------ Get server side include body
2559: sub ssi_body {
1.381 albertel 2560: my ($filelink,%form)=@_;
1.606 matthew 2561: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2562: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2563: }
1.953 www 2564: my $output='';
2565: my $response;
1.980 raeburn 2566: if ($filelink=~/^https?\:/) {
1.954 raeburn 2567: ($output,$response)=&externalssi($filelink);
1.953 www 2568: } else {
1.1004 droeschl 2569: $filelink .= $filelink=~/\?/ ? '&' : '?';
2570: $filelink .= 'inhibitmenu=yes';
1.953 www 2571: ($output,$response)=&ssi($filelink,%form);
2572: }
1.778 albertel 2573: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2574: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2575: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2576: if (wantarray) {
2577: return ($output, $response);
2578: } else {
2579: return $output;
2580: }
1.8 www 2581: }
2582:
1.15 www 2583: # --------------------------------------------------------- Server Side Include
2584:
1.782 albertel 2585: sub absolute_url {
2586: my ($host_name) = @_;
2587: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2588: if ($host_name eq '') {
2589: $host_name = $ENV{'SERVER_NAME'};
2590: }
2591: return $protocol.$host_name;
2592: }
2593:
1.942 foxr 2594: #
2595: # Server side include.
2596: # Parameters:
2597: # fn Possibly encrypted resource name/id.
2598: # form Hash that describes how the rendering should be done
2599: # and other things.
1.944 foxr 2600: # Returns:
1.950 raeburn 2601: # Scalar context: The content of the response.
2602: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2603: #
1.15 www 2604: sub ssi {
2605:
1.944 foxr 2606: my ($fn,%form)=@_;
1.15 www 2607: my $ua=new LWP::UserAgent;
1.23 www 2608: my $request;
1.711 albertel 2609:
2610: $form{'no_update_last_known'}=1;
1.895 albertel 2611: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2612: if (%form) {
1.782 albertel 2613: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2614: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2615: } else {
1.782 albertel 2616: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2617: }
2618:
1.15 www 2619: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2620: my $response= $ua->request($request);
1.944 foxr 2621: if (wantarray) {
1.1172.2.3 raeburn 2622: return ($response->content, $response);
1.944 foxr 2623: } else {
1.1172.2.3 raeburn 2624: return $response->content;
1.942 foxr 2625: }
1.324 www 2626: }
2627:
2628: sub externalssi {
2629: my ($url)=@_;
2630: my $ua=new LWP::UserAgent;
2631: my $request=new HTTP::Request('GET',$url);
2632: my $response=$ua->request($request);
1.954 raeburn 2633: if (wantarray) {
2634: return ($response->content, $response);
2635: } else {
2636: return $response->content;
2637: }
1.15 www 2638: }
1.254 www 2639:
1.492 albertel 2640: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2641:
2642: sub allowuploaded {
2643: my ($srcurl,$url)=@_;
2644: $url=&clutter(&declutter($url));
2645: my $dir=$url;
2646: $dir=~s/\/[^\/]+$//;
2647: my %httpref=();
2648: my $httpurl=&hreflocation('',$url);
2649: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2650: &Apache::lonnet::appenv(\%httpref);
1.254 www 2651: }
1.477 raeburn 2652:
1.1172.2.13 raeburn 2653: #
2654: # Determine if the current user should be able to edit a particular resource,
2655: # when viewing in course context.
2656: # (a) When viewing resource used to determine if "Edit" item is included in
2657: # Functions.
2658: # (b) When displaying folder contents in course editor, used to determine if
2659: # "Edit" link will be displayed alongside resource.
2660: #
2661: # input: six args -- filename (decluttered), course number, course domain,
2662: # url, symb (if registered) and group (if this is a group
2663: # item -- e.g., bulletin board, group page etc.).
2664: # output: array of five scalars --
2665: # $cfile -- url for file editing if editable on current server
2666: # $home -- homeserver of resource (i.e., for author if published,
2667: # or course if uploaded.).
2668: # $switchserver -- 1 if server switch will be needed.
2669: # $forceedit -- 1 if icon/link should be to go to edit mode
2670: # $forceview -- 1 if icon/link should be to go to view mode
2671: #
2672:
2673: sub can_edit_resource {
2674: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2675: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2676: #
2677: # For aboutme pages user can only edit his/her own.
2678: #
2679: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2680: my ($sdom,$sname) = ($1,$2);
2681: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2682: $home = $env{'user.home'};
2683: $cfile = $resurl;
2684: if ($env{'form.forceedit'}) {
2685: $forceview = 1;
2686: } else {
2687: $forceedit = 1;
2688: }
2689: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2690: } else {
2691: return;
2692: }
2693: }
2694:
2695: if ($env{'request.course.id'}) {
2696: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2697: if ($group ne '') {
2698: # if this is a group homepage or group bulletin board, check group privs
2699: my $allowed = 0;
2700: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2701: if ((&allowed('mdg',$env{'request.course.id'}.
2702: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2703: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2704: $allowed = 1;
2705: }
2706: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2707: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2708: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2709: $allowed = 1;
2710: }
2711: }
2712: if ($allowed) {
2713: $home=&homeserver($cnum,$cdom);
2714: if ($env{'form.forceedit'}) {
2715: $forceview = 1;
2716: } else {
2717: $forceedit = 1;
2718: }
2719: $cfile = $resurl;
2720: } else {
2721: return;
2722: }
2723: } else {
1.1172.2.15 raeburn 2724: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2725: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2726: return;
2727: }
2728: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2729: #
2730: # No edit allowed where CC has switched to student role.
2731: #
2732: return;
2733: }
2734: }
2735: }
2736:
2737: if ($file ne '') {
2738: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2739: if (&is_course_upload($file,$cnum,$cdom)) {
2740: $uploaded = 1;
2741: $incourse = 1;
2742: if ($file =~/\.(htm|html|css|js|txt)$/) {
2743: $cfile = &hreflocation('',$file);
2744: if ($env{'form.forceedit'}) {
2745: $forceview = 1;
2746: } else {
2747: $forceedit = 1;
2748: }
2749: }
2750: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2751: $incourse = 1;
2752: if ($env{'form.forceedit'}) {
2753: $forceview = 1;
2754: } else {
2755: $forceedit = 1;
2756: }
2757: $cfile = $resurl;
2758: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2759: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2760: $incourse = 1;
2761: if ($env{'form.forceedit'}) {
2762: $forceview = 1;
2763: } else {
2764: $forceedit = 1;
2765: }
2766: $cfile = $resurl;
2767: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2768: $incourse = 1;
2769: $cfile = $resurl.'/smpedit';
2770: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2771: $incourse = 1;
2772: if ($env{'form.forceedit'}) {
2773: $forceview = 1;
2774: } else {
2775: $forceedit = 1;
2776: }
2777: $cfile = $resurl;
1.1172.2.15 raeburn 2778: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2779: $incourse = 1;
2780: if ($env{'form.forceedit'}) {
2781: $forceview = 1;
2782: } else {
2783: $forceedit = 1;
2784: }
2785: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2786: }
2787: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2788: my $template = '/res/lib/templates/simpleproblem.problem';
2789: if (&is_on_map($template)) {
2790: $incourse = 1;
2791: $forceview = 1;
2792: $cfile = $template;
2793: }
2794: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2795: $incourse = 1;
2796: if ($env{'form.forceedit'}) {
2797: $forceview = 1;
2798: } else {
2799: $forceedit = 1;
2800: }
2801: $cfile = $resurl;
2802: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2803: $incourse = 1;
2804: $forceview = 1;
2805: if ($symb) {
2806: my ($map,$id,$res)=&decode_symb($symb);
2807: $env{'request.symb'} = $symb;
2808: $cfile = &clutter($res);
2809: } else {
2810: $cfile = $env{'form.suppurl'};
2811: $cfile =~ s{^http://}{};
2812: $cfile = '/adm/wrapper/ext/'.$cfile;
2813: }
2814: }
2815: }
2816: if ($uploaded || $incourse) {
2817: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2818: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2819: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2820: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2821: # Check that the user has permission to edit this resource
2822: my $setpriv = 1;
2823: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2824: if (defined($cfudom)) {
2825: $home=&homeserver($cfuname,$cfudom);
2826: $cfile=$file;
2827: }
2828: }
2829: if (($cfile ne '') && (!$incourse || $uploaded) &&
2830: (($home ne '') && ($home ne 'no_host'))) {
2831: my @ids=¤t_machine_ids();
2832: unless (grep(/^\Q$home\E$/,@ids)) {
2833: $switchserver=1;
2834: }
2835: }
2836: }
2837: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2838: }
2839:
2840: sub is_course_upload {
2841: my ($file,$cnum,$cdom) = @_;
2842: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2843: $uploadpath =~ s{^\/}{};
2844: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2845: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2846: return 1;
2847: }
2848: return;
2849: }
2850:
2851: sub in_course {
2852: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2853: if ($hideprivileged) {
2854: my $skipuser;
1.1172.2.23 raeburn 2855: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2856: my @possdoms = ($cdom);
2857: if ($coursehash{'checkforpriv'}) {
2858: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2859: }
2860: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2861: $skipuser = 1;
2862: if ($coursehash{'nothideprivileged'}) {
2863: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2864: my $user;
2865: if ($item =~ /:/) {
2866: $user = $item;
2867: } else {
2868: $user = join(':',split(/[\@]/,$item));
2869: }
2870: if ($user eq $uname.':'.$udom) {
2871: undef($skipuser);
2872: last;
2873: }
2874: }
2875: }
2876: if ($skipuser) {
2877: return 0;
2878: }
2879: }
2880: }
2881: $type ||= 'any';
2882: if (!defined($cdom) || !defined($cnum)) {
2883: my $cid = $env{'request.course.id'};
2884: $cdom = $env{'course.'.$cid.'.domain'};
2885: $cnum = $env{'course.'.$cid.'.num'};
2886: }
2887: my $typesref;
2888: if (($type eq 'any') || ($type eq 'all')) {
2889: $typesref = ['active','previous','future'];
2890: } elsif ($type eq 'previous' || $type eq 'future') {
2891: $typesref = [$type];
2892: }
2893: my %roles = &get_my_roles($uname,$udom,'userroles',
2894: $typesref,undef,[$cdom]);
2895: my ($tmp) = keys(%roles);
2896: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2897: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2898: if (@course_roles > 0) {
2899: return 1;
2900: }
2901: return 0;
2902: }
2903:
1.478 albertel 2904: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2905: # input: action, courseID, current domain, intended
1.637 raeburn 2906: # path to file, source of file, instruction to parse file for objects,
2907: # ref to hash for embedded objects,
2908: # ref to hash for codebase of java objects.
1.1095 raeburn 2909: # reference to scalar to accommodate mime type determined
2910: # from File::MMagic if $parser = parse.
1.637 raeburn 2911: #
1.485 raeburn 2912: # output: url to file (if action was uploaddoc),
2913: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2914: #
1.478 albertel 2915: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2916: # course.
1.477 raeburn 2917: #
1.478 albertel 2918: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2919: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2920: # course's home server.
1.477 raeburn 2921: #
1.478 albertel 2922: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2923: # be copied from $source (current location) to
2924: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2925: # and will then be copied to
2926: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2927: # course's home server.
1.485 raeburn 2928: #
1.481 raeburn 2929: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2930: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2931: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2932: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2933: # in course's home server.
1.637 raeburn 2934: #
1.477 raeburn 2935:
2936: sub process_coursefile {
1.1095 raeburn 2937: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2938: $mimetype)=@_;
1.477 raeburn 2939: my $fetchresult;
1.638 albertel 2940: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2941: if ($action eq 'propagate') {
1.638 albertel 2942: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2943: $home);
1.481 raeburn 2944: } else {
1.477 raeburn 2945: my $fpath = '';
2946: my $fname = $file;
1.478 albertel 2947: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2948: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2949: my $filepath = &build_filepath($fpath);
1.481 raeburn 2950: if ($action eq 'copy') {
2951: if ($source eq '') {
2952: $fetchresult = 'no source file';
2953: return $fetchresult;
2954: } else {
2955: my $destination = $filepath.'/'.$fname;
2956: rename($source,$destination);
2957: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2958: $home);
1.481 raeburn 2959: }
2960: } elsif ($action eq 'uploaddoc') {
2961: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2962: print $fh $env{'form.'.$source};
1.481 raeburn 2963: close($fh);
1.637 raeburn 2964: if ($parser eq 'parse') {
1.1024 raeburn 2965: my $mm = new File::MMagic;
1.1095 raeburn 2966: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2967: if ($type eq 'text/html') {
1.1024 raeburn 2968: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2969: unless ($parse_result eq 'ok') {
2970: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2971: }
1.637 raeburn 2972: }
1.1095 raeburn 2973: if (ref($mimetype)) {
2974: $$mimetype = $type;
2975: }
1.637 raeburn 2976: }
1.477 raeburn 2977: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2978: $home);
1.481 raeburn 2979: if ($fetchresult eq 'ok') {
2980: return '/uploaded/'.$fpath.'/'.$fname;
2981: } else {
2982: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2983: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2984: return '/adm/notfound.html';
2985: }
1.477 raeburn 2986: }
2987: }
1.485 raeburn 2988: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2989: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2990: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2991: }
2992: return $fetchresult;
2993: }
2994:
1.637 raeburn 2995: sub build_filepath {
2996: my ($fpath) = @_;
2997: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2998: unless ($fpath eq '') {
2999: my @parts=split('/',$fpath);
3000: foreach my $part (@parts) {
3001: $filepath.= '/'.$part;
3002: if ((-e $filepath)!=1) {
3003: mkdir($filepath,0777);
3004: }
3005: }
3006: }
3007: return $filepath;
3008: }
3009:
3010: sub store_edited_file {
1.638 albertel 3011: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3012: my $file = $primary_url;
3013: $file =~ s#^/uploaded/$docudom/$docuname/##;
3014: my $fpath = '';
3015: my $fname = $file;
3016: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3017: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3018: my $filepath = &build_filepath($fpath);
3019: open(my $fh,'>'.$filepath.'/'.$fname);
3020: print $fh $content;
3021: close($fh);
1.638 albertel 3022: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3023: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3024: $home);
1.637 raeburn 3025: if ($$fetchresult eq 'ok') {
3026: return '/uploaded/'.$fpath.'/'.$fname;
3027: } else {
1.638 albertel 3028: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3029: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3030: return '/adm/notfound.html';
3031: }
3032: }
3033:
1.531 albertel 3034: sub clean_filename {
1.831 albertel 3035: my ($fname,$args)=@_;
1.315 www 3036: # Replace Windows backslashes by forward slashes
1.257 www 3037: $fname=~s/\\/\//g;
1.831 albertel 3038: if (!$args->{'keep_path'}) {
3039: # Get rid of everything but the actual filename
3040: $fname=~s/^.*\/([^\/]+)$/$1/;
3041: }
1.315 www 3042: # Replace spaces by underscores
3043: $fname=~s/\s+/\_/g;
3044: # Replace all other weird characters by nothing
1.831 albertel 3045: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3046: # Replace all .\d. sequences with _\d. so they no longer look like version
3047: # numbers
3048: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3049: return $fname;
3050: }
1.1051 raeburn 3051: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3052: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3053: # image with the same aspect ratio as the original, but with dimensions which do
3054: # not exceed $resizewidth and $resizeheight.
3055:
1.984 neumanie 3056: sub resizeImage {
1.1051 raeburn 3057: my ($img_path,$resizewidth,$resizeheight) = @_;
3058: my $ima = Image::Magick->new;
3059: my $resized;
3060: if (-e $img_path) {
3061: $ima->Read($img_path);
3062: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3063: my $width = $ima->Get('width');
3064: my $height = $ima->Get('height');
3065: if ($width > $resizewidth) {
3066: my $factor = $width/$resizewidth;
3067: my $newheight = $height/$factor;
3068: $ima->Scale(width=>$resizewidth,height=>$newheight);
3069: $resized = 1;
3070: }
3071: }
3072: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3073: my $width = $ima->Get('width');
3074: my $height = $ima->Get('height');
3075: if ($height > $resizeheight) {
3076: my $factor = $height/$resizeheight;
3077: my $newwidth = $width/$factor;
3078: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3079: $resized = 1;
3080: }
3081: }
3082: if ($resized) {
3083: $ima->Write($img_path);
3084: }
3085: }
3086: return;
1.977 amueller 3087: }
3088:
1.608 albertel 3089: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3090: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3091: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3092: # $context - possible values: coursedoc, existingfile, overwrite,
3093: # canceloverwrite, or ''.
3094: # if 'coursedoc': upload to the current course
3095: # if 'existingfile': write file to tmp/overwrites directory
3096: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3097: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3098: # $subdir - directory in userfile to store the file into
1.858 raeburn 3099: # $parser - instruction to parse file for objects ($parser = parse)
3100: # $allfiles - reference to hash for embedded objects
3101: # $codebase - reference to hash for codebase of java objects
3102: # $desuname - username for permanent storage of uploaded file
3103: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3104: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3105: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3106: # $resizewidth - width (pixels) to which to resize uploaded image
3107: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3108: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3109: # from File::MMagic.
1.858 raeburn 3110: #
1.686 albertel 3111: # output: url of file in userspace, or error: <message>
3112: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3113:
1.531 albertel 3114: sub userfileupload {
1.1090 raeburn 3115: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3116: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3117: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3118: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3119: $fname=&clean_filename($fname);
1.1090 raeburn 3120: # See if there is anything left
1.257 www 3121: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3122: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3123: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3124: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3125: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3126: my $now = time;
1.1090 raeburn 3127: my $filepath;
1.1095 raeburn 3128: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3129: $filepath = 'tmp/helprequests/'.$now;
3130: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3131: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3132: '_'.$env{'user.domain'}.'/pending';
3133: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3134: my ($docuname,$docudom);
3135: if ($destudom) {
3136: $docudom = $destudom;
3137: } else {
3138: $docudom = $env{'user.domain'};
3139: }
3140: if ($destuname) {
3141: $docuname = $destuname;
3142: } else {
3143: $docuname = $env{'user.name'};
3144: }
3145: if (exists($env{'form.group'})) {
3146: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3147: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3148: }
3149: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3150: if ($context eq 'canceloverwrite') {
3151: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3152: if (-e $tempfile) {
3153: my @info = stat($tempfile);
3154: if ($info[9] eq $env{'form.timestamp'}) {
3155: unlink($tempfile);
3156: }
3157: }
3158: return;
1.523 raeburn 3159: }
3160: }
1.1090 raeburn 3161: # Create the directory if not present
1.741 raeburn 3162: my @parts=split(/\//,$filepath);
3163: my $fullpath = $perlvar{'lonDaemons'};
3164: for (my $i=0;$i<@parts;$i++) {
3165: $fullpath .= '/'.$parts[$i];
3166: if ((-e $fullpath)!=1) {
3167: mkdir($fullpath,0777);
3168: }
3169: }
3170: open(my $fh,'>'.$fullpath.'/'.$fname);
3171: print $fh $env{'form.'.$formname};
3172: close($fh);
1.1090 raeburn 3173: if ($context eq 'existingfile') {
3174: my @info = stat($fullpath.'/'.$fname);
3175: return ($fullpath.'/'.$fname,$info[9]);
3176: } else {
3177: return $fullpath.'/'.$fname;
3178: }
1.523 raeburn 3179: }
1.995 raeburn 3180: if ($subdir eq 'scantron') {
3181: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3182: } else {
1.995 raeburn 3183: $fname="$subdir/$fname";
3184: }
1.1090 raeburn 3185: if ($context eq 'coursedoc') {
1.638 albertel 3186: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3187: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3188: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3189: return &finishuserfileupload($docuname,$docudom,
3190: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3191: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3192: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3193: } else {
1.1172.2.21 raeburn 3194: if ($env{'form.folder'}) {
3195: $fname=$env{'form.folder'}.'/'.$fname;
3196: }
1.638 albertel 3197: return &process_coursefile('uploaddoc',$docuname,$docudom,
3198: $fname,$formname,$parser,
1.1095 raeburn 3199: $allfiles,$codebase,$mimetype);
1.481 raeburn 3200: }
1.719 banghart 3201: } elsif (defined($destuname)) {
3202: my $docuname=$destuname;
3203: my $docudom=$destudom;
1.860 raeburn 3204: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3205: $parser,$allfiles,$codebase,
1.1051 raeburn 3206: $thumbwidth,$thumbheight,
1.1095 raeburn 3207: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3208: } else {
1.638 albertel 3209: my $docuname=$env{'user.name'};
3210: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3211: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3212: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3213: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3214: }
1.860 raeburn 3215: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3216: $parser,$allfiles,$codebase,
1.1051 raeburn 3217: $thumbwidth,$thumbheight,
1.1095 raeburn 3218: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3219: }
1.271 www 3220: }
3221:
3222: sub finishuserfileupload {
1.860 raeburn 3223: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3224: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3225: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3226: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3227:
1.860 raeburn 3228: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3229: $file=$fname;
3230: if ($fname=~m|/|) {
3231: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3232: $path.=$fnamepath.'/';
3233: }
1.259 www 3234: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3235: my $count;
3236: for ($count=4;$count<=$#parts;$count++) {
3237: $filepath.="/$parts[$count]";
3238: if ((-e $filepath)!=1) {
3239: mkdir($filepath,0777);
3240: }
3241: }
1.984 neumanie 3242:
1.258 www 3243: # Save the file
3244: {
1.701 albertel 3245: if (!open(FH,'>'.$filepath.'/'.$file)) {
3246: &logthis('Failed to create '.$filepath.'/'.$file);
3247: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3248: return '/adm/notfound.html';
3249: }
1.1090 raeburn 3250: if ($context eq 'overwrite') {
1.1117 foxr 3251: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3252: my $target = $filepath.'/'.$file;
3253: if (-e $source) {
3254: my @info = stat($source);
3255: if ($info[9] eq $env{'form.timestamp'}) {
3256: unless (&File::Copy::move($source,$target)) {
3257: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3258: return "Moving from $source failed";
3259: }
3260: } else {
3261: return "Temporary file: $source had unexpected date/time for last modification";
3262: }
3263: } else {
3264: return "Temporary file: $source missing";
3265: }
3266: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3267: &logthis('Failed to write to '.$filepath.'/'.$file);
3268: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3269: return '/adm/notfound.html';
3270: }
1.570 albertel 3271: close(FH);
1.1051 raeburn 3272: if ($resizewidth && $resizeheight) {
3273: my $mm = new File::MMagic;
3274: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3275: if ($mime_type =~ m{^image/}) {
3276: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3277: }
1.977 amueller 3278: }
1.258 www 3279: }
1.1152 raeburn 3280: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3281: if (ref($mimetype)) {
3282: if ($$mimetype eq '') {
3283: my $mm = new File::MMagic;
3284: my $type = $mm->checktype_filename($filepath.'/'.$file);
3285: $$mimetype = $type;
3286: }
3287: }
3288: }
1.637 raeburn 3289: if ($parser eq 'parse') {
1.1152 raeburn 3290: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3291: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3292: $allfiles,$codebase);
3293: unless ($parse_result eq 'ok') {
3294: &logthis('Failed to parse '.$filepath.$file.
3295: ' for embedded media: '.$parse_result);
3296: }
1.637 raeburn 3297: }
3298: }
1.860 raeburn 3299: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3300: my $input = $filepath.'/'.$file;
3301: my $output = $filepath.'/'.'tn-'.$file;
3302: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3303: system("convert -sample $thumbsize $input $output");
3304: if (-e $filepath.'/'.'tn-'.$file) {
3305: $fetchthumb = 1;
3306: }
3307: }
1.858 raeburn 3308:
1.259 www 3309: # Notify homeserver to grep it
3310: #
1.984 neumanie 3311: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3312: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3313: if ($fetchresult eq 'ok') {
1.860 raeburn 3314: if ($fetchthumb) {
3315: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3316: if ($thumbresult ne 'ok') {
3317: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3318: $docuhome.': '.$thumbresult);
3319: }
3320: }
1.259 www 3321: #
1.258 www 3322: # Return the URL to it
1.494 albertel 3323: return '/uploaded/'.$path.$file;
1.263 www 3324: } else {
1.494 albertel 3325: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3326: ': '.$fetchresult);
1.263 www 3327: return '/adm/notfound.html';
1.858 raeburn 3328: }
1.493 albertel 3329: }
3330:
1.637 raeburn 3331: sub extract_embedded_items {
1.961 raeburn 3332: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3333: my @state = ();
1.1164 raeburn 3334: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3335: my %javafiles = (
3336: codebase => '',
3337: code => '',
3338: archive => ''
3339: );
3340: my %mediafiles = (
3341: src => '',
3342: movie => '',
3343: );
1.648 raeburn 3344: my $p;
3345: if ($content) {
3346: $p = HTML::LCParser->new($content);
3347: } else {
1.961 raeburn 3348: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3349: }
1.641 albertel 3350: while (my $t=$p->get_token()) {
1.640 albertel 3351: if ($t->[0] eq 'S') {
3352: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3353: push(@state, $tagname);
1.648 raeburn 3354: if (lc($tagname) eq 'allow') {
3355: &add_filetype($allfiles,$attr->{'src'},'src');
3356: }
1.640 albertel 3357: if (lc($tagname) eq 'img') {
3358: &add_filetype($allfiles,$attr->{'src'},'src');
3359: }
1.886 albertel 3360: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3361: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3362: &add_filetype($allfiles,$attr->{'href'},'href');
3363: }
1.886 albertel 3364: }
1.645 raeburn 3365: if (lc($tagname) eq 'script') {
1.1164 raeburn 3366: my $src;
1.645 raeburn 3367: if ($attr->{'archive'} =~ /\.jar$/i) {
3368: &add_filetype($allfiles,$attr->{'archive'},'archive');
3369: } else {
1.1164 raeburn 3370: if ($attr->{'src'} ne '') {
3371: $src = $attr->{'src'};
3372: &add_filetype($allfiles,$src,'src');
3373: }
3374: }
3375: my $text = $p->get_trimmed_text();
3376: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3377: my @swfargs = split(/,/,$1);
3378: foreach my $item (@swfargs) {
3379: $item =~ s/["']//g;
3380: $item =~ s/^\s+//;
3381: $item =~ s/\s+$//;
3382: }
3383: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3384: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3385: push(@{$related{$swfargs[0]}},$swfargs[2]);
3386: } else {
3387: $related{$swfargs[0]} = [$swfargs[2]];
3388: }
3389: }
1.645 raeburn 3390: }
3391: }
3392: if (lc($tagname) eq 'link') {
3393: if (lc($attr->{'rel'}) eq 'stylesheet') {
3394: &add_filetype($allfiles,$attr->{'href'},'href');
3395: }
3396: }
1.640 albertel 3397: if (lc($tagname) eq 'object' ||
3398: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3399: foreach my $item (keys(%javafiles)) {
3400: $javafiles{$item} = '';
3401: }
1.1164 raeburn 3402: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3403: $lastids{lc($tagname)} = $attr->{'id'};
3404: }
1.640 albertel 3405: }
3406: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3407: my $name = lc($attr->{'name'});
3408: foreach my $item (keys(%javafiles)) {
3409: if ($name eq $item) {
3410: $javafiles{$item} = $attr->{'value'};
3411: last;
3412: }
3413: }
1.1164 raeburn 3414: my $pathfrom;
1.640 albertel 3415: foreach my $item (keys(%mediafiles)) {
3416: if ($name eq $item) {
1.1164 raeburn 3417: $pathfrom = $attr->{'value'};
3418: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3419: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3420: last;
3421: }
3422: }
1.1164 raeburn 3423: if ($name eq 'flashvars') {
3424: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3425: }
3426: if ($pathfrom ne '') {
3427: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3428: $pathfrom);
3429: }
1.640 albertel 3430: }
3431: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3432: foreach my $item (keys(%javafiles)) {
3433: if ($attr->{$item}) {
3434: $javafiles{$item} = $attr->{$item};
3435: last;
3436: }
3437: }
3438: foreach my $item (keys(%mediafiles)) {
3439: if ($attr->{$item}) {
3440: &add_filetype($allfiles,$attr->{$item},$item);
3441: last;
3442: }
3443: }
1.1164 raeburn 3444: if (lc($tagname) eq 'embed') {
3445: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3446: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3447: $attr->{'src'});
3448: }
3449: }
1.640 albertel 3450: }
1.1164 raeburn 3451: if ($t->[4] =~ m{/>$}) {
3452: pop(@state);
3453: }
1.640 albertel 3454: } elsif ($t->[0] eq 'E') {
3455: my ($tagname) = ($t->[1]);
3456: if ($javafiles{'codebase'} ne '') {
3457: $javafiles{'codebase'} .= '/';
3458: }
3459: if (lc($tagname) eq 'applet' ||
3460: lc($tagname) eq 'object' ||
3461: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3462: ) {
3463: foreach my $item (keys(%javafiles)) {
3464: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3465: my $file=$javafiles{'codebase'}.$javafiles{$item};
3466: &add_filetype($allfiles,$file,$item);
3467: }
3468: }
3469: }
3470: pop @state;
3471: }
3472: }
1.1164 raeburn 3473: foreach my $id (sort(keys(%flashvars))) {
3474: if ($shockwave{$id} ne '') {
3475: my @pairs = split(/\&/,$flashvars{$id});
3476: foreach my $pair (@pairs) {
3477: my ($key,$value) = split(/\=/,$pair);
3478: if ($key eq 'thumb') {
3479: &add_filetype($allfiles,$value,$key);
3480: } elsif ($key eq 'content') {
3481: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3482: my ($ext) = ($value =~ /\.([^.]+)$/);
3483: if ($ext ne '') {
3484: &add_filetype($allfiles,$path.$value,$ext);
3485: }
3486: }
3487: }
3488: }
3489: }
1.637 raeburn 3490: return 'ok';
3491: }
3492:
1.639 albertel 3493: sub add_filetype {
3494: my ($allfiles,$file,$type)=@_;
3495: if (exists($allfiles->{$file})) {
3496: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3497: push(@{$allfiles->{$file}}, &escape($type));
3498: }
3499: } else {
3500: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3501: }
3502: }
3503:
1.1164 raeburn 3504: sub embedded_dependency {
3505: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3506: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3507: if (($identifier ne '') &&
3508: (ref($related->{$identifier}) eq 'ARRAY') &&
3509: ($pathfrom ne '')) {
3510: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3511: foreach my $dep (@{$related->{$identifier}}) {
3512: &add_filetype($allfiles,$path.$dep,'object');
3513: }
3514: }
3515: }
3516: return;
3517: }
3518:
1.493 albertel 3519: sub removeuploadedurl {
1.984 neumanie 3520: my ($url)=@_;
3521: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3522: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3523: }
3524:
3525: sub removeuserfile {
3526: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3527: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3528: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3529: if ($result eq 'ok') {
1.798 raeburn 3530: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3531: my $metafile = $fname.'.meta';
3532: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3533: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3534: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3535: my $sqlresult =
1.823 albertel 3536: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3537: 'portfolio_metadata',$group,
3538: 'delete');
1.798 raeburn 3539: }
3540: }
3541: return $result;
1.257 www 3542: }
1.15 www 3543:
1.530 albertel 3544: sub mkdiruserfile {
3545: my ($docuname,$docudom,$dir)=@_;
3546: my $home=&homeserver($docuname,$docudom);
3547: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3548: }
3549:
1.531 albertel 3550: sub renameuserfile {
3551: my ($docuname,$docudom,$old,$new)=@_;
3552: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3553: my $result = &reply("renameuserfile:$docudom:$docuname:".
3554: &escape("$old").':'.&escape("$new"),$home);
3555: if ($result eq 'ok') {
3556: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3557: my $oldmeta = $old.'.meta';
3558: my $newmeta = $new.'.meta';
3559: my $metaresult =
3560: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3561: my $url = "/uploaded/$docudom/$docuname/$old";
3562: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3563: my $sqlresult =
1.823 albertel 3564: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3565: 'portfolio_metadata',$group,
3566: 'delete');
1.798 raeburn 3567: }
3568: }
3569: return $result;
1.531 albertel 3570: }
3571:
1.14 www 3572: # ------------------------------------------------------------------------- Log
3573:
3574: sub log {
3575: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3576: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3577: }
3578:
3579: # ------------------------------------------------------------------ Course Log
1.352 www 3580: #
3581: # This routine flushes several buffers of non-mission-critical nature
3582: #
1.157 www 3583:
3584: sub flushcourselogs {
1.352 www 3585: &logthis('Flushing log buffers');
3586: #
3587: # course logs
3588: # This is a log of all transactions in a course, which can be used
3589: # for data mining purposes
3590: #
3591: # It also collects the courseid database, which lists last transaction
3592: # times and course titles for all courseids
3593: #
3594: my %courseidbuffer=();
1.921 raeburn 3595: foreach my $crsid (keys(%courselogs)) {
1.352 www 3596: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3597: &escape($courselogs{$crsid}),
3598: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3599: delete $courselogs{$crsid};
3600: } else {
3601: &logthis('Failed to flush log buffer for '.$crsid);
3602: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3603: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3604: " exceeded maximum size, deleting.</font>");
3605: delete $courselogs{$crsid};
3606: }
1.352 www 3607: }
1.920 raeburn 3608: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3609: 'description' => $coursedescrbuf{$crsid},
3610: 'inst_code' => $courseinstcodebuf{$crsid},
3611: 'type' => $coursetypebuf{$crsid},
3612: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3613: };
1.191 harris41 3614: }
1.352 www 3615: #
3616: # Write course id database (reverse lookup) to homeserver of courses
3617: # Is used in pickcourse
3618: #
1.840 albertel 3619: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3620: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3621: $courseidbuffer{$crs_home},
3622: $crs_home,'timeonly');
1.352 www 3623: }
3624: #
3625: # File accesses
3626: # Writes to the dynamic metadata of resources to get hit counts, etc.
3627: #
1.449 matthew 3628: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3629: if ($entry =~ /___count$/) {
3630: my ($dom,$name);
1.807 albertel 3631: ($dom,$name,undef)=
1.811 albertel 3632: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3633: if (! defined($dom) || $dom eq '' ||
3634: ! defined($name) || $name eq '') {
1.620 albertel 3635: my $cid = $env{'request.course.id'};
3636: $dom = $env{'request.'.$cid.'.domain'};
3637: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3638: }
1.450 matthew 3639: my $value = $accesshash{$entry};
3640: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3641: my %temphash=($url => $value);
1.449 matthew 3642: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3643: if ($result eq 'ok') {
3644: delete $accesshash{$entry};
3645: }
3646: } else {
1.811 albertel 3647: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3648: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3649: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3650: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3651: delete $accesshash{$entry};
3652: }
1.185 www 3653: }
1.191 harris41 3654: }
1.352 www 3655: #
3656: # Roles
3657: # Reverse lookup of user roles for course faculty/staff and co-authorship
3658: #
1.800 albertel 3659: foreach my $entry (keys(%userrolehash)) {
1.351 www 3660: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3661: split(/\:/,$entry);
3662: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3663: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3664: $rudom,$runame) eq 'ok') {
3665: delete $userrolehash{$entry};
3666: }
3667: }
1.662 raeburn 3668: #
3669: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3670: #
3671: my %domrolebuffer = ();
1.1000 raeburn 3672: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3673: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3674: if ($domrolebuffer{$rudom}) {
3675: $domrolebuffer{$rudom}.='&'.&escape($entry).
3676: '='.&escape($domainrolehash{$entry});
3677: } else {
3678: $domrolebuffer{$rudom}.=&escape($entry).
3679: '='.&escape($domainrolehash{$entry});
3680: }
3681: delete $domainrolehash{$entry};
3682: }
3683: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3684: my %servers = &get_servers($dom,'library');
3685: foreach my $tryserver (keys(%servers)) {
3686: unless (&reply('domroleput:'.$dom.':'.
3687: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3688: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3689: }
1.662 raeburn 3690: }
3691: }
1.186 www 3692: $dumpcount++;
1.157 www 3693: }
3694:
3695: sub courselog {
3696: my $what=shift;
1.158 www 3697: $what=time.':'.$what;
1.620 albertel 3698: unless ($env{'request.course.id'}) { return ''; }
3699: $coursedombuf{$env{'request.course.id'}}=
3700: $env{'course.'.$env{'request.course.id'}.'.domain'};
3701: $coursenumbuf{$env{'request.course.id'}}=
3702: $env{'course.'.$env{'request.course.id'}.'.num'};
3703: $coursehombuf{$env{'request.course.id'}}=
3704: $env{'course.'.$env{'request.course.id'}.'.home'};
3705: $coursedescrbuf{$env{'request.course.id'}}=
3706: $env{'course.'.$env{'request.course.id'}.'.description'};
3707: $courseinstcodebuf{$env{'request.course.id'}}=
3708: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3709: $courseownerbuf{$env{'request.course.id'}}=
3710: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3711: $coursetypebuf{$env{'request.course.id'}}=
3712: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3713: if (defined $courselogs{$env{'request.course.id'}}) {
3714: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3715: } else {
1.620 albertel 3716: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3717: }
1.620 albertel 3718: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3719: &flushcourselogs();
3720: }
1.158 www 3721: }
3722:
3723: sub courseacclog {
3724: my $fnsymb=shift;
1.620 albertel 3725: unless ($env{'request.course.id'}) { return ''; }
3726: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3727: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3728: $what.=':POST';
1.583 matthew 3729: # FIXME: Probably ought to escape things....
1.800 albertel 3730: foreach my $key (keys(%env)) {
3731: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3732: my $formitem = $1;
3733: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3734: $what.=':'.$formitem.'='.$env{$key};
3735: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3736: $what.=':'.$formitem.'='.$env{$key};
3737: }
1.158 www 3738: }
1.191 harris41 3739: }
1.583 matthew 3740: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3741: # FIXME: We should not be depending on a form parameter that someone
3742: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3743: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3744: $what.= ':POST';
3745: # FIXME: Probably ought to escape things....
3746: foreach my $element ('courseexp','crsfulltext','crsrelated',
3747: 'crsdiscuss') {
1.620 albertel 3748: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3749: }
3750: }
1.158 www 3751: }
3752: &courselog($what);
1.149 www 3753: }
3754:
1.185 www 3755: sub countacc {
3756: my $url=&declutter(shift);
1.458 matthew 3757: return if (! defined($url) || $url eq '');
1.620 albertel 3758: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3759: #
3760: # Mark that this url was used in this course
3761: #
1.620 albertel 3762: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3763: #
3764: # Increase the access count for this resource in this child process
3765: #
1.281 www 3766: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3767: $accesshash{$key}++;
1.185 www 3768: }
1.349 www 3769:
1.361 www 3770: sub linklog {
3771: my ($from,$to)=@_;
3772: $from=&declutter($from);
3773: $to=&declutter($to);
3774: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3775: $accesshash{$to.'___'.$from.'___goto'}=1;
3776: }
1.1160 www 3777:
3778: sub statslog {
3779: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3780: if ($users<2) { return; }
3781: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3782: 'course' => $env{'request.course.id'},
3783: 'sections' => '"all"',
3784: 'num_students' => $users,
3785: 'part' => $part,
3786: 'symb' => $symb,
3787: 'mean_tries' => $av_attempts,
3788: 'deg_of_diff' => $degdiff});
3789: foreach my $key (keys(%dynstore)) {
3790: $accesshash{$key}=$dynstore{$key};
3791: }
3792: }
1.361 www 3793:
1.349 www 3794: sub userrolelog {
3795: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3796: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3797: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3798: $userrolehash
3799: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3800: =$tend.':'.$tstart;
1.662 raeburn 3801: }
1.1169 droeschl 3802: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3803: $userrolehash
3804: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3805: =$tend.':'.$tstart;
3806: }
1.1169 droeschl 3807: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3808: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3809: $domainrolehash
3810: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3811: = $tend.':'.$tstart;
3812: }
1.351 www 3813: }
3814:
1.957 raeburn 3815: sub courserolelog {
3816: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3817: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3818: my $cdom = $1;
3819: my $cnum = $2;
3820: my $sec = $3;
3821: my $namespace = 'rolelog';
3822: my %storehash = (
3823: role => $trole,
3824: start => $tstart,
3825: end => $tend,
3826: selfenroll => $selfenroll,
3827: context => $context,
3828: );
3829: if ($trole eq 'gr') {
3830: $namespace = 'groupslog';
3831: $storehash{'group'} = $sec;
3832: } else {
3833: $storehash{'section'} = $sec;
3834: }
3835: &write_log('course',$namespace,\%storehash,$delflag,$username,
3836: $domain,$cnum,$cdom);
3837: if (($trole ne 'st') || ($sec ne '')) {
3838: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3839: }
3840: }
3841: return;
3842: }
3843:
1.1172.2.9 raeburn 3844: sub domainrolelog {
3845: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3846: if ($area =~ m{^/($match_domain)/$}) {
3847: my $cdom = $1;
3848: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3849: my $namespace = 'rolelog';
3850: my %storehash = (
3851: role => $trole,
3852: start => $tstart,
3853: end => $tend,
3854: context => $context,
3855: );
3856: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3857: $domain,$domconfiguser,$cdom);
3858: }
3859: return;
3860:
3861: }
3862:
3863: sub coauthorrolelog {
3864: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3865: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3866: my $audom = $1;
3867: my $auname = $2;
3868: my $namespace = 'rolelog';
3869: my %storehash = (
3870: role => $trole,
3871: start => $tstart,
3872: end => $tend,
3873: context => $context,
3874: );
3875: &write_log('author',$namespace,\%storehash,$delflag,$username,
3876: $domain,$auname,$audom);
3877: }
3878: return;
3879: }
3880:
1.351 www 3881: sub get_course_adv_roles {
1.948 raeburn 3882: my ($cid,$codes) = @_;
1.620 albertel 3883: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3884: my %coursehash=&coursedescription($cid);
1.988 raeburn 3885: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3886: my %nothide=();
1.800 albertel 3887: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3888: if ($user !~ /:/) {
3889: $nothide{join(':',split(/[\@]/,$user))}=1;
3890: } else {
3891: $nothide{$user}=1;
3892: }
1.470 www 3893: }
1.1172.2.23 raeburn 3894: my @possdoms = ($coursehash{'domain'});
3895: if ($coursehash{'checkforpriv'}) {
3896: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3897: }
1.351 www 3898: my %returnhash=();
3899: my %dumphash=
3900: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3901: my $now=time;
1.997 raeburn 3902: my %privileged;
1.1000 raeburn 3903: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3904: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3905: if (($tstart) && ($tstart<0)) { next; }
3906: if (($tend) && ($tend<$now)) { next; }
3907: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3908: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3909: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 3910: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 3911: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3912: if ($role eq 'cr') { next; }
1.948 raeburn 3913: if ($codes) {
3914: if ($section) { $role .= ':'.$section; }
3915: if ($returnhash{$role}) {
3916: $returnhash{$role}.=','.$username.':'.$domain;
3917: } else {
3918: $returnhash{$role}=$username.':'.$domain;
3919: }
1.351 www 3920: } else {
1.988 raeburn 3921: my $key=&plaintext($role,$crstype);
1.973 bisitz 3922: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3923: if ($returnhash{$key}) {
3924: $returnhash{$key}.=','.$username.':'.$domain;
3925: } else {
3926: $returnhash{$key}=$username.':'.$domain;
3927: }
1.351 www 3928: }
1.948 raeburn 3929: }
1.400 www 3930: return %returnhash;
3931: }
3932:
3933: sub get_my_roles {
1.937 raeburn 3934: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3935: unless (defined($uname)) { $uname=$env{'user.name'}; }
3936: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3937: my (%dumphash,%nothide);
1.1086 raeburn 3938: if ($context eq 'userroles') {
1.1166 raeburn 3939: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 3940: } else {
1.1172.2.23 raeburn 3941: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3942: if ($hidepriv) {
3943: my %coursehash=&coursedescription($udom.'_'.$uname);
3944: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3945: if ($user !~ /:/) {
3946: $nothide{join(':',split(/[\@]/,$user))} = 1;
3947: } else {
3948: $nothide{$user} = 1;
3949: }
3950: }
3951: }
1.858 raeburn 3952: }
1.400 www 3953: my %returnhash=();
3954: my $now=time;
1.999 raeburn 3955: my %privileged;
1.800 albertel 3956: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3957: my ($role,$tend,$tstart);
3958: if ($context eq 'userroles') {
1.1149 raeburn 3959: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3960: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3961: } else {
3962: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3963: }
1.400 www 3964: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3965: my $status = 'active';
1.939 raeburn 3966: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3967: $status = 'previous';
3968: }
3969: if (($tstart) && ($now<$tstart)) {
3970: $status = 'future';
3971: }
3972: if (ref($types) eq 'ARRAY') {
3973: if (!grep(/^\Q$status\E$/,@{$types})) {
3974: next;
3975: }
3976: } else {
3977: if ($status ne 'active') {
3978: next;
3979: }
3980: }
1.867 raeburn 3981: my ($rolecode,$username,$domain,$section,$area);
3982: if ($context eq 'userroles') {
1.1172.2.9 raeburn 3983: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 3984: (undef,$domain,$username,$section) = split(/\//,$area);
3985: } else {
3986: ($role,$username,$domain,$section) = split(/\:/,$entry);
3987: }
1.832 raeburn 3988: if (ref($roledoms) eq 'ARRAY') {
3989: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3990: next;
3991: }
3992: }
3993: if (ref($roles) eq 'ARRAY') {
3994: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3995: if ($role =~ /^cr\//) {
3996: if (!grep(/^cr$/,@{$roles})) {
3997: next;
3998: }
1.1104 raeburn 3999: } elsif ($role =~ /^gr\//) {
4000: if (!grep(/^gr$/,@{$roles})) {
4001: next;
4002: }
1.922 raeburn 4003: } else {
4004: next;
4005: }
1.832 raeburn 4006: }
1.867 raeburn 4007: }
1.937 raeburn 4008: if ($hidepriv) {
1.1172.2.23 raeburn 4009: my @privroles = ('dc','su');
1.999 raeburn 4010: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4011: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4012: } else {
1.1172.2.23 raeburn 4013: my $possdoms = [$domain];
4014: if (ref($roledoms) eq 'ARRAY') {
4015: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4016: }
1.1172.2.23 raeburn 4017: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4018: if (!$nothide{$username.':'.$domain}) {
4019: next;
4020: }
4021: }
1.937 raeburn 4022: }
4023: }
1.933 raeburn 4024: if ($withsec) {
4025: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4026: $tstart.':'.$tend;
4027: } else {
4028: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4029: }
1.832 raeburn 4030: }
1.373 www 4031: return %returnhash;
1.399 www 4032: }
4033:
4034: # ----------------------------------------------------- Frontpage Announcements
4035: #
4036: #
4037:
4038: sub postannounce {
4039: my ($server,$text)=@_;
1.844 albertel 4040: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4041: unless ($text=~/\w/) { $text=''; }
4042: return &reply('setannounce:'.&escape($text),$server);
4043: }
4044:
4045: sub getannounce {
1.448 albertel 4046:
4047: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4048: my $announcement='';
1.800 albertel 4049: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4050: close($fh);
1.399 www 4051: if ($announcement=~/\w/) {
4052: return
4053: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4054: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4055: } else {
4056: return '';
4057: }
4058: } else {
4059: return '';
4060: }
1.351 www 4061: }
1.353 www 4062:
4063: # ---------------------------------------------------------- Course ID routines
4064: # Deal with domain's nohist_courseid.db files
4065: #
4066:
4067: sub courseidput {
1.921 raeburn 4068: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4069: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4070: my $outcome;
4071: if ($caller eq 'timeonly') {
4072: my $cids = '';
4073: foreach my $item (keys(%$storehash)) {
4074: $cids.=&escape($item).'&';
4075: }
4076: $cids=~s/\&$//;
4077: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4078: $coursehome);
4079: } else {
4080: my $items = '';
4081: foreach my $item (keys(%$storehash)) {
4082: $items.= &escape($item).'='.
4083: &freeze_escape($$storehash{$item}).'&';
4084: }
4085: $items=~s/\&$//;
4086: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4087: $coursehome);
1.918 raeburn 4088: }
4089: if ($outcome eq 'unknown_cmd') {
4090: my $what;
4091: foreach my $cid (keys(%$storehash)) {
4092: $what .= &escape($cid).'=';
1.921 raeburn 4093: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4094: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4095: }
4096: $what =~ s/\:$/&/;
4097: }
4098: $what =~ s/\&$//;
4099: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4100: } else {
4101: return $outcome;
4102: }
1.353 www 4103: }
4104:
4105: sub courseiddump {
1.921 raeburn 4106: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4107: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4108: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 4109: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 4110: my $as_hash = 1;
4111: my %returnhash;
4112: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4113: my %libserv = &all_library();
4114: foreach my $tryserver (keys(%libserv)) {
4115: if ( ( $hostidflag == 1
4116: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4117: || (!defined($hostidflag)) ) {
4118:
1.918 raeburn 4119: if (($domfilter eq '') ||
4120: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4121: my $rep;
4122: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4123: $rep = &LONCAPA::Lond::dump_course_id_handler(
4124: join(":", (&host_domain($tryserver), $sincefilter,
4125: &escape($descfilter), &escape($instcodefilter),
4126: &escape($ownerfilter), &escape($coursefilter),
4127: &escape($typefilter), &escape($regexp_ok),
4128: $as_hash, &escape($selfenrollonly),
4129: &escape($catfilter), $showhidden, $caller,
4130: &escape($cloner), &escape($cc_clone), $cloneonly,
4131: &escape($createdbefore), &escape($createdafter),
4132: &escape($creationcontext), $domcloner)));
4133: } else {
4134: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4135: $sincefilter.':'.&escape($descfilter).':'.
4136: &escape($instcodefilter).':'.&escape($ownerfilter).
4137: ':'.&escape($coursefilter).':'.&escape($typefilter).
4138: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4139: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4140: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4141: &escape($cc_clone).':'.$cloneonly.':'.
4142: &escape($createdbefore).':'.&escape($createdafter).':'.
4143: &escape($creationcontext).':'.$domcloner,
4144: $tryserver);
4145: }
4146:
1.918 raeburn 4147: my @pairs=split(/\&/,$rep);
4148: foreach my $item (@pairs) {
4149: my ($key,$value)=split(/\=/,$item,2);
4150: $key = &unescape($key);
4151: next if ($key =~ /^error: 2 /);
4152: my $result = &thaw_unescape($value);
4153: if (ref($result) eq 'HASH') {
4154: $returnhash{$key}=$result;
4155: } else {
1.921 raeburn 4156: my @responses = split(/:/,$value);
4157: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4158: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4159: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4160: }
1.1008 raeburn 4161: }
1.353 www 4162: }
4163: }
4164: }
4165: }
4166: return %returnhash;
4167: }
4168:
1.1055 raeburn 4169: sub courselastaccess {
4170: my ($cdom,$cnum,$hostidref) = @_;
4171: my %returnhash;
4172: if ($cdom && $cnum) {
4173: my $chome = &homeserver($cnum,$cdom);
4174: if ($chome ne 'no_host') {
4175: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4176: &extract_lastaccess(\%returnhash,$rep);
4177: }
4178: } else {
4179: if (!$cdom) { $cdom=''; }
4180: my %libserv = &all_library();
4181: foreach my $tryserver (keys(%libserv)) {
4182: if (ref($hostidref) eq 'ARRAY') {
4183: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4184: }
4185: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4186: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4187: &extract_lastaccess(\%returnhash,$rep);
4188: }
4189: }
4190: }
4191: return %returnhash;
4192: }
4193:
4194: sub extract_lastaccess {
4195: my ($returnhash,$rep) = @_;
4196: if (ref($returnhash) eq 'HASH') {
4197: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4198: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4199: $rep eq '') {
4200: my @pairs=split(/\&/,$rep);
4201: foreach my $item (@pairs) {
4202: my ($key,$value)=split(/\=/,$item,2);
4203: $key = &unescape($key);
4204: next if ($key =~ /^error: 2 /);
4205: $returnhash->{$key} = &thaw_unescape($value);
4206: }
4207: }
4208: }
4209: return;
4210: }
4211:
1.658 raeburn 4212: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4213:
4214: sub dcmailput {
1.685 raeburn 4215: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4216: my $status = &Apache::lonnet::critical(
1.740 www 4217: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4218: &escape($message),$server);
1.662 raeburn 4219: return $status;
4220: }
4221:
1.658 raeburn 4222: sub dcmaildump {
4223: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4224: my %returnhash=();
1.846 albertel 4225:
4226: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4227: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4228: &escape($enddate).':';
4229: my @esc_senders=map { &escape($_)} @$senders;
4230: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4231: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4232: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4233: if (($key) && ($value)) {
4234: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4235: }
4236: }
4237: }
4238: return %returnhash;
4239: }
1.662 raeburn 4240: # ---------------------------------------------------------- Domain roles
4241:
4242: sub get_domain_roles {
4243: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4244: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4245: $startdate = '.';
4246: }
1.1018 raeburn 4247: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4248: $enddate = '.';
4249: }
1.922 raeburn 4250: my $rolelist;
4251: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4252: $rolelist = join('&',@{$roles});
1.922 raeburn 4253: }
1.662 raeburn 4254: my %personnel = ();
1.841 albertel 4255:
4256: my %servers = &get_servers($dom,'library');
4257: foreach my $tryserver (keys(%servers)) {
4258: %{$personnel{$tryserver}}=();
4259: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4260: &escape($startdate).':'.
4261: &escape($enddate).':'.
4262: &escape($rolelist), $tryserver))) {
4263: my ($key,$value) = split(/\=/,$line,2);
4264: if (($key) && ($value)) {
4265: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4266: }
4267: }
1.662 raeburn 4268: }
4269: return %personnel;
4270: }
1.658 raeburn 4271:
1.1057 www 4272: # ----------------------------------------------------------- Interval timing
1.149 www 4273:
1.1153 www 4274: {
4275: # Caches needed for speedup of navmaps
4276: # We don't want to cache this for very long at all (5 seconds at most)
4277: #
4278: # The user for whom we cache
4279: my $cachedkey='';
4280: # The cached times for this user
4281: my %cachedtimes=();
4282: # When this was last done
4283: my $cachedtime=();
4284:
4285: sub load_all_first_access {
1.1154 raeburn 4286: my ($uname,$udom)=@_;
1.1156 www 4287: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4288: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4289: return;
4290: }
4291: $cachedtime=time;
4292: $cachedkey=$uname.':'.$udom;
4293: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4294: }
4295:
1.504 albertel 4296: sub get_first_access {
1.1162 raeburn 4297: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4298: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4299: if ($argsymb) { $symb=$argsymb; }
4300: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4301: if ($argmap) { $map = $argmap; }
1.926 albertel 4302: if ($type eq 'course') {
4303: $res='course';
4304: } elsif ($type eq 'map') {
1.588 albertel 4305: $res=&symbread($map);
4306: } else {
4307: $res=$symb;
4308: }
1.1153 www 4309: &load_all_first_access($uname,$udom);
4310: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4311: }
4312:
4313: sub set_first_access {
1.1162 raeburn 4314: my ($type,$interval)=@_;
1.790 albertel 4315: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4316: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4317: if ($type eq 'course') {
4318: $res='course';
4319: } elsif ($type eq 'map') {
1.588 albertel 4320: $res=&symbread($map);
4321: } else {
4322: $res=$symb;
4323: }
1.1153 www 4324: $cachedkey='';
1.1162 raeburn 4325: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4326: if (!$firstaccess) {
1.1162 raeburn 4327: my $start = time;
4328: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4329: $udom,$uname);
4330: if ($putres eq 'ok') {
4331: &put('timerinterval',{"$courseid\0$res"=>$interval},
4332: $udom,$uname);
4333: &appenv(
4334: {
4335: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4336: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4337: }
4338: );
4339: }
4340: return $putres;
1.505 albertel 4341: }
4342: return 'already_set';
1.504 albertel 4343: }
1.1153 www 4344: }
1.110 www 4345: # --------------------------------------------- Set Expire Date for Spreadsheet
4346:
4347: sub expirespread {
4348: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4349: my $cid=$env{'request.course.id'};
1.110 www 4350: if ($cid) {
4351: my $now=time;
4352: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4353: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4354: $env{'course.'.$cid.'.num'}.
1.110 www 4355: ':nohist_expirationdates:'.
4356: &escape($key).'='.$now,
1.620 albertel 4357: $env{'course.'.$cid.'.home'})
1.110 www 4358: }
4359: return 'ok';
1.14 www 4360: }
4361:
1.109 www 4362: # ----------------------------------------------------- Devalidate Spreadsheets
4363:
4364: sub devalidate {
1.325 www 4365: my ($symb,$uname,$udom)=@_;
1.620 albertel 4366: my $cid=$env{'request.course.id'};
1.109 www 4367: if ($cid) {
1.391 matthew 4368: # delete the stored spreadsheets for
4369: # - the student level sheet of this user in course's homespace
4370: # - the assessment level sheet for this resource
4371: # for this user in user's homespace
1.553 albertel 4372: # - current conditional state info
1.325 www 4373: my $key=$uname.':'.$udom.':';
1.109 www 4374: my $status=
1.299 matthew 4375: &del('nohist_calculatedsheets',
1.391 matthew 4376: [$key.'studentcalc:'],
1.620 albertel 4377: $env{'course.'.$cid.'.domain'},
4378: $env{'course.'.$cid.'.num'})
1.133 albertel 4379: .' '.
4380: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4381: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4382: unless ($status eq 'ok ok') {
4383: &logthis('Could not devalidate spreadsheet '.
1.325 www 4384: $uname.' at '.$udom.' for '.
1.109 www 4385: $symb.': '.$status);
1.133 albertel 4386: }
1.553 albertel 4387: &delenv('user.state.'.$cid);
1.109 www 4388: }
4389: }
4390:
1.265 albertel 4391: sub get_scalar {
4392: my ($string,$end) = @_;
4393: my $value;
4394: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4395: $value = $1;
4396: } elsif ($$string =~ s/^([^&]*?)&//) {
4397: $value = $1;
4398: }
4399: return &unescape($value);
4400: }
4401:
4402: sub array2str {
4403: my (@array) = @_;
4404: my $result=&arrayref2str(\@array);
4405: $result=~s/^__ARRAY_REF__//;
4406: $result=~s/__END_ARRAY_REF__$//;
4407: return $result;
4408: }
4409:
1.204 albertel 4410: sub arrayref2str {
4411: my ($arrayref) = @_;
1.265 albertel 4412: my $result='__ARRAY_REF__';
1.204 albertel 4413: foreach my $elem (@$arrayref) {
1.265 albertel 4414: if(ref($elem) eq 'ARRAY') {
4415: $result.=&arrayref2str($elem).'&';
4416: } elsif(ref($elem) eq 'HASH') {
4417: $result.=&hashref2str($elem).'&';
4418: } elsif(ref($elem)) {
4419: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4420: } else {
4421: $result.=&escape($elem).'&';
4422: }
4423: }
4424: $result=~s/\&$//;
1.265 albertel 4425: $result .= '__END_ARRAY_REF__';
1.204 albertel 4426: return $result;
4427: }
4428:
1.168 albertel 4429: sub hash2str {
1.204 albertel 4430: my (%hash) = @_;
4431: my $result=&hashref2str(\%hash);
1.265 albertel 4432: $result=~s/^__HASH_REF__//;
4433: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4434: return $result;
4435: }
4436:
4437: sub hashref2str {
4438: my ($hashref)=@_;
1.265 albertel 4439: my $result='__HASH_REF__';
1.800 albertel 4440: foreach my $key (sort(keys(%$hashref))) {
4441: if (ref($key) eq 'ARRAY') {
4442: $result.=&arrayref2str($key).'=';
4443: } elsif (ref($key) eq 'HASH') {
4444: $result.=&hashref2str($key).'=';
4445: } elsif (ref($key)) {
1.265 albertel 4446: $result.='=';
1.800 albertel 4447: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4448: } else {
1.1132 raeburn 4449: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4450: }
4451:
1.800 albertel 4452: if(ref($hashref->{$key}) eq 'ARRAY') {
4453: $result.=&arrayref2str($hashref->{$key}).'&';
4454: } elsif(ref($hashref->{$key}) eq 'HASH') {
4455: $result.=&hashref2str($hashref->{$key}).'&';
4456: } elsif(ref($hashref->{$key})) {
1.265 albertel 4457: $result.='&';
1.800 albertel 4458: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4459: } else {
1.800 albertel 4460: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4461: }
4462: }
1.168 albertel 4463: $result=~s/\&$//;
1.265 albertel 4464: $result .= '__END_HASH_REF__';
1.168 albertel 4465: return $result;
4466: }
4467:
4468: sub str2hash {
1.265 albertel 4469: my ($string)=@_;
4470: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4471: return %$hash;
4472: }
4473:
4474: sub str2hashref {
1.168 albertel 4475: my ($string) = @_;
1.265 albertel 4476:
4477: my %hash;
4478:
4479: if($string !~ /^__HASH_REF__/) {
4480: if (! ($string eq '' || !defined($string))) {
4481: $hash{'error'}='Not hash reference';
4482: }
4483: return (\%hash, $string);
4484: }
4485:
4486: $string =~ s/^__HASH_REF__//;
4487:
4488: while($string !~ /^__END_HASH_REF__/) {
4489: #key
4490: my $key='';
4491: if($string =~ /^__HASH_REF__/) {
4492: ($key, $string)=&str2hashref($string);
4493: if(defined($key->{'error'})) {
4494: $hash{'error'}='Bad data';
4495: return (\%hash, $string);
4496: }
4497: } elsif($string =~ /^__ARRAY_REF__/) {
4498: ($key, $string)=&str2arrayref($string);
4499: if($key->[0] eq 'Array reference error') {
4500: $hash{'error'}='Bad data';
4501: return (\%hash, $string);
4502: }
4503: } else {
4504: $string =~ s/^(.*?)=//;
1.267 albertel 4505: $key=&unescape($1);
1.265 albertel 4506: }
4507: $string =~ s/^=//;
4508:
4509: #value
4510: my $value='';
4511: if($string =~ /^__HASH_REF__/) {
4512: ($value, $string)=&str2hashref($string);
4513: if(defined($value->{'error'})) {
4514: $hash{'error'}='Bad data';
4515: return (\%hash, $string);
4516: }
4517: } elsif($string =~ /^__ARRAY_REF__/) {
4518: ($value, $string)=&str2arrayref($string);
4519: if($value->[0] eq 'Array reference error') {
4520: $hash{'error'}='Bad data';
4521: return (\%hash, $string);
4522: }
4523: } else {
4524: $value=&get_scalar(\$string,'__END_HASH_REF__');
4525: }
4526: $string =~ s/^&//;
4527:
4528: $hash{$key}=$value;
1.204 albertel 4529: }
1.265 albertel 4530:
4531: $string =~ s/^__END_HASH_REF__//;
4532:
4533: return (\%hash, $string);
1.204 albertel 4534: }
4535:
4536: sub str2array {
1.265 albertel 4537: my ($string)=@_;
4538: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4539: return @$array;
4540: }
4541:
4542: sub str2arrayref {
1.204 albertel 4543: my ($string) = @_;
1.265 albertel 4544: my @array;
4545:
4546: if($string !~ /^__ARRAY_REF__/) {
4547: if (! ($string eq '' || !defined($string))) {
4548: $array[0]='Array reference error';
4549: }
4550: return (\@array, $string);
4551: }
4552:
4553: $string =~ s/^__ARRAY_REF__//;
4554:
4555: while($string !~ /^__END_ARRAY_REF__/) {
4556: my $value='';
4557: if($string =~ /^__HASH_REF__/) {
4558: ($value, $string)=&str2hashref($string);
4559: if(defined($value->{'error'})) {
4560: $array[0] ='Array reference error';
4561: return (\@array, $string);
4562: }
4563: } elsif($string =~ /^__ARRAY_REF__/) {
4564: ($value, $string)=&str2arrayref($string);
4565: if($value->[0] eq 'Array reference error') {
4566: $array[0] ='Array reference error';
4567: return (\@array, $string);
4568: }
4569: } else {
4570: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4571: }
4572: $string =~ s/^&//;
4573:
4574: push(@array, $value);
1.191 harris41 4575: }
1.265 albertel 4576:
4577: $string =~ s/^__END_ARRAY_REF__//;
4578:
4579: return (\@array, $string);
1.168 albertel 4580: }
4581:
1.167 albertel 4582: # -------------------------------------------------------------------Temp Store
4583:
1.168 albertel 4584: sub tmpreset {
4585: my ($symb,$namespace,$domain,$stuname) = @_;
4586: if (!$symb) {
4587: $symb=&symbread();
1.620 albertel 4588: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4589: }
4590: $symb=escape($symb);
4591:
1.620 albertel 4592: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4593: $namespace=~s/\//\_/g;
4594: $namespace=~s/\W//g;
4595:
1.620 albertel 4596: if (!$domain) { $domain=$env{'user.domain'}; }
4597: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4598: if ($domain eq 'public' && $stuname eq 'public') {
4599: $stuname=$ENV{'REMOTE_ADDR'};
4600: }
1.1117 foxr 4601: my $path=LONCAPA::tempdir();
1.168 albertel 4602: my %hash;
4603: if (tie(%hash,'GDBM_File',
4604: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4605: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4606: foreach my $key (keys(%hash)) {
1.180 albertel 4607: if ($key=~ /:$symb/) {
1.168 albertel 4608: delete($hash{$key});
4609: }
4610: }
4611: }
4612: }
4613:
1.167 albertel 4614: sub tmpstore {
1.168 albertel 4615: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4616:
4617: if (!$symb) {
4618: $symb=&symbread();
1.620 albertel 4619: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4620: }
4621: $symb=escape($symb);
4622:
4623: if (!$namespace) {
4624: # I don't think we would ever want to store this for a course.
4625: # it seems this will only be used if we don't have a course.
1.620 albertel 4626: #$namespace=$env{'request.course.id'};
1.168 albertel 4627: #if (!$namespace) {
1.620 albertel 4628: $namespace=$env{'request.state'};
1.168 albertel 4629: #}
4630: }
4631: $namespace=~s/\//\_/g;
4632: $namespace=~s/\W//g;
1.620 albertel 4633: if (!$domain) { $domain=$env{'user.domain'}; }
4634: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4635: if ($domain eq 'public' && $stuname eq 'public') {
4636: $stuname=$ENV{'REMOTE_ADDR'};
4637: }
1.168 albertel 4638: my $now=time;
4639: my %hash;
1.1117 foxr 4640: my $path=LONCAPA::tempdir();
1.168 albertel 4641: if (tie(%hash,'GDBM_File',
4642: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4643: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4644: $hash{"version:$symb"}++;
4645: my $version=$hash{"version:$symb"};
4646: my $allkeys='';
4647: foreach my $key (keys(%$storehash)) {
4648: $allkeys.=$key.':';
1.591 albertel 4649: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4650: }
4651: $hash{"$version:$symb:timestamp"}=$now;
4652: $allkeys.='timestamp';
4653: $hash{"$version:keys:$symb"}=$allkeys;
4654: if (untie(%hash)) {
4655: return 'ok';
4656: } else {
4657: return "error:$!";
4658: }
4659: } else {
4660: return "error:$!";
4661: }
4662: }
1.167 albertel 4663:
1.168 albertel 4664: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4665:
1.168 albertel 4666: sub tmprestore {
4667: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4668:
1.168 albertel 4669: if (!$symb) {
4670: $symb=&symbread();
1.620 albertel 4671: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4672: }
4673: $symb=escape($symb);
4674:
1.620 albertel 4675: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4676:
1.620 albertel 4677: if (!$domain) { $domain=$env{'user.domain'}; }
4678: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4679: if ($domain eq 'public' && $stuname eq 'public') {
4680: $stuname=$ENV{'REMOTE_ADDR'};
4681: }
1.168 albertel 4682: my %returnhash;
4683: $namespace=~s/\//\_/g;
4684: $namespace=~s/\W//g;
4685: my %hash;
1.1117 foxr 4686: my $path=LONCAPA::tempdir();
1.168 albertel 4687: if (tie(%hash,'GDBM_File',
4688: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4689: &GDBM_READER(),0640)) {
1.168 albertel 4690: my $version=$hash{"version:$symb"};
4691: $returnhash{'version'}=$version;
4692: my $scope;
4693: for ($scope=1;$scope<=$version;$scope++) {
4694: my $vkeys=$hash{"$scope:keys:$symb"};
4695: my @keys=split(/:/,$vkeys);
4696: my $key;
4697: $returnhash{"$scope:keys"}=$vkeys;
4698: foreach $key (@keys) {
1.591 albertel 4699: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4700: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4701: }
4702: }
1.168 albertel 4703: if (!(untie(%hash))) {
4704: return "error:$!";
4705: }
4706: } else {
4707: return "error:$!";
4708: }
4709: return %returnhash;
1.167 albertel 4710: }
4711:
1.9 www 4712: # ----------------------------------------------------------------------- Store
4713:
4714: sub store {
1.124 www 4715: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4716: my $home='';
4717:
1.168 albertel 4718: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4719:
1.213 www 4720: $symb=&symbclean($symb);
1.122 albertel 4721: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4722:
1.620 albertel 4723: if (!$domain) { $domain=$env{'user.domain'}; }
4724: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4725:
4726: &devalidate($symb,$stuname,$domain);
1.109 www 4727:
4728: $symb=escape($symb);
1.187 www 4729: if (!$namespace) {
1.620 albertel 4730: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4731: return '';
4732: }
4733: }
1.620 albertel 4734: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4735:
4736: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4737: $$storehash{'host'}=$perlvar{'lonHostID'};
4738:
1.12 www 4739: my $namevalue='';
1.800 albertel 4740: foreach my $key (keys(%$storehash)) {
4741: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4742: }
1.12 www 4743: $namevalue=~s/\&$//;
1.187 www 4744: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4745: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4746: }
4747:
1.47 www 4748: # -------------------------------------------------------------- Critical Store
4749:
4750: sub cstore {
1.124 www 4751: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4752: my $home='';
4753:
1.168 albertel 4754: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4755:
1.213 www 4756: $symb=&symbclean($symb);
1.122 albertel 4757: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4758:
1.620 albertel 4759: if (!$domain) { $domain=$env{'user.domain'}; }
4760: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4761:
4762: &devalidate($symb,$stuname,$domain);
1.109 www 4763:
4764: $symb=escape($symb);
1.187 www 4765: if (!$namespace) {
1.620 albertel 4766: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4767: return '';
4768: }
4769: }
1.620 albertel 4770: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4771:
4772: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4773: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4774:
1.47 www 4775: my $namevalue='';
1.800 albertel 4776: foreach my $key (keys(%$storehash)) {
4777: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4778: }
1.47 www 4779: $namevalue=~s/\&$//;
1.187 www 4780: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4781: return critical
4782: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4783: }
4784:
1.9 www 4785: # --------------------------------------------------------------------- Restore
4786:
4787: sub restore {
1.124 www 4788: my ($symb,$namespace,$domain,$stuname) = @_;
4789: my $home='';
4790:
1.168 albertel 4791: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4792:
1.122 albertel 4793: if (!$symb) {
1.1172.2.26 raeburn 4794: return if ($namespace eq 'courserequests');
4795: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4796: } else {
1.1172.2.26 raeburn 4797: unless ($namespace eq 'courserequests') {
4798: $symb=&escape(&symbclean($symb));
4799: }
1.122 albertel 4800: }
1.188 www 4801: if (!$namespace) {
1.620 albertel 4802: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4803: return '';
4804: }
4805: }
1.620 albertel 4806: if (!$domain) { $domain=$env{'user.domain'}; }
4807: if (!$stuname) { $stuname=$env{'user.name'}; }
4808: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4809: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4810:
1.12 www 4811: my %returnhash=();
1.800 albertel 4812: foreach my $line (split(/\&/,$answer)) {
4813: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4814: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4815: }
1.75 www 4816: my $version;
4817: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4818: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4819: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4820: }
1.75 www 4821: }
1.13 www 4822: return %returnhash;
1.34 www 4823: }
4824:
4825: # ---------------------------------------------------------- Course Description
1.1118 foxr 4826: #
4827: #
1.34 www 4828:
4829: sub coursedescription {
1.731 albertel 4830: my ($courseid,$args)=@_;
1.34 www 4831: $courseid=~s/^\///;
1.49 www 4832: $courseid=~s/\_/\//g;
1.34 www 4833: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4834: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4835: my $normalid=$cdomain.'_'.$cnum;
4836: # need to always cache even if we get errors otherwise we keep
4837: # trying and trying and trying to get the course description.
4838: my %envhash=();
4839: my %returnhash=();
1.731 albertel 4840:
4841: my $expiretime=600;
4842: if ($env{'request.course.id'} eq $normalid) {
4843: $expiretime=120;
4844: }
4845:
4846: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4847: if (!$args->{'freshen_cache'}
4848: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4849: foreach my $key (keys(%env)) {
4850: next if ($key !~ /^\Q$prefix\E(.*)/);
4851: my ($setting) = $1;
4852: $returnhash{$setting} = $env{$key};
4853: }
4854: return %returnhash;
4855: }
4856:
1.1118 foxr 4857: # get the data again
4858:
1.731 albertel 4859: if (!$args->{'one_time'}) {
4860: $envhash{'course.'.$normalid.'.last_cache'}=time;
4861: }
1.811 albertel 4862:
1.34 www 4863: if ($chome ne 'no_host') {
1.302 albertel 4864: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4865: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4866: my $username = $env{'user.name'}; # Defult username
4867: if(defined $args->{'user'}) {
4868: $username = $args->{'user'};
4869: }
1.129 albertel 4870: $returnhash{'home'}= $chome;
4871: $returnhash{'domain'} = $cdomain;
4872: $returnhash{'num'} = $cnum;
1.741 raeburn 4873: if (!defined($returnhash{'type'})) {
4874: $returnhash{'type'} = 'Course';
4875: }
1.130 albertel 4876: while (my ($name,$value) = each %returnhash) {
1.53 www 4877: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4878: }
1.270 www 4879: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4880: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4881: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4882: $envhash{'course.'.$normalid.'.home'}=$chome;
4883: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4884: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4885: }
4886: }
1.731 albertel 4887: if (!$args->{'one_time'}) {
1.949 raeburn 4888: &appenv(\%envhash);
1.731 albertel 4889: }
1.302 albertel 4890: return %returnhash;
1.461 www 4891: }
4892:
1.1080 raeburn 4893: sub update_released_required {
4894: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4895: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4896: $cid = $env{'request.course.id'};
4897: $cdom = $env{'course.'.$cid.'.domain'};
4898: $cnum = $env{'course.'.$cid.'.num'};
4899: $chome = $env{'course.'.$cid.'.home'};
4900: }
4901: if ($needsrelease) {
4902: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4903: my $needsupdate;
4904: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4905: $needsupdate = 1;
4906: } else {
4907: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4908: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4909: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4910: $needsupdate = 1;
4911: }
4912: }
4913: if ($needsupdate) {
4914: my %needshash = (
4915: 'internal.releaserequired' => $needsrelease,
4916: );
4917: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4918: if ($putresult eq 'ok') {
4919: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4920: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4921: if (ref($crsinfo{$cid}) eq 'HASH') {
4922: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4923: &courseidput($cdom,\%crsinfo,$chome,'notime');
4924: }
4925: }
4926: }
4927: }
4928: return;
4929: }
4930:
1.461 www 4931: # -------------------------------------------------See if a user is privileged
4932:
4933: sub privileged {
1.1172.2.23 raeburn 4934: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 4935: my $now = time;
1.1172.2.23 raeburn 4936: my $roles;
4937: if (ref($possroles) eq 'ARRAY') {
4938: $roles = $possroles;
4939: } else {
4940: $roles = ['dc','su'];
4941: }
4942: if (ref($possdomains) eq 'ARRAY') {
4943: my %privileged = &privileged_by_domain($possdomains,$roles);
4944: foreach my $dom (@{$possdomains}) {
4945: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
4946: (ref($privileged{$dom}) eq 'HASH')) {
4947: foreach my $role (@{$roles}) {
4948: if (ref($privileged{$dom}{$role}) eq 'HASH') {
4949: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
4950: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
4951: return 1 unless (($end && $end < $now) ||
4952: ($start && $start > $now));
4953: }
4954: }
4955: }
4956: }
4957: }
4958: } else {
4959: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4960: my $now = time;
1.1170 droeschl 4961:
1.1172.2.23 raeburn 4962: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 4963: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 4964: if (grep(/^\Q$trole\E$/,@{$roles})) {
4965: return 1 unless ($tend && $tend < $now)
4966: or ($tstart && $tstart > $now);
1.1170 droeschl 4967: }
1.1172.2.23 raeburn 4968: }
4969: }
1.461 www 4970: return 0;
1.9 www 4971: }
1.1 albertel 4972:
1.1172.2.23 raeburn 4973: sub privileged_by_domain {
4974: my ($domains,$roles) = @_;
4975: my %privileged = ();
4976: my $cachetime = 60*60*24;
4977: my $now = time;
4978: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
4979: return %privileged;
4980: }
4981: foreach my $dom (@{$domains}) {
4982: next if (ref($privileged{$dom}) eq 'HASH');
4983: my $needroles;
4984: foreach my $role (@{$roles}) {
4985: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
4986: if (defined($cached)) {
4987: if (ref($result) eq 'HASH') {
4988: $privileged{$dom}{$role} = $result;
4989: }
4990: } else {
4991: $needroles = 1;
4992: }
4993: }
4994: if ($needroles) {
4995: my %dompersonnel = &get_domain_roles($dom,$roles);
4996: $privileged{$dom} = {};
4997: foreach my $server (keys(%dompersonnel)) {
4998: if (ref($dompersonnel{$server}) eq 'HASH') {
4999: foreach my $item (keys(%{$dompersonnel{$server}})) {
5000: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5001: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5002: next if ($end && $end < $now);
5003: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5004: $dompersonnel{$server}{$item};
5005: }
5006: }
5007: }
5008: if (ref($privileged{$dom}) eq 'HASH') {
5009: foreach my $role (@{$roles}) {
5010: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5011: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5012: } else {
5013: my %hash = ();
5014: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5015: }
5016: }
5017: }
5018: }
5019: }
5020: return %privileged;
5021: }
5022:
1.103 harris41 5023: # -------------------------------------------------------- Get user privileges
1.11 www 5024:
5025: sub rolesinit {
1.1169 droeschl 5026: my ($domain, $username) = @_;
5027: my %userroles = ('user.login.time' => time);
5028: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5029:
5030: # firstaccess and timerinterval are related to timed maps/resources.
5031: # also, blocking can be triggered by an activating timer
5032: # it's saved in the user's %env.
5033: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5034: my %timerinterval = &dump('timerinterval', $domain, $username);
5035: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5036: %timerintchk, %timerintenv);
5037:
1.1162 raeburn 5038: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5039: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5040: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5041: }
1.1169 droeschl 5042:
1.1162 raeburn 5043: foreach my $key (keys(%timerinterval)) {
5044: my ($cid,$rest) = split(/\0/,$key);
5045: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5046: }
1.1169 droeschl 5047:
1.11 www 5048: my %allroles=();
1.1162 raeburn 5049: my %allgroups=();
1.11 www 5050:
1.1169 droeschl 5051: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5052: my $role = $rolesdump{$area};
5053: $area =~ s/\_\w\w$//;
5054:
5055: my ($trole, $tend, $tstart, $group_privs);
5056:
5057: if ($role =~ /^cr/) {
5058: # Custom role, defined by a user
5059: # e.g., user.role.cr/msu/smith/mynewrole
5060: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5061: $trole = $1;
5062: ($tend, $tstart) = split('_', $2);
5063: } else {
5064: $trole = $role;
5065: }
5066: } elsif ($role =~ m|^gr/|) {
5067: # Role of member in a group, defined within a course/community
5068: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5069: ($trole, $tend, $tstart) = split(/_/, $role);
5070: next if $tstart eq '-1';
5071: ($trole, $group_privs) = split(/\//, $trole);
5072: $group_privs = &unescape($group_privs);
5073: } else {
5074: # Just a normal role, defined in roles.tab
5075: ($trole, $tend, $tstart) = split(/_/,$role);
5076: }
5077:
5078: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5079: $username);
5080: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5081:
5082: # role expired or not available yet?
5083: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5084: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5085:
5086: next if $area eq '' or $trole eq '';
5087:
5088: my $spec = "$trole.$area";
5089: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5090:
5091: if ($trole =~ /^cr\//) {
5092: # Custom role, defined by a user
5093: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5094: } elsif ($trole eq 'gr') {
5095: # Role of a member in a group, defined within a course/community
5096: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5097: next;
5098: } else {
5099: # Normal role, defined in roles.tab
5100: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5101: }
5102:
5103: my $cid = $tdomain.'_'.$trest;
5104: unless ($firstaccchk{$cid}) {
5105: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5106: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5107: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5108: $coursetimerstarts{$cid}{$item};
5109: }
5110: }
5111: $firstaccchk{$cid} = 1;
5112: }
5113: unless ($timerintchk{$cid}) {
5114: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5115: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5116: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5117: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5118: }
1.12 www 5119: }
1.1169 droeschl 5120: $timerintchk{$cid} = 1;
1.191 harris41 5121: }
1.11 www 5122: }
1.1169 droeschl 5123:
5124: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5125: \%allroles, \%allgroups);
5126: $env{'user.adv'} = $userroles{'user.adv'};
5127:
1.1162 raeburn 5128: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5129: }
5130:
1.567 raeburn 5131: sub set_arearole {
1.1172.2.19 raeburn 5132: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5133: unless ($nolog) {
1.567 raeburn 5134: # log the associated role with the area
1.1172.2.19 raeburn 5135: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5136: }
1.743 albertel 5137: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5138: }
5139:
5140: sub custom_roleprivs {
5141: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5142: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5143: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 5144: if (&hostname($homsvr) ne '') {
1.567 raeburn 5145: my ($rdummy,$roledef)=
5146: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5147: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5148: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5149: if (defined($syspriv)) {
1.1043 raeburn 5150: if ($trest =~ /^$match_community$/) {
5151: $syspriv =~ s/bre\&S//;
5152: }
1.567 raeburn 5153: $$allroles{'cm./'}.=':'.$syspriv;
5154: $$allroles{$spec.'./'}.=':'.$syspriv;
5155: }
5156: if ($tdomain ne '') {
5157: if (defined($dompriv)) {
5158: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5159: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5160: }
5161: if (($trest ne '') && (defined($coursepriv))) {
5162: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5163: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5164: }
5165: }
5166: }
5167: }
5168: }
5169:
1.678 raeburn 5170: sub group_roleprivs {
5171: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5172: my $access = 1;
5173: my $now = time;
5174: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5175: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5176: if ($access) {
1.811 albertel 5177: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5178: $$allgroups{$course}{$group} .=':'.$group_privs;
5179: }
5180: }
1.567 raeburn 5181:
5182: sub standard_roleprivs {
5183: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5184: if (defined($pr{$trole.':s'})) {
5185: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5186: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5187: }
5188: if ($tdomain ne '') {
5189: if (defined($pr{$trole.':d'})) {
5190: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5191: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5192: }
5193: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5194: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5195: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5196: }
5197: }
5198: }
5199:
5200: sub set_userprivs {
1.1064 raeburn 5201: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5202: my $author=0;
5203: my $adv=0;
1.678 raeburn 5204: my %grouproles = ();
5205: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5206: my @groupkeys;
1.1000 raeburn 5207: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5208: push(@groupkeys,$role);
5209: }
5210: if (ref($groups_roles) eq 'HASH') {
5211: foreach my $key (keys(%{$groups_roles})) {
5212: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5213: push(@groupkeys,$key);
5214: }
5215: }
5216: }
5217: if (@groupkeys > 0) {
5218: foreach my $role (@groupkeys) {
5219: my ($trole,$area,$sec,$extendedarea);
5220: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5221: $trole = $1;
5222: $area = $2;
5223: $sec = $3;
5224: $extendedarea = $area.$sec;
5225: if (exists($$allgroups{$area})) {
5226: foreach my $group (keys(%{$$allgroups{$area}})) {
5227: my $spec = $trole.'.'.$extendedarea;
5228: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5229: $$allgroups{$area}{$group};
1.1064 raeburn 5230: }
1.678 raeburn 5231: }
5232: }
5233: }
5234: }
5235: }
1.800 albertel 5236: foreach my $group (keys(%grouproles)) {
5237: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5238: }
1.800 albertel 5239: foreach my $role (keys(%{$allroles})) {
5240: my %thesepriv;
1.941 raeburn 5241: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5242: foreach my $item (split(/:/,$$allroles{$role})) {
5243: if ($item ne '') {
5244: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5245: if ($restrictions eq '') {
5246: $thesepriv{$privilege}='F';
5247: } elsif ($thesepriv{$privilege} ne 'F') {
5248: $thesepriv{$privilege}.=$restrictions;
5249: }
5250: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5251: }
5252: }
5253: my $thesestr='';
1.1104 raeburn 5254: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5255: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5256: }
5257: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5258: }
5259: return ($author,$adv);
5260: }
5261:
1.994 raeburn 5262: sub role_status {
1.1104 raeburn 5263: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5264: my @pwhere = ();
5265: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5266: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5267: unless (!defined($$role) || $$role eq '') {
5268: $$where=join('.',@pwhere);
5269: $$trolecode=$$role.'.'.$$where;
5270: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5271: $$tstatus='is';
1.1104 raeburn 5272: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5273: $$tstatus='future';
1.1034 raeburn 5274: if ($$tstart<$now) {
5275: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5276: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5277: my (%allroles,%allgroups,$group_privs,
5278: %groups_roles,@rolecodes);
1.1002 raeburn 5279: my %userroles = (
5280: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5281: );
1.1064 raeburn 5282: @rolecodes = ('cm');
1.1002 raeburn 5283: my $spec=$$role.'.'.$$where;
5284: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5285: if ($$role =~ /^cr\//) {
5286: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5287: push(@rolecodes,'cr');
1.1002 raeburn 5288: } elsif ($$role eq 'gr') {
1.1064 raeburn 5289: push(@rolecodes,$$role);
1.1002 raeburn 5290: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5291: $env{'user.name'});
1.1064 raeburn 5292: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5293: (undef,my $group_privs) = split(/\//,$trole);
5294: $group_privs = &unescape($group_privs);
5295: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5296: 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 5297: &get_groups_roles($tdomain,$trest,
5298: \%course_roles,\@rolecodes,
5299: \%groups_roles);
1.1002 raeburn 5300: } else {
1.1064 raeburn 5301: push(@rolecodes,$$role);
1.1002 raeburn 5302: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5303: }
1.1064 raeburn 5304: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5305: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5306: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5307: }
5308: }
1.1034 raeburn 5309: $$tstatus = 'is';
1.1002 raeburn 5310: }
1.994 raeburn 5311: }
5312: if ($$tend) {
1.1104 raeburn 5313: if ($$tend<$update) {
1.994 raeburn 5314: $$tstatus='expired';
5315: } elsif ($$tend<$now) {
5316: $$tstatus='will_not';
5317: }
5318: }
5319: }
5320: }
5321: }
5322:
1.1104 raeburn 5323: sub get_groups_roles {
5324: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5325: return unless((ref($cdom_courseroles) eq 'HASH') &&
5326: (ref($rolecodes) eq 'ARRAY') &&
5327: (ref($groups_roles) eq 'HASH'));
5328: if (keys(%{$cdom_courseroles}) > 0) {
5329: my ($cnum) = ($rest =~ /^($match_courseid)/);
5330: if ($cdom ne '' && $cnum ne '') {
5331: foreach my $key (keys(%{$cdom_courseroles})) {
5332: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5333: my $crsrole = $1;
5334: my $crssec = $2;
5335: if ($crsrole =~ /^cr/) {
5336: unless (grep(/^cr$/,@{$rolecodes})) {
5337: push(@{$rolecodes},'cr');
5338: }
5339: } else {
5340: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5341: push(@{$rolecodes},$crsrole);
5342: }
5343: }
5344: my $rolekey = "$crsrole./$cdom/$cnum";
5345: if ($crssec ne '') {
5346: $rolekey .= "/$crssec";
5347: }
5348: $rolekey .= './';
5349: $groups_roles->{$rolekey} = $rolecodes;
5350: }
5351: }
5352: }
5353: }
5354: return;
5355: }
5356:
5357: sub delete_env_groupprivs {
5358: my ($where,$courseroles,$possroles) = @_;
5359: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5360: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5361: unless (ref($courseroles->{$udom}) eq 'HASH') {
5362: %{$courseroles->{$udom}} =
5363: &get_my_roles('','','userroles',['active'],
5364: $possroles,[$udom],1);
5365: }
5366: if (ref($courseroles->{$udom}) eq 'HASH') {
5367: foreach my $item (keys(%{$courseroles->{$udom}})) {
5368: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5369: my $area = '/'.$cdom.'/'.$cnum;
5370: my $privkey = "user.priv.$crsrole.$area";
5371: if ($crssec ne '') {
5372: $privkey .= '/'.$crssec;
5373: }
5374: $privkey .= ".$area/$group";
5375: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5376: }
5377: }
5378: return;
5379: }
5380:
1.994 raeburn 5381: sub check_adhoc_privs {
1.1104 raeburn 5382: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5383: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5384: my $setprivs;
1.994 raeburn 5385: if ($env{$cckey}) {
5386: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5387: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5388: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5389: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5390: $setprivs = 1;
1.994 raeburn 5391: }
5392: } else {
1.1088 raeburn 5393: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5394: $setprivs = 1;
1.994 raeburn 5395: }
1.1172.2.9 raeburn 5396: return $setprivs;
1.994 raeburn 5397: }
5398:
5399: sub set_adhoc_privileges {
5400: # role can be cc or ca
1.1088 raeburn 5401: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5402: my $area = '/'.$dcdom.'/'.$pickedcourse;
5403: my $spec = $role.'.'.$area;
5404: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5405: $env{'user.name'},1);
1.994 raeburn 5406: my %ccrole = ();
5407: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5408: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5409: &appenv(\%userroles,[$role,'cm']);
5410: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5411: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5412: &appenv( {'request.role' => $spec,
5413: 'request.role.domain' => $dcdom,
5414: 'request.course.sec' => ''
5415: }
5416: );
5417: my $tadv=0;
5418: if (&allowed('adv') eq 'F') { $tadv=1; }
5419: &appenv({'request.role.adv' => $tadv});
5420: }
1.994 raeburn 5421: }
5422:
1.12 www 5423: # --------------------------------------------------------------- get interface
5424:
5425: sub get {
1.131 albertel 5426: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5427: my $items='';
1.800 albertel 5428: foreach my $item (@$storearr) {
5429: $items.=&escape($item).'&';
1.191 harris41 5430: }
1.12 www 5431: $items=~s/\&$//;
1.620 albertel 5432: if (!$udomain) { $udomain=$env{'user.domain'}; }
5433: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5434: my $uhome=&homeserver($uname,$udomain);
5435:
1.133 albertel 5436: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5437: my @pairs=split(/\&/,$rep);
1.273 albertel 5438: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5439: return @pairs;
5440: }
1.15 www 5441: my %returnhash=();
1.42 www 5442: my $i=0;
1.800 albertel 5443: foreach my $item (@$storearr) {
5444: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5445: $i++;
1.191 harris41 5446: }
1.15 www 5447: return %returnhash;
1.27 www 5448: }
5449:
5450: # --------------------------------------------------------------- del interface
5451:
5452: sub del {
1.133 albertel 5453: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5454: my $items='';
1.800 albertel 5455: foreach my $item (@$storearr) {
5456: $items.=&escape($item).'&';
1.191 harris41 5457: }
1.984 neumanie 5458:
1.27 www 5459: $items=~s/\&$//;
1.620 albertel 5460: if (!$udomain) { $udomain=$env{'user.domain'}; }
5461: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5462: my $uhome=&homeserver($uname,$udomain);
5463: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5464: }
5465:
5466: # -------------------------------------------------------------- dump interface
5467:
1.1172.2.22 raeburn 5468: sub unserialize {
5469: my ($rep, $escapedkeys) = @_;
5470:
5471: return {} if $rep =~ /^error/;
5472:
5473: my %returnhash=();
5474: foreach my $item (split(/\&/,$rep)) {
5475: my ($key, $value) = split(/=/, $item, 2);
5476: $key = unescape($key) unless $escapedkeys;
5477: next if $key =~ /^error: 2 /;
5478: $returnhash{$key} = &thaw_unescape($value);
5479: }
5480: return \%returnhash;
5481: }
5482:
5483: # see Lond::dump_with_regexp
5484: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5485: sub dump {
1.1172.2.22 raeburn 5486: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5487: if (!$udomain) { $udomain=$env{'user.domain'}; }
5488: if (!$uname) { $uname=$env{'user.name'}; }
5489: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5490:
1.1172.2.22 raeburn 5491: my $reply;
5492: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5493: # user is hosted on this machine
5494: $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5495: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5496: return %{&unserialize($reply, $escapedkeys)};
5497: }
1.755 albertel 5498: if ($regexp) {
5499: $regexp=&escape($regexp);
5500: } else {
5501: $regexp='.';
5502: }
1.1166 raeburn 5503: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5504: my @pairs=split(/\&/,$rep);
5505: my %returnhash=();
1.1098 foxr 5506: if (!($rep =~ /^error/ )) {
5507: foreach my $item (@pairs) {
5508: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5509: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5510: next if ($key =~ /^error: 2 /);
5511: $returnhash{$key}=&thaw_unescape($value);
5512: }
1.755 albertel 5513: }
5514: return %returnhash;
1.407 www 5515: }
5516:
1.1098 foxr 5517:
1.717 albertel 5518: # --------------------------------------------------------- dumpstore interface
5519:
5520: sub dumpstore {
5521: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5522: # same as dump but keys must be escaped. They may contain colon separated
5523: # lists of values that may themself contain colons (e.g. symbs).
5524: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5525: }
5526:
1.407 www 5527: # -------------------------------------------------------------- keys interface
5528:
5529: sub getkeys {
5530: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5531: if (!$udomain) { $udomain=$env{'user.domain'}; }
5532: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5533: my $uhome=&homeserver($uname,$udomain);
5534: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5535: my @keyarray=();
1.800 albertel 5536: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5537: next if ($key =~ /^error: 2 /);
1.800 albertel 5538: push(@keyarray,&unescape($key));
1.407 www 5539: }
5540: return @keyarray;
1.318 matthew 5541: }
5542:
1.319 matthew 5543: # --------------------------------------------------------------- currentdump
5544: sub currentdump {
1.328 matthew 5545: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5546: $courseid = $env{'request.course.id'} if (! defined($courseid));
5547: $sdom = $env{'user.domain'} if (! defined($sdom));
5548: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5549: my $uhome = &homeserver($sname,$sdom);
5550: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5551: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5552: #
1.318 matthew 5553: my %returnhash=();
1.319 matthew 5554: #
5555: if ($rep eq "unknown_cmd") {
5556: # an old lond will not know currentdump
5557: # Do a dump and make it look like a currentdump
1.822 albertel 5558: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5559: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5560: my %hash = @tmp;
5561: @tmp=();
1.424 matthew 5562: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5563: } else {
5564: my @pairs=split(/\&/,$rep);
1.800 albertel 5565: foreach my $pair (@pairs) {
5566: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5567: my ($symb,$param) = split(/:/,$key);
5568: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5569: &thaw_unescape($value);
1.319 matthew 5570: }
1.191 harris41 5571: }
1.12 www 5572: return %returnhash;
1.424 matthew 5573: }
5574:
5575: sub convert_dump_to_currentdump{
5576: my %hash = %{shift()};
5577: my %returnhash;
5578: # Code ripped from lond, essentially. The only difference
5579: # here is the unescaping done by lonnet::dump(). Conceivably
5580: # we might run in to problems with parameter names =~ /^v\./
5581: while (my ($key,$value) = each(%hash)) {
5582: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5583: $symb = &unescape($symb);
5584: $param = &unescape($param);
1.424 matthew 5585: next if ($v eq 'version' || $symb eq 'keys');
5586: next if (exists($returnhash{$symb}) &&
5587: exists($returnhash{$symb}->{$param}) &&
5588: $returnhash{$symb}->{'v.'.$param} > $v);
5589: $returnhash{$symb}->{$param}=$value;
5590: $returnhash{$symb}->{'v.'.$param}=$v;
5591: }
5592: #
5593: # Remove all of the keys in the hashes which keep track of
5594: # the version of the parameter.
5595: while (my ($symb,$param_hash) = each(%returnhash)) {
5596: # use a foreach because we are going to delete from the hash.
5597: foreach my $key (keys(%$param_hash)) {
5598: delete($param_hash->{$key}) if ($key =~ /^v\./);
5599: }
5600: }
5601: return \%returnhash;
1.12 www 5602: }
5603:
1.627 albertel 5604: # ------------------------------------------------------ critical inc interface
5605:
5606: sub cinc {
5607: return &inc(@_,'critical');
5608: }
5609:
1.449 matthew 5610: # --------------------------------------------------------------- inc interface
5611:
5612: sub inc {
1.627 albertel 5613: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5614: if (!$udomain) { $udomain=$env{'user.domain'}; }
5615: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5616: my $uhome=&homeserver($uname,$udomain);
5617: my $items='';
5618: if (! ref($store)) {
5619: # got a single value, so use that instead
5620: $items = &escape($store).'=&';
5621: } elsif (ref($store) eq 'SCALAR') {
5622: $items = &escape($$store).'=&';
5623: } elsif (ref($store) eq 'ARRAY') {
5624: $items = join('=&',map {&escape($_);} @{$store});
5625: } elsif (ref($store) eq 'HASH') {
5626: while (my($key,$value) = each(%{$store})) {
5627: $items.= &escape($key).'='.&escape($value).'&';
5628: }
5629: }
5630: $items=~s/\&$//;
1.627 albertel 5631: if ($critical) {
5632: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5633: } else {
5634: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5635: }
1.449 matthew 5636: }
5637:
1.12 www 5638: # --------------------------------------------------------------- put interface
5639:
5640: sub put {
1.134 albertel 5641: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5642: if (!$udomain) { $udomain=$env{'user.domain'}; }
5643: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5644: my $uhome=&homeserver($uname,$udomain);
1.12 www 5645: my $items='';
1.800 albertel 5646: foreach my $item (keys(%$storehash)) {
5647: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5648: }
1.12 www 5649: $items=~s/\&$//;
1.134 albertel 5650: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5651: }
5652:
1.631 albertel 5653: # ------------------------------------------------------------ newput interface
5654:
5655: sub newput {
5656: my ($namespace,$storehash,$udomain,$uname)=@_;
5657: if (!$udomain) { $udomain=$env{'user.domain'}; }
5658: if (!$uname) { $uname=$env{'user.name'}; }
5659: my $uhome=&homeserver($uname,$udomain);
5660: my $items='';
5661: foreach my $key (keys(%$storehash)) {
5662: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5663: }
5664: $items=~s/\&$//;
5665: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5666: }
5667:
5668: # --------------------------------------------------------- putstore interface
5669:
1.524 raeburn 5670: sub putstore {
1.715 albertel 5671: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5672: if (!$udomain) { $udomain=$env{'user.domain'}; }
5673: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5674: my $uhome=&homeserver($uname,$udomain);
5675: my $items='';
1.715 albertel 5676: foreach my $key (keys(%$storehash)) {
5677: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5678: }
1.715 albertel 5679: $items=~s/\&$//;
1.716 albertel 5680: my $esc_symb=&escape($symb);
5681: my $esc_v=&escape($version);
1.715 albertel 5682: my $reply =
1.716 albertel 5683: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5684: $uhome);
5685: if ($reply eq 'unknown_cmd') {
1.716 albertel 5686: # gfall back to way things use to be done
1.715 albertel 5687: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5688: $uname);
1.524 raeburn 5689: }
1.715 albertel 5690: return $reply;
5691: }
5692:
5693: sub old_putstore {
1.716 albertel 5694: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5695: if (!$udomain) { $udomain=$env{'user.domain'}; }
5696: if (!$uname) { $uname=$env{'user.name'}; }
5697: my $uhome=&homeserver($uname,$udomain);
5698: my %newstorehash;
1.800 albertel 5699: foreach my $item (keys(%$storehash)) {
5700: my $key = $version.':'.&escape($symb).':'.$item;
5701: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5702: }
5703: my $items='';
5704: my %allitems = ();
1.800 albertel 5705: foreach my $item (keys(%newstorehash)) {
5706: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5707: my $key = $1.':keys:'.$2;
5708: $allitems{$key} .= $3.':';
5709: }
1.800 albertel 5710: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5711: }
1.800 albertel 5712: foreach my $item (keys(%allitems)) {
5713: $allitems{$item} =~ s/\:$//;
5714: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5715: }
5716: $items=~s/\&$//;
5717: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5718: }
5719:
1.47 www 5720: # ------------------------------------------------------ critical put interface
5721:
5722: sub cput {
1.134 albertel 5723: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5724: if (!$udomain) { $udomain=$env{'user.domain'}; }
5725: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5726: my $uhome=&homeserver($uname,$udomain);
1.47 www 5727: my $items='';
1.800 albertel 5728: foreach my $item (keys(%$storehash)) {
5729: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5730: }
1.47 www 5731: $items=~s/\&$//;
1.134 albertel 5732: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5733: }
5734:
5735: # -------------------------------------------------------------- eget interface
5736:
5737: sub eget {
1.133 albertel 5738: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5739: my $items='';
1.800 albertel 5740: foreach my $item (@$storearr) {
5741: $items.=&escape($item).'&';
1.191 harris41 5742: }
1.12 www 5743: $items=~s/\&$//;
1.620 albertel 5744: if (!$udomain) { $udomain=$env{'user.domain'}; }
5745: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5746: my $uhome=&homeserver($uname,$udomain);
5747: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5748: my @pairs=split(/\&/,$rep);
5749: my %returnhash=();
1.42 www 5750: my $i=0;
1.800 albertel 5751: foreach my $item (@$storearr) {
5752: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5753: $i++;
1.191 harris41 5754: }
1.12 www 5755: return %returnhash;
5756: }
5757:
1.667 albertel 5758: # ------------------------------------------------------------ tmpput interface
5759: sub tmpput {
1.802 raeburn 5760: my ($storehash,$server,$context)=@_;
1.667 albertel 5761: my $items='';
1.800 albertel 5762: foreach my $item (keys(%$storehash)) {
5763: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5764: }
5765: $items=~s/\&$//;
1.802 raeburn 5766: if (defined($context)) {
5767: $items .= ':'.&escape($context);
5768: }
1.667 albertel 5769: return &reply("tmpput:$items",$server);
5770: }
5771:
5772: # ------------------------------------------------------------ tmpget interface
5773: sub tmpget {
1.688 albertel 5774: my ($token,$server)=@_;
5775: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5776: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5777: my %returnhash;
5778: foreach my $item (split(/\&/,$rep)) {
5779: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5780: next if ($key =~ /^error: 2 /);
1.667 albertel 5781: $returnhash{&unescape($key)}=&thaw_unescape($value);
5782: }
5783: return %returnhash;
5784: }
5785:
1.1113 raeburn 5786: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5787: sub tmpdel {
5788: my ($token,$server)=@_;
5789: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5790: return &reply("tmpdel:$token",$server);
5791: }
5792:
1.1172.2.13 raeburn 5793: # ------------------------------------------------------------ get_timebased_id
5794:
5795: sub get_timebased_id {
5796: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5797: $maxtries) = @_;
5798: my ($newid,$error,$dellock);
5799: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5800: return ('','ok','invalid call to get suffix');
5801: }
5802:
5803: # set defaults for any optional args for which values were not supplied
5804: if ($who eq '') {
5805: $who = $env{'user.name'}.':'.$env{'user.domain'};
5806: }
5807: if (!$locktries) {
5808: $locktries = 3;
5809: }
5810: if (!$maxtries) {
5811: $maxtries = 10;
5812: }
5813:
5814: if (($cdom eq '') || ($cnum eq '')) {
5815: if ($env{'request.course.id'}) {
5816: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5817: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5818: }
5819: if (($cdom eq '') || ($cnum eq '')) {
5820: return ('','ok','call to get suffix not in course context');
5821: }
5822: }
5823:
5824: # construct locking item
5825: my $lockhash = {
5826: $prefix."\0".'locked_'.$keyid => $who,
5827: };
5828: my $tries = 0;
5829:
5830: # attempt to get lock on nohist_$namespace file
5831: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5832: while (($gotlock ne 'ok') && $tries <$locktries) {
5833: $tries ++;
5834: sleep 1;
5835: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5836: }
5837:
5838: # attempt to get unique identifier, based on current timestamp
5839: if ($gotlock eq 'ok') {
5840: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5841: my $id = time;
5842: $newid = $id;
5843: my $idtries = 0;
5844: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5845: if ($idtype eq 'concat') {
5846: $newid = $id.$idtries;
5847: } else {
5848: $newid ++;
5849: }
5850: $idtries ++;
5851: }
5852: if (!exists($inuse{$prefix."\0".$newid})) {
5853: my %new_item = (
5854: $prefix."\0".$newid => $who,
5855: );
5856: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5857: $cdom,$cnum);
5858: if ($putresult ne 'ok') {
5859: undef($newid);
5860: $error = 'error saving new item: '.$putresult;
5861: }
5862: } else {
5863: $error = ('error: no unique suffix available for the new item ');
5864: }
5865: # remove lock
5866: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5867: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5868: } else {
5869: $error = "error: could not obtain lockfile\n";
5870: $dellock = 'ok';
5871: }
5872: return ($newid,$dellock,$error);
5873: }
5874:
1.765 albertel 5875: # -------------------------------------------------- portfolio access checking
5876:
5877: sub portfolio_access {
1.766 albertel 5878: my ($requrl) = @_;
1.765 albertel 5879: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5880: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5881: if ($result) {
5882: my %setters;
5883: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5884: my ($startblock,$endblock) =
5885: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5886: if ($startblock && $endblock) {
5887: return 'B';
5888: }
5889: } else {
5890: my ($startblock,$endblock) =
5891: &Apache::loncommon::blockcheck(\%setters,'port');
5892: if ($startblock && $endblock) {
5893: return 'B';
5894: }
5895: }
5896: }
1.765 albertel 5897: if ($result eq 'ok') {
1.766 albertel 5898: return 'F';
1.765 albertel 5899: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5900: return 'A';
1.765 albertel 5901: }
1.766 albertel 5902: return '';
1.765 albertel 5903: }
5904:
5905: sub get_portfolio_access {
1.767 albertel 5906: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5907:
5908: if (!ref($access_hash)) {
5909: my $current_perms = &get_portfile_permissions($udom,$unum);
5910: my %access_controls = &get_access_controls($current_perms,$group,
5911: $file_name);
5912: $access_hash = $access_controls{$file_name};
5913: }
5914:
1.765 albertel 5915: my ($public,$guest,@domains,@users,@courses,@groups);
5916: my $now = time;
5917: if (ref($access_hash) eq 'HASH') {
5918: foreach my $key (keys(%{$access_hash})) {
5919: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5920: if ($start > $now) {
5921: next;
5922: }
5923: if ($end && $end<$now) {
5924: next;
5925: }
5926: if ($scope eq 'public') {
5927: $public = $key;
5928: last;
5929: } elsif ($scope eq 'guest') {
5930: $guest = $key;
5931: } elsif ($scope eq 'domains') {
5932: push(@domains,$key);
5933: } elsif ($scope eq 'users') {
5934: push(@users,$key);
5935: } elsif ($scope eq 'course') {
5936: push(@courses,$key);
5937: } elsif ($scope eq 'group') {
5938: push(@groups,$key);
5939: }
5940: }
5941: if ($public) {
5942: return 'ok';
5943: }
5944: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5945: if ($guest) {
5946: return $guest;
5947: }
5948: } else {
5949: if (@domains > 0) {
5950: foreach my $domkey (@domains) {
5951: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5952: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5953: return 'ok';
5954: }
5955: }
5956: }
5957: }
5958: if (@users > 0) {
5959: foreach my $userkey (@users) {
1.865 raeburn 5960: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5961: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5962: if (ref($item) eq 'HASH') {
5963: if (($item->{'uname'} eq $env{'user.name'}) &&
5964: ($item->{'udom'} eq $env{'user.domain'})) {
5965: return 'ok';
5966: }
5967: }
5968: }
5969: }
1.765 albertel 5970: }
5971: }
5972: my %roleshash;
5973: my @courses_and_groups = @courses;
5974: push(@courses_and_groups,@groups);
5975: if (@courses_and_groups > 0) {
5976: my (%allgroups,%allroles);
5977: my ($start,$end,$role,$sec,$group);
5978: foreach my $envkey (%env) {
1.1060 raeburn 5979: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5980: my $cid = $2.'_'.$3;
5981: if ($1 eq 'gr') {
5982: $group = $4;
5983: $allgroups{$cid}{$group} = $env{$envkey};
5984: } else {
5985: if ($4 eq '') {
5986: $sec = 'none';
5987: } else {
5988: $sec = $4;
5989: }
5990: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5991: }
1.811 albertel 5992: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5993: my $cid = $2.'_'.$3;
5994: if ($4 eq '') {
5995: $sec = 'none';
5996: } else {
5997: $sec = $4;
5998: }
5999: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6000: }
6001: }
6002: if (keys(%allroles) == 0) {
6003: return;
6004: }
6005: foreach my $key (@courses_and_groups) {
6006: my %content = %{$$access_hash{$key}};
6007: my $cnum = $content{'number'};
6008: my $cdom = $content{'domain'};
6009: my $cid = $cdom.'_'.$cnum;
6010: if (!exists($allroles{$cid})) {
6011: next;
6012: }
6013: foreach my $role_id (keys(%{$content{'roles'}})) {
6014: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6015: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6016: my @status = @{$content{'roles'}{$role_id}{'access'}};
6017: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6018: foreach my $role (keys(%{$allroles{$cid}})) {
6019: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6020: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6021: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6022: if (grep/^all$/,@sections) {
6023: return 'ok';
6024: } else {
6025: if (grep/^$sec$/,@sections) {
6026: return 'ok';
6027: }
6028: }
6029: }
6030: }
6031: if (keys(%{$allgroups{$cid}}) == 0) {
6032: if (grep/^none$/,@groups) {
6033: return 'ok';
6034: }
6035: } else {
6036: if (grep/^all$/,@groups) {
6037: return 'ok';
6038: }
6039: foreach my $group (keys(%{$allgroups{$cid}})) {
6040: if (grep/^$group$/,@groups) {
6041: return 'ok';
6042: }
6043: }
6044: }
6045: }
6046: }
6047: }
6048: }
6049: }
6050: if ($guest) {
6051: return $guest;
6052: }
6053: }
6054: }
6055: return;
6056: }
6057:
6058: sub course_group_datechecker {
6059: my ($dates,$now,$status) = @_;
6060: my ($start,$end) = split(/\./,$dates);
6061: if (!$start && !$end) {
6062: return 'ok';
6063: }
6064: if (grep/^active$/,@{$status}) {
6065: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6066: return 'ok';
6067: }
6068: }
6069: if (grep/^previous$/,@{$status}) {
6070: if ($end > $now ) {
6071: return 'ok';
6072: }
6073: }
6074: if (grep/^future$/,@{$status}) {
6075: if ($start > $now) {
6076: return 'ok';
6077: }
6078: }
6079: return;
6080: }
6081:
6082: sub parse_portfolio_url {
6083: my ($url) = @_;
6084:
6085: my ($type,$udom,$unum,$group,$file_name);
6086:
1.823 albertel 6087: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6088: $type = 1;
6089: $udom = $1;
6090: $unum = $2;
6091: $file_name = $3;
1.823 albertel 6092: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6093: $type = 2;
6094: $udom = $1;
6095: $unum = $2;
6096: $group = $3;
6097: $file_name = $3.'/'.$4;
6098: }
6099: if (wantarray) {
6100: return ($type,$udom,$unum,$file_name,$group);
6101: }
6102: return $type;
6103: }
6104:
6105: sub is_portfolio_url {
6106: my ($url) = @_;
6107: return scalar(&parse_portfolio_url($url));
6108: }
6109:
1.798 raeburn 6110: sub is_portfolio_file {
6111: my ($file) = @_;
1.820 raeburn 6112: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6113: return 1;
6114: }
6115: return;
6116: }
6117:
1.976 raeburn 6118: sub usertools_access {
1.1084 raeburn 6119: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6120: my ($access,%tools);
6121: if ($context eq '') {
6122: $context = 'tools';
6123: }
6124: if ($context eq 'requestcourses') {
6125: %tools = (
6126: official => 1,
6127: unofficial => 1,
1.1006 raeburn 6128: community => 1,
1.985 raeburn 6129: );
1.1172.2.9 raeburn 6130: } elsif ($context eq 'requestauthor') {
6131: %tools = (
6132: requestauthor => 1,
6133: );
1.985 raeburn 6134: } else {
6135: %tools = (
6136: aboutme => 1,
6137: blog => 1,
1.1172.2.6 raeburn 6138: webdav => 1,
1.985 raeburn 6139: portfolio => 1,
6140: );
6141: }
1.976 raeburn 6142: return if (!defined($tools{$tool}));
6143:
6144: if ((!defined($udom)) || (!defined($uname))) {
6145: $udom = $env{'user.domain'};
6146: $uname = $env{'user.name'};
6147: }
6148:
1.978 raeburn 6149: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6150: if ($action ne 'reload') {
1.985 raeburn 6151: if ($context eq 'requestcourses') {
6152: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6153: } elsif ($context eq 'requestauthor') {
6154: return $env{'environment.canrequest.author'};
1.985 raeburn 6155: } else {
6156: return $env{'environment.availabletools.'.$tool};
6157: }
6158: }
1.976 raeburn 6159: }
6160:
1.1172.2.9 raeburn 6161: my ($toolstatus,$inststatus,$envkey);
6162: if ($context eq 'requestauthor') {
6163: $envkey = $context;
6164: } else {
6165: $envkey = $context.'.'.$tool;
6166: }
1.976 raeburn 6167:
1.985 raeburn 6168: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6169: ($action ne 'reload')) {
1.1172.2.9 raeburn 6170: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6171: $inststatus = $env{'environment.inststatus'};
6172: } else {
1.1084 raeburn 6173: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6174: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6175: $inststatus = $userenvref->{'inststatus'};
6176: } else {
1.1172.2.9 raeburn 6177: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6178: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6179: $inststatus = $userenv{'inststatus'};
6180: }
1.976 raeburn 6181: }
6182:
6183: if ($toolstatus ne '') {
6184: if ($toolstatus) {
6185: $access = 1;
6186: } else {
6187: $access = 0;
6188: }
6189: return $access;
6190: }
6191:
1.1084 raeburn 6192: my ($is_adv,%domdef);
6193: if (ref($is_advref) eq 'HASH') {
6194: $is_adv = $is_advref->{'is_adv'};
6195: } else {
6196: $is_adv = &is_advanced_user($udom,$uname);
6197: }
6198: if (ref($domdefref) eq 'HASH') {
6199: %domdef = %{$domdefref};
6200: } else {
6201: %domdef = &get_domain_defaults($udom);
6202: }
1.976 raeburn 6203: if (ref($domdef{$tool}) eq 'HASH') {
6204: if ($is_adv) {
6205: if ($domdef{$tool}{'_LC_adv'} ne '') {
6206: if ($domdef{$tool}{'_LC_adv'}) {
6207: $access = 1;
6208: } else {
6209: $access = 0;
6210: }
6211: return $access;
6212: }
6213: }
6214: if ($inststatus ne '') {
6215: my ($hasaccess,$hasnoaccess);
6216: foreach my $affiliation (split(/:/,$inststatus)) {
6217: if ($domdef{$tool}{$affiliation} ne '') {
6218: if ($domdef{$tool}{$affiliation}) {
6219: $hasaccess = 1;
6220: } else {
6221: $hasnoaccess = 1;
6222: }
6223: }
6224: }
6225: if ($hasaccess || $hasnoaccess) {
6226: if ($hasaccess) {
6227: $access = 1;
6228: } elsif ($hasnoaccess) {
6229: $access = 0;
6230: }
6231: return $access;
6232: }
6233: } else {
6234: if ($domdef{$tool}{'default'} ne '') {
6235: if ($domdef{$tool}{'default'}) {
6236: $access = 1;
6237: } elsif ($domdef{$tool}{'default'} == 0) {
6238: $access = 0;
6239: }
6240: return $access;
6241: }
6242: }
6243: } else {
1.1172.2.6 raeburn 6244: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6245: $access = 1;
6246: } else {
6247: $access = 0;
6248: }
1.976 raeburn 6249: return $access;
6250: }
6251: }
6252:
1.1050 raeburn 6253: sub is_course_owner {
6254: my ($cdom,$cnum,$udom,$uname) = @_;
6255: if (($udom eq '') || ($uname eq '')) {
6256: $udom = $env{'user.domain'};
6257: $uname = $env{'user.name'};
6258: }
6259: unless (($udom eq '') || ($uname eq '')) {
6260: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6261: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6262: return 1;
6263: } else {
6264: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6265: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6266: return 1;
6267: }
6268: }
6269: }
6270: }
6271: return;
6272: }
6273:
1.976 raeburn 6274: sub is_advanced_user {
6275: my ($udom,$uname) = @_;
1.1085 raeburn 6276: if ($udom ne '' && $uname ne '') {
6277: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6278: if (wantarray) {
6279: return ($env{'user.adv'},$env{'user.author'});
6280: } else {
6281: return $env{'user.adv'};
6282: }
1.1085 raeburn 6283: }
6284: }
1.976 raeburn 6285: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6286: my %allroles;
1.1128 raeburn 6287: my ($is_adv,$is_author);
1.976 raeburn 6288: foreach my $role (keys(%roleshash)) {
6289: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6290: my $area = '/'.$tdomain.'/'.$trest;
6291: if ($sec ne '') {
6292: $area .= '/'.$sec;
6293: }
6294: if (($area ne '') && ($trole ne '')) {
6295: my $spec=$trole.'.'.$area;
6296: if ($trole =~ /^cr\//) {
6297: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6298: } elsif ($trole ne 'gr') {
6299: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6300: }
1.1128 raeburn 6301: if ($trole eq 'au') {
6302: $is_author = 1;
6303: }
1.976 raeburn 6304: }
6305: }
6306: foreach my $role (keys(%allroles)) {
6307: last if ($is_adv);
6308: foreach my $item (split(/:/,$allroles{$role})) {
6309: if ($item ne '') {
6310: my ($privilege,$restrictions)=split(/&/,$item);
6311: if ($privilege eq 'adv') {
6312: $is_adv = 1;
6313: last;
6314: }
6315: }
6316: }
6317: }
1.1128 raeburn 6318: if (wantarray) {
6319: return ($is_adv,$is_author);
6320: }
1.976 raeburn 6321: return $is_adv;
6322: }
1.798 raeburn 6323:
1.1035 raeburn 6324: sub check_can_request {
1.1036 raeburn 6325: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6326: my $canreq = 0;
6327: my ($types,$typename) = &Apache::loncommon::course_types();
6328: my @options = ('approval','validate','autolimit');
6329: my $optregex = join('|',@options);
6330: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6331: foreach my $type (@{$types}) {
6332: if (&usertools_access($env{'user.name'},
6333: $env{'user.domain'},
6334: $type,undef,'requestcourses')) {
6335: $canreq ++;
1.1036 raeburn 6336: if (ref($request_domains) eq 'HASH') {
6337: push(@{$request_domains->{$type}},$env{'user.domain'});
6338: }
1.1035 raeburn 6339: if ($dom eq $env{'user.domain'}) {
6340: $can_request->{$type} = 1;
6341: }
6342: }
6343: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6344: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6345: if (@curr > 0) {
1.1036 raeburn 6346: foreach my $item (@curr) {
6347: if (ref($request_domains) eq 'HASH') {
6348: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6349: if ($otherdom ne '') {
6350: if (ref($request_domains->{$type}) eq 'ARRAY') {
6351: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6352: push(@{$request_domains->{$type}},$otherdom);
6353: }
6354: } else {
6355: push(@{$request_domains->{$type}},$otherdom);
6356: }
6357: }
6358: }
6359: }
6360: unless($dom eq $env{'user.domain'}) {
6361: $canreq ++;
1.1035 raeburn 6362: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6363: $can_request->{$type} = 1;
6364: }
6365: }
6366: }
6367: }
6368: }
6369: }
6370: return $canreq;
6371: }
6372:
1.341 www 6373: # ---------------------------------------------- Custom access rule evaluation
6374:
6375: sub customaccess {
6376: my ($priv,$uri)=@_;
1.807 albertel 6377: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6378: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6379: $udom = &LONCAPA::clean_domain($udom);
6380: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6381: my $access=0;
1.800 albertel 6382: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6383: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6384: if ($type eq 'user') {
6385: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6386: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6387: if ($tdom) {
6388: if ($tdom ne $env{'user.domain'}) { next; }
6389: }
1.896 albertel 6390: if ($tuname) {
6391: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6392: }
6393: $access=($effect eq 'allow');
6394: last;
6395: }
6396: } else {
6397: if ($role) {
6398: if ($role ne $urole) { next; }
6399: }
6400: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6401: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6402: if ($tdom) {
6403: if ($tdom ne $udom) { next; }
6404: }
6405: if ($tcrs) {
6406: if ($tcrs ne $ucrs) { next; }
6407: }
6408: if ($tsec) {
6409: if ($tsec ne $usec) { next; }
6410: }
6411: $access=($effect eq 'allow');
6412: last;
6413: }
6414: if ($realm eq '' && $role eq '') {
6415: $access=($effect eq 'allow');
6416: }
1.402 bowersj2 6417: }
1.341 www 6418: }
6419: return $access;
6420: }
6421:
1.103 harris41 6422: # ------------------------------------------------- Check for a user privilege
1.12 www 6423:
6424: sub allowed {
1.810 raeburn 6425: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6426: my $ver_orguri=$uri;
1.439 www 6427: $uri=&deversion($uri);
1.152 www 6428: my $orguri=$uri;
1.52 www 6429: $uri=&declutter($uri);
1.809 raeburn 6430:
1.810 raeburn 6431: if ($priv eq 'evb') {
6432: # Evade communication block restrictions for specified role in a course
6433: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6434: return $1;
6435: } else {
6436: return;
6437: }
6438: }
6439:
1.620 albertel 6440: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6441: # Free bre access to adm and meta resources
1.775 albertel 6442: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6443: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6444: && ($priv eq 'bre')) {
1.14 www 6445: return 'F';
1.159 www 6446: }
6447:
1.545 banghart 6448: # Free bre access to user's own portfolio contents
1.714 raeburn 6449: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6450: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6451: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6452: my %setters;
6453: my ($startblock,$endblock) =
6454: &Apache::loncommon::blockcheck(\%setters,'port');
6455: if ($startblock && $endblock) {
6456: return 'B';
6457: } else {
6458: return 'F';
6459: }
1.545 banghart 6460: }
6461:
1.762 raeburn 6462: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6463: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6464: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6465: if (exists($env{'request.course.id'})) {
6466: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6467: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6468: if (($domain eq $cdom) && ($name eq $cnum)) {
6469: my $courseprivid=$env{'request.course.id'};
6470: $courseprivid=~s/\_/\//;
6471: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6472: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6473: return $1;
1.762 raeburn 6474: } else {
6475: if ($env{'request.course.sec'}) {
6476: $courseprivid.='/'.$env{'request.course.sec'};
6477: }
6478: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6479: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6480: return $2;
6481: }
1.714 raeburn 6482: }
6483: }
6484: }
6485: }
6486:
1.159 www 6487: # Free bre to public access
6488:
6489: if ($priv eq 'bre') {
1.238 www 6490: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6491: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6492: return 'F';
6493: }
1.238 www 6494: if ($copyright eq 'priv') {
6495: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6496: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6497: return '';
6498: }
6499: }
6500: if ($copyright eq 'domain') {
6501: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6502: unless (($env{'user.domain'} eq $1) ||
6503: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6504: return '';
6505: }
1.262 matthew 6506: }
1.620 albertel 6507: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6508: # Library role, so allow browsing of resources in this domain.
6509: return 'F';
1.238 www 6510: }
1.341 www 6511: if ($copyright eq 'custom') {
6512: unless (&customaccess($priv,$uri)) { return ''; }
6513: }
1.14 www 6514: }
1.264 matthew 6515: # Domain coordinator is trying to create a course
1.620 albertel 6516: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6517: # uri is the requested domain in this case.
6518: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6519: # a role of dc for the domain in question.
1.620 albertel 6520: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6521: }
1.29 www 6522:
1.52 www 6523: my $thisallowed='';
6524: my $statecond=0;
6525: my $courseprivid='';
6526:
1.1039 raeburn 6527: my $ownaccess;
1.1043 raeburn 6528: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6529: if (($priv eq 'bro') && ($env{'user.author'})) {
6530: if ($uri eq '') {
6531: $ownaccess = 1;
6532: } else {
6533: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6534: my $udom = $env{'user.domain'};
6535: my $uname = $env{'user.name'};
6536: if ($uri =~ m{^\Q$udom\E/?$}) {
6537: $ownaccess = 1;
1.1040 raeburn 6538: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6539: unless ($uri =~ m{\.\./}) {
6540: $ownaccess = 1;
6541: }
6542: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6543: my $now = time;
6544: if ($uri =~ m{^([^/]+)/?$}) {
6545: my $adom = $1;
6546: foreach my $key (keys(%env)) {
1.1042 raeburn 6547: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6548: my ($start,$end) = split('.',$env{$key});
6549: if (($now >= $start) && (!$end || $end < $now)) {
6550: $ownaccess = 1;
6551: last;
6552: }
6553: }
6554: }
6555: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6556: my $adom = $1;
6557: my $aname = $2;
1.1042 raeburn 6558: foreach my $role ('ca','aa') {
6559: if ($env{"user.role.$role./$adom/$aname"}) {
6560: my ($start,$end) =
6561: split('.',$env{"user.role.$role./$adom/$aname"});
6562: if (($now >= $start) && (!$end || $end < $now)) {
6563: $ownaccess = 1;
6564: last;
6565: }
1.1039 raeburn 6566: }
6567: }
6568: }
6569: }
6570: }
6571: }
6572: }
6573:
1.52 www 6574: # Course
6575:
1.620 albertel 6576: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6577: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6578: $thisallowed.=$1;
6579: }
1.52 www 6580: }
1.29 www 6581:
1.52 www 6582: # Domain
6583:
1.620 albertel 6584: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6585: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6586: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6587: $thisallowed.=$1;
6588: }
1.12 www 6589: }
1.52 www 6590:
1.1141 raeburn 6591: # User who is not author or co-author might still be able to edit
6592: # resource of an author in the domain (e.g., if Domain Coordinator).
6593: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6594: (&allowed('mdc',$env{'request.course.id'}))) {
6595: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6596: $thisallowed.=$1;
6597: }
6598: }
6599:
1.52 www 6600: # Course: uri itself is a course
1.66 www 6601: my $courseuri=$uri;
6602: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6603: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6604:
1.620 albertel 6605: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6606: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6607: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6608: $thisallowed.=$1;
6609: }
1.12 www 6610: }
1.29 www 6611:
1.665 albertel 6612: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6613: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6614: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6615: $thisallowed='';
1.671 raeburn 6616: my ($match)=&is_on_map($uri);
6617: if ($match) {
6618: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6619: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6620: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6621: if (@blockers > 0) {
6622: $thisallowed = 'B';
6623: } else {
6624: $thisallowed.=$1;
6625: }
1.671 raeburn 6626: }
6627: } else {
1.705 albertel 6628: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6629: if ($refuri) {
6630: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6631: $thisallowed='F';
1.671 raeburn 6632: } else {
6633: $refuri=&declutter($refuri);
6634: my ($match) = &is_on_map($refuri);
6635: if ($match) {
1.1162 raeburn 6636: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6637: if (@blockers > 0) {
6638: $thisallowed = 'B';
6639: } else {
6640: $thisallowed='F';
6641: }
1.671 raeburn 6642: }
1.669 raeburn 6643: }
1.671 raeburn 6644: }
6645: }
1.314 www 6646: }
1.492 albertel 6647:
1.766 albertel 6648: if ($priv eq 'bre'
6649: && $thisallowed ne 'F'
6650: && $thisallowed ne '2'
6651: && &is_portfolio_url($uri)) {
6652: $thisallowed = &portfolio_access($uri);
6653: }
6654:
1.52 www 6655: # Full access at system, domain or course-wide level? Exit.
1.29 www 6656: if ($thisallowed=~/F/) {
6657: return 'F';
6658: }
6659:
1.52 www 6660: # If this is generating or modifying users, exit with special codes
1.29 www 6661:
1.643 www 6662: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6663: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6664: my ($audom,$auname)=split('/',$uri);
1.643 www 6665: # no author name given, so this just checks on the general right to make a co-author in this domain
6666: unless ($auname) { return $thisallowed; }
6667: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6668: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6669: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6670: ($audom ne $env{'request.role.domain'}))) { return ''; }
6671: }
1.52 www 6672: return $thisallowed;
6673: }
6674: #
1.103 harris41 6675: # Gathered so far: system, domain and course wide privileges
1.52 www 6676: #
6677: # Course: See if uri or referer is an individual resource that is part of
6678: # the course
6679:
1.620 albertel 6680: if ($env{'request.course.id'}) {
1.232 www 6681:
1.620 albertel 6682: $courseprivid=$env{'request.course.id'};
6683: if ($env{'request.course.sec'}) {
6684: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6685: }
6686: $courseprivid=~s/\_/\//;
6687: my $checkreferer=1;
1.232 www 6688: my ($match,$cond)=&is_on_map($uri);
6689: if ($match) {
6690: $statecond=$cond;
1.620 albertel 6691: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6692: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6693: my $value = $1;
6694: if ($priv eq 'bre') {
6695: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6696: if (@blockers > 0) {
6697: $thisallowed = 'B';
6698: } else {
6699: $thisallowed.=$value;
6700: }
6701: } else {
6702: $thisallowed.=$value;
6703: }
1.52 www 6704: $checkreferer=0;
6705: }
1.29 www 6706: }
1.83 www 6707:
1.148 www 6708: if ($checkreferer) {
1.620 albertel 6709: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6710: unless ($refuri) {
1.800 albertel 6711: foreach my $key (keys(%env)) {
6712: if ($key=~/^httpref\..*\*/) {
6713: my $pattern=$key;
1.156 www 6714: $pattern=~s/^httpref\.\/res\///;
1.148 www 6715: $pattern=~s/\*/\[\^\/\]\+/g;
6716: $pattern=~s/\//\\\//g;
1.152 www 6717: if ($orguri=~/$pattern/) {
1.800 albertel 6718: $refuri=$env{$key};
1.148 www 6719: }
6720: }
1.191 harris41 6721: }
1.148 www 6722: }
1.232 www 6723:
1.148 www 6724: if ($refuri) {
1.152 www 6725: $refuri=&declutter($refuri);
1.232 www 6726: my ($match,$cond)=&is_on_map($refuri);
6727: if ($match) {
6728: my $refstatecond=$cond;
1.620 albertel 6729: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6730: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6731: my $value = $1;
6732: if ($priv eq 'bre') {
6733: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6734: if (@blockers > 0) {
6735: $thisallowed = 'B';
6736: } else {
6737: $thisallowed.=$value;
6738: }
6739: } else {
6740: $thisallowed.=$value;
6741: }
1.53 www 6742: $uri=$refuri;
6743: $statecond=$refstatecond;
1.52 www 6744: }
6745: }
1.148 www 6746: }
1.29 www 6747: }
1.52 www 6748: }
1.29 www 6749:
1.52 www 6750: #
1.103 harris41 6751: # Gathered now: all privileges that could apply, and condition number
1.52 www 6752: #
6753: #
6754: # Full or no access?
6755: #
1.29 www 6756:
1.52 www 6757: if ($thisallowed=~/F/) {
6758: return 'F';
6759: }
1.29 www 6760:
1.52 www 6761: unless ($thisallowed) {
6762: return '';
6763: }
1.29 www 6764:
1.52 www 6765: # Restrictions exist, deal with them
6766: #
6767: # C:according to course preferences
6768: # R:according to resource settings
6769: # L:unless locked
6770: # X:according to user session state
6771: #
6772:
6773: # Possibly locked functionality, check all courses
1.54 www 6774: # Locks might take effect only after 10 minutes cache expiration for other
6775: # courses, and 2 minutes for current course
1.52 www 6776:
6777: my $envkey;
6778: if ($thisallowed=~/L/) {
1.1000 raeburn 6779: foreach $envkey (keys(%env)) {
1.54 www 6780: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6781: my $courseid=$2;
6782: my $roleid=$1.'.'.$2;
1.92 www 6783: $courseid=~s/^\///;
1.54 www 6784: my $expiretime=600;
1.620 albertel 6785: if ($env{'request.role'} eq $roleid) {
1.54 www 6786: $expiretime=120;
6787: }
6788: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6789: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6790: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6791: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6792: }
1.620 albertel 6793: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6794: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6795: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6796: &log($env{'user.domain'},$env{'user.name'},
6797: $env{'user.home'},
1.57 www 6798: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6799: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6800: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6801: return '';
6802: }
6803: }
1.620 albertel 6804: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6805: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6806: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6807: &log($env{'user.domain'},$env{'user.name'},
6808: $env{'user.home'},
1.57 www 6809: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6810: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6811: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6812: return '';
6813: }
6814: }
6815: }
1.29 www 6816: }
1.52 www 6817: }
6818:
6819: #
6820: # Rest of the restrictions depend on selected course
6821: #
6822:
1.620 albertel 6823: unless ($env{'request.course.id'}) {
1.766 albertel 6824: if ($thisallowed eq 'A') {
6825: return 'A';
1.814 raeburn 6826: } elsif ($thisallowed eq 'B') {
6827: return 'B';
1.766 albertel 6828: } else {
6829: return '1';
6830: }
1.52 www 6831: }
1.29 www 6832:
1.52 www 6833: #
6834: # Now user is definitely in a course
6835: #
1.53 www 6836:
6837:
6838: # Course preferences
6839:
6840: if ($thisallowed=~/C/) {
1.620 albertel 6841: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6842: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6843: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6844: =~/\Q$rolecode\E/) {
1.1103 raeburn 6845: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6846: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6847: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6848: $env{'request.course.id'});
6849: }
1.237 www 6850: return '';
6851: }
6852:
1.620 albertel 6853: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6854: =~/\Q$unamedom\E/) {
1.1103 raeburn 6855: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6856: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6857: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6858: $env{'request.course.id'});
6859: }
1.54 www 6860: return '';
6861: }
1.53 www 6862: }
6863:
6864: # Resource preferences
6865:
6866: if ($thisallowed=~/R/) {
1.620 albertel 6867: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6868: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6869: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6870: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6871: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6872: }
6873: return '';
1.54 www 6874: }
1.53 www 6875: }
1.30 www 6876:
1.246 www 6877: # Restricted by state or randomout?
1.30 www 6878:
1.52 www 6879: if ($thisallowed=~/X/) {
1.620 albertel 6880: if ($env{'acc.randomout'}) {
1.579 albertel 6881: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6882: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6883: return '';
6884: }
1.247 www 6885: }
6886: if (&condval($statecond)) {
1.52 www 6887: return '2';
6888: } else {
6889: return '';
6890: }
6891: }
1.30 www 6892:
1.766 albertel 6893: if ($thisallowed eq 'A') {
6894: return 'A';
1.814 raeburn 6895: } elsif ($thisallowed eq 'B') {
6896: return 'B';
1.766 albertel 6897: }
1.52 www 6898: return 'F';
1.232 www 6899: }
1.1162 raeburn 6900:
1.1172.2.13 raeburn 6901: # ------------------------------------------- Check construction space access
6902:
6903: sub constructaccess {
6904: my ($url,$setpriv)=@_;
6905:
6906: # We do not allow editing of previous versions of files
6907: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
6908:
6909: # Get username and domain from URL
6910: my ($ownername,$ownerdomain,$ownerhome);
6911:
6912: ($ownerdomain,$ownername) =
6913: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
6914:
6915: # The URL does not really point to any authorspace, forget it
6916: unless (($ownername) && ($ownerdomain)) { return ''; }
6917:
6918: # Now we need to see if the user has access to the authorspace of
6919: # $ownername at $ownerdomain
6920:
6921: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
6922: # Real author for this?
6923: $ownerhome = $env{'user.home'};
6924: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
6925: return ($ownername,$ownerdomain,$ownerhome);
6926: }
6927: } else {
6928: # Co-author for this?
6929: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
6930: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
6931: $ownerhome = &homeserver($ownername,$ownerdomain);
6932: return ($ownername,$ownerdomain,$ownerhome);
6933: }
6934: }
6935:
6936: # We don't have any access right now. If we are not possibly going to do anything about this,
6937: # we might as well leave
6938: unless ($setpriv) { return ''; }
6939:
6940: # Backdoor access?
6941: my $allowed=&allowed('eco',$ownerdomain);
6942: # Nope
6943: unless ($allowed) { return ''; }
6944: # Looks like we may have access, but could be locked by the owner of the construction space
6945: if ($allowed eq 'U') {
6946: my %blocked=&get('environment',['domcoord.author'],
6947: $ownerdomain,$ownername);
6948: # Is blocked by owner
6949: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
6950: }
6951: if (($allowed eq 'F') || ($allowed eq 'U')) {
6952: # Grant temporary access
6953: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 6954: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 6955: if (!$update) { $update = $then; }
6956: my $refresh=$env{'user.refresh.time'};
6957: if (!$refresh) { $refresh = $update; }
6958: my $now = time;
6959: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
6960: $now,'ca','constructaccess');
6961: $ownerhome = &homeserver($ownername,$ownerdomain);
6962: return($ownername,$ownerdomain,$ownerhome);
6963: }
6964: # No business here
6965: return '';
6966: }
6967:
1.1162 raeburn 6968: sub get_comm_blocks {
6969: my ($cdom,$cnum) = @_;
6970: if ($cdom eq '' || $cnum eq '') {
6971: return unless ($env{'request.course.id'});
6972: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6973: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6974: }
6975: my %commblocks;
6976: my $hashid=$cdom.'_'.$cnum;
6977: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6978: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6979: %commblocks = %{$blocksref};
6980: } else {
6981: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6982: my $cachetime = 600;
6983: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6984: }
6985: return %commblocks;
6986: }
6987:
6988: sub has_comm_blocking {
6989: my ($priv,$symb,$uri,$blocks) = @_;
6990: return unless ($env{'request.course.id'});
6991: return unless ($priv eq 'bre');
6992: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6993: my %commblocks;
6994: if (ref($blocks) eq 'HASH') {
6995: %commblocks = %{$blocks};
6996: } else {
6997: %commblocks = &get_comm_blocks();
6998: }
6999: return unless (keys(%commblocks) > 0);
7000: if (!$symb) { $symb=&symbread($uri,1); }
7001: my ($map,$resid,undef)=&decode_symb($symb);
7002: my %tocheck = (
7003: maps => $map,
7004: resources => $symb,
7005: );
7006: my @blockers;
7007: my $now = time;
1.1163 raeburn 7008: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7009: foreach my $block (keys(%commblocks)) {
7010: if ($block =~ /^(\d+)____(\d+)$/) {
7011: my ($start,$end) = ($1,$2);
7012: if ($start <= $now && $end >= $now) {
7013: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7014: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7015: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7016: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7017: unless (grep(/^\Q$block\E$/,@blockers)) {
7018: push(@blockers,$block);
7019: }
7020: }
7021: }
7022: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7023: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7024: unless (grep(/^\Q$block\E$/,@blockers)) {
7025: push(@blockers,$block);
7026: }
7027: }
7028: }
7029: }
7030: }
7031: }
7032: } elsif ($block =~ /^firstaccess____(.+)$/) {
7033: my $item = $1;
1.1163 raeburn 7034: my @to_test;
1.1162 raeburn 7035: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7036: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7037: my $check_interval;
7038: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7039: my @interval;
7040: my $type = 'map';
7041: if ($item eq 'course') {
7042: $type = 'course';
7043: @interval=&EXT("resource.0.interval");
7044: } else {
7045: if ($item =~ /___\d+___/) {
7046: $type = 'resource';
7047: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7048: if (ref($navmap)) {
7049: my $res = $navmap->getBySymb($item);
7050: push(@to_test,$res);
7051: }
1.1162 raeburn 7052: } else {
7053: my $mapsymb = &symbread($item,1);
7054: if ($mapsymb) {
7055: if (ref($navmap)) {
7056: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7057: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7058: foreach my $res (@to_test) {
1.1162 raeburn 7059: my $symb = $res->symb();
7060: next if ($symb eq $mapsymb);
7061: if ($symb ne '') {
7062: @interval=&EXT("resource.0.interval",$symb);
7063: last;
7064: }
7065: }
7066: }
7067: }
7068: }
7069: }
7070: if ($interval[0] =~ /\d+/) {
7071: my $first_access;
7072: if ($type eq 'resource') {
7073: $first_access=&get_first_access($interval[1],$item);
7074: } elsif ($type eq 'map') {
7075: $first_access=&get_first_access($interval[1],undef,$item);
7076: } else {
7077: $first_access=&get_first_access($interval[1]);
7078: }
7079: if ($first_access) {
7080: my $timesup = $first_access+$interval[0];
7081: if ($timesup > $now) {
1.1163 raeburn 7082: foreach my $res (@to_test) {
7083: if ($res->is_problem()) {
7084: if ($res->completable()) {
7085: unless (grep(/^\Q$block\E$/,@blockers)) {
7086: push(@blockers,$block);
7087: }
7088: last;
7089: }
7090: }
1.1162 raeburn 7091: }
7092: }
7093: }
7094: }
7095: }
7096: }
7097: }
7098: }
7099: }
7100: return @blockers;
7101: }
7102:
7103: sub check_docs_block {
7104: my ($docsblock,$tocheck) =@_;
7105: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7106: return;
7107: }
7108: if (ref($docsblock->{'maps'}) eq 'HASH') {
7109: if ($tocheck->{'maps'}) {
7110: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7111: return 1;
7112: }
7113: }
7114: }
7115: if (ref($docsblock->{'resources'}) eq 'HASH') {
7116: if ($tocheck->{'resources'}) {
7117: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7118: return 1;
7119: }
7120: }
7121: }
7122: return;
7123: }
7124:
1.1133 foxr 7125: #
7126: # Removes the versino from a URI and
7127: # splits it in to its filename and path to the filename.
7128: # Seems like File::Basename could have done this more clearly.
7129: # Parameters:
7130: # $uri - input URI
7131: # Returns:
7132: # Two element list consisting of
7133: # $pathname - the URI up to and excluding the trailing /
7134: # $filename - The part of the URI following the last /
7135: # NOTE:
7136: # Another realization of this is simply:
7137: # use File::Basename;
7138: # ...
7139: # $uri = shift;
7140: # $filename = basename($uri);
7141: # $path = dirname($uri);
7142: # return ($filename, $path);
7143: #
7144: # The implementation below is probably faster however.
7145: #
1.710 albertel 7146: sub split_uri_for_cond {
7147: my $uri=&deversion(&declutter(shift));
7148: my @uriparts=split(/\//,$uri);
7149: my $filename=pop(@uriparts);
7150: my $pathname=join('/',@uriparts);
7151: return ($pathname,$filename);
7152: }
1.232 www 7153: # --------------------------------------------------- Is a resource on the map?
7154:
7155: sub is_on_map {
1.710 albertel 7156: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7157: #Trying to find the conditional for the file
1.620 albertel 7158: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7159: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7160: if ($match) {
1.289 bowersj2 7161: return (1,$1);
7162: } else {
1.434 www 7163: return (0,0);
1.289 bowersj2 7164: }
1.12 www 7165: }
7166:
1.427 www 7167: # --------------------------------------------------------- Get symb from alias
7168:
7169: sub get_symb_from_alias {
7170: my $symb=shift;
7171: my ($map,$resid,$url)=&decode_symb($symb);
7172: # Already is a symb
7173: if ($url) { return $symb; }
7174: # Must be an alias
7175: my $aliassymb='';
7176: my %bighash;
1.620 albertel 7177: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7178: &GDBM_READER(),0640)) {
7179: my $rid=$bighash{'mapalias_'.$symb};
7180: if ($rid) {
7181: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7182: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7183: $resid,$bighash{'src_'.$rid});
1.427 www 7184: }
7185: untie %bighash;
7186: }
7187: return $aliassymb;
7188: }
7189:
1.12 www 7190: # ----------------------------------------------------------------- Define Role
7191:
7192: sub definerole {
7193: if (allowed('mcr','/')) {
7194: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7195: foreach my $role (split(':',$sysrole)) {
7196: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7197: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7198: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7199: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7200: return "refused:s:$crole&$cqual";
7201: }
7202: }
1.191 harris41 7203: }
1.800 albertel 7204: foreach my $role (split(':',$domrole)) {
7205: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7206: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7207: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7208: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7209: return "refused:d:$crole&$cqual";
7210: }
7211: }
1.191 harris41 7212: }
1.800 albertel 7213: foreach my $role (split(':',$courole)) {
7214: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7215: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7216: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7217: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7218: return "refused:c:$crole&$cqual";
7219: }
7220: }
1.191 harris41 7221: }
1.620 albertel 7222: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7223: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7224: "rolesdef_$rolename=".
7225: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7226: return reply($command,$env{'user.home'});
1.12 www 7227: } else {
7228: return 'refused';
7229: }
1.105 harris41 7230: }
7231:
7232: # ---------------- Make a metadata query against the network of library servers
7233:
7234: sub metadata_query {
1.244 matthew 7235: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 7236: my %rhash;
1.845 albertel 7237: my %libserv = &all_library();
1.244 matthew 7238: my @server_list = (defined($server_array) ? @$server_array
7239: : keys(%libserv) );
7240: for my $server (@server_list) {
1.118 harris41 7241: unless ($custom or $customshow) {
7242: my $reply=&reply("querysend:".&escape($query),$server);
7243: $rhash{$server}=$reply;
7244: }
7245: else {
7246: my $reply=&reply("querysend:".&escape($query).':'.
7247: &escape($custom).':'.&escape($customshow),
7248: $server);
7249: $rhash{$server}=$reply;
7250: }
1.112 harris41 7251: }
1.118 harris41 7252: return \%rhash;
1.240 www 7253: }
7254:
7255: # ----------------------------------------- Send log queries and wait for reply
7256:
7257: sub log_query {
7258: my ($uname,$udom,$query,%filters)=@_;
7259: my $uhome=&homeserver($uname,$udom);
7260: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7261: my $uhost=&hostname($uhome);
1.800 albertel 7262: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7263: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7264: $uhome);
1.479 albertel 7265: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7266: return get_query_reply($queryid);
7267: }
7268:
1.818 raeburn 7269: # -------------------------- Update MySQL table for portfolio file
7270:
7271: sub update_portfolio_table {
1.821 raeburn 7272: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7273: if ($group ne '') {
7274: $file_name =~s /^\Q$group\E//;
7275: }
1.818 raeburn 7276: my $homeserver = &homeserver($uname,$udom);
7277: my $queryid=
1.821 raeburn 7278: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7279: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7280: my $reply = &get_query_reply($queryid);
7281: return $reply;
7282: }
7283:
1.899 raeburn 7284: # -------------------------- Update MySQL allusers table
7285:
7286: sub update_allusers_table {
7287: my ($uname,$udom,$names) = @_;
7288: my $homeserver = &homeserver($uname,$udom);
7289: my $queryid=
7290: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7291: 'lastname='.&escape($names->{'lastname'}).'%%'.
7292: 'firstname='.&escape($names->{'firstname'}).'%%'.
7293: 'middlename='.&escape($names->{'middlename'}).'%%'.
7294: 'generation='.&escape($names->{'generation'}).'%%'.
7295: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7296: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7297: return;
1.899 raeburn 7298: }
7299:
1.508 raeburn 7300: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7301:
7302: sub fetch_enrollment_query {
1.511 raeburn 7303: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7304: my $homeserver;
1.547 raeburn 7305: my $maxtries = 1;
1.508 raeburn 7306: if ($context eq 'automated') {
7307: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7308: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7309: } else {
7310: $homeserver = &homeserver($cnum,$dom);
7311: }
1.838 albertel 7312: my $host=&hostname($homeserver);
1.506 raeburn 7313: my $cmd = '';
1.1000 raeburn 7314: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7315: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7316: }
7317: $cmd =~ s/%%$//;
7318: $cmd = &escape($cmd);
7319: my $query = 'fetchenrollment';
1.620 albertel 7320: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7321: unless ($queryid=~/^\Q$host\E\_/) {
7322: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7323: return 'error: '.$queryid;
7324: }
1.506 raeburn 7325: my $reply = &get_query_reply($queryid);
1.547 raeburn 7326: my $tries = 1;
7327: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7328: $reply = &get_query_reply($queryid);
7329: $tries ++;
7330: }
1.526 raeburn 7331: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7332: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7333: } else {
1.901 albertel 7334: my @responses = split(/:/,$reply);
1.515 raeburn 7335: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7336: foreach my $line (@responses) {
7337: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7338: $$replyref{$key} = $value;
7339: }
7340: } else {
1.1117 foxr 7341: my $pathname = LONCAPA::tempdir();
1.800 albertel 7342: foreach my $line (@responses) {
7343: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7344: $$replyref{$key} = $value;
7345: if ($value > 0) {
1.800 albertel 7346: foreach my $item (@{$$affiliatesref{$key}}) {
7347: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7348: my $destname = $pathname.'/'.$filename;
7349: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7350: if ($xml_classlist =~ /^error/) {
7351: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7352: } else {
1.506 raeburn 7353: if ( open(FILE,">$destname") ) {
7354: print FILE &unescape($xml_classlist);
7355: close(FILE);
1.526 raeburn 7356: } else {
7357: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7358: }
7359: }
7360: }
7361: }
7362: }
7363: }
7364: return 'ok';
7365: }
7366: return 'error';
7367: }
7368:
1.242 www 7369: sub get_query_reply {
7370: my $queryid=shift;
1.1117 foxr 7371: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7372: my $reply='';
7373: for (1..100) {
7374: sleep 2;
7375: if (-e $replyfile.'.end') {
1.448 albertel 7376: if (open(my $fh,$replyfile)) {
1.904 albertel 7377: $reply = join('',<$fh>);
7378: close($fh);
1.240 www 7379: } else { return 'error: reply_file_error'; }
1.242 www 7380: return &unescape($reply);
7381: }
1.240 www 7382: }
1.242 www 7383: return 'timeout:'.$queryid;
1.240 www 7384: }
7385:
7386: sub courselog_query {
1.241 www 7387: #
7388: # possible filters:
7389: # url: url or symb
7390: # username
7391: # domain
7392: # action: view, submit, grade
7393: # start: timestamp
7394: # end: timestamp
7395: #
1.240 www 7396: my (%filters)=@_;
1.620 albertel 7397: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7398: if ($filters{'url'}) {
7399: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7400: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7401: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7402: }
1.620 albertel 7403: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7404: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7405: return &log_query($cname,$cdom,'courselog',%filters);
7406: }
7407:
7408: sub userlog_query {
1.858 raeburn 7409: #
7410: # possible filters:
7411: # action: log check role
7412: # start: timestamp
7413: # end: timestamp
7414: #
1.240 www 7415: my ($uname,$udom,%filters)=@_;
7416: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7417: }
7418:
1.506 raeburn 7419: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7420:
7421: sub auto_run {
1.508 raeburn 7422: my ($cnum,$cdom) = @_;
1.876 raeburn 7423: my $response = 0;
7424: my $settings;
7425: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7426: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7427: $settings = $domconfig{'autoenroll'};
7428: if ($settings->{'run'} eq '1') {
7429: $response = 1;
7430: }
7431: } else {
1.934 raeburn 7432: my $homeserver;
7433: if (&is_course($cdom,$cnum)) {
7434: $homeserver = &homeserver($cnum,$cdom);
7435: } else {
7436: $homeserver = &domain($cdom,'primary');
7437: }
7438: if ($homeserver ne 'no_host') {
7439: $response = &reply('autorun:'.$cdom,$homeserver);
7440: }
1.876 raeburn 7441: }
1.506 raeburn 7442: return $response;
7443: }
1.776 albertel 7444:
1.506 raeburn 7445: sub auto_get_sections {
1.508 raeburn 7446: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7447: my $homeserver;
7448: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7449: $homeserver = &homeserver($cnum,$cdom);
7450: }
7451: if (!defined($homeserver)) {
7452: if ($cdom =~ /^$match_domain$/) {
7453: $homeserver = &domain($cdom,'primary');
7454: }
7455: }
7456: my @secs;
7457: if (defined($homeserver)) {
7458: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7459: unless ($response eq 'refused') {
7460: @secs = split(/:/,$response);
7461: }
1.506 raeburn 7462: }
7463: return @secs;
7464: }
1.776 albertel 7465:
1.506 raeburn 7466: sub auto_new_course {
1.1099 raeburn 7467: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7468: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7469: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7470: return $response;
7471: }
1.776 albertel 7472:
1.506 raeburn 7473: sub auto_validate_courseID {
1.508 raeburn 7474: my ($cnum,$cdom,$inst_course_id) = @_;
7475: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7476: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7477: return $response;
7478: }
1.776 albertel 7479:
1.1007 raeburn 7480: sub auto_validate_instcode {
1.1020 raeburn 7481: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7482: my ($homeserver,$response);
7483: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7484: $homeserver = &homeserver($cnum,$cdom);
7485: }
7486: if (!defined($homeserver)) {
7487: if ($cdom =~ /^$match_domain$/) {
7488: $homeserver = &domain($cdom,'primary');
7489: }
7490: }
1.1065 raeburn 7491: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7492: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7493: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7494: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7495: }
7496:
1.506 raeburn 7497: sub auto_create_password {
1.873 raeburn 7498: my ($cnum,$cdom,$authparam,$udom) = @_;
7499: my ($homeserver,$response);
1.506 raeburn 7500: my $create_passwd = 0;
7501: my $authchk = '';
1.873 raeburn 7502: if ($udom =~ /^$match_domain$/) {
7503: $homeserver = &domain($udom,'primary');
7504: }
7505: if ($homeserver eq '') {
7506: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7507: $homeserver = &homeserver($cnum,$cdom);
7508: }
7509: }
7510: if ($homeserver eq '') {
7511: $authchk = 'nodomain';
1.506 raeburn 7512: } else {
1.873 raeburn 7513: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7514: if ($response eq 'refused') {
7515: $authchk = 'refused';
7516: } else {
1.901 albertel 7517: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7518: }
1.506 raeburn 7519: }
7520: return ($authparam,$create_passwd,$authchk);
7521: }
7522:
1.706 raeburn 7523: sub auto_photo_permission {
7524: my ($cnum,$cdom,$students) = @_;
7525: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7526: my ($outcome,$perm_reqd,$conditions) =
7527: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7528: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7529: return (undef,undef);
7530: }
1.706 raeburn 7531: return ($outcome,$perm_reqd,$conditions);
7532: }
7533:
7534: sub auto_checkphotos {
7535: my ($uname,$udom,$pid) = @_;
7536: my $homeserver = &homeserver($uname,$udom);
7537: my ($result,$resulttype);
7538: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7539: &escape($uname).':'.&escape($pid),
7540: $homeserver));
1.709 albertel 7541: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7542: return (undef,undef);
7543: }
1.706 raeburn 7544: if ($outcome) {
7545: ($result,$resulttype) = split(/:/,$outcome);
7546: }
7547: return ($result,$resulttype);
7548: }
7549:
7550: sub auto_photochoice {
7551: my ($cnum,$cdom) = @_;
7552: my $homeserver = &homeserver($cnum,$cdom);
7553: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7554: &escape($cdom),
7555: $homeserver)));
1.709 albertel 7556: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7557: return (undef,undef);
7558: }
1.706 raeburn 7559: return ($update,$comment);
7560: }
7561:
7562: sub auto_photoupdate {
7563: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7564: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7565: my $host=&hostname($homeserver);
1.706 raeburn 7566: my $cmd = '';
7567: my $maxtries = 1;
1.800 albertel 7568: foreach my $affiliate (keys(%{$affiliatesref})) {
7569: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7570: }
7571: $cmd =~ s/%%$//;
7572: $cmd = &escape($cmd);
7573: my $query = 'institutionalphotos';
7574: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7575: unless ($queryid=~/^\Q$host\E\_/) {
7576: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7577: return 'error: '.$queryid;
7578: }
7579: my $reply = &get_query_reply($queryid);
7580: my $tries = 1;
7581: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7582: $reply = &get_query_reply($queryid);
7583: $tries ++;
7584: }
7585: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7586: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7587: } else {
7588: my @responses = split(/:/,$reply);
7589: my $outcome = shift(@responses);
7590: foreach my $item (@responses) {
7591: my ($key,$value) = split(/=/,$item);
7592: $$photo{$key} = $value;
7593: }
7594: return $outcome;
7595: }
7596: return 'error';
7597: }
7598:
1.521 raeburn 7599: sub auto_instcode_format {
1.793 albertel 7600: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7601: $cat_order) = @_;
1.521 raeburn 7602: my $courses = '';
1.772 raeburn 7603: my @homeservers;
1.521 raeburn 7604: if ($caller eq 'global') {
1.841 albertel 7605: my %servers = &get_servers($codedom,'library');
7606: foreach my $tryserver (keys(%servers)) {
7607: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7608: push(@homeservers,$tryserver);
7609: }
1.584 raeburn 7610: }
1.1022 raeburn 7611: } elsif ($caller eq 'requests') {
7612: if ($codedom =~ /^$match_domain$/) {
7613: my $chome = &domain($codedom,'primary');
7614: unless ($chome eq 'no_host') {
7615: push(@homeservers,$chome);
7616: }
7617: }
1.521 raeburn 7618: } else {
1.772 raeburn 7619: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7620: }
1.793 albertel 7621: foreach my $code (keys(%{$instcodes})) {
7622: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7623: }
7624: chop($courses);
1.772 raeburn 7625: my $ok_response = 0;
7626: my $response;
7627: while (@homeservers > 0 && $ok_response == 0) {
7628: my $server = shift(@homeservers);
7629: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7630: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7631: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7632: split(/:/,$response);
1.772 raeburn 7633: %{$codes} = (%{$codes},&str2hash($codes_str));
7634: push(@{$codetitles},&str2array($codetitles_str));
7635: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7636: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7637: $ok_response = 1;
7638: }
7639: }
7640: if ($ok_response) {
1.521 raeburn 7641: return 'ok';
1.772 raeburn 7642: } else {
7643: return $response;
1.521 raeburn 7644: }
7645: }
7646:
1.792 raeburn 7647: sub auto_instcode_defaults {
7648: my ($domain,$returnhash,$code_order) = @_;
7649: my @homeservers;
1.841 albertel 7650:
7651: my %servers = &get_servers($domain,'library');
7652: foreach my $tryserver (keys(%servers)) {
7653: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7654: push(@homeservers,$tryserver);
7655: }
1.792 raeburn 7656: }
1.841 albertel 7657:
1.792 raeburn 7658: my $response;
1.841 albertel 7659: foreach my $server (@homeservers) {
1.792 raeburn 7660: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7661: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7662:
7663: foreach my $pair (split(/\&/,$response)) {
7664: my ($name,$value)=split(/\=/,$pair);
7665: if ($name eq 'code_order') {
7666: @{$code_order} = split(/\&/,&unescape($value));
7667: } else {
7668: $returnhash->{&unescape($name)}=&unescape($value);
7669: }
7670: }
7671: return 'ok';
1.792 raeburn 7672: }
1.841 albertel 7673:
7674: return $response;
1.1003 raeburn 7675: }
7676:
7677: sub auto_possible_instcodes {
1.1007 raeburn 7678: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7679: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7680: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7681: return;
7682: }
1.1003 raeburn 7683: my (@homeservers,$uhome);
7684: if (defined(&domain($domain,'primary'))) {
7685: $uhome=&domain($domain,'primary');
7686: push(@homeservers,&domain($domain,'primary'));
7687: } else {
7688: my %servers = &get_servers($domain,'library');
7689: foreach my $tryserver (keys(%servers)) {
7690: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7691: push(@homeservers,$tryserver);
7692: }
7693: }
7694: }
7695: my $response;
7696: foreach my $server (@homeservers) {
7697: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7698: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7699: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7700: split(':',$response);
7701: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7702: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7703: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7704: my ($name,$value)=split('=',$item);
7705: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7706: }
7707: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7708: my ($name,$value)=split('=',$item);
7709: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7710: }
7711: return 'ok';
7712: }
7713: return $response;
7714: }
1.792 raeburn 7715:
1.1010 raeburn 7716: sub auto_courserequest_checks {
7717: my ($dom) = @_;
1.1020 raeburn 7718: my ($homeserver,%validations);
7719: if ($dom =~ /^$match_domain$/) {
7720: $homeserver = &domain($dom,'primary');
7721: }
7722: unless ($homeserver eq 'no_host') {
7723: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7724: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7725: my @items = split(/&/,$response);
7726: foreach my $item (@items) {
7727: my ($key,$value) = split('=',$item);
7728: $validations{&unescape($key)} = &thaw_unescape($value);
7729: }
7730: }
7731: }
1.1010 raeburn 7732: return %validations;
7733: }
7734:
1.1020 raeburn 7735: sub auto_courserequest_validation {
7736: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7737: my ($homeserver,$response);
7738: if ($dom =~ /^$match_domain$/) {
7739: $homeserver = &domain($dom,'primary');
7740: }
7741: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7742:
1.1020 raeburn 7743: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7744: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7745: ':'.&escape($instcode).':'.&escape($instseclist),
7746: $homeserver));
7747: }
7748: return $response;
7749: }
7750:
1.777 albertel 7751: sub auto_validate_class_sec {
1.918 raeburn 7752: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7753: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7754: my $ownerlist;
7755: if (ref($owners) eq 'ARRAY') {
7756: $ownerlist = join(',',@{$owners});
7757: } else {
7758: $ownerlist = $owners;
7759: }
1.773 raeburn 7760: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7761: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7762: return $response;
7763: }
7764:
1.679 raeburn 7765: # ------------------------------------------------------- Course Group routines
7766:
7767: sub get_coursegroups {
1.809 raeburn 7768: my ($cdom,$cnum,$group,$namespace) = @_;
7769: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7770: }
7771:
1.679 raeburn 7772: sub modify_coursegroup {
7773: my ($cdom,$cnum,$groupsettings) = @_;
7774: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7775: }
7776:
1.809 raeburn 7777: sub toggle_coursegroup_status {
7778: my ($cdom,$cnum,$group,$action) = @_;
7779: my ($from_namespace,$to_namespace);
7780: if ($action eq 'delete') {
7781: $from_namespace = 'coursegroups';
7782: $to_namespace = 'deleted_groups';
7783: } else {
7784: $from_namespace = 'deleted_groups';
7785: $to_namespace = 'coursegroups';
7786: }
7787: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7788: if (my $tmp = &error(%curr_group)) {
7789: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7790: return ('read error',$tmp);
7791: } else {
7792: my %savedsettings = %curr_group;
1.809 raeburn 7793: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7794: my $deloutcome;
7795: if ($result eq 'ok') {
1.809 raeburn 7796: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7797: } else {
7798: return ('write error',$result);
7799: }
7800: if ($deloutcome eq 'ok') {
7801: return 'ok';
7802: } else {
7803: return ('delete error',$deloutcome);
7804: }
7805: }
7806: }
7807:
1.679 raeburn 7808: sub modify_group_roles {
1.957 raeburn 7809: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7810: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7811: my $role = 'gr/'.&escape($userprivs);
7812: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7813: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7814: if ($result eq 'ok') {
7815: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7816: }
1.679 raeburn 7817: return $result;
7818: }
7819:
7820: sub modify_coursegroup_membership {
7821: my ($cdom,$cnum,$membership) = @_;
7822: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7823: return $result;
7824: }
7825:
1.682 raeburn 7826: sub get_active_groups {
7827: my ($udom,$uname,$cdom,$cnum) = @_;
7828: my $now = time;
7829: my %groups = ();
7830: foreach my $key (keys(%env)) {
1.811 albertel 7831: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7832: my ($start,$end) = split(/\./,$env{$key});
7833: if (($end!=0) && ($end<$now)) { next; }
7834: if (($start!=0) && ($start>$now)) { next; }
7835: if ($1 eq $cdom && $2 eq $cnum) {
7836: $groups{$3} = $env{$key} ;
7837: }
7838: }
7839: }
7840: return %groups;
7841: }
7842:
1.683 raeburn 7843: sub get_group_membership {
7844: my ($cdom,$cnum,$group) = @_;
7845: return(&dump('groupmembership',$cdom,$cnum,$group));
7846: }
7847:
7848: sub get_users_groups {
7849: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7850: my @usersgroups;
1.683 raeburn 7851: my $cachetime=1800;
7852:
7853: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7854: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7855: if (defined($cached)) {
1.734 albertel 7856: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7857: } else {
7858: $grouplist = '';
1.816 raeburn 7859: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7860: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7861: my $access_end = $env{'course.'.$courseid.
7862: '.default_enrollment_end_date'};
7863: my $now = time;
7864: foreach my $key (keys(%roleshash)) {
7865: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7866: my $group = $1;
7867: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7868: my $start = $2;
7869: my $end = $1;
7870: if ($start == -1) { next; } # deleted from group
7871: if (($start!=0) && ($start>$now)) { next; }
7872: if (($end!=0) && ($end<$now)) {
7873: if ($access_end && $access_end < $now) {
7874: if ($access_end - $end < 86400) {
7875: push(@usersgroups,$group);
1.733 raeburn 7876: }
7877: }
1.817 raeburn 7878: next;
1.733 raeburn 7879: }
1.817 raeburn 7880: push(@usersgroups,$group);
1.683 raeburn 7881: }
7882: }
7883: }
1.817 raeburn 7884: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7885: $grouplist = join(':',@usersgroups);
7886: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7887: }
1.733 raeburn 7888: return @usersgroups;
1.683 raeburn 7889: }
7890:
7891: sub devalidate_getgroups_cache {
7892: my ($udom,$uname,$cdom,$cnum)=@_;
7893: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7894:
1.683 raeburn 7895: my $hashid="$udom:$uname:$courseid";
7896: &devalidate_cache_new('getgroups',$hashid);
7897: }
7898:
1.12 www 7899: # ------------------------------------------------------------------ Plain Text
7900:
7901: sub plaintext {
1.988 raeburn 7902: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7903: if ($short =~ m{^cr/}) {
1.758 albertel 7904: return (split('/',$short))[-1];
7905: }
1.742 raeburn 7906: if (!defined($cid)) {
7907: $cid = $env{'request.course.id'};
7908: }
7909: my %rolenames = (
1.1008 raeburn 7910: Course => 'std',
7911: Community => 'alt1',
1.742 raeburn 7912: );
1.1037 raeburn 7913: if ($cid ne '') {
7914: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7915: unless ($forcedefault) {
7916: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7917: &Apache::lonlocal::mt_escape(\$roletext);
7918: return &Apache::lonlocal::mt($roletext);
7919: }
7920: }
7921: }
7922: if ((defined($type)) && (defined($rolenames{$type})) &&
7923: (defined($rolenames{$type})) &&
7924: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7925: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7926: } elsif ($cid ne '') {
7927: my $crstype = $env{'course.'.$cid.'.type'};
7928: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7929: (defined($prp{$short}{$rolenames{$crstype}}))) {
7930: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7931: }
1.742 raeburn 7932: }
1.1037 raeburn 7933: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7934: }
7935:
7936: # ----------------------------------------------------------------- Assign Role
7937:
7938: sub assignrole {
1.957 raeburn 7939: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7940: $context)=@_;
1.21 www 7941: my $mrole;
7942: if ($role =~ /^cr\//) {
1.393 www 7943: my $cwosec=$url;
1.811 albertel 7944: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7945: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7946: my $refused = 1;
7947: if ($context eq 'requestcourses') {
7948: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7949: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7950: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7951: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7952: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7953: if ($crsenv{'internal.courseowner'} eq
7954: $env{'user.name'}.':'.$env{'user.domain'}) {
7955: $refused = '';
7956: }
7957: }
7958: }
7959: }
7960: }
7961: if ($refused) {
7962: &logthis('Refused custom assignrole: '.
7963: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7964: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7965: return 'refused';
7966: }
1.104 www 7967: }
1.21 www 7968: $mrole='cr';
1.678 raeburn 7969: } elsif ($role =~ /^gr\//) {
7970: my $cwogrp=$url;
1.811 albertel 7971: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7972: unless (&allowed('mdg',$cwogrp)) {
7973: &logthis('Refused group assignrole: '.
7974: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7975: $env{'user.name'}.' at '.$env{'user.domain'});
7976: return 'refused';
7977: }
7978: $mrole='gr';
1.21 www 7979: } else {
1.82 www 7980: my $cwosec=$url;
1.811 albertel 7981: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7982: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7983: my $refused;
7984: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7985: if (!(&allowed('c'.$role,$url))) {
7986: $refused = 1;
7987: }
7988: } else {
7989: $refused = 1;
7990: }
1.947 raeburn 7991: if ($refused) {
1.1045 raeburn 7992: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7993: if (!$selfenroll && $context eq 'course') {
7994: my %crsenv;
7995: if ($role eq 'cc' || $role eq 'co') {
7996: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7997: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7998: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7999: if ($crsenv{'internal.courseowner'} eq
8000: $env{'user.name'}.':'.$env{'user.domain'}) {
8001: $refused = '';
8002: }
8003: }
8004: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8005: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8006: if ($crsenv{'internal.courseowner'} eq
8007: $env{'user.name'}.':'.$env{'user.domain'}) {
8008: $refused = '';
8009: }
8010: }
8011: }
8012: }
8013: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8014: $refused = '';
1.1017 raeburn 8015: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8016: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8017: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8018: my $wrongcc;
8019: if ($cnum =~ /^$match_community$/) {
8020: $wrongcc = 1 if ($role eq 'cc');
8021: } else {
8022: $wrongcc = 1 if ($role eq 'co');
8023: }
8024: unless ($wrongcc) {
8025: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8026: if ($crsenv{'internal.courseowner'} eq
8027: $env{'user.name'}.':'.$env{'user.domain'}) {
8028: $refused = '';
8029: }
1.1017 raeburn 8030: }
8031: }
1.1172.2.9 raeburn 8032: } elsif ($context eq 'requestauthor') {
8033: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8034: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8035: if ($env{'environment.requestauthor'} eq 'automatic') {
8036: $refused = '';
8037: } else {
8038: my %domdefaults = &get_domain_defaults($udom);
8039: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8040: my $checkbystatus;
8041: if ($env{'user.adv'}) {
8042: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8043: if ($disposition eq 'automatic') {
8044: $refused = '';
8045: } elsif ($disposition eq '') {
8046: $checkbystatus = 1;
8047: }
8048: } else {
8049: $checkbystatus = 1;
8050: }
8051: if ($checkbystatus) {
8052: if ($env{'environment.inststatus'}) {
8053: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8054: foreach my $type (@inststatuses) {
8055: if (($type ne '') &&
8056: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8057: $refused = '';
8058: }
8059: }
8060: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8061: $refused = '';
8062: }
8063: }
8064: }
8065: }
8066: }
1.1017 raeburn 8067: }
8068: if ($refused) {
1.947 raeburn 8069: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8070: ' '.$role.' '.$end.' '.$start.' by '.
8071: $env{'user.name'}.' at '.$env{'user.domain'});
8072: return 'refused';
8073: }
1.932 raeburn 8074: }
1.1131 raeburn 8075: } elsif ($role eq 'au') {
8076: if ($url ne '/'.$udom.'/') {
8077: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8078: ' to assign author role for '.$uname.':'.$udom.
8079: ' in domain: '.$url.' refused (wrong domain).');
8080: return 'refused';
8081: }
1.104 www 8082: }
1.21 www 8083: $mrole=$role;
8084: }
1.620 albertel 8085: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8086: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8087: if ($end) { $command.='_'.$end; }
1.21 www 8088: if ($start) {
8089: if ($end) {
1.81 www 8090: $command.='_'.$start;
1.21 www 8091: } else {
1.81 www 8092: $command.='_0_'.$start;
1.21 www 8093: }
8094: }
1.739 raeburn 8095: my $origstart = $start;
8096: my $origend = $end;
1.957 raeburn 8097: my $delflag;
1.357 www 8098: # actually delete
8099: if ($deleteflag) {
1.373 www 8100: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8101: # modify command to delete the role
1.620 albertel 8102: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8103: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8104: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8105: # set start and finish to negative values for userrolelog
8106: $start=-1;
8107: $end=-1;
1.957 raeburn 8108: $delflag = 1;
1.357 www 8109: }
8110: }
8111: # send command
1.349 www 8112: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8113: # log new user role if status is ok
1.349 www 8114: if ($answer eq 'ok') {
1.663 raeburn 8115: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8116: if (($role eq 'cc') || ($role eq 'in') ||
8117: ($role eq 'ep') || ($role eq 'ad') ||
8118: ($role eq 'ta') || ($role eq 'st') ||
8119: ($role=~/^cr/) || ($role eq 'gr') ||
8120: ($role eq 'co')) {
1.1172.2.13 raeburn 8121: # for course roles, perform group memberships changes triggered by role change.
8122: unless ($role =~ /^gr/) {
8123: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8124: $origstart,$selfenroll,$context);
8125: }
1.1172.2.9 raeburn 8126: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8127: $selfenroll,$context);
8128: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8129: ($role eq 'au') || ($role eq 'dc')) {
8130: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8131: $context);
8132: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8133: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8134: $context);
8135: }
1.1053 raeburn 8136: if ($role eq 'cc') {
8137: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8138: }
1.349 www 8139: }
8140: return $answer;
1.169 harris41 8141: }
8142:
1.1053 raeburn 8143: sub autoupdate_coowners {
8144: my ($url,$end,$start,$uname,$udom) = @_;
8145: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8146: if (($cdom ne '') && ($cnum ne '')) {
8147: my $now = time;
8148: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8149: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8150: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8151: my $instcode = $coursehash{'internal.coursecode'};
8152: if ($instcode ne '') {
1.1056 raeburn 8153: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8154: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8155: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8156: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8157: if ($result eq 'valid') {
8158: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8159: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8160: push(@newcoowners,$coowner);
8161: }
8162: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8163: push(@newcoowners,$uname.':'.$udom);
8164: }
8165: @newcoowners = sort(@newcoowners);
8166: } else {
8167: push(@newcoowners,$uname.':'.$udom);
8168: }
8169: } else {
8170: if ($coursehash{'internal.co-owners'}) {
8171: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8172: unless ($coowner eq $uname.':'.$udom) {
8173: push(@newcoowners,$coowner);
8174: }
8175: }
8176: unless (@newcoowners > 0) {
8177: $delcoowners = 1;
8178: $coowners = '';
8179: }
8180: }
8181: }
8182: if (@newcoowners || $delcoowners) {
8183: &store_coowners($cdom,$cnum,$coursehash{'home'},
8184: $delcoowners,@newcoowners);
8185: }
8186: }
8187: }
8188: }
8189: }
8190: }
8191: }
8192:
8193: sub store_coowners {
8194: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8195: my $cid = $cdom.'_'.$cnum;
8196: my ($coowners,$delresult,$putresult);
8197: if (@newcoowners) {
8198: $coowners = join(',',@newcoowners);
8199: my %coownershash = (
8200: 'internal.co-owners' => $coowners,
8201: );
8202: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8203: if ($putresult eq 'ok') {
8204: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8205: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8206: }
8207: }
8208: }
8209: if ($delcoowners) {
8210: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8211: if ($delresult eq 'ok') {
8212: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8213: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8214: }
8215: }
8216: }
8217: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8218: my %crsinfo =
8219: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8220: if (ref($crsinfo{$cid}) eq 'HASH') {
8221: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8222: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8223: }
8224: }
8225: }
8226:
1.169 harris41 8227: # -------------------------------------------------- Modify user authentication
1.197 www 8228: # Overrides without validation
8229:
1.169 harris41 8230: sub modifyuserauth {
8231: my ($udom,$uname,$umode,$upass)=@_;
8232: my $uhome=&homeserver($uname,$udom);
1.197 www 8233: unless (&allowed('mau',$udom)) { return 'refused'; }
8234: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8235: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8236: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8237: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8238: &escape($upass),$uhome);
1.620 albertel 8239: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8240: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8241: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8242: &log($udom,,$uname,$uhome,
1.620 albertel 8243: 'Authentication changed by '.$env{'user.domain'}.', '.
8244: $env{'user.name'}.', '.$umode.
1.197 www 8245: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8246: unless ($reply eq 'ok') {
1.197 www 8247: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8248: return 'error: '.$reply;
8249: }
1.170 harris41 8250: return 'ok';
1.80 www 8251: }
8252:
1.81 www 8253: # --------------------------------------------------------------- Modify a user
1.80 www 8254:
1.81 www 8255: sub modifyuser {
1.206 matthew 8256: my ($udom, $uname, $uid,
8257: $umode, $upass, $first,
8258: $middle, $last, $gene,
1.1058 raeburn 8259: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8260: $udom= &LONCAPA::clean_domain($udom);
8261: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8262: my $showcandelete = 'none';
8263: if (ref($candelete) eq 'ARRAY') {
8264: if (@{$candelete} > 0) {
8265: $showcandelete = join(', ',@{$candelete});
8266: }
8267: }
1.81 www 8268: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8269: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8270: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8271: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8272: ' desiredhome not specified').
1.620 albertel 8273: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8274: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8275: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8276: my $newuser;
8277: if ($uhome eq 'no_host') {
8278: $newuser = 1;
8279: }
1.80 www 8280: # ----------------------------------------------------------------- Create User
1.406 albertel 8281: if (($uhome eq 'no_host') &&
8282: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8283: my $unhome='';
1.844 albertel 8284: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8285: $unhome = $desiredhome;
1.620 albertel 8286: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8287: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8288: } else { # load balancing routine for determining $unhome
1.81 www 8289: my $loadm=10000000;
1.841 albertel 8290: my %servers = &get_servers($udom,'library');
8291: foreach my $tryserver (keys(%servers)) {
8292: my $answer=reply('load',$tryserver);
8293: if (($answer=~/\d+/) && ($answer<$loadm)) {
8294: $loadm=$answer;
8295: $unhome=$tryserver;
8296: }
1.80 www 8297: }
8298: }
8299: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8300: return 'error: unable to find a home server for '.$uname.
8301: ' in domain '.$udom;
1.80 www 8302: }
8303: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8304: &escape($upass),$unhome);
8305: unless ($reply eq 'ok') {
8306: return 'error: '.$reply;
8307: }
1.230 stredwic 8308: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8309: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8310: return 'error: unable verify users home machine.';
1.80 www 8311: }
1.209 matthew 8312: } # End of creation of new user
1.80 www 8313: # ---------------------------------------------------------------------- Add ID
8314: if ($uid) {
8315: $uid=~tr/A-Z/a-z/;
8316: my %uidhash=&idrget($udom,$uname);
1.196 www 8317: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8318: && (!$forceid)) {
1.80 www 8319: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8320: return 'error: user id "'.$uid.'" does not match '.
8321: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8322: }
8323: } else {
8324: &idput($udom,($uname => $uid));
8325: }
8326: }
8327: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8328: my @tmp=&get('environment',
1.899 raeburn 8329: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8330: 'permanentemail','inststatus'],
1.134 albertel 8331: $udom,$uname);
1.1075 raeburn 8332: my (%names,%oldnames);
1.313 matthew 8333: if ($tmp[0] =~ m/^error:.*/) {
8334: %names=();
8335: } else {
8336: %names = @tmp;
1.1075 raeburn 8337: %oldnames = %names;
1.313 matthew 8338: }
1.388 www 8339: #
1.1058 raeburn 8340: # If name, email and/or uid are blank (e.g., because an uploaded file
8341: # of users did not contain them), do not overwrite existing values
8342: # unless field is in $candelete array ref.
8343: #
8344:
8345: my @fields = ('firstname','middlename','lastname','generation',
8346: 'permanentemail','id');
8347: my %newvalues;
8348: if (ref($candelete) eq 'ARRAY') {
8349: foreach my $field (@fields) {
8350: if (grep(/^\Q$field\E$/,@{$candelete})) {
8351: if ($field eq 'firstname') {
8352: $names{$field} = $first;
8353: } elsif ($field eq 'middlename') {
8354: $names{$field} = $middle;
8355: } elsif ($field eq 'lastname') {
8356: $names{$field} = $last;
8357: } elsif ($field eq 'generation') {
8358: $names{$field} = $gene;
8359: } elsif ($field eq 'permanentemail') {
8360: $names{$field} = $email;
8361: } elsif ($field eq 'id') {
8362: $names{$field} = $uid;
8363: }
8364: }
8365: }
8366: }
1.388 www 8367: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8368: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8369: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8370: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8371: if ($email) {
8372: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8373: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8374: }
1.899 raeburn 8375: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8376: if (defined($inststatus)) {
8377: $names{'inststatus'} = '';
8378: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8379: if (ref($usertypes) eq 'HASH') {
8380: my @okstatuses;
8381: foreach my $item (split(/:/,$inststatus)) {
8382: if (defined($usertypes->{$item})) {
8383: push(@okstatuses,$item);
8384: }
8385: }
8386: if (@okstatuses) {
8387: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8388: }
8389: }
8390: }
1.1075 raeburn 8391: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8392: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8393: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8394: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8395: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8396: } else {
8397: $logmsg .= ' during self creation';
8398: }
1.1075 raeburn 8399: my $changed;
8400: if ($newuser) {
8401: $changed = 1;
8402: } else {
8403: foreach my $field (@fields) {
8404: if ($names{$field} ne $oldnames{$field}) {
8405: $changed = 1;
8406: last;
8407: }
8408: }
8409: }
8410: unless ($changed) {
8411: $logmsg = 'No changes in user information needed for: '.$logmsg;
8412: &logthis($logmsg);
8413: return 'ok';
8414: }
8415: my $reply = &put('environment', \%names, $udom,$uname);
8416: if ($reply ne 'ok') {
8417: return 'error: '.$reply;
8418: }
1.1087 raeburn 8419: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8420: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8421: }
1.1075 raeburn 8422: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8423: &devalidate_cache_new('namescache',$uname.':'.$udom);
8424: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8425: &logthis($logmsg);
1.134 albertel 8426: return 'ok';
1.80 www 8427: }
8428:
1.81 www 8429: # -------------------------------------------------------------- Modify student
1.80 www 8430:
1.81 www 8431: sub modifystudent {
8432: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8433: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8434: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8435: if (!$cid) {
1.620 albertel 8436: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8437: return 'not_in_class';
8438: }
1.80 www 8439: }
8440: # --------------------------------------------------------------- Make the user
1.81 www 8441: my $reply=&modifyuser
1.209 matthew 8442: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8443: $desiredhome,$email,$inststatus);
1.80 www 8444: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8445: # This will cause &modify_student_enrollment to get the uid from the
8446: # students environment
8447: $uid = undef if (!$forceid);
1.455 albertel 8448: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8449: $gene,$usec,$end,$start,$type,$locktype,
8450: $cid,$selfenroll,$context,$credits);
1.297 matthew 8451: return $reply;
8452: }
8453:
8454: sub modify_student_enrollment {
1.1172.2.23 raeburn 8455: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8456: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8457: my ($cdom,$cnum,$chome);
8458: if (!$cid) {
1.620 albertel 8459: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8460: return 'not_in_class';
8461: }
1.620 albertel 8462: $cdom=$env{'course.'.$cid.'.domain'};
8463: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8464: } else {
8465: ($cdom,$cnum)=split(/_/,$cid);
8466: }
1.620 albertel 8467: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8468: if (!$chome) {
1.457 raeburn 8469: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8470: }
1.455 albertel 8471: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8472: # Make sure the user exists
1.81 www 8473: my $uhome=&homeserver($uname,$udom);
8474: if (($uhome eq '') || ($uhome eq 'no_host')) {
8475: return 'error: no such user';
8476: }
1.297 matthew 8477: # Get student data if we were not given enough information
8478: if (!defined($first) || $first eq '' ||
8479: !defined($last) || $last eq '' ||
8480: !defined($uid) || $uid eq '' ||
8481: !defined($middle) || $middle eq '' ||
8482: !defined($gene) || $gene eq '') {
1.294 matthew 8483: # They did not supply us with enough data to enroll the student, so
8484: # we need to pick up more information.
1.297 matthew 8485: my %tmp = &get('environment',
1.294 matthew 8486: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8487: ,$udom,$uname);
8488:
1.800 albertel 8489: #foreach my $key (keys(%tmp)) {
8490: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8491: #}
1.294 matthew 8492: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8493: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8494: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8495: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8496: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8497: }
1.556 albertel 8498: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8499: my $user = "$uname:$udom";
8500: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8501: my $reply=cput('classlist',
1.1148 raeburn 8502: {$user =>
1.1172.2.19 raeburn 8503: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8504: $cdom,$cnum);
1.1148 raeburn 8505: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8506: &devalidate_getsection_cache($udom,$uname,$cid);
8507: } else {
1.81 www 8508: return 'error: '.$reply;
8509: }
1.297 matthew 8510: # Add student role to user
1.83 www 8511: my $uurl='/'.$cid;
1.81 www 8512: $uurl=~s/\_/\//g;
8513: if ($usec) {
8514: $uurl.='/'.$usec;
8515: }
1.1148 raeburn 8516: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8517: $selfenroll,$context);
8518: if ($result ne 'ok') {
8519: if ($old_entry{$user} ne '') {
8520: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8521: } else {
8522: $reply = &del('classlist',[$user],$cdom,$cnum);
8523: }
8524: }
8525: return $result;
1.21 www 8526: }
8527:
1.556 albertel 8528: sub format_name {
8529: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8530: my $name;
8531: if ($first ne 'lastname') {
8532: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8533: } else {
8534: if ($lastname=~/\S/) {
8535: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8536: $name=~s/\s+,/,/;
8537: } else {
8538: $name.= $firstname.' '.$middlename.' '.$generation;
8539: }
8540: }
8541: $name=~s/^\s+//;
8542: $name=~s/\s+$//;
8543: $name=~s/\s+/ /g;
8544: return $name;
8545: }
8546:
1.84 www 8547: # ------------------------------------------------- Write to course preferences
8548:
8549: sub writecoursepref {
8550: my ($courseid,%prefs)=@_;
8551: $courseid=~s/^\///;
8552: $courseid=~s/\_/\//g;
8553: my ($cdomain,$cnum)=split(/\//,$courseid);
8554: my $chome=homeserver($cnum,$cdomain);
8555: if (($chome eq '') || ($chome eq 'no_host')) {
8556: return 'error: no such course';
8557: }
8558: my $cstring='';
1.800 albertel 8559: foreach my $pref (keys(%prefs)) {
8560: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8561: }
1.84 www 8562: $cstring=~s/\&$//;
8563: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8564: }
8565:
8566: # ---------------------------------------------------------- Make/modify course
8567:
8568: sub createcourse {
1.741 raeburn 8569: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8570: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8571: $url=&declutter($url);
8572: my $cid='';
1.1028 raeburn 8573: if ($context eq 'requestcourses') {
8574: my $can_create = 0;
8575: my ($ownername,$ownerdom) = split(':',$course_owner);
8576: if ($udom eq $ownerdom) {
8577: if (&usertools_access($ownername,$ownerdom,$category,undef,
8578: $context)) {
8579: $can_create = 1;
8580: }
8581: } else {
8582: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8583: $category);
8584: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8585: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8586: if (@curr > 0) {
8587: my @options = qw(approval validate autolimit);
8588: my $optregex = join('|',@options);
8589: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8590: $can_create = 1;
8591: }
8592: }
8593: }
8594: }
8595: if ($can_create) {
8596: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8597: unless (&allowed('ccc',$udom)) {
8598: return 'refused';
8599: }
1.1017 raeburn 8600: }
8601: } else {
8602: return 'refused';
8603: }
1.1028 raeburn 8604: } elsif (!&allowed('ccc',$udom)) {
8605: return 'refused';
1.84 www 8606: }
1.1011 raeburn 8607: # --------------------------------------------------------------- Get Unique ID
8608: my $uname;
8609: if ($cnum =~ /^$match_courseid$/) {
8610: my $chome=&homeserver($cnum,$udom,'true');
8611: if (($chome eq '') || ($chome eq 'no_host')) {
8612: $uname = $cnum;
8613: } else {
1.1038 raeburn 8614: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8615: }
8616: } else {
1.1038 raeburn 8617: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8618: }
8619: return $uname if ($uname =~ /^error/);
8620: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8621: if (!defined($course_server)) {
8622: if (defined(&domain($udom,'primary'))) {
8623: $course_server = &domain($udom,'primary');
8624: } else {
8625: $course_server = $env{'user.home'};
8626: }
8627: }
8628: my %host_servers =
8629: &Apache::lonnet::get_servers($udom,'library');
8630: unless ($host_servers{$course_server}) {
8631: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8632: }
1.84 www 8633: # ------------------------------------------------------------- Make the course
8634: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8635: $course_server);
1.84 www 8636: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8637: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8638: if (($uhome eq '') || ($uhome eq 'no_host')) {
8639: return 'error: no such course';
8640: }
1.271 www 8641: # ----------------------------------------------------------------- Course made
1.516 raeburn 8642: # log existence
1.1029 raeburn 8643: my $now = time;
1.918 raeburn 8644: my $newcourse = {
8645: $udom.'_'.$uname => {
1.921 raeburn 8646: description => $description,
8647: inst_code => $inst_code,
8648: owner => $course_owner,
8649: type => $crstype,
1.1029 raeburn 8650: creator => $env{'user.name'}.':'.
8651: $env{'user.domain'},
8652: created => $now,
8653: context => $context,
1.918 raeburn 8654: },
8655: };
1.921 raeburn 8656: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8657: # set toplevel url
1.271 www 8658: my $topurl=$url;
8659: unless ($nonstandard) {
8660: # ------------------------------------------ For standard courses, make top url
8661: my $mapurl=&clutter($url);
1.278 www 8662: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8663: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8664: <map>
8665: <resource id="1" type="start"></resource>
8666: <resource id="2" src="$mapurl"></resource>
8667: <resource id="3" type="finish"></resource>
8668: <link index="1" from="1" to="2"></link>
8669: <link index="2" from="2" to="3"></link>
8670: </map>
8671: ENDINITMAP
8672: $topurl=&declutter(
1.638 albertel 8673: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8674: );
8675: }
8676: # ----------------------------------------------------------- Write preferences
1.84 www 8677: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8678: ('description' => $description,
8679: 'url' => $topurl,
8680: 'internal.creator' => $env{'user.name'}.':'.
8681: $env{'user.domain'},
8682: 'internal.created' => $now,
8683: 'internal.creationcontext' => $context)
8684: );
1.84 www 8685: return '/'.$udom.'/'.$uname;
8686: }
8687:
1.1011 raeburn 8688: # ------------------------------------------------------------------- Create ID
8689: sub generate_coursenum {
1.1038 raeburn 8690: my ($udom,$crstype) = @_;
1.1011 raeburn 8691: my $domdesc = &domain($udom);
8692: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8693: my $first;
8694: if ($crstype eq 'Community') {
8695: $first = '0';
8696: } else {
8697: $first = int(1+rand(9));
8698: }
8699: my $uname=$first.
1.1011 raeburn 8700: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8701: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8702: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8703: # ----------------------------------------------- Make sure that does not exist
8704: my $uhome=&homeserver($uname,$udom,'true');
8705: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8706: if ($crstype eq 'Community') {
8707: $first = '0';
8708: } else {
8709: $first = int(1+rand(9));
8710: }
8711: $uname=$first.
1.1011 raeburn 8712: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8713: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8714: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8715: $uhome=&homeserver($uname,$udom,'true');
8716: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8717: return 'error: unable to generate unique course-ID';
8718: }
8719: }
8720: return $uname;
8721: }
8722:
1.813 albertel 8723: sub is_course {
1.1167 droeschl 8724: my ($cdom, $cnum) = scalar(@_) == 1 ?
8725: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8726:
8727: return unless $cdom and $cnum;
8728:
8729: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8730: '.');
8731:
1.1172.2.23 raeburn 8732: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8733: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8734: }
8735:
1.1015 raeburn 8736: sub store_userdata {
8737: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8738: my $result;
1.1016 raeburn 8739: if ($datakey ne '') {
1.1013 raeburn 8740: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8741: if ($udom eq '' || $uname eq '') {
8742: $udom = $env{'user.domain'};
8743: $uname = $env{'user.name'};
8744: }
8745: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8746: if (($uhome eq '') || ($uhome eq 'no_host')) {
8747: $result = 'error: no_host';
8748: } else {
8749: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8750: $storehash->{'host'} = $perlvar{'lonHostID'};
8751:
8752: my $namevalue='';
8753: foreach my $key (keys(%{$storehash})) {
8754: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8755: }
8756: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 8757: unless ($namespace eq 'courserequests') {
8758: $datakey = &escape($datakey);
8759: }
1.1105 raeburn 8760: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8761: $namevalue,$uhome);
1.1013 raeburn 8762: }
8763: } else {
8764: $result = 'error: data to store was not a hash reference';
8765: }
8766: } else {
8767: $result= 'error: invalid requestkey';
8768: }
8769: return $result;
8770: }
8771:
1.21 www 8772: # ---------------------------------------------------------- Assign Custom Role
8773:
8774: sub assigncustomrole {
1.957 raeburn 8775: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8776: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8777: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8778: }
8779:
8780: # ----------------------------------------------------------------- Revoke Role
8781:
8782: sub revokerole {
1.957 raeburn 8783: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8784: my $now=time;
1.965 raeburn 8785: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8786: }
8787:
8788: # ---------------------------------------------------------- Revoke Custom Role
8789:
8790: sub revokecustomrole {
1.957 raeburn 8791: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8792: my $now=time;
1.357 www 8793: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8794: $deleteflag,$selfenroll,$context);
1.17 www 8795: }
8796:
1.533 banghart 8797: # ------------------------------------------------------------ Disk usage
1.535 albertel 8798: sub diskusage {
1.955 raeburn 8799: my ($udom,$uname,$directorypath,$getpropath)=@_;
8800: $directorypath =~ s/\/$//;
8801: my $listing=&reply('du2:'.&escape($directorypath).':'
8802: .&escape($getpropath).':'.&escape($uname).':'
8803: .&escape($udom),homeserver($uname,$udom));
8804: if ($listing eq 'unknown_cmd') {
8805: if ($getpropath) {
8806: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8807: }
8808: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8809: }
1.514 albertel 8810: return $listing;
1.512 banghart 8811: }
8812:
1.566 banghart 8813: sub is_locked {
1.1096 raeburn 8814: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8815: my @check;
8816: my $is_locked;
1.1093 raeburn 8817: push (@check,$file_name);
1.613 albertel 8818: my %locked = &get('file_permissions',\@check,
1.620 albertel 8819: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8820: my ($tmp)=keys(%locked);
8821: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8822:
1.566 banghart 8823: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8824: $is_locked = 'false';
8825: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8826: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8827: $is_locked = 'true';
1.1096 raeburn 8828: if (ref($which) eq 'ARRAY') {
8829: push(@{$which},$entry);
8830: } else {
8831: last;
8832: }
1.745 raeburn 8833: }
8834: }
1.566 banghart 8835: } else {
8836: $is_locked = 'false';
8837: }
1.1093 raeburn 8838: return $is_locked;
1.566 banghart 8839: }
8840:
1.759 albertel 8841: sub declutter_portfile {
8842: my ($file) = @_;
1.833 albertel 8843: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8844: return $file;
8845: }
8846:
1.559 banghart 8847: # ------------------------------------------------------------- Mark as Read Only
8848:
8849: sub mark_as_readonly {
8850: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8851: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8852: my ($tmp)=keys(%current_permissions);
8853: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8854: foreach my $file (@{$files}) {
1.759 albertel 8855: $file = &declutter_portfile($file);
1.561 banghart 8856: push(@{$current_permissions{$file}},$what);
1.559 banghart 8857: }
1.613 albertel 8858: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8859: return;
8860: }
8861:
1.572 banghart 8862: # ------------------------------------------------------------Save Selected Files
8863:
8864: sub save_selected_files {
8865: my ($user, $path, @files) = @_;
8866: my $filename = $user."savedfiles";
1.573 banghart 8867: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8868: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8869: foreach my $file (@files) {
1.620 albertel 8870: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8871: }
8872: foreach my $file (@other_files) {
1.574 banghart 8873: print (OUT $file."\n");
1.572 banghart 8874: }
1.574 banghart 8875: close (OUT);
1.572 banghart 8876: return 'ok';
8877: }
8878:
1.574 banghart 8879: sub clear_selected_files {
8880: my ($user) = @_;
8881: my $filename = $user."savedfiles";
1.1117 foxr 8882: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8883: print (OUT undef);
8884: close (OUT);
8885: return ("ok");
8886: }
8887:
1.572 banghart 8888: sub files_in_path {
8889: my ($user, $path) = @_;
8890: my $filename = $user."savedfiles";
8891: my %return_files;
1.1117 foxr 8892: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8893: while (my $line_in = <IN>) {
1.574 banghart 8894: chomp ($line_in);
8895: my @paths_and_file = split (m!/!, $line_in);
8896: my $file_part = pop (@paths_and_file);
8897: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8898: $path_part.='/';
8899: my $path_and_file = $path_part.$file_part;
8900: if ($path_part eq $path) {
8901: $return_files{$file_part}= 'selected';
8902: }
8903: }
1.574 banghart 8904: close (IN);
8905: return (\%return_files);
1.572 banghart 8906: }
8907:
8908: # called in portfolio select mode, to show files selected NOT in current directory
8909: sub files_not_in_path {
8910: my ($user, $path) = @_;
8911: my $filename = $user."savedfiles";
8912: my @return_files;
8913: my $path_part;
1.1117 foxr 8914: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8915: while (my $line = <IN>) {
1.572 banghart 8916: #ok, I know it's clunky, but I want it to work
1.800 albertel 8917: my @paths_and_file = split(m|/|, $line);
8918: my $file_part = pop(@paths_and_file);
8919: chomp($file_part);
8920: my $path_part = join('/', @paths_and_file);
1.572 banghart 8921: $path_part .= '/';
8922: my $path_and_file = $path_part.$file_part;
8923: if ($path_part ne $path) {
1.800 albertel 8924: push(@return_files, ($path_and_file));
1.572 banghart 8925: }
8926: }
1.800 albertel 8927: close(OUT);
1.574 banghart 8928: return (@return_files);
1.572 banghart 8929: }
8930:
1.745 raeburn 8931: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8932:
1.745 raeburn 8933: sub get_portfile_permissions {
8934: my ($domain,$user) = @_;
1.613 albertel 8935: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8936: my ($tmp)=keys(%current_permissions);
8937: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8938: return \%current_permissions;
8939: }
8940:
8941: #---------------------------------------------Get portfolio file access controls
8942:
1.749 raeburn 8943: sub get_access_controls {
1.745 raeburn 8944: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8945: my %access;
8946: my $real_file = $file;
8947: $file =~ s/\.meta$//;
1.745 raeburn 8948: if (defined($file)) {
1.749 raeburn 8949: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8950: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8951: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8952: }
8953: }
1.745 raeburn 8954: } else {
1.749 raeburn 8955: foreach my $key (keys(%{$current_permissions})) {
8956: if ($key =~ /\0accesscontrol$/) {
8957: if (defined($group)) {
8958: if ($key !~ m-^\Q$group\E/-) {
8959: next;
8960: }
8961: }
8962: my ($fullpath) = split(/\0/,$key);
8963: if (ref($$current_permissions{$key}) eq 'HASH') {
8964: foreach my $control (keys(%{$$current_permissions{$key}})) {
8965: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8966: }
8967: }
8968: }
8969: }
8970: }
8971: return %access;
8972: }
8973:
8974: sub modify_access_controls {
8975: my ($file_name,$changes,$domain,$user)=@_;
8976: my ($outcome,$deloutcome);
8977: my %store_permissions;
8978: my %new_values;
8979: my %new_control;
8980: my %translation;
8981: my @deletions = ();
8982: my $now = time;
8983: if (exists($$changes{'activate'})) {
8984: if (ref($$changes{'activate'}) eq 'HASH') {
8985: my @newitems = sort(keys(%{$$changes{'activate'}}));
8986: my $numnew = scalar(@newitems);
8987: for (my $i=0; $i<$numnew; $i++) {
8988: my $newkey = $newitems[$i];
8989: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8990: if ($newkey =~ /^\d+:/) {
8991: $newkey =~ s/^(\d+)/$newid/;
8992: $translation{$1} = $newid;
8993: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8994: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8995: $translation{$1} = $newid;
8996: }
1.749 raeburn 8997: $new_values{$file_name."\0".$newkey} =
8998: $$changes{'activate'}{$newitems[$i]};
8999: $new_control{$newkey} = $now;
9000: }
9001: }
9002: }
9003: my %todelete;
9004: my %changed_items;
9005: foreach my $action ('delete','update') {
9006: if (exists($$changes{$action})) {
9007: if (ref($$changes{$action}) eq 'HASH') {
9008: foreach my $key (keys(%{$$changes{$action}})) {
9009: my ($itemnum) = ($key =~ /^([^:]+):/);
9010: if ($action eq 'delete') {
9011: $todelete{$itemnum} = 1;
9012: } else {
9013: $changed_items{$itemnum} = $key;
9014: }
9015: }
1.745 raeburn 9016: }
9017: }
1.749 raeburn 9018: }
9019: # get lock on access controls for file.
9020: my $lockhash = {
9021: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9022: ':'.$env{'user.domain'},
9023: };
9024: my $tries = 0;
9025: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9026:
9027: while (($gotlock ne 'ok') && $tries <3) {
9028: $tries ++;
9029: sleep 1;
9030: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9031: }
9032: if ($gotlock eq 'ok') {
9033: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9034: my ($tmp)=keys(%curr_permissions);
9035: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9036: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9037: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9038: if (ref($curr_controls) eq 'HASH') {
9039: foreach my $control_item (keys(%{$curr_controls})) {
9040: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9041: if (defined($todelete{$itemnum})) {
9042: push(@deletions,$file_name."\0".$control_item);
9043: } else {
9044: if (defined($changed_items{$itemnum})) {
9045: $new_control{$changed_items{$itemnum}} = $now;
9046: push(@deletions,$file_name."\0".$control_item);
9047: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9048: } else {
9049: $new_control{$control_item} = $$curr_controls{$control_item};
9050: }
9051: }
1.745 raeburn 9052: }
9053: }
9054: }
1.970 raeburn 9055: my ($group);
9056: if (&is_course($domain,$user)) {
9057: ($group,my $file) = split(/\//,$file_name,2);
9058: }
1.749 raeburn 9059: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9060: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9061: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9062: # remove lock
9063: my @del_lock = ($file_name."\0".'locked_access_records');
9064: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9065: my $sqlresult =
1.970 raeburn 9066: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9067: $group);
1.749 raeburn 9068: } else {
9069: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9070: }
1.749 raeburn 9071: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9072: }
9073:
1.827 raeburn 9074: sub make_public_indefinitely {
9075: my ($requrl) = @_;
9076: my $now = time;
9077: my $action = 'activate';
9078: my $aclnum = 0;
9079: if (&is_portfolio_url($requrl)) {
9080: my (undef,$udom,$unum,$file_name,$group) =
9081: &parse_portfolio_url($requrl);
9082: my $current_perms = &get_portfile_permissions($udom,$unum);
9083: my %access_controls = &get_access_controls($current_perms,
9084: $group,$file_name);
9085: foreach my $key (keys(%{$access_controls{$file_name}})) {
9086: my ($num,$scope,$end,$start) =
9087: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9088: if ($scope eq 'public') {
9089: if ($start <= $now && $end == 0) {
9090: $action = 'none';
9091: } else {
9092: $action = 'update';
9093: $aclnum = $num;
9094: }
9095: last;
9096: }
9097: }
9098: if ($action eq 'none') {
9099: return 'ok';
9100: } else {
9101: my %changes;
9102: my $newend = 0;
9103: my $newstart = $now;
9104: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9105: $changes{$action}{$newkey} = {
9106: type => 'public',
9107: time => {
9108: start => $newstart,
9109: end => $newend,
9110: },
9111: };
9112: my ($outcome,$deloutcome,$new_values,$translation) =
9113: &modify_access_controls($file_name,\%changes,$udom,$unum);
9114: return $outcome;
9115: }
9116: } else {
9117: return 'invalid';
9118: }
9119: }
9120:
1.745 raeburn 9121: #------------------------------------------------------Get Marked as Read Only
9122:
9123: sub get_marked_as_readonly {
9124: my ($domain,$user,$what,$group) = @_;
9125: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9126: my @readonly_files;
1.629 banghart 9127: my $cmp1=$what;
9128: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9129: while (my ($file_name,$value) = each(%{$current_permissions})) {
9130: if (defined($group)) {
9131: if ($file_name !~ m-^\Q$group\E/-) {
9132: next;
9133: }
9134: }
1.561 banghart 9135: if (ref($value) eq "ARRAY"){
9136: foreach my $stored_what (@{$value}) {
1.629 banghart 9137: my $cmp2=$stored_what;
1.759 albertel 9138: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9139: $cmp2=join('',@{$stored_what});
1.745 raeburn 9140: }
1.629 banghart 9141: if ($cmp1 eq $cmp2) {
1.561 banghart 9142: push(@readonly_files, $file_name);
1.745 raeburn 9143: last;
1.563 banghart 9144: } elsif (!defined($what)) {
9145: push(@readonly_files, $file_name);
1.745 raeburn 9146: last;
1.561 banghart 9147: }
9148: }
1.745 raeburn 9149: }
1.561 banghart 9150: }
9151: return @readonly_files;
9152: }
1.577 banghart 9153: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9154:
1.577 banghart 9155: sub get_marked_as_readonly_hash {
1.745 raeburn 9156: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9157: my %readonly_files;
1.745 raeburn 9158: while (my ($file_name,$value) = each(%{$current_permissions})) {
9159: if (defined($group)) {
9160: if ($file_name !~ m-^\Q$group\E/-) {
9161: next;
9162: }
9163: }
1.577 banghart 9164: if (ref($value) eq "ARRAY"){
9165: foreach my $stored_what (@{$value}) {
1.745 raeburn 9166: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9167: foreach my $lock_descriptor(@{$stored_what}) {
9168: if ($lock_descriptor eq 'graded') {
9169: $readonly_files{$file_name} = 'graded';
9170: } elsif ($lock_descriptor eq 'handback') {
9171: $readonly_files{$file_name} = 'handback';
9172: } else {
9173: if (!exists($readonly_files{$file_name})) {
9174: $readonly_files{$file_name} = 'locked';
9175: }
9176: }
1.745 raeburn 9177: }
1.750 banghart 9178: }
1.577 banghart 9179: }
9180: }
9181: }
9182: return %readonly_files;
9183: }
1.559 banghart 9184: # ------------------------------------------------------------ Unmark as Read Only
9185:
9186: sub unmark_as_readonly {
1.629 banghart 9187: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9188: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9189: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9190: $file_name = &declutter_portfile($file_name);
1.634 albertel 9191: my $symb_crs = $what;
9192: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9193: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9194: my ($tmp)=keys(%current_permissions);
9195: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9196: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9197: foreach my $file (@readonly_files) {
1.759 albertel 9198: my $clean_file = &declutter_portfile($file);
9199: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9200: my $current_locks = $current_permissions{$file};
1.563 banghart 9201: my @new_locks;
9202: my @del_keys;
9203: if (ref($current_locks) eq "ARRAY"){
9204: foreach my $locker (@{$current_locks}) {
1.632 albertel 9205: my $compare=$locker;
1.749 raeburn 9206: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9207: $compare=join('',@{$locker});
1.746 raeburn 9208: if ($compare ne $symb_crs) {
9209: push(@new_locks, $locker);
9210: }
1.563 banghart 9211: }
9212: }
1.650 albertel 9213: if (scalar(@new_locks) > 0) {
1.563 banghart 9214: $current_permissions{$file} = \@new_locks;
9215: } else {
9216: push(@del_keys, $file);
1.613 albertel 9217: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9218: delete($current_permissions{$file});
1.563 banghart 9219: }
9220: }
1.561 banghart 9221: }
1.613 albertel 9222: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9223: return;
9224: }
1.512 banghart 9225:
1.17 www 9226: # ------------------------------------------------------------ Directory lister
9227:
9228: sub dirlist {
1.955 raeburn 9229: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9230: $uri=~s/^\///;
9231: $uri=~s/\/$//;
1.253 stredwic 9232: my ($udom, $uname);
1.955 raeburn 9233: if ($getuserdir) {
1.253 stredwic 9234: $udom = $userdomain;
9235: $uname = $username;
1.955 raeburn 9236: } else {
9237: (undef,$udom,$uname)=split(/\//,$uri);
9238: if(defined($userdomain)) {
9239: $udom = $userdomain;
9240: }
9241: if(defined($username)) {
9242: $uname = $username;
9243: }
1.253 stredwic 9244: }
1.955 raeburn 9245: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9246:
1.955 raeburn 9247: $dirRoot = $perlvar{'lonDocRoot'};
9248: if (defined($getpropath)) {
9249: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9250: $dirRoot =~ s/\/$//;
1.955 raeburn 9251: } elsif (defined($getuserdir)) {
9252: my $subdir=$uname.'__';
9253: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9254: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9255: ."/$udom/$subdir/$uname";
9256: } elsif (defined($alternateRoot)) {
9257: $dirRoot = $alternateRoot;
1.751 banghart 9258: }
1.253 stredwic 9259:
9260: if($udom) {
9261: if($uname) {
1.1135 raeburn 9262: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9263: if ($uhome eq 'no_host') {
9264: return ([],'no_host');
9265: }
1.955 raeburn 9266: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9267: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9268: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9269: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9270: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9271: } else {
9272: @listing_results = map { &unescape($_); } split(/:/,$listing);
9273: }
1.605 matthew 9274: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9275: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9276: @listing_results = split(/:/,$listing);
9277: } else {
9278: @listing_results = map { &unescape($_); } split(/:/,$listing);
9279: }
1.1135 raeburn 9280: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9281: ($listing eq 'rejected') || ($listing eq 'refused') ||
9282: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9283: return ([],$listing);
9284: } else {
9285: return (\@listing_results);
1.1135 raeburn 9286: }
1.955 raeburn 9287: } elsif(!$alternateRoot) {
1.1136 raeburn 9288: my (%allusers,%listerror);
1.841 albertel 9289: my %servers = &get_servers($udom,'library');
1.955 raeburn 9290: foreach my $tryserver (keys(%servers)) {
9291: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9292: &escape($udom),$tryserver);
9293: if ($listing eq 'unknown_cmd') {
9294: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9295: $udom, $tryserver);
9296: } else {
9297: @listing_results = map { &unescape($_); } split(/:/,$listing);
9298: }
1.841 albertel 9299: if ($listing eq 'unknown_cmd') {
9300: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9301: $udom, $tryserver);
9302: @listing_results = split(/:/,$listing);
9303: } else {
9304: @listing_results =
9305: map { &unescape($_); } split(/:/,$listing);
9306: }
1.1136 raeburn 9307: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9308: ($listing eq 'rejected') || ($listing eq 'refused') ||
9309: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9310: $listerror{$tryserver} = $listing;
9311: } else {
1.841 albertel 9312: foreach my $line (@listing_results) {
9313: my ($entry) = split(/&/,$line,2);
9314: $allusers{$entry} = 1;
9315: }
9316: }
1.253 stredwic 9317: }
1.1136 raeburn 9318: my @alluserslist=();
1.800 albertel 9319: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9320: push(@alluserslist,$user.'&user');
1.253 stredwic 9321: }
1.1136 raeburn 9322: return (\@alluserslist);
1.253 stredwic 9323: } else {
1.1136 raeburn 9324: return ([],'missing username');
1.253 stredwic 9325: }
1.955 raeburn 9326: } elsif(!defined($getpropath)) {
1.1136 raeburn 9327: my $path = $perlvar{'lonDocRoot'}.'/res/';
9328: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9329: return (\@all_domains);
1.955 raeburn 9330: } else {
1.1136 raeburn 9331: return ([],'missing domain');
1.275 stredwic 9332: }
9333: }
9334:
9335: # --------------------------------------------- GetFileTimestamp
9336: # This function utilizes dirlist and returns the date stamp for
9337: # when it was last modified. It will also return an error of -1
9338: # if an error occurs
9339:
9340: sub GetFileTimestamp {
1.955 raeburn 9341: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9342: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9343: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9344: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9345: undef,$getuserdir);
9346: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9347: return -1;
9348: }
9349: if (ref($fileref) eq 'ARRAY') {
9350: my @stats = split('&',$fileref->[0]);
1.375 matthew 9351: # @stats contains first the filename, then the stat output
9352: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9353: } else {
9354: return -1;
1.253 stredwic 9355: }
1.26 www 9356: }
9357:
1.712 albertel 9358: sub stat_file {
9359: my ($uri) = @_;
1.787 albertel 9360: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9361:
1.955 raeburn 9362: my ($udom,$uname,$file);
1.712 albertel 9363: if ($uri =~ m-^/(uploaded|editupload)/-) {
9364: ($udom,$uname,$file) =
1.811 albertel 9365: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9366: $file = 'userfiles/'.$file;
9367: }
9368: if ($uri =~ m-^/res/-) {
9369: ($udom,$uname) =
1.807 albertel 9370: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9371: $file = $uri;
9372: }
9373:
9374: if (!$udom || !$uname || !$file) {
9375: # unable to handle the uri
9376: return ();
9377: }
1.956 raeburn 9378: my $getpropath;
9379: if ($file =~ /^userfiles\//) {
9380: $getpropath = 1;
9381: }
1.1136 raeburn 9382: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9383: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9384: return ();
9385: } else {
9386: if (ref($listref) eq 'ARRAY') {
9387: my @stats = split('&',$listref->[0]);
9388: shift(@stats); #filename is first
9389: return @stats;
9390: }
1.712 albertel 9391: }
9392: return ();
9393: }
9394:
1.26 www 9395: # -------------------------------------------------------- Value of a Condition
9396:
1.713 albertel 9397: # gets the value of a specific preevaluated condition
9398: # stored in the string $env{user.state.<cid>}
9399: # or looks up a condition reference in the bighash and if if hasn't
9400: # already been evaluated recurses into docondval to get the value of
9401: # the condition, then memoizing it to
9402: # $env{user.state.<cid>.<condition>}
1.40 www 9403: sub directcondval {
9404: my $number=shift;
1.620 albertel 9405: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9406: &Apache::lonuserstate::evalstate();
9407: }
1.713 albertel 9408: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9409: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9410: } elsif ($number =~ /^_/) {
9411: my $sub_condition;
9412: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9413: &GDBM_READER(),0640)) {
9414: $sub_condition=$bighash{'conditions'.$number};
9415: untie(%bighash);
9416: }
9417: my $value = &docondval($sub_condition);
1.949 raeburn 9418: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9419: return $value;
9420: }
1.620 albertel 9421: if ($env{'user.state.'.$env{'request.course.id'}}) {
9422: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9423: } else {
9424: return 2;
9425: }
9426: }
9427:
1.713 albertel 9428: # get the collection of conditions for this resource
1.26 www 9429: sub condval {
9430: my $condidx=shift;
1.54 www 9431: my $allpathcond='';
1.713 albertel 9432: foreach my $cond (split(/\|/,$condidx)) {
9433: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9434: $allpathcond.=
9435: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9436: }
1.191 harris41 9437: }
1.54 www 9438: $allpathcond=~s/\|$//;
1.713 albertel 9439: return &docondval($allpathcond);
9440: }
9441:
9442: #evaluates an expression of conditions
9443: sub docondval {
9444: my ($allpathcond) = @_;
9445: my $result=0;
9446: if ($env{'request.course.id'}
9447: && defined($allpathcond)) {
9448: my $operand='|';
9449: my @stack;
9450: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9451: if ($chunk eq '(') {
9452: push @stack,($operand,$result);
9453: } elsif ($chunk eq ')') {
9454: my $before=pop @stack;
9455: if (pop @stack eq '&') {
9456: $result=$result>$before?$before:$result;
9457: } else {
9458: $result=$result>$before?$result:$before;
9459: }
9460: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9461: $operand=$chunk;
9462: } else {
9463: my $new=directcondval($chunk);
9464: if ($operand eq '&') {
9465: $result=$result>$new?$new:$result;
9466: } else {
9467: $result=$result>$new?$result:$new;
9468: }
9469: }
9470: }
1.26 www 9471: }
9472: return $result;
1.421 albertel 9473: }
9474:
9475: # ---------------------------------------------------- Devalidate courseresdata
9476:
9477: sub devalidatecourseresdata {
9478: my ($coursenum,$coursedomain)=@_;
9479: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9480: &devalidate_cache_new('courseres',$hashid);
1.28 www 9481: }
9482:
1.763 www 9483:
1.200 www 9484: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9485: #
9486: # Parameters:
9487: # $coursenum - Number of the course.
9488: # $coursedomain - Domain at which the course was created.
9489: # Returns:
9490: # A hash of the course parameters along (I think) with timestamps
9491: # and version info.
1.877 foxr 9492:
1.624 albertel 9493: sub get_courseresdata {
9494: my ($coursenum,$coursedomain)=@_;
1.200 www 9495: my $coursehom=&homeserver($coursenum,$coursedomain);
9496: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9497: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9498: my %dumpreply;
1.417 albertel 9499: unless (defined($cached)) {
1.624 albertel 9500: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9501: $result=\%dumpreply;
1.251 albertel 9502: my ($tmp) = keys(%dumpreply);
9503: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9504: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9505: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9506: return $tmp;
1.416 albertel 9507: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9508: $result=undef;
1.599 albertel 9509: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9510: }
9511: }
1.624 albertel 9512: return $result;
9513: }
9514:
1.633 albertel 9515: sub devalidateuserresdata {
9516: my ($uname,$udom)=@_;
9517: my $hashid="$udom:$uname";
9518: &devalidate_cache_new('userres',$hashid);
9519: }
9520:
1.624 albertel 9521: sub get_userresdata {
9522: my ($uname,$udom)=@_;
9523: #most student don\'t have any data set, check if there is some data
9524: if (&EXT_cache_status($udom,$uname)) { return undef; }
9525:
9526: my $hashid="$udom:$uname";
9527: my ($result,$cached)=&is_cached_new('userres',$hashid);
9528: if (!defined($cached)) {
9529: my %resourcedata=&dump('resourcedata',$udom,$uname);
9530: $result=\%resourcedata;
9531: &do_cache_new('userres',$hashid,$result,600);
9532: }
9533: my ($tmp)=keys(%$result);
9534: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9535: return $result;
9536: }
9537: #error 2 occurs when the .db doesn't exist
9538: if ($tmp!~/error: 2 /) {
1.672 albertel 9539: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9540: " Trying to get resource data for ".
9541: $uname." at ".$udom.": ".
9542: $tmp."</font>");
9543: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9544: #&EXT_cache_set($udom,$uname);
9545: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9546: undef($tmp); # not really an error so don't send it back
1.624 albertel 9547: }
9548: return $tmp;
9549: }
1.879 foxr 9550: #----------------------------------------------- resdata - return resource data
9551: # Purpose:
9552: # Return resource data for either users or for a course.
9553: # Parameters:
9554: # $name - Course/user name.
9555: # $domain - Name of the domain the user/course is registered on.
9556: # $type - Type of thing $name is (must be 'course' or 'user'
9557: # @which - Array of names of resources desired.
9558: # Returns:
9559: # The value of the first reasource in @which that is found in the
9560: # resource hash.
9561: # Exceptional Conditions:
9562: # If the $type passed in is not valid (not the string 'course' or
9563: # 'user', an undefined reference is returned.
9564: # If none of the resources are found, an undef is returned
1.624 albertel 9565: sub resdata {
9566: my ($name,$domain,$type,@which)=@_;
9567: my $result;
9568: if ($type eq 'course') {
9569: $result=&get_courseresdata($name,$domain);
9570: } elsif ($type eq 'user') {
9571: $result=&get_userresdata($name,$domain);
9572: }
9573: if (!ref($result)) { return $result; }
1.251 albertel 9574: foreach my $item (@which) {
1.927 albertel 9575: if (defined($result->{$item->[0]})) {
9576: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9577: }
1.250 albertel 9578: }
1.291 albertel 9579: return undef;
1.200 www 9580: }
9581:
1.379 matthew 9582: #
9583: # EXT resource caching routines
9584: #
9585:
9586: sub clear_EXT_cache_status {
1.383 albertel 9587: &delenv('cache.EXT.');
1.379 matthew 9588: }
9589:
9590: sub EXT_cache_status {
9591: my ($target_domain,$target_user) = @_;
1.383 albertel 9592: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9593: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9594: # We know already the user has no data
9595: return 1;
9596: } else {
9597: return 0;
9598: }
9599: }
9600:
9601: sub EXT_cache_set {
9602: my ($target_domain,$target_user) = @_;
1.383 albertel 9603: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9604: #&appenv({$cachename => time});
1.379 matthew 9605: }
9606:
1.28 www 9607: # --------------------------------------------------------- Value of a Variable
1.58 www 9608: sub EXT {
1.715 albertel 9609:
1.1172.2.28 raeburn 9610: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9611: unless ($varname) { return ''; }
1.218 albertel 9612: #get real user name/domain, courseid and symb
9613: my $courseid;
1.359 albertel 9614: my $publicuser;
1.427 www 9615: if ($symbparm) {
9616: $symbparm=&get_symb_from_alias($symbparm);
9617: }
1.218 albertel 9618: if (!($uname && $udom)) {
1.790 albertel 9619: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9620: if (!$symbparm) { $symbparm=$cursymb; }
9621: } else {
1.620 albertel 9622: $courseid=$env{'request.course.id'};
1.218 albertel 9623: }
1.48 www 9624: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9625: my $rest;
1.320 albertel 9626: if (defined($therest[0])) {
1.48 www 9627: $rest=join('.',@therest);
9628: } else {
9629: $rest='';
9630: }
1.320 albertel 9631:
1.57 www 9632: my $qualifierrest=$qualifier;
9633: if ($rest) { $qualifierrest.='.'.$rest; }
9634: my $spacequalifierrest=$space;
9635: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9636: if ($realm eq 'user') {
1.48 www 9637: # --------------------------------------------------------------- user.resource
9638: if ($space eq 'resource') {
1.651 albertel 9639: if ( (defined($Apache::lonhomework::parsing_a_problem)
9640: || defined($Apache::lonhomework::parsing_a_task))
9641: &&
1.744 albertel 9642: ($symbparm eq &symbread()) ) {
9643: # if we are in the middle of processing the resource the
9644: # get the value we are planning on committing
9645: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9646: return $Apache::lonhomework::results{$qualifierrest};
9647: } else {
9648: return $Apache::lonhomework::history{$qualifierrest};
9649: }
1.335 albertel 9650: } else {
1.359 albertel 9651: my %restored;
1.620 albertel 9652: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9653: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9654: } else {
9655: %restored=&restore($symbparm,$courseid,$udom,$uname);
9656: }
1.335 albertel 9657: return $restored{$qualifierrest};
9658: }
1.48 www 9659: # ----------------------------------------------------------------- user.access
9660: } elsif ($space eq 'access') {
1.218 albertel 9661: # FIXME - not supporting calls for a specific user
1.48 www 9662: return &allowed($qualifier,$rest);
9663: # ------------------------------------------ user.preferences, user.environment
9664: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9665: if (($uname eq $env{'user.name'}) &&
9666: ($udom eq $env{'user.domain'})) {
9667: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9668: } else {
1.359 albertel 9669: my %returnhash;
9670: if (!$publicuser) {
9671: %returnhash=&userenvironment($udom,$uname,
9672: $qualifierrest);
9673: }
1.218 albertel 9674: return $returnhash{$qualifierrest};
9675: }
1.48 www 9676: # ----------------------------------------------------------------- user.course
9677: } elsif ($space eq 'course') {
1.218 albertel 9678: # FIXME - not supporting calls for a specific user
1.620 albertel 9679: return $env{join('.',('request.course',$qualifier))};
1.48 www 9680: # ------------------------------------------------------------------- user.role
9681: } elsif ($space eq 'role') {
1.218 albertel 9682: # FIXME - not supporting calls for a specific user
1.620 albertel 9683: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9684: if ($qualifier eq 'value') {
9685: return $role;
9686: } elsif ($qualifier eq 'extent') {
9687: return $where;
9688: }
9689: # ----------------------------------------------------------------- user.domain
9690: } elsif ($space eq 'domain') {
1.218 albertel 9691: return $udom;
1.48 www 9692: # ------------------------------------------------------------------- user.name
9693: } elsif ($space eq 'name') {
1.218 albertel 9694: return $uname;
1.48 www 9695: # ---------------------------------------------------- Any other user namespace
1.29 www 9696: } else {
1.359 albertel 9697: my %reply;
9698: if (!$publicuser) {
9699: %reply=&get($space,[$qualifierrest],$udom,$uname);
9700: }
9701: return $reply{$qualifierrest};
1.48 www 9702: }
1.236 www 9703: } elsif ($realm eq 'query') {
9704: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9705: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9706: [$spacequalifierrest]);
1.620 albertel 9707: return $env{'form.'.$spacequalifierrest};
1.236 www 9708: } elsif ($realm eq 'request') {
1.48 www 9709: # ------------------------------------------------------------- request.browser
9710: if ($space eq 'browser') {
1.1145 bisitz 9711: return $env{'browser.'.$qualifier};
1.57 www 9712: # ------------------------------------------------------------ request.filename
9713: } else {
1.620 albertel 9714: return $env{'request.'.$spacequalifierrest};
1.29 www 9715: }
1.28 www 9716: } elsif ($realm eq 'course') {
1.48 www 9717: # ---------------------------------------------------------- course.description
1.620 albertel 9718: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9719: } elsif ($realm eq 'resource') {
1.165 www 9720:
1.620 albertel 9721: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9722: if (!$symbparm) { $symbparm=&symbread(); }
9723: }
1.693 albertel 9724:
9725: if ($space eq 'title') {
9726: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9727: return &gettitle($symbparm);
9728: }
9729:
9730: if ($space eq 'map') {
9731: my ($map) = &decode_symb($symbparm);
9732: return &symbread($map);
9733: }
1.905 albertel 9734: if ($space eq 'filename') {
9735: if ($symbparm) {
9736: return &clutter((&decode_symb($symbparm))[2]);
9737: }
9738: return &hreflocation('',$env{'request.filename'});
9739: }
1.693 albertel 9740:
9741: my ($section, $group, @groups);
1.593 albertel 9742: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 9743: if (($courseid eq '') && ($cid)) {
9744: $courseid = $cid;
9745: }
9746: if (($symbparm && $courseid) &&
9747: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9748:
1.218 albertel 9749: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9750:
1.60 www 9751: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9752: my $symbp=$symbparm;
1.735 albertel 9753: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9754:
9755: my $symbparm=$symbp.'.'.$spacequalifierrest;
9756: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9757:
1.620 albertel 9758: if (($env{'user.name'} eq $uname) &&
9759: ($env{'user.domain'} eq $udom)) {
9760: $section=$env{'request.course.sec'};
1.733 raeburn 9761: @groups = split(/:/,$env{'request.course.groups'});
9762: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9763: } else {
1.539 albertel 9764: if (! defined($usection)) {
1.551 albertel 9765: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9766: } else {
9767: $section = $usection;
9768: }
1.733 raeburn 9769: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9770: }
9771:
9772: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9773: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9774: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9775:
1.593 albertel 9776: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9777: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9778: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9779:
1.60 www 9780: # ----------------------------------------------------------- first, check user
1.624 albertel 9781:
9782: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9783: ([$courselevelr,'resource'],
9784: [$courselevelm,'map' ],
9785: [$courselevel, 'course' ]));
1.931 albertel 9786: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9787:
1.594 albertel 9788: # ------------------------------------------------ second, check some of course
1.684 raeburn 9789: my $coursereply;
1.691 raeburn 9790: if (@groups > 0) {
9791: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9792: $mapparm,$spacequalifierrest);
1.927 albertel 9793: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9794: }
1.96 www 9795:
1.684 raeburn 9796: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9797: $env{'course.'.$courseid.'.domain'},
9798: 'course',
9799: ([$seclevelr, 'resource'],
9800: [$seclevelm, 'map' ],
9801: [$seclevel, 'course' ],
9802: [$courselevelr,'resource']));
9803: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9804:
1.60 www 9805: # ------------------------------------------------------ third, check map parms
1.218 albertel 9806: my %parmhash=();
9807: my $thisparm='';
9808: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9809: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9810: &GDBM_READER(),0640)) {
1.218 albertel 9811: $thisparm=$parmhash{$symbparm};
9812: untie(%parmhash);
9813: }
1.927 albertel 9814: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9815: }
1.594 albertel 9816: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9817:
1.218 albertel 9818: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9819: my $filename;
9820: if (!$symbparm) { $symbparm=&symbread(); }
9821: if ($symbparm) {
1.409 www 9822: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9823: } else {
1.620 albertel 9824: $filename=$env{'request.filename'};
1.282 albertel 9825: }
9826: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9827: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9828: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9829: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9830:
1.927 albertel 9831: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9832: if ($symbparm && defined($courseid) &&
1.620 albertel 9833: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9834: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9835: $env{'course.'.$courseid.'.domain'},
9836: 'course',
1.927 albertel 9837: ([$courselevelm,'map' ],
9838: [$courselevel, 'course']));
9839: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9840: }
1.145 www 9841: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9842: unless ($space eq '0') {
1.336 albertel 9843: my @parts=split(/_/,$space);
9844: my $id=pop(@parts);
9845: my $part=join('_',@parts);
9846: if ($part eq '') { $part='0'; }
1.927 albertel 9847: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9848: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9849: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9850: }
1.395 albertel 9851: if ($recurse) { return undef; }
9852: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9853: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9854: # ---------------------------------------------------- Any other user namespace
9855: } elsif ($realm eq 'environment') {
9856: # ----------------------------------------------------------------- environment
1.620 albertel 9857: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9858: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9859: } else {
1.770 albertel 9860: if ($uname eq 'anonymous' && $udom eq '') {
9861: return '';
9862: }
1.219 albertel 9863: my %returnhash=&userenvironment($udom,$uname,
9864: $spacequalifierrest);
9865: return $returnhash{$spacequalifierrest};
9866: }
1.28 www 9867: } elsif ($realm eq 'system') {
1.48 www 9868: # ----------------------------------------------------------------- system.time
9869: if ($space eq 'time') {
9870: return time;
9871: }
1.696 albertel 9872: } elsif ($realm eq 'server') {
9873: # ----------------------------------------------------------------- system.time
9874: if ($space eq 'name') {
9875: return $ENV{'SERVER_NAME'};
9876: }
1.28 www 9877: }
1.48 www 9878: return '';
1.61 www 9879: }
9880:
1.927 albertel 9881: sub get_reply {
9882: my ($reply_value) = @_;
1.940 raeburn 9883: if (ref($reply_value) eq 'ARRAY') {
9884: if (wantarray) {
9885: return @$reply_value;
9886: }
9887: return $reply_value->[0];
9888: } else {
9889: return $reply_value;
1.927 albertel 9890: }
9891: }
9892:
1.691 raeburn 9893: sub check_group_parms {
9894: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9895: my @groupitems = ();
9896: my $resultitem;
1.927 albertel 9897: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9898: foreach my $group (@{$groups}) {
9899: foreach my $level (@levels) {
1.927 albertel 9900: my $item = $courseid.'.['.$group.'].'.$level->[0];
9901: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9902: }
9903: }
9904: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9905: $env{'course.'.$courseid.'.domain'},
9906: 'course',@groupitems);
9907: return $coursereply;
9908: }
9909:
9910: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9911: my ($courseid,@groups) = @_;
9912: @groups = sort(@groups);
1.691 raeburn 9913: return @groups;
9914: }
9915:
1.395 albertel 9916: sub packages_tab_default {
9917: my ($uri,$varname)=@_;
9918: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 9919:
9920: my (@extension,@specifics,$do_default);
9921: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 9922: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 9923: if ($pack_type eq 'default') {
9924: $do_default=1;
9925: } elsif ($pack_type eq 'extension') {
9926: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 9927: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 9928: # only look at packages defaults for packages that this id is
1.738 albertel 9929: push(@specifics,[$package,$pack_type,$pack_part]);
9930: }
9931: }
9932: # first look for a package that matches the requested part id
9933: foreach my $package (@specifics) {
9934: my (undef,$pack_type,$pack_part)=@{$package};
9935: next if ($pack_part ne $part);
9936: if (defined($packagetab{"$pack_type&$name&default"})) {
9937: return $packagetab{"$pack_type&$name&default"};
9938: }
9939: }
9940: # look for any possible matching non extension_ package
9941: foreach my $package (@specifics) {
9942: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 9943: if (defined($packagetab{"$pack_type&$name&default"})) {
9944: return $packagetab{"$pack_type&$name&default"};
9945: }
1.585 albertel 9946: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 9947: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9948: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 9949: }
9950: }
1.738 albertel 9951: # look for any posible extension_ match
9952: foreach my $package (@extension) {
9953: my ($package,$pack_type)=@{$package};
9954: if (defined($packagetab{"$pack_type&$name&default"})) {
9955: return $packagetab{"$pack_type&$name&default"};
9956: }
9957: if (defined($packagetab{$package."&$name&default"})) {
9958: return $packagetab{$package."&$name&default"};
9959: }
9960: }
9961: # look for a global default setting
9962: if ($do_default && defined($packagetab{"default&$name&default"})) {
9963: return $packagetab{"default&$name&default"};
9964: }
1.395 albertel 9965: return undef;
9966: }
9967:
1.334 albertel 9968: sub add_prefix_and_part {
9969: my ($prefix,$part)=@_;
9970: my $keyroot;
9971: if (defined($prefix) && $prefix !~ /^__/) {
9972: # prefix that has a part already
9973: $keyroot=$prefix;
9974: } elsif (defined($prefix)) {
9975: # prefix that is missing a part
9976: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9977: } else {
9978: # no prefix at all
9979: if (defined($part)) { $keyroot='_'.$part; }
9980: }
9981: return $keyroot;
9982: }
9983:
1.71 www 9984: # ---------------------------------------------------------------- Get metadata
9985:
1.599 albertel 9986: my %metaentry;
1.1070 www 9987: my %importedpartids;
1.71 www 9988: sub metadata {
1.176 www 9989: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9990: $uri=&declutter($uri);
1.288 albertel 9991: # if it is a non metadata possible uri return quickly
1.529 albertel 9992: if (($uri eq '') ||
9993: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 9994: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 9995: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9996: return undef;
9997: }
1.1140 www 9998: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9999: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10000: return undef;
1.288 albertel 10001: }
1.73 www 10002: my $filename=$uri;
10003: $uri=~s/\.meta$//;
1.172 www 10004: #
10005: # Is the metadata already cached?
1.177 www 10006: # Look at timestamp of caching
1.172 www 10007: # Everything is cached by the main uri, libraries are never directly cached
10008: #
1.428 albertel 10009: if (!defined($liburi)) {
1.599 albertel 10010: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10011: if (defined($cached)) { return $result->{':'.$what}; }
10012: }
10013: {
1.1069 www 10014: # Imported parts would go here
1.1070 www 10015: my %importedids=();
10016: my @origfileimportpartids=();
1.1069 www 10017: my $importedparts=0;
1.172 www 10018: #
10019: # Is this a recursive call for a library?
10020: #
1.599 albertel 10021: # if (! exists($metacache{$uri})) {
10022: # $metacache{$uri}={};
10023: # }
1.924 albertel 10024: my $cachetime = 60*60;
1.171 www 10025: if ($liburi) {
10026: $liburi=&declutter($liburi);
10027: $filename=$liburi;
1.401 bowersj2 10028: } else {
1.599 albertel 10029: &devalidate_cache_new('meta',$uri);
10030: undef(%metaentry);
1.401 bowersj2 10031: }
1.140 www 10032: my %metathesekeys=();
1.73 www 10033: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10034: my $metastring;
1.1140 www 10035: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10036: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10037: $metastring =
1.929 albertel 10038: &Apache::lonnet::ssi_body($which,
1.924 albertel 10039: ('grade_target' => 'meta'));
10040: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10041: } elsif (($uri !~ m -^(editupload)/-) &&
10042: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10043: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10044: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10045: $metastring=&getfile($file);
1.489 albertel 10046: }
1.208 albertel 10047: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10048: my $token;
1.140 www 10049: undef %metathesekeys;
1.71 www 10050: while ($token=$parser->get_token) {
1.339 albertel 10051: if ($token->[0] eq 'S') {
10052: if (defined($token->[2]->{'package'})) {
1.172 www 10053: #
10054: # This is a package - get package info
10055: #
1.339 albertel 10056: my $package=$token->[2]->{'package'};
10057: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10058: if (defined($token->[2]->{'id'})) {
10059: $keyroot.='_'.$token->[2]->{'id'};
10060: }
1.599 albertel 10061: if ($metaentry{':packages'}) {
10062: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10063: } else {
1.599 albertel 10064: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10065: }
1.736 albertel 10066: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10067: my $part=$keyroot;
10068: $part=~s/^\_//;
1.736 albertel 10069: if ($pack_entry=~/^\Q$package\E\&/ ||
10070: $pack_entry=~/^\Q$package\E_0\&/) {
10071: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10072: # ignore package.tab specified default values
10073: # here &package_tab_default() will fetch those
10074: if ($subp eq 'default') { next; }
1.736 albertel 10075: my $value=$packagetab{$pack_entry};
1.432 albertel 10076: my $unikey;
10077: if ($pack =~ /_0$/) {
10078: $unikey='parameter_0_'.$name;
10079: $part=0;
10080: } else {
10081: $unikey='parameter'.$keyroot.'_'.$name;
10082: }
1.339 albertel 10083: if ($subp eq 'display') {
10084: $value.=' [Part: '.$part.']';
10085: }
1.599 albertel 10086: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10087: $metathesekeys{$unikey}=1;
1.599 albertel 10088: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10089: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10090: }
1.599 albertel 10091: if (defined($metaentry{':'.$unikey.'.default'})) {
10092: $metaentry{':'.$unikey}=
10093: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10094: }
1.339 albertel 10095: }
10096: }
10097: } else {
1.172 www 10098: #
10099: # This is not a package - some other kind of start tag
1.339 albertel 10100: #
10101: my $entry=$token->[1];
1.1068 www 10102: my $unikey='';
1.175 www 10103:
1.339 albertel 10104: if ($entry eq 'import') {
1.175 www 10105: #
10106: # Importing a library here
1.339 albertel 10107: #
1.1067 www 10108: my $location=$parser->get_text('/import');
10109: my $dir=$filename;
10110: $dir=~s|[^/]*$||;
10111: $location=&filelocation($dir,$location);
1.1069 www 10112:
1.1068 www 10113: my $importmode=$token->[2]->{'importmode'};
10114: if ($importmode eq 'problem') {
1.1069 www 10115: # Import as problem/response
1.1068 www 10116: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10117: } elsif ($importmode eq 'part') {
10118: # Import as part(s)
1.1069 www 10119: $importedparts=1;
10120: # We need to get the original file and the imported file to get the part order correct
10121: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10122: # Load and inspect original file
1.1070 www 10123: if ($#origfileimportpartids<0) {
10124: undef(%importedpartids);
10125: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10126: my $origfile=&getfile($origfilelocation);
10127: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10128: }
10129:
1.1069 www 10130: # Load and inspect imported file
10131: my $impfile=&getfile($location);
10132: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10133: if ($#impfilepartids>=0) {
10134: # This problem had parts
1.1070 www 10135: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10136: } else {
10137: # Importing by turning a single problem into a problem part
10138: # It gets the import-tags ID as part-ID
10139: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10140: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10141: }
1.1068 www 10142: } else {
10143: # Normal import
10144: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10145: if (defined($token->[2]->{'id'})) {
10146: $unikey.='_'.$token->[2]->{'id'};
10147: }
1.1067 www 10148: }
10149:
1.339 albertel 10150: if ($depthcount<20) {
1.736 albertel 10151: my $metadata =
10152: &metadata($uri,'keys', $location,$unikey,
10153: $depthcount+1);
10154: foreach my $meta (split(',',$metadata)) {
10155: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10156: $metathesekeys{$meta}=1;
1.339 albertel 10157: }
1.1068 www 10158:
10159: }
1.1067 www 10160: } else {
10161: #
10162: # Not importing, some other kind of non-package, non-library start tag
10163: #
10164: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10165: if (defined($token->[2]->{'id'})) {
10166: $unikey.='_'.$token->[2]->{'id'};
10167: }
1.339 albertel 10168: if (defined($token->[2]->{'name'})) {
10169: $unikey.='_'.$token->[2]->{'name'};
10170: }
10171: $metathesekeys{$unikey}=1;
1.736 albertel 10172: foreach my $param (@{$token->[3]}) {
10173: $metaentry{':'.$unikey.'.'.$param} =
10174: $token->[2]->{$param};
1.339 albertel 10175: }
10176: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10177: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10178: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10179: # only ws inside the tag, and not in default, so use default
10180: # as value
1.599 albertel 10181: $metaentry{':'.$unikey}=$default;
1.908 albertel 10182: } elsif ( $internaltext =~ /\S/ ) {
10183: # something interesting inside the tag
10184: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10185: } else {
1.908 albertel 10186: # no interesting values, don't set a default
1.339 albertel 10187: }
1.172 www 10188: # end of not-a-package not-a-library import
1.339 albertel 10189: }
1.172 www 10190: # end of not-a-package start tag
1.339 albertel 10191: }
1.172 www 10192: # the next is the end of "start tag"
1.339 albertel 10193: }
10194: }
1.483 albertel 10195: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10196: $extension = lc($extension);
10197: if ($extension eq 'htm') { $extension='html'; }
10198:
1.737 albertel 10199: foreach my $key (keys(%packagetab)) {
1.483 albertel 10200: #no specific packages #how's our extension
10201: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10202: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10203: \%metathesekeys);
10204: }
1.883 albertel 10205:
10206: if (!exists($metaentry{':packages'})
10207: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10208: foreach my $key (keys(%packagetab)) {
1.483 albertel 10209: #no specific packages well let's get default then
10210: if ($key!~/^default&/) { next; }
1.488 albertel 10211: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10212: \%metathesekeys);
10213: }
10214: }
1.338 www 10215: # are there custom rights to evaluate
1.599 albertel 10216: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10217:
1.338 www 10218: #
10219: # Importing a rights file here
1.339 albertel 10220: #
10221: unless ($depthcount) {
1.599 albertel 10222: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10223: my $dir=$filename;
10224: $dir=~s|[^/]*$||;
10225: $location=&filelocation($dir,$location);
1.736 albertel 10226: my $rights_metadata =
10227: &metadata($uri,'keys',$location,'_rights',
10228: $depthcount+1);
10229: foreach my $rights (split(',',$rights_metadata)) {
10230: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10231: $metathesekeys{$rights}=1;
1.339 albertel 10232: }
10233: }
10234: }
1.737 albertel 10235: # uniqifiy package listing
10236: my %seen;
10237: my @uniq_packages =
10238: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10239: $metaentry{':packages'} = join(',',@uniq_packages);
10240:
1.1070 www 10241: if ($importedparts) {
10242: # We had imported parts and need to rebuild partorder
10243: $metaentry{':partorder'}='';
10244: $metathesekeys{'partorder'}=1;
10245: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10246: if ($origfileimportpartids[$index] eq 'part') {
10247: # original part, part of the problem
10248: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10249: } else {
10250: # we have imported parts at this position
10251: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10252: }
10253: }
10254: $metaentry{':partorder'}=~s/^\,//;
10255: }
10256:
1.737 albertel 10257: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10258: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10259: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10260: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10261: # this is the end of "was not already recently cached
1.71 www 10262: }
1.599 albertel 10263: return $metaentry{':'.$what};
1.261 albertel 10264: }
10265:
1.488 albertel 10266: sub metadata_create_package_def {
1.483 albertel 10267: my ($uri,$key,$package,$metathesekeys)=@_;
10268: my ($pack,$name,$subp)=split(/\&/,$key);
10269: if ($subp eq 'default') { next; }
10270:
1.599 albertel 10271: if (defined($metaentry{':packages'})) {
10272: $metaentry{':packages'}.=','.$package;
1.483 albertel 10273: } else {
1.599 albertel 10274: $metaentry{':packages'}=$package;
1.483 albertel 10275: }
10276: my $value=$packagetab{$key};
10277: my $unikey;
10278: $unikey='parameter_0_'.$name;
1.599 albertel 10279: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10280: $$metathesekeys{$unikey}=1;
1.599 albertel 10281: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10282: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10283: }
1.599 albertel 10284: if (defined($metaentry{':'.$unikey.'.default'})) {
10285: $metaentry{':'.$unikey}=
10286: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10287: }
10288: }
10289:
1.261 albertel 10290: sub metadata_generate_part0 {
10291: my ($metadata,$metacache,$uri) = @_;
10292: my %allnames;
1.737 albertel 10293: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10294: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10295: my $part=$$metacache{':'.$metakey.'.part'};
10296: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10297: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10298: $allnames{$name}=$part;
10299: }
10300: }
10301: }
10302: foreach my $name (keys(%allnames)) {
10303: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10304: my $key=":parameter_0_$name";
1.261 albertel 10305: $$metacache{"$key.part"}='0';
10306: $$metacache{"$key.name"}=$name;
1.428 albertel 10307: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10308: $allnames{$name}.'_'.$name.
10309: '.type'};
1.428 albertel 10310: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10311: '.display'};
1.644 www 10312: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10313: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10314: $$metacache{"$key.display"}=$olddis;
10315: }
1.71 www 10316: }
10317:
1.764 albertel 10318: # ------------------------------------------------------ Devalidate title cache
10319:
10320: sub devalidate_title_cache {
10321: my ($url)=@_;
10322: if (!$env{'request.course.id'}) { return; }
10323: my $symb=&symbread($url);
10324: if (!$symb) { return; }
10325: my $key=$env{'request.course.id'}."\0".$symb;
10326: &devalidate_cache_new('title',$key);
10327: }
10328:
1.1014 droeschl 10329: # ------------------------------------------------- Get the title of a course
10330:
10331: sub current_course_title {
10332: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10333: }
1.301 www 10334: # ------------------------------------------------- Get the title of a resource
10335:
10336: sub gettitle {
10337: my $urlsymb=shift;
10338: my $symb=&symbread($urlsymb);
1.534 albertel 10339: if ($symb) {
1.620 albertel 10340: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10341: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10342: if (defined($cached)) {
10343: return $result;
10344: }
1.534 albertel 10345: my ($map,$resid,$url)=&decode_symb($symb);
10346: my $title='';
1.907 albertel 10347: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10348: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10349: } else {
10350: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10351: &GDBM_READER(),0640)) {
10352: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10353: $title=$bighash{'title_'.$mapid.'.'.$resid};
10354: untie(%bighash);
10355: }
1.534 albertel 10356: }
10357: $title=~s/\&colon\;/\:/gs;
10358: if ($title) {
1.1159 www 10359: # Remember both $symb and $title for dynamic metadata
10360: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10361: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10362: # Cache this title and then return it
1.599 albertel 10363: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10364: }
10365: $urlsymb=$url;
10366: }
10367: my $title=&metadata($urlsymb,'title');
10368: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10369: return $title;
1.301 www 10370: }
1.613 albertel 10371:
1.614 albertel 10372: sub get_slot {
10373: my ($which,$cnum,$cdom)=@_;
10374: if (!$cnum || !$cdom) {
1.790 albertel 10375: (undef,my $courseid)=&whichuser();
1.620 albertel 10376: $cdom=$env{'course.'.$courseid.'.domain'};
10377: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10378: }
1.703 albertel 10379: my $key=join("\0",'slots',$cdom,$cnum,$which);
10380: my %slotinfo;
10381: if (exists($remembered{$key})) {
10382: $slotinfo{$which} = $remembered{$key};
10383: } else {
10384: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10385: &Apache::lonhomework::showhash(%slotinfo);
10386: my ($tmp)=keys(%slotinfo);
10387: if ($tmp=~/^error:/) { return (); }
10388: $remembered{$key} = $slotinfo{$which};
10389: }
1.616 albertel 10390: if (ref($slotinfo{$which}) eq 'HASH') {
10391: return %{$slotinfo{$which}};
10392: }
10393: return $slotinfo{$which};
1.614 albertel 10394: }
1.1150 raeburn 10395:
10396: sub get_reservable_slots {
10397: my ($cnum,$cdom,$uname,$udom) = @_;
10398: my $now = time;
10399: my $reservable_info;
10400: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10401: if (exists($remembered{$key})) {
10402: $reservable_info = $remembered{$key};
10403: } else {
10404: my %resv;
10405: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10406: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10407: $reservable_info = \%resv;
10408: $remembered{$key} = $reservable_info;
10409: }
10410: return $reservable_info;
10411: }
10412:
10413: sub get_course_slots {
10414: my ($cnum,$cdom) = @_;
10415: my $hashid=$cnum.':'.$cdom;
10416: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10417: if (defined($cached)) {
10418: if (ref($result) eq 'HASH') {
10419: return %{$result};
10420: }
10421: } else {
10422: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10423: my ($tmp) = keys(%slots);
10424: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10425: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10426: return %slots;
10427: }
10428: }
10429: return;
10430: }
10431:
10432: sub devalidate_slots_cache {
10433: my ($cnum,$cdom)=@_;
10434: my $hashid=$cnum.':'.$cdom;
10435: &devalidate_cache_new('allslots',$hashid);
10436: }
10437:
1.1172.2.8 raeburn 10438: sub get_coursechange {
10439: my ($cdom,$cnum) = @_;
10440: if ($cdom eq '' || $cnum eq '') {
10441: return unless ($env{'request.course.id'});
10442: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10443: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10444: }
10445: my $hashid=$cdom.'_'.$cnum;
10446: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10447: if ((defined($cached)) && ($change ne '')) {
10448: return $change;
10449: } else {
10450: my %crshash;
10451: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10452: if ($crshash{'internal.contentchange'} eq '') {
10453: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10454: if ($change eq '') {
10455: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10456: $change = $crshash{'internal.created'};
10457: }
10458: } else {
10459: $change = $crshash{'internal.contentchange'};
10460: }
10461: my $cachetime = 600;
10462: &do_cache_new('crschange',$hashid,$change,$cachetime);
10463: }
10464: return $change;
10465: }
10466:
10467: sub devalidate_coursechange_cache {
10468: my ($cnum,$cdom)=@_;
10469: my $hashid=$cnum.':'.$cdom;
10470: &devalidate_cache_new('crschange',$hashid);
10471: }
10472:
1.31 www 10473: # ------------------------------------------------- Update symbolic store links
10474:
10475: sub symblist {
10476: my ($mapname,%newhash)=@_;
1.438 www 10477: $mapname=&deversion(&declutter($mapname));
1.31 www 10478: my %hash;
1.620 albertel 10479: if (($env{'request.course.fn'}) && (%newhash)) {
10480: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10481: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10482: foreach my $url (keys(%newhash)) {
1.711 albertel 10483: next if ($url eq 'last_known'
10484: && $env{'form.no_update_last_known'});
10485: $hash{declutter($url)}=&encode_symb($mapname,
10486: $newhash{$url}->[1],
10487: $newhash{$url}->[0]);
1.191 harris41 10488: }
1.31 www 10489: if (untie(%hash)) {
10490: return 'ok';
10491: }
10492: }
10493: }
10494: return 'error';
1.212 www 10495: }
10496:
10497: # --------------------------------------------------------------- Verify a symb
10498:
10499: sub symbverify {
1.1172.2.11 raeburn 10500: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10501: my $thisfn=$thisurl;
1.439 www 10502: $thisfn=&declutter($thisfn);
1.215 www 10503: # direct jump to resource in page or to a sequence - will construct own symbs
10504: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10505: # check URL part
1.409 www 10506: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10507:
1.431 www 10508: unless ($url eq $thisfn) { return 0; }
1.213 www 10509:
1.216 www 10510: $symb=&symbclean($symb);
1.510 www 10511: $thisurl=&deversion($thisurl);
1.439 www 10512: $thisfn=&deversion($thisfn);
1.213 www 10513:
10514: my %bighash;
10515: my $okay=0;
1.431 www 10516:
1.620 albertel 10517: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10518: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10519: my $noclutter;
1.1032 raeburn 10520: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10521: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10522: if ($map =~ m{^uploaded/.+\.page$}) {
10523: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10524: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10525: $noclutter = 1;
10526: }
10527: }
10528: my $ids;
10529: if ($noclutter) {
10530: $ids=$bighash{'ids_'.$thisurl};
10531: } else {
10532: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10533: }
1.1102 raeburn 10534: unless ($ids) {
1.1172.2.13 raeburn 10535: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10536: $ids=$bighash{$idkey};
1.216 www 10537: }
10538: if ($ids) {
10539: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10540: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10541: $symb =~ s/\?.+$//;
10542: }
1.800 albertel 10543: foreach my $id (split(/\,/,$ids)) {
10544: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10545: if (
10546: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10547: eq $symb) {
1.1172.2.11 raeburn 10548: if (ref($encstate)) {
10549: $$encstate = $bighash{'encrypted_'.$id};
10550: }
1.1172.2.13 raeburn 10551: if (($env{'request.role.adv'}) ||
10552: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10553: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10554: $okay=1;
10555: last;
10556: }
10557: }
10558: }
1.216 www 10559: }
1.213 www 10560: untie(%bighash);
10561: }
10562: return $okay;
1.31 www 10563: }
10564:
1.210 www 10565: # --------------------------------------------------------------- Clean-up symb
10566:
10567: sub symbclean {
10568: my $symb=shift;
1.568 albertel 10569: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10570: # remove version from map
10571: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10572:
1.210 www 10573: # remove version from URL
10574: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10575:
1.507 www 10576: # remove wrapper
10577:
1.510 www 10578: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10579: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10580: return $symb;
1.409 www 10581: }
10582:
10583: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10584:
10585: sub encode_symb {
10586: my ($map,$resid,$url)=@_;
10587: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10588: }
1.409 www 10589:
10590: sub decode_symb {
1.568 albertel 10591: my $symb=shift;
10592: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10593: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10594: return (&fixversion($map),$resid,&fixversion($url));
10595: }
10596:
10597: sub fixversion {
10598: my $fn=shift;
1.609 banghart 10599: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10600: my %bighash;
10601: my $uri=&clutter($fn);
1.620 albertel 10602: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10603: # is this cached?
1.599 albertel 10604: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10605: if (defined($cached)) { return $result; }
10606: # unfortunately not cached, or expired
1.620 albertel 10607: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10608: &GDBM_READER(),0640)) {
10609: if ($bighash{'version_'.$uri}) {
10610: my $version=$bighash{'version_'.$uri};
1.444 www 10611: unless (($version eq 'mostrecent') ||
10612: ($version==&getversion($uri))) {
1.440 www 10613: $uri=~s/\.(\w+)$/\.$version\.$1/;
10614: }
10615: }
10616: untie %bighash;
1.413 www 10617: }
1.599 albertel 10618: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10619: }
10620:
10621: sub deversion {
10622: my $url=shift;
10623: $url=~s/\.\d+\.(\w+)$/\.$1/;
10624: return $url;
1.210 www 10625: }
10626:
1.31 www 10627: # ------------------------------------------------------ Return symb list entry
10628:
10629: sub symbread {
1.249 www 10630: my ($thisfn,$donotrecurse)=@_;
1.1172.2.13 raeburn 10631: my $cache_str;
10632: if ($thisfn ne '') {
10633: $cache_str='request.symbread.cached.'.$thisfn;
10634: if ($env{$cache_str} ne '') {
1.1172.2.8 raeburn 10635: return $env{$cache_str};
10636: }
1.1172.2.13 raeburn 10637: } else {
1.242 www 10638: # no filename provided? try from environment
1.620 albertel 10639: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10640: return $env{$cache_str}=&symbclean($env{'request.symb'});
10641: }
10642: $thisfn=$env{'request.filename'};
1.44 www 10643: }
1.569 albertel 10644: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10645: # is that filename actually a symb? Verify, clean, and return
10646: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10647: if (&symbverify($thisfn,$1)) {
1.620 albertel 10648: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10649: }
1.242 www 10650: }
1.44 www 10651: $thisfn=declutter($thisfn);
1.31 www 10652: my %hash;
1.37 www 10653: my %bighash;
10654: my $syval='';
1.620 albertel 10655: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10656: my $targetfn = $thisfn;
1.609 banghart 10657: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10658: $targetfn = 'adm/wrapper/'.$thisfn;
10659: }
1.687 albertel 10660: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10661: $targetfn=$1;
10662: }
1.620 albertel 10663: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10664: &GDBM_READER(),0640)) {
1.481 raeburn 10665: $syval=$hash{$targetfn};
1.37 www 10666: untie(%hash);
10667: }
10668: # ---------------------------------------------------------- There was an entry
10669: if ($syval) {
1.601 albertel 10670: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10671: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10672: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10673: #return $env{$cache_str}='';
1.601 albertel 10674: #}
10675: #$syval.=$1;
10676: #}
1.37 www 10677: } else {
10678: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10679: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10680: &GDBM_READER(),0640)) {
1.37 www 10681: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10682: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10683: unless ($ids) {
10684: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10685: }
10686: unless ($ids) {
10687: # alias?
10688: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10689: }
1.37 www 10690: if ($ids) {
10691: # ------------------------------------------------------------------- Has ID(s)
10692: my @possibilities=split(/\,/,$ids);
1.39 www 10693: if ($#possibilities==0) {
10694: # ----------------------------------------------- There is only one possibility
1.37 www 10695: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10696: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10697: $resid,$thisfn);
1.249 www 10698: } elsif (!$donotrecurse) {
1.39 www 10699: # ------------------------------------------ There is more than one possibility
10700: my $realpossible=0;
1.800 albertel 10701: foreach my $id (@possibilities) {
10702: my $file=$bighash{'src_'.$id};
1.39 www 10703: if (&allowed('bre',$file)) {
1.800 albertel 10704: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10705: if ($bighash{'map_type_'.$mapid} ne 'page') {
10706: $realpossible++;
1.626 albertel 10707: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10708: $resid,$thisfn);
1.39 www 10709: }
10710: }
1.191 harris41 10711: }
1.39 www 10712: if ($realpossible!=1) { $syval=''; }
1.249 www 10713: } else {
10714: $syval='';
1.37 www 10715: }
10716: }
10717: untie(%bighash)
1.481 raeburn 10718: }
1.31 www 10719: }
1.62 www 10720: if ($syval) {
1.620 albertel 10721: return $env{$cache_str}=$syval;
1.62 www 10722: }
1.31 www 10723: }
1.949 raeburn 10724: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10725: return $env{$cache_str}='';
1.31 www 10726: }
10727:
10728: # ---------------------------------------------------------- Return random seed
10729:
1.32 www 10730: sub numval {
10731: my $txt=shift;
10732: $txt=~tr/A-J/0-9/;
10733: $txt=~tr/a-j/0-9/;
10734: $txt=~tr/K-T/0-9/;
10735: $txt=~tr/k-t/0-9/;
10736: $txt=~tr/U-Z/0-5/;
10737: $txt=~tr/u-z/0-5/;
10738: $txt=~s/\D//g;
1.564 albertel 10739: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10740: return int($txt);
1.368 albertel 10741: }
10742:
1.484 albertel 10743: sub numval2 {
10744: my $txt=shift;
10745: $txt=~tr/A-J/0-9/;
10746: $txt=~tr/a-j/0-9/;
10747: $txt=~tr/K-T/0-9/;
10748: $txt=~tr/k-t/0-9/;
10749: $txt=~tr/U-Z/0-5/;
10750: $txt=~tr/u-z/0-5/;
10751: $txt=~s/\D//g;
10752: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10753: my $total;
10754: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10755: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10756: return int($total);
10757: }
10758:
1.575 albertel 10759: sub numval3 {
10760: use integer;
10761: my $txt=shift;
10762: $txt=~tr/A-J/0-9/;
10763: $txt=~tr/a-j/0-9/;
10764: $txt=~tr/K-T/0-9/;
10765: $txt=~tr/k-t/0-9/;
10766: $txt=~tr/U-Z/0-5/;
10767: $txt=~tr/u-z/0-5/;
10768: $txt=~s/\D//g;
10769: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10770: my $total;
10771: foreach my $val (@txts) { $total+=$val; }
10772: if ($_64bit) { $total=(($total<<32)>>32); }
10773: return $total;
10774: }
10775:
1.675 albertel 10776: sub digest {
10777: my ($data)=@_;
10778: my $digest=&Digest::MD5::md5($data);
10779: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10780: my ($e,$f);
10781: {
10782: use integer;
10783: $e=($a+$b);
10784: $f=($c+$d);
10785: if ($_64bit) {
10786: $e=(($e<<32)>>32);
10787: $f=(($f<<32)>>32);
10788: }
10789: }
10790: if (wantarray) {
10791: return ($e,$f);
10792: } else {
10793: my $g;
10794: {
10795: use integer;
10796: $g=($e+$f);
10797: if ($_64bit) {
10798: $g=(($g<<32)>>32);
10799: }
10800: }
10801: return $g;
10802: }
10803: }
10804:
1.368 albertel 10805: sub latest_rnd_algorithm_id {
1.675 albertel 10806: return '64bit5';
1.366 albertel 10807: }
1.32 www 10808:
1.503 albertel 10809: sub get_rand_alg {
10810: my ($courseid)=@_;
1.790 albertel 10811: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10812: if ($courseid) {
1.620 albertel 10813: return $env{"course.$courseid.rndseed"};
1.503 albertel 10814: }
10815: return &latest_rnd_algorithm_id();
10816: }
10817:
1.562 albertel 10818: sub validCODE {
10819: my ($CODE)=@_;
10820: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10821: return 0;
10822: }
10823:
1.491 albertel 10824: sub getCODE {
1.620 albertel 10825: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10826: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10827: defined($Apache::lonhomework::parsing_a_task) ) &&
10828: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10829: return $Apache::lonhomework::history{'resource.CODE'};
10830: }
10831: return undef;
10832: }
1.1133 foxr 10833: #
10834: # Determines the random seed for a specific context:
10835: #
10836: # parameters:
10837: # symb - in course context the symb for the seed.
10838: # course_id - The course id of the form domain_coursenum.
10839: # domain - Domain for the user.
10840: # course - Course for the user.
10841: # cenv - environment of the course.
10842: #
10843: # NOTE:
10844: # All parameters are picked out of the environment if missing
10845: # or not defined.
10846: # If a symb cannot be determined the current time is used instead.
10847: #
10848: # For a given well defined symb, courside, domain, username,
10849: # and course environment, the seed is reproducible.
10850: #
1.31 www 10851: sub rndseed {
1.1133 foxr 10852: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10853: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10854: if (!defined($symb)) {
1.366 albertel 10855: unless ($symb=$wsymb) { return time; }
10856: }
1.1146 foxr 10857: if (!defined $courseid) {
10858: $courseid=$wcourseid;
10859: }
10860: if (!defined $domain) { $domain=$wdomain; }
10861: if (!defined $username) { $username=$wusername }
1.1133 foxr 10862:
10863: my $which;
10864: if (defined($cenv->{'rndseed'})) {
10865: $which = $cenv->{'rndseed'};
10866: } else {
10867: $which =&get_rand_alg($courseid);
10868: }
1.491 albertel 10869: if (defined(&getCODE())) {
1.675 albertel 10870: if ($which eq '64bit5') {
10871: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10872: } elsif ($which eq '64bit4') {
1.575 albertel 10873: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10874: } else {
10875: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10876: }
1.675 albertel 10877: } elsif ($which eq '64bit5') {
10878: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10879: } elsif ($which eq '64bit4') {
10880: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10881: } elsif ($which eq '64bit3') {
10882: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10883: } elsif ($which eq '64bit2') {
10884: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10885: } elsif ($which eq '64bit') {
10886: return &rndseed_64bit($symb,$courseid,$domain,$username);
10887: }
10888: return &rndseed_32bit($symb,$courseid,$domain,$username);
10889: }
10890:
10891: sub rndseed_32bit {
10892: my ($symb,$courseid,$domain,$username)=@_;
10893: {
10894: use integer;
10895: my $symbchck=unpack("%32C*",$symb) << 27;
10896: my $symbseed=numval($symb) << 22;
10897: my $namechck=unpack("%32C*",$username) << 17;
10898: my $nameseed=numval($username) << 12;
10899: my $domainseed=unpack("%32C*",$domain) << 7;
10900: my $courseseed=unpack("%32C*",$courseid);
10901: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10902: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10903: #&logthis("rndseed :$num:$symb");
1.564 albertel 10904: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10905: return $num;
10906: }
10907: }
10908:
10909: sub rndseed_64bit {
10910: my ($symb,$courseid,$domain,$username)=@_;
10911: {
10912: use integer;
10913: my $symbchck=unpack("%32S*",$symb) << 21;
10914: my $symbseed=numval($symb) << 10;
10915: my $namechck=unpack("%32S*",$username);
10916:
10917: my $nameseed=numval($username) << 21;
10918: my $domainseed=unpack("%32S*",$domain) << 10;
10919: my $courseseed=unpack("%32S*",$courseid);
10920:
10921: my $num1=$symbchck+$symbseed+$namechck;
10922: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10923: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10924: #&logthis("rndseed :$num:$symb");
1.564 albertel 10925: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 10926: return "$num1,$num2";
1.155 albertel 10927: }
1.366 albertel 10928: }
10929:
1.443 albertel 10930: sub rndseed_64bit2 {
10931: my ($symb,$courseid,$domain,$username)=@_;
10932: {
10933: use integer;
10934: # strings need to be an even # of cahracters long, it it is odd the
10935: # last characters gets thrown away
10936: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10937: my $symbseed=numval($symb) << 10;
10938: my $namechck=unpack("%32S*",$username.' ');
10939:
10940: my $nameseed=numval($username) << 21;
1.501 albertel 10941: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10942: my $courseseed=unpack("%32S*",$courseid.' ');
10943:
10944: my $num1=$symbchck+$symbseed+$namechck;
10945: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10946: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10947: #&logthis("rndseed :$num:$symb");
1.803 albertel 10948: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 10949: return "$num1,$num2";
10950: }
10951: }
10952:
10953: sub rndseed_64bit3 {
10954: my ($symb,$courseid,$domain,$username)=@_;
10955: {
10956: use integer;
10957: # strings need to be an even # of cahracters long, it it is odd the
10958: # last characters gets thrown away
10959: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10960: my $symbseed=numval2($symb) << 10;
10961: my $namechck=unpack("%32S*",$username.' ');
10962:
10963: my $nameseed=numval2($username) << 21;
1.443 albertel 10964: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10965: my $courseseed=unpack("%32S*",$courseid.' ');
10966:
10967: my $num1=$symbchck+$symbseed+$namechck;
10968: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10969: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10970: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 10971: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10972:
1.503 albertel 10973: return "$num1:$num2";
1.443 albertel 10974: }
10975: }
10976:
1.575 albertel 10977: sub rndseed_64bit4 {
10978: my ($symb,$courseid,$domain,$username)=@_;
10979: {
10980: use integer;
10981: # strings need to be an even # of cahracters long, it it is odd the
10982: # last characters gets thrown away
10983: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10984: my $symbseed=numval3($symb) << 10;
10985: my $namechck=unpack("%32S*",$username.' ');
10986:
10987: my $nameseed=numval3($username) << 21;
10988: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10989: my $courseseed=unpack("%32S*",$courseid.' ');
10990:
10991: my $num1=$symbchck+$symbseed+$namechck;
10992: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10993: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10994: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 10995: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10996:
1.575 albertel 10997: return "$num1:$num2";
10998: }
10999: }
11000:
1.675 albertel 11001: sub rndseed_64bit5 {
11002: my ($symb,$courseid,$domain,$username)=@_;
11003: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11004: return "$num1:$num2";
11005: }
11006:
1.366 albertel 11007: sub rndseed_CODE_64bit {
11008: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11009: {
1.366 albertel 11010: use integer;
1.443 albertel 11011: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11012: my $symbseed=numval2($symb);
1.491 albertel 11013: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11014: my $CODEseed=numval(&getCODE());
1.443 albertel 11015: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11016: my $num1=$symbseed+$CODEchck;
11017: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11018: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11019: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11020: if ($_64bit) { $num1=(($num1<<32)>>32); }
11021: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11022: return "$num1:$num2";
1.366 albertel 11023: }
11024: }
11025:
1.575 albertel 11026: sub rndseed_CODE_64bit4 {
11027: my ($symb,$courseid,$domain,$username)=@_;
11028: {
11029: use integer;
11030: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11031: my $symbseed=numval3($symb);
11032: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11033: my $CODEseed=numval3(&getCODE());
11034: my $courseseed=unpack("%32S*",$courseid.' ');
11035: my $num1=$symbseed+$CODEchck;
11036: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11037: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11038: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11039: if ($_64bit) { $num1=(($num1<<32)>>32); }
11040: if ($_64bit) { $num2=(($num2<<32)>>32); }
11041: return "$num1:$num2";
11042: }
11043: }
11044:
1.675 albertel 11045: sub rndseed_CODE_64bit5 {
11046: my ($symb,$courseid,$domain,$username)=@_;
11047: my $code = &getCODE();
11048: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11049: return "$num1:$num2";
11050: }
11051:
1.366 albertel 11052: sub setup_random_from_rndseed {
11053: my ($rndseed)=@_;
1.503 albertel 11054: if ($rndseed =~/([,:])/) {
11055: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11056: &Math::Random::random_set_seed(abs($num1),abs($num2));
11057: } else {
11058: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11059: }
1.36 albertel 11060: }
11061:
1.474 albertel 11062: sub latest_receipt_algorithm_id {
1.835 albertel 11063: return 'receipt3';
1.474 albertel 11064: }
11065:
1.480 www 11066: sub recunique {
11067: my $fucourseid=shift;
11068: my $unique;
1.835 albertel 11069: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11070: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11071: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11072: } else {
11073: $unique=$perlvar{'lonReceipt'};
11074: }
11075: return unpack("%32C*",$unique);
11076: }
11077:
11078: sub recprefix {
11079: my $fucourseid=shift;
11080: my $prefix;
1.835 albertel 11081: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11082: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11083: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11084: } else {
11085: $prefix=$perlvar{'lonHostID'};
11086: }
11087: return unpack("%32C*",$prefix);
11088: }
11089:
1.76 www 11090: sub ireceipt {
1.474 albertel 11091: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11092:
11093: my $return =&recprefix($fucourseid).'-';
11094:
11095: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11096: $env{'request.state'} eq 'construct') {
11097: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11098: return $return;
11099: }
11100:
1.76 www 11101: my $cuname=unpack("%32C*",$funame);
11102: my $cudom=unpack("%32C*",$fudom);
11103: my $cucourseid=unpack("%32C*",$fucourseid);
11104: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11105: my $cunique=&recunique($fucourseid);
1.474 albertel 11106: my $cpart=unpack("%32S*",$part);
1.835 albertel 11107: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11108:
1.790 albertel 11109: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11110:
11111: $return.= ($cunique%$cuname+
11112: $cunique%$cudom+
11113: $cusymb%$cuname+
11114: $cusymb%$cudom+
11115: $cucourseid%$cuname+
11116: $cucourseid%$cudom+
11117: $cpart%$cuname+
11118: $cpart%$cudom);
11119: } else {
11120: $return.= ($cunique%$cuname+
11121: $cunique%$cudom+
11122: $cusymb%$cuname+
11123: $cusymb%$cudom+
11124: $cucourseid%$cuname+
11125: $cucourseid%$cudom);
11126: }
11127: return $return;
1.76 www 11128: }
11129:
11130: sub receipt {
1.474 albertel 11131: my ($part)=@_;
1.790 albertel 11132: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11133: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11134: }
1.260 ng 11135:
1.790 albertel 11136: sub whichuser {
11137: my ($passedsymb)=@_;
11138: my ($symb,$courseid,$domain,$name,$publicuser);
11139: if (defined($env{'form.grade_symb'})) {
11140: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11141: my $allowed=&allowed('vgr',$tmp_courseid);
11142: if (!$allowed &&
11143: exists($env{'request.course.sec'}) &&
11144: $env{'request.course.sec'} !~ /^\s*$/) {
11145: $allowed=&allowed('vgr',$tmp_courseid.
11146: '/'.$env{'request.course.sec'});
11147: }
11148: if ($allowed) {
11149: ($symb)=&get_env_multiple('form.grade_symb');
11150: $courseid=$tmp_courseid;
11151: ($domain)=&get_env_multiple('form.grade_domain');
11152: ($name)=&get_env_multiple('form.grade_username');
11153: return ($symb,$courseid,$domain,$name,$publicuser);
11154: }
11155: }
11156: if (!$passedsymb) {
11157: $symb=&symbread();
11158: } else {
11159: $symb=$passedsymb;
11160: }
11161: $courseid=$env{'request.course.id'};
11162: $domain=$env{'user.domain'};
11163: $name=$env{'user.name'};
11164: if ($name eq 'public' && $domain eq 'public') {
11165: if (!defined($env{'form.username'})) {
11166: $env{'form.username'}.=time.rand(10000000);
11167: }
11168: $name.=$env{'form.username'};
11169: }
11170: return ($symb,$courseid,$domain,$name,$publicuser);
11171:
11172: }
11173:
1.36 albertel 11174: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11175: # returns either the contents of the file or
11176: # -1 if the file doesn't exist
1.481 raeburn 11177: #
11178: # if the target is a file that was uploaded via DOCS,
11179: # a check will be made to see if a current copy exists on the local server,
11180: # if it does this will be served, otherwise a copy will be retrieved from
11181: # the home server for the course and stored in /home/httpd/html/userfiles on
11182: # the local server.
1.472 albertel 11183:
1.36 albertel 11184: sub getfile {
1.538 albertel 11185: my ($file) = @_;
1.609 banghart 11186: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11187: &repcopy($file);
11188: return &readfile($file);
11189: }
11190:
11191: sub repcopy_userfile {
11192: my ($file)=@_;
1.1142 raeburn 11193: my $londocroot = $perlvar{'lonDocRoot'};
11194: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11195: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11196: my ($cdom,$cnum,$filename) =
1.811 albertel 11197: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11198: my $uri="/uploaded/$cdom/$cnum/$filename";
11199: if (-e "$file") {
1.828 www 11200: # we already have a local copy, check it out
1.538 albertel 11201: my @fileinfo = stat($file);
1.828 www 11202: my $rtncode;
11203: my $info;
1.538 albertel 11204: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11205: if ($lwpresp ne 'ok') {
1.828 www 11206: # there is no such file anymore, even though we had a local copy
1.482 albertel 11207: if ($rtncode eq '404') {
1.538 albertel 11208: unlink($file);
1.482 albertel 11209: }
11210: return -1;
11211: }
11212: if ($info < $fileinfo[9]) {
1.828 www 11213: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11214: return 'ok';
1.828 www 11215: } else {
11216: # the file is outdated, get rid of it
11217: unlink($file);
1.482 albertel 11218: }
1.828 www 11219: }
11220: # one way or the other, at this point, we don't have the file
11221: # construct the correct path for the file
11222: my @parts = ($cdom,$cnum);
11223: if ($filename =~ m|^(.+)/[^/]+$|) {
11224: push @parts, split(/\//,$1);
11225: }
11226: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11227: foreach my $part (@parts) {
11228: $path .= '/'.$part;
11229: if (!-e $path) {
11230: mkdir($path,0770);
1.482 albertel 11231: }
11232: }
1.828 www 11233: # now the path exists for sure
11234: # get a user agent
11235: my $ua=new LWP::UserAgent;
11236: my $transferfile=$file.'.in.transfer';
11237: # FIXME: this should flock
11238: if (-e $transferfile) { return 'ok'; }
11239: my $request;
11240: $uri=~s/^\///;
1.980 raeburn 11241: my $homeserver = &homeserver($cnum,$cdom);
11242: my $protocol = $protocol{$homeserver};
11243: $protocol = 'http' if ($protocol ne 'https');
11244: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11245: my $response=$ua->request($request,$transferfile);
11246: # did it work?
11247: if ($response->is_error()) {
11248: unlink($transferfile);
11249: &logthis("Userfile repcopy failed for $uri");
11250: return -1;
11251: }
11252: # worked, rename the transfer file
11253: rename($transferfile,$file);
1.607 raeburn 11254: return 'ok';
1.481 raeburn 11255: }
11256:
1.517 albertel 11257: sub tokenwrapper {
11258: my $uri=shift;
1.980 raeburn 11259: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11260: $uri=~s|^/||;
1.620 albertel 11261: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11262: my $token=$1;
1.552 albertel 11263: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11264: if ($udom && $uname && $file) {
11265: $file=~s|(\?\.*)*$||;
1.949 raeburn 11266: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11267: my $homeserver = &homeserver($uname,$udom);
11268: my $protocol = $protocol{$homeserver};
11269: $protocol = 'http' if ($protocol ne 'https');
11270: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11271: (($uri=~/\?/)?'&':'?').'token='.$token.
11272: '&tokenissued='.$perlvar{'lonHostID'};
11273: } else {
11274: return '/adm/notfound.html';
11275: }
11276: }
11277:
1.828 www 11278: # call with reqtype HEAD: get last modification time
11279: # call with reqtype GET: get the file contents
11280: # Do not call this with reqtype GET for large files! It loads everything into memory
11281: #
1.481 raeburn 11282: sub getuploaded {
11283: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11284: $uri=~s/^\///;
1.980 raeburn 11285: my $homeserver = &homeserver($cnum,$cdom);
11286: my $protocol = $protocol{$homeserver};
11287: $protocol = 'http' if ($protocol ne 'https');
11288: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11289: my $ua=new LWP::UserAgent;
11290: my $request=new HTTP::Request($reqtype,$uri);
11291: my $response=$ua->request($request);
11292: $$rtncode = $response->code;
1.482 albertel 11293: if (! $response->is_success()) {
11294: return 'failed';
11295: }
11296: if ($reqtype eq 'HEAD') {
1.486 www 11297: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11298: } elsif ($reqtype eq 'GET') {
11299: $$info = $response->content;
1.472 albertel 11300: }
1.482 albertel 11301: return 'ok';
1.36 albertel 11302: }
11303:
1.481 raeburn 11304: sub readfile {
11305: my $file = shift;
11306: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11307: my $fh;
11308: open($fh,"<$file");
11309: my $a='';
1.800 albertel 11310: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11311: return $a;
11312: }
11313:
1.36 albertel 11314: sub filelocation {
1.590 banghart 11315: my ($dir,$file) = @_;
11316: my $location;
11317: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11318:
11319: if ($file =~ m-^/adm/-) {
11320: $file=~s-^/adm/wrapper/-/-;
11321: $file=~s-^/adm/coursedocs/showdoc/-/-;
11322: }
1.882 albertel 11323:
1.1139 www 11324: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11325: $location = $file;
1.609 banghart 11326: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11327: my ($udom,$uname,$filename)=
1.811 albertel 11328: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11329: my $home=&homeserver($uname,$udom);
11330: my $is_me=0;
11331: my @ids=¤t_machine_ids();
11332: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11333: if ($is_me) {
1.1117 foxr 11334: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11335: } else {
11336: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11337: $udom.'/'.$uname.'/'.$filename;
11338: }
1.882 albertel 11339: } elsif ($file =~ m-^/adm/-) {
11340: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11341: } else {
11342: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11343: $file=~s:^/(res|priv)/:/:;
11344: my $space=$1;
1.590 banghart 11345: if ( !( $file =~ m:^/:) ) {
11346: $location = $dir. '/'.$file;
11347: } else {
1.1142 raeburn 11348: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11349: }
1.59 albertel 11350: }
1.590 banghart 11351: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11352: while ($location=~m{/\.\./}) {
11353: if ($location =~ m{/[^/]+/\.\./}) {
11354: $location=~ s{/[^/]+/\.\./}{/}g;
11355: } else {
11356: $location=~ s{/\.\./}{/}g;
11357: }
11358: } #remove dir/..
1.590 banghart 11359: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11360: return $location;
1.46 www 11361: }
1.36 albertel 11362:
1.46 www 11363: sub hreflocation {
11364: my ($dir,$file)=@_;
1.980 raeburn 11365: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11366: $file=filelocation($dir,$file);
1.700 albertel 11367: } elsif ($file=~m-^/adm/-) {
11368: $file=~s-^/adm/wrapper/-/-;
11369: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11370: }
11371: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11372: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11373: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11374: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11375: {/uploaded/$1/$2/}x;
1.46 www 11376: }
1.913 albertel 11377: if ($file=~ m{^/userfiles/}) {
11378: $file =~ s{^/userfiles/}{/uploaded/};
11379: }
1.462 albertel 11380: return $file;
1.465 albertel 11381: }
11382:
1.1139 www 11383:
11384:
11385:
11386:
1.465 albertel 11387: sub current_machine_domains {
1.853 albertel 11388: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11389: }
11390:
11391: sub machine_domains {
11392: my ($hostname) = @_;
1.465 albertel 11393: my @domains;
1.838 albertel 11394: my %hostname = &all_hostnames();
1.465 albertel 11395: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11396: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11397: if ($hostname eq $name) {
1.844 albertel 11398: push(@domains,&host_domain($id));
1.465 albertel 11399: }
11400: }
11401: return @domains;
11402: }
11403:
11404: sub current_machine_ids {
1.853 albertel 11405: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11406: }
11407:
11408: sub machine_ids {
11409: my ($hostname) = @_;
11410: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11411: my @ids;
1.888 albertel 11412: my %name_to_host = &all_names();
1.889 albertel 11413: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11414: return @{ $name_to_host{$hostname} };
11415: }
11416: return;
1.31 www 11417: }
11418:
1.824 raeburn 11419: sub additional_machine_domains {
11420: my @domains;
11421: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11422: while( my $line = <$fh>) {
11423: $line =~ s/\s//g;
11424: push(@domains,$line);
11425: }
11426: return @domains;
11427: }
11428:
11429: sub default_login_domain {
11430: my $domain = $perlvar{'lonDefDomain'};
11431: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11432: foreach my $posdom (¤t_machine_domains(),
11433: &additional_machine_domains()) {
11434: if (lc($posdom) eq lc($testdomain)) {
11435: $domain=$posdom;
11436: last;
11437: }
11438: }
11439: return $domain;
11440: }
11441:
1.31 www 11442: # ------------------------------------------------------------- Declutters URLs
11443:
11444: sub declutter {
11445: my $thisfn=shift;
1.569 albertel 11446: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11447: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11448: $thisfn=~s/^\///;
1.697 albertel 11449: $thisfn=~s|^adm/wrapper/||;
11450: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11451: $thisfn=~s/^res\///;
1.1172 bisitz 11452: $thisfn=~s/^priv\///;
1.1032 raeburn 11453: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11454: $thisfn=~s/\?.+$//;
11455: }
1.268 www 11456: return $thisfn;
11457: }
11458:
11459: # ------------------------------------------------------------- Clutter up URLs
11460:
11461: sub clutter {
11462: my $thisfn='/'.&declutter(shift);
1.887 albertel 11463: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11464: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11465: $thisfn='/res'.$thisfn;
11466: }
1.1031 raeburn 11467: if ($thisfn !~m|^/adm|) {
11468: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11469: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11470: } else {
11471: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11472: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11473: if ($embstyle eq 'ssi'
11474: || ($embstyle eq 'hdn')
11475: || ($embstyle eq 'rat')
11476: || ($embstyle eq 'prv')
11477: || ($embstyle eq 'ign')) {
11478: #do nothing with these
11479: } elsif (($embstyle eq 'img')
1.695 albertel 11480: || ($embstyle eq 'emb')
11481: || ($embstyle eq 'wrp')) {
11482: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11483: } elsif ($embstyle eq 'unk'
11484: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11485: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11486: } else {
1.718 www 11487: # &logthis("Got a blank emb style");
1.695 albertel 11488: }
1.694 albertel 11489: }
11490: }
1.31 www 11491: return $thisfn;
1.12 www 11492: }
11493:
1.787 albertel 11494: sub clutter_with_no_wrapper {
11495: my $uri = &clutter(shift);
11496: if ($uri =~ m-^/adm/-) {
11497: $uri =~ s-^/adm/wrapper/-/-;
11498: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11499: }
11500: return $uri;
11501: }
11502:
1.557 albertel 11503: sub freeze_escape {
11504: my ($value)=@_;
11505: if (ref($value)) {
11506: $value=&nfreeze($value);
11507: return '__FROZEN__'.&escape($value);
11508: }
11509: return &escape($value);
11510: }
11511:
1.11 www 11512:
1.557 albertel 11513: sub thaw_unescape {
11514: my ($value)=@_;
11515: if ($value =~ /^__FROZEN__/) {
11516: substr($value,0,10,undef);
11517: $value=&unescape($value);
11518: return &thaw($value);
11519: }
11520: return &unescape($value);
11521: }
11522:
1.436 albertel 11523: sub correct_line_ends {
11524: my ($result)=@_;
11525: $$result =~s/\r\n/\n/mg;
11526: $$result =~s/\r/\n/mg;
1.415 albertel 11527: }
1.1 albertel 11528: # ================================================================ Main Program
11529:
1.184 www 11530: sub goodbye {
1.204 albertel 11531: &logthis("Starting Shut down");
1.443 albertel 11532: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11533: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11534: #converted
1.599 albertel 11535: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11536: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11537: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11538: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11539: #1.1 only
1.870 albertel 11540: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11541: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11542: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11543: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11544: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11545: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11546: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11547: &flushcourselogs();
11548: &logthis("Shutting down");
11549: }
11550:
1.852 albertel 11551: sub get_dns {
1.1172.2.17 raeburn 11552: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11553: if (!$ignore_cache) {
11554: my ($content,$cached)=
11555: &Apache::lonnet::is_cached_new('dns',$url);
11556: if ($cached) {
1.1172.2.17 raeburn 11557: &$func($content,$hashref);
1.869 albertel 11558: return;
11559: }
11560: }
11561:
11562: my %alldns;
1.852 albertel 11563: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11564: foreach my $dns (<$config>) {
11565: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11566: my $line = $1;
11567: my ($host,$protocol) = split(/:/,$line);
11568: if ($protocol ne 'https') {
11569: $protocol = 'http';
11570: }
11571: $alldns{$host} = $protocol;
1.869 albertel 11572: }
11573: while (%alldns) {
11574: my ($dns) = keys(%alldns);
1.852 albertel 11575: my $ua=new LWP::UserAgent;
1.1134 raeburn 11576: $ua->timeout(30);
1.979 raeburn 11577: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11578: my $response=$ua->request($request);
1.979 raeburn 11579: delete($alldns{$dns});
1.852 albertel 11580: next if ($response->is_error());
11581: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11582: unless ($nocache) {
1.1172.2.23 raeburn 11583: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11584: }
11585: &$func(\@content,$hashref);
1.869 albertel 11586: return;
1.852 albertel 11587: }
11588: close($config);
1.871 albertel 11589: my $which = (split('/',$url))[3];
11590: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11591: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11592: my @content = <$config>;
1.1172.2.17 raeburn 11593: &$func(\@content,$hashref);
11594: return;
11595: }
11596:
11597: # ------------------------------------------------------Get DNS checksums file
11598: sub parse_dns_checksums_tab {
11599: my ($lines,$hashref) = @_;
11600: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11601: my $loncaparev = &get_server_loncaparev($machine_dom);
11602: my ($release,$timestamp) = split(/\-/,$loncaparev);
11603: my (%chksum,%revnum);
11604: if (ref($lines) eq 'ARRAY') {
11605: chomp(@{$lines});
11606: my $versions = shift(@{$lines});
11607: my %supported;
11608: if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
11609: my $releaseslist = $1;
11610: if ($releaseslist =~ /,/) {
11611: map { $supported{$_} = 1; } split(/,/,$releaseslist);
11612: } elsif ($releaseslist) {
11613: $supported{$releaseslist} = 1;
11614: }
11615: }
11616: if ($supported{$release}) {
11617: my $matchthis = 0;
11618: foreach my $line (@{$lines}) {
11619: if ($line =~ /^(\d[\w\.]+)$/) {
11620: if ($matchthis) {
11621: last;
11622: } elsif ($1 eq $release) {
11623: $matchthis = 1;
11624: }
11625: } elsif ($matchthis) {
11626: my ($file,$version,$shasum) = split(/,/,$line);
11627: $chksum{$file} = $shasum;
11628: $revnum{$file} = $version;
11629: }
11630: }
11631: if (ref($hashref) eq 'HASH') {
11632: %{$hashref} = (
11633: sums => \%chksum,
11634: versions => \%revnum,
11635: );
11636: }
11637: }
11638: }
1.869 albertel 11639: return;
1.852 albertel 11640: }
1.1172.2.17 raeburn 11641:
11642: sub fetch_dns_checksums {
11643: my %checksums;
11644: &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
11645: \%checksums);
11646: return \%checksums;
11647: }
11648:
1.327 albertel 11649: # ------------------------------------------------------------ Read domain file
11650: {
1.852 albertel 11651: my $loaded;
1.846 albertel 11652: my %domain;
11653:
1.852 albertel 11654: sub parse_domain_tab {
11655: my ($lines) = @_;
11656: foreach my $line (@$lines) {
11657: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11658:
1.846 albertel 11659: chomp($line);
1.852 albertel 11660: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11661: my %this_domain;
11662: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11663: 'lang_def', 'city', 'longi', 'lati',
11664: 'primary') {
11665: $this_domain{$field} = shift(@elements);
11666: }
11667: $domain{$name} = \%this_domain;
1.852 albertel 11668: }
11669: }
1.864 albertel 11670:
11671: sub reset_domain_info {
11672: undef($loaded);
11673: undef(%domain);
11674: }
11675:
1.852 albertel 11676: sub load_domain_tab {
1.869 albertel 11677: my ($ignore_cache) = @_;
11678: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11679: my $fh;
11680: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11681: my @lines = <$fh>;
11682: &parse_domain_tab(\@lines);
1.448 albertel 11683: }
1.852 albertel 11684: close($fh);
11685: $loaded = 1;
1.327 albertel 11686: }
1.846 albertel 11687:
11688: sub domain {
1.852 albertel 11689: &load_domain_tab() if (!$loaded);
11690:
1.846 albertel 11691: my ($name,$what) = @_;
11692: return if ( !exists($domain{$name}) );
11693:
11694: if (!$what) {
11695: return $domain{$name}{'description'};
11696: }
11697: return $domain{$name}{$what};
11698: }
1.974 raeburn 11699:
11700: sub domain_info {
11701: &load_domain_tab() if (!$loaded);
11702: return %domain;
11703: }
11704:
1.327 albertel 11705: }
11706:
11707:
1.1 albertel 11708: # ------------------------------------------------------------- Read hosts file
11709: {
1.838 albertel 11710: my %hostname;
1.844 albertel 11711: my %hostdom;
1.845 albertel 11712: my %libserv;
1.852 albertel 11713: my $loaded;
1.888 albertel 11714: my %name_to_host;
1.1074 raeburn 11715: my %internetdom;
1.1107 raeburn 11716: my %LC_dns_serv;
1.852 albertel 11717:
11718: sub parse_hosts_tab {
11719: my ($file) = @_;
11720: foreach my $configline (@$file) {
11721: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11722: chomp($configline);
11723: if ($configline =~ /^\^/) {
11724: if ($configline =~ /^\^([\w.\-]+)/) {
11725: $LC_dns_serv{$1} = 1;
11726: }
11727: next;
11728: }
1.1074 raeburn 11729: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11730: $name=~s/\s//g;
11731: if ($id && $domain && $role && $name) {
11732: $hostname{$id}=$name;
1.888 albertel 11733: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11734: $hostdom{$id}=$domain;
11735: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11736: if (defined($protocol)) {
11737: if ($protocol eq 'https') {
11738: $protocol{$id} = $protocol;
11739: } else {
11740: $protocol{$id} = 'http';
11741: }
1.968 raeburn 11742: } else {
1.969 raeburn 11743: $protocol{$id} = 'http';
1.968 raeburn 11744: }
1.1074 raeburn 11745: if (defined($intdom)) {
11746: $internetdom{$id} = $intdom;
11747: }
1.852 albertel 11748: }
11749: }
11750: }
1.864 albertel 11751:
11752: sub reset_hosts_info {
1.897 albertel 11753: &purge_remembered();
1.864 albertel 11754: &reset_domain_info();
11755: &reset_hosts_ip_info();
1.892 albertel 11756: undef(%name_to_host);
1.864 albertel 11757: undef(%hostname);
11758: undef(%hostdom);
11759: undef(%libserv);
11760: undef($loaded);
11761: }
1.1 albertel 11762:
1.852 albertel 11763: sub load_hosts_tab {
1.869 albertel 11764: my ($ignore_cache) = @_;
11765: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11766: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11767: my @config = <$config>;
11768: &parse_hosts_tab(\@config);
11769: close($config);
11770: $loaded=1;
1.1 albertel 11771: }
1.852 albertel 11772:
1.838 albertel 11773: sub hostname {
1.852 albertel 11774: &load_hosts_tab() if (!$loaded);
11775:
1.838 albertel 11776: my ($lonid) = @_;
11777: return $hostname{$lonid};
11778: }
1.845 albertel 11779:
1.838 albertel 11780: sub all_hostnames {
1.852 albertel 11781: &load_hosts_tab() if (!$loaded);
11782:
1.838 albertel 11783: return %hostname;
11784: }
1.845 albertel 11785:
1.888 albertel 11786: sub all_names {
11787: &load_hosts_tab() if (!$loaded);
11788:
11789: return %name_to_host;
11790: }
11791:
1.974 raeburn 11792: sub all_host_domain {
11793: &load_hosts_tab() if (!$loaded);
11794: return %hostdom;
11795: }
11796:
1.845 albertel 11797: sub is_library {
1.852 albertel 11798: &load_hosts_tab() if (!$loaded);
11799:
1.845 albertel 11800: return exists($libserv{$_[0]});
11801: }
11802:
11803: sub all_library {
1.852 albertel 11804: &load_hosts_tab() if (!$loaded);
11805:
1.845 albertel 11806: return %libserv;
11807: }
11808:
1.1062 droeschl 11809: sub unique_library {
11810: #2x reverse removes all hostnames that appear more than once
11811: my %unique = reverse &all_library();
11812: return reverse %unique;
11813: }
11814:
1.841 albertel 11815: sub get_servers {
1.852 albertel 11816: &load_hosts_tab() if (!$loaded);
11817:
1.841 albertel 11818: my ($domain,$type) = @_;
11819: my %possible_hosts = ($type eq 'library') ? %libserv
11820: : %hostname;
11821: my %result;
1.842 albertel 11822: if (ref($domain) eq 'ARRAY') {
11823: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11824: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11825: $result{$host} = $hostname;
11826: }
11827: }
11828: } else {
11829: while ( my ($host,$hostname) = each(%possible_hosts)) {
11830: if ($hostdom{$host} eq $domain) {
11831: $result{$host} = $hostname;
11832: }
1.841 albertel 11833: }
11834: }
11835: return %result;
11836: }
1.845 albertel 11837:
1.1062 droeschl 11838: sub get_unique_servers {
11839: my %unique = reverse &get_servers(@_);
11840: return reverse %unique;
11841: }
11842:
1.844 albertel 11843: sub host_domain {
1.852 albertel 11844: &load_hosts_tab() if (!$loaded);
11845:
1.844 albertel 11846: my ($lonid) = @_;
11847: return $hostdom{$lonid};
11848: }
11849:
1.841 albertel 11850: sub all_domains {
1.852 albertel 11851: &load_hosts_tab() if (!$loaded);
11852:
1.841 albertel 11853: my %seen;
11854: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11855: return @uniq;
11856: }
1.1074 raeburn 11857:
11858: sub internet_dom {
11859: &load_hosts_tab() if (!$loaded);
11860:
11861: my ($lonid) = @_;
11862: return $internetdom{$lonid};
11863: }
1.1107 raeburn 11864:
11865: sub is_LC_dns {
11866: &load_hosts_tab() if (!$loaded);
11867:
11868: my ($hostname) = @_;
11869: return exists($LC_dns_serv{$hostname});
11870: }
11871:
1.1 albertel 11872: }
11873:
1.847 albertel 11874: {
11875: my %iphost;
1.856 albertel 11876: my %name_to_ip;
11877: my %lonid_to_ip;
1.869 albertel 11878:
1.847 albertel 11879: sub get_hosts_from_ip {
11880: my ($ip) = @_;
11881: my %iphosts = &get_iphost();
11882: if (ref($iphosts{$ip})) {
11883: return @{$iphosts{$ip}};
11884: }
11885: return;
1.839 albertel 11886: }
1.864 albertel 11887:
11888: sub reset_hosts_ip_info {
11889: undef(%iphost);
11890: undef(%name_to_ip);
11891: undef(%lonid_to_ip);
11892: }
1.856 albertel 11893:
11894: sub get_host_ip {
11895: my ($lonid) = @_;
11896: if (exists($lonid_to_ip{$lonid})) {
11897: return $lonid_to_ip{$lonid};
11898: }
11899: my $name=&hostname($lonid);
11900: my $ip = gethostbyname($name);
11901: return if (!$ip || length($ip) ne 4);
11902: $ip=inet_ntoa($ip);
11903: $name_to_ip{$name} = $ip;
11904: $lonid_to_ip{$lonid} = $ip;
11905: return $ip;
11906: }
1.847 albertel 11907:
11908: sub get_iphost {
1.869 albertel 11909: my ($ignore_cache) = @_;
1.894 albertel 11910:
1.869 albertel 11911: if (!$ignore_cache) {
11912: if (%iphost) {
11913: return %iphost;
11914: }
11915: my ($ip_info,$cached)=
11916: &Apache::lonnet::is_cached_new('iphost','iphost');
11917: if ($cached) {
11918: %iphost = %{$ip_info->[0]};
11919: %name_to_ip = %{$ip_info->[1]};
11920: %lonid_to_ip = %{$ip_info->[2]};
11921: return %iphost;
11922: }
11923: }
1.894 albertel 11924:
11925: # get yesterday's info for fallback
11926: my %old_name_to_ip;
11927: my ($ip_info,$cached)=
11928: &Apache::lonnet::is_cached_new('iphost','iphost');
11929: if ($cached) {
11930: %old_name_to_ip = %{$ip_info->[1]};
11931: }
11932:
1.888 albertel 11933: my %name_to_host = &all_names();
11934: foreach my $name (keys(%name_to_host)) {
1.847 albertel 11935: my $ip;
11936: if (!exists($name_to_ip{$name})) {
11937: $ip = gethostbyname($name);
11938: if (!$ip || length($ip) ne 4) {
1.894 albertel 11939: if (defined($old_name_to_ip{$name})) {
11940: $ip = $old_name_to_ip{$name};
11941: &logthis("Can't find $name defaulting to old $ip");
11942: } else {
11943: &logthis("Name $name no IP found");
11944: next;
11945: }
11946: } else {
11947: $ip=inet_ntoa($ip);
1.847 albertel 11948: }
11949: $name_to_ip{$name} = $ip;
11950: } else {
11951: $ip = $name_to_ip{$name};
1.653 albertel 11952: }
1.888 albertel 11953: foreach my $id (@{ $name_to_host{$name} }) {
11954: $lonid_to_ip{$id} = $ip;
11955: }
11956: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 11957: }
1.1172.2.23 raeburn 11958: &do_cache_new('iphost','iphost',
11959: [\%iphost,\%name_to_ip,\%lonid_to_ip],
11960: 48*60*60);
1.869 albertel 11961:
1.847 albertel 11962: return %iphost;
1.598 albertel 11963: }
11964:
1.992 raeburn 11965: #
11966: # Given a DNS returns the loncapa host name for that DNS
11967: #
11968: sub host_from_dns {
11969: my ($dns) = @_;
11970: my @hosts;
11971: my $ip;
11972:
1.993 raeburn 11973: if (exists($name_to_ip{$dns})) {
1.992 raeburn 11974: $ip = $name_to_ip{$dns};
11975: }
11976: if (!$ip) {
11977: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11978: if (length($ip) == 4) {
11979: $ip = &IO::Socket::inet_ntoa($ip);
11980: }
11981: }
11982: if ($ip) {
11983: @hosts = get_hosts_from_ip($ip);
11984: return $hosts[0];
11985: }
11986: return undef;
1.986 foxr 11987: }
1.992 raeburn 11988:
1.1074 raeburn 11989: sub get_internet_names {
11990: my ($lonid) = @_;
11991: return if ($lonid eq '');
11992: my ($idnref,$cached)=
11993: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11994: if ($cached) {
11995: return $idnref;
11996: }
11997: my $ip = &get_host_ip($lonid);
11998: my @hosts = &get_hosts_from_ip($ip);
11999: my %iphost = &get_iphost();
12000: my (@idns,%seen);
12001: foreach my $id (@hosts) {
12002: my $dom = &host_domain($id);
12003: my $prim_id = &domain($dom,'primary');
12004: my $prim_ip = &get_host_ip($prim_id);
12005: next if ($seen{$prim_ip});
12006: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12007: foreach my $id (@{$iphost{$prim_ip}}) {
12008: my $intdom = &internet_dom($id);
12009: unless (grep(/^\Q$intdom\E$/,@idns)) {
12010: push(@idns,$intdom);
12011: }
12012: }
12013: }
12014: $seen{$prim_ip} = 1;
12015: }
1.1172.2.23 raeburn 12016: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12017: }
12018:
1.986 foxr 12019: }
12020:
1.1079 raeburn 12021: sub all_loncaparevs {
12022: 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);
12023: }
12024:
1.1172.2.27 raeburn 12025: # ------------------------------------------------------- Read loncaparev table
12026: {
12027: sub load_loncaparevs {
12028: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12029: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12030: while (my $configline=<$config>) {
12031: chomp($configline);
12032: my ($hostid,$loncaparev)=split(/:/,$configline);
12033: $loncaparevs{$hostid}=$loncaparev;
12034: }
12035: close($config);
12036: }
12037: }
12038: }
12039: }
12040:
12041: # ----------------------------------------------------- Read serverhostID table
12042: {
12043: sub load_serverhomeIDs {
12044: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12045: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12046: while (my $configline=<$config>) {
12047: chomp($configline);
12048: my ($name,$id)=split(/:/,$configline);
12049: $serverhomeIDs{$name}=$id;
12050: }
12051: close($config);
12052: }
12053: }
12054: }
12055: }
12056:
12057:
1.862 albertel 12058: BEGIN {
12059:
12060: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12061: unless ($readit) {
12062: {
12063: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12064: %perlvar = (%perlvar,%{$configvars});
12065: }
12066:
12067:
1.1 albertel 12068: # ------------------------------------------------------ Read spare server file
12069: {
1.448 albertel 12070: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12071:
12072: while (my $configline=<$config>) {
12073: chomp($configline);
1.284 matthew 12074: if ($configline) {
1.784 albertel 12075: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12076: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12077: push(@{ $spareid{$type} }, $host);
1.1 albertel 12078: }
12079: }
1.448 albertel 12080: close($config);
1.1 albertel 12081: }
1.11 www 12082: # ------------------------------------------------------------ Read permissions
12083: {
1.448 albertel 12084: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12085:
12086: while (my $configline=<$config>) {
1.448 albertel 12087: chomp($configline);
12088: if ($configline) {
12089: my ($role,$perm)=split(/ /,$configline);
12090: if ($perm ne '') { $pr{$role}=$perm; }
12091: }
1.11 www 12092: }
1.448 albertel 12093: close($config);
1.11 www 12094: }
12095:
12096: # -------------------------------------------- Read plain texts for permissions
12097: {
1.448 albertel 12098: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12099:
12100: while (my $configline=<$config>) {
1.448 albertel 12101: chomp($configline);
12102: if ($configline) {
1.742 raeburn 12103: my ($short,@plain)=split(/:/,$configline);
12104: %{$prp{$short}} = ();
12105: if (@plain > 0) {
12106: $prp{$short}{'std'} = $plain[0];
12107: for (my $i=1; $i<@plain; $i++) {
12108: $prp{$short}{'alt'.$i} = $plain[$i];
12109: }
12110: }
1.448 albertel 12111: }
1.135 www 12112: }
1.448 albertel 12113: close($config);
1.135 www 12114: }
12115:
12116: # ---------------------------------------------------------- Read package table
12117: {
1.448 albertel 12118: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12119:
12120: while (my $configline=<$config>) {
1.483 albertel 12121: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12122: chomp($configline);
12123: my ($short,$plain)=split(/:/,$configline);
12124: my ($pack,$name)=split(/\&/,$short);
12125: if ($plain ne '') {
12126: $packagetab{$pack.'&'.$name.'&name'}=$name;
12127: $packagetab{$short}=$plain;
12128: }
1.11 www 12129: }
1.448 albertel 12130: close($config);
1.329 matthew 12131: }
12132:
1.1172.2.27 raeburn 12133: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12134:
1.1172.2.27 raeburn 12135: &load_loncaparevs();
12136:
12137: # ------------------------------------------------------- Read serverhostID table
12138:
12139: &load_serverhomeIDs();
1.1074 raeburn 12140:
1.1172.2.27 raeburn 12141: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12142: {
12143: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12144: if (-e $file) {
12145: my $parser = HTML::LCParser->new($file);
12146: while (my $token = $parser->get_token()) {
12147: if ($token->[0] eq 'S') {
12148: my $item = $token->[1];
12149: my $name = $token->[2]{'name'};
12150: my $value = $token->[2]{'value'};
12151: if ($item ne '' && $name ne '' && $value ne '') {
12152: my $release = $parser->get_text();
12153: $release =~ s/(^\s*|\s*$ )//gx;
12154: $needsrelease{$item.':'.$name.':'.$value} = $release;
12155: }
12156: }
12157: }
12158: }
1.1073 raeburn 12159: }
12160:
1.1138 raeburn 12161: # ---------------------------------------------------------- Read managers table
12162: {
12163: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12164: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12165: while (my $configline=<$config>) {
12166: chomp($configline);
12167: next if ($configline =~ /^\#/);
12168: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12169: $managerstab{$configline} = 1;
12170: }
12171: }
12172: close($config);
12173: }
12174: }
12175: }
12176:
1.329 matthew 12177: # ------------- set up temporary directory
12178: {
1.1117 foxr 12179: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12180:
1.11 www 12181: }
12182:
1.794 albertel 12183: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12184: 'compress_threshold'=> 20_000,
12185: });
1.185 www 12186:
1.281 www 12187: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12188: $dumpcount=0;
1.958 www 12189: $locknum=0;
1.22 www 12190:
1.163 harris41 12191: &logtouch();
1.672 albertel 12192: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12193: $readit=1;
1.564 albertel 12194: {
12195: use integer;
12196: my $test=(2**32)+1;
1.568 albertel 12197: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12198: &logthis(" Detected 64bit platform ($_64bit)");
12199: }
1.1172.2.18 raeburn 12200:
12201: {
12202: eval {
12203: ($apache) =
12204: (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12205: };
12206: if ($@) {
12207: $apache = 1.3;
12208: }
12209: }
12210:
1.195 www 12211: }
1.1 albertel 12212: }
1.179 www 12213:
1.1 albertel 12214: 1;
1.191 harris41 12215: __END__
12216:
1.243 albertel 12217: =pod
12218:
1.191 harris41 12219: =head1 NAME
12220:
1.243 albertel 12221: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12222:
12223: =head1 SYNOPSIS
12224:
1.243 albertel 12225: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12226:
12227: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12228:
1.243 albertel 12229: Common parameters:
12230:
12231: =over 4
12232:
12233: =item *
12234:
12235: $uname : an internal username (if $cname expecting a course Id specifically)
12236:
12237: =item *
12238:
12239: $udom : a domain (if $cdom expecting a course's domain specifically)
12240:
12241: =item *
12242:
12243: $symb : a resource instance identifier
12244:
12245: =item *
12246:
12247: $namespace : the name of a .db file that contains the data needed or
12248: being set.
12249:
12250: =back
12251:
1.394 bowersj2 12252: =head1 OVERVIEW
1.191 harris41 12253:
1.394 bowersj2 12254: lonnet provides subroutines which interact with the
12255: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12256: about classes, users, and resources.
1.243 albertel 12257:
12258: For many of these objects you can also use this to store data about
12259: them or modify them in various ways.
1.191 harris41 12260:
1.394 bowersj2 12261: =head2 Symbs
1.191 harris41 12262:
1.394 bowersj2 12263: To identify a specific instance of a resource, LON-CAPA uses symbols
12264: or "symbs"X<symb>. These identifiers are built from the URL of the
12265: map, the resource number of the resource in the map, and the URL of
12266: the resource itself. The latter is somewhat redundant, but might help
12267: if maps change.
12268:
12269: An example is
12270:
12271: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12272:
12273: The respective map entry is
12274:
12275: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12276: title="Problem 2">
12277: </resource>
12278:
12279: Symbs are used by the random number generator, as well as to store and
12280: restore data specific to a certain instance of for example a problem.
12281:
12282: =head2 Storing And Retrieving Data
12283:
12284: X<store()>X<cstore()>X<restore()>Three of the most important functions
12285: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12286: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12287: is is the non-critical message twin of cstore. These functions are for
12288: handlers to store a perl hash to a user's permanent data space in an
12289: easy manner, and to retrieve it again on another call. It is expected
12290: that a handler would use this once at the beginning to retrieve data,
12291: and then again once at the end to send only the new data back.
12292:
12293: The data is stored in the user's data directory on the user's
12294: homeserver under the ID of the course.
12295:
12296: The hash that is returned by restore will have all of the previous
12297: value for all of the elements of the hash.
12298:
12299: Example:
12300:
12301: #creating a hash
12302: my %hash;
12303: $hash{'foo'}='bar';
12304:
12305: #storing it
12306: &Apache::lonnet::cstore(\%hash);
12307:
12308: #changing a value
12309: $hash{'foo'}='notbar';
12310:
12311: #adding a new value
12312: $hash{'bar'}='foo';
12313: &Apache::lonnet::cstore(\%hash);
12314:
12315: #retrieving the hash
12316: my %history=&Apache::lonnet::restore();
12317:
12318: #print the hash
12319: foreach my $key (sort(keys(%history))) {
12320: print("\%history{$key} = $history{$key}");
12321: }
12322:
12323: Will print out:
1.191 harris41 12324:
1.394 bowersj2 12325: %history{1:foo} = bar
12326: %history{1:keys} = foo:timestamp
12327: %history{1:timestamp} = 990455579
12328: %history{2:bar} = foo
12329: %history{2:foo} = notbar
12330: %history{2:keys} = foo:bar:timestamp
12331: %history{2:timestamp} = 990455580
12332: %history{bar} = foo
12333: %history{foo} = notbar
12334: %history{timestamp} = 990455580
12335: %history{version} = 2
12336:
12337: Note that the special hash entries C<keys>, C<version> and
12338: C<timestamp> were added to the hash. C<version> will be equal to the
12339: total number of versions of the data that have been stored. The
12340: C<timestamp> attribute will be the UNIX time the hash was
12341: stored. C<keys> is available in every historical section to list which
12342: keys were added or changed at a specific historical revision of a
12343: hash.
12344:
12345: B<Warning>: do not store the hash that restore returns directly. This
12346: will cause a mess since it will restore the historical keys as if the
12347: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12348:
1.394 bowersj2 12349: Calling convention:
1.191 harris41 12350:
1.1172.2.27 raeburn 12351: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12352: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12353:
1.394 bowersj2 12354: For more detailed information, see lonnet specific documentation.
1.191 harris41 12355:
1.394 bowersj2 12356: =head1 RETURN MESSAGES
1.191 harris41 12357:
1.394 bowersj2 12358: =over 4
1.191 harris41 12359:
1.394 bowersj2 12360: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12361:
1.394 bowersj2 12362: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12363: when the connection is brought back up
1.191 harris41 12364:
1.394 bowersj2 12365: =item * B<con_failed>: unable to contact remote host and unable to save message
12366: for later delivery
1.191 harris41 12367:
1.967 bisitz 12368: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12369:
1.394 bowersj2 12370: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12371: that was requested
1.191 harris41 12372:
1.243 albertel 12373: =back
1.191 harris41 12374:
1.243 albertel 12375: =head1 PUBLIC SUBROUTINES
1.191 harris41 12376:
1.243 albertel 12377: =head2 Session Environment Functions
1.191 harris41 12378:
1.243 albertel 12379: =over 4
1.191 harris41 12380:
1.394 bowersj2 12381: =item *
12382: X<appenv()>
1.949 raeburn 12383: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12384: the user envirnoment file, and will be restored for each access this
1.620 albertel 12385: user makes during this session, also modifies the %env for the current
1.949 raeburn 12386: process. Optional rolesarrayref - if defined contains a reference to an array
12387: of roles which are exempt from the restriction on modifying user.role entries
12388: in the user's environment.db and in %env.
1.191 harris41 12389:
12390: =item *
1.394 bowersj2 12391: X<delenv()>
1.987 raeburn 12392: B<delenv($delthis,$regexp)>: removes all items from the session
12393: environment file that begin with $delthis. If the
12394: optional second arg - $regexp - is true, $delthis is treated as a
12395: regular expression, otherwise \Q$delthis\E is used.
12396: The values are also deleted from the current processes %env.
1.191 harris41 12397:
1.795 albertel 12398: =item * get_env_multiple($name)
12399:
12400: gets $name from the %env hash, it seemlessly handles the cases where multiple
12401: values may be defined and end up as an array ref.
12402:
12403: returns an array of values
12404:
1.243 albertel 12405: =back
12406:
12407: =head2 User Information
1.191 harris41 12408:
1.243 albertel 12409: =over 4
1.191 harris41 12410:
12411: =item *
1.394 bowersj2 12412: X<queryauthenticate()>
12413: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12414: authentication scheme
12415:
12416: =item *
1.394 bowersj2 12417: X<authenticate()>
1.1073 raeburn 12418: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12419: authenticate user from domain's lib servers (first use the current
12420: one). C<$upass> should be the users password.
1.1073 raeburn 12421: $checkdefauth is optional (value is 1 if a check should be made to
12422: authenticate user using default authentication method, and allow
12423: account creation if username does not have account in the domain).
12424: $clientcancheckhost is optional (value is 1 if checking whether the
12425: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12426:
12427: =item *
1.394 bowersj2 12428: X<homeserver()>
12429: B<homeserver($uname,$udom)>: find the server which has
12430: the user's directory and files (there must be only one), this caches
12431: the answer, and also caches if there is a borken connection.
1.191 harris41 12432:
12433: =item *
1.394 bowersj2 12434: X<idget()>
12435: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12436: (IDs are a unique resource in a domain, there must be only 1 ID per
12437: username, and only 1 username per ID in a specific domain) (returns
12438: hash: id=>name,id=>name)
1.191 harris41 12439:
12440: =item *
1.394 bowersj2 12441: X<idrget()>
12442: B<idrget($udom,@unames)>: find the IDs behind a list of
12443: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12444:
12445: =item *
1.394 bowersj2 12446: X<idput()>
12447: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12448:
12449: =item *
1.394 bowersj2 12450: X<rolesinit()>
1.1169 droeschl 12451: B<rolesinit($udom,$username)>: get user privileges.
12452: returns user role, first access and timer interval hashes
1.243 albertel 12453:
12454: =item *
1.1171 droeschl 12455: X<privileged()>
12456: B<privileged($username,$domain)>: returns a true if user has a
12457: privileged and active role (i.e. su or dc), false otherwise.
12458:
12459: =item *
1.551 albertel 12460: X<getsection()>
12461: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12462: course $cname, return section name/number or '' for "not in course"
12463: and '-1' for "no section"
12464:
12465: =item *
1.394 bowersj2 12466: X<userenvironment()>
12467: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12468: passed in @what from the requested user's environment, returns a hash
12469:
1.858 raeburn 12470: =item *
12471: X<userlog_query()>
1.859 albertel 12472: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12473: activity.log file. %filters defines filters applied when parsing the
12474: log file. These can be start or end timestamps, or the type of action
12475: - log to look for Login or Logout events, check for Checkin or
12476: Checkout, role for role selection. The response is in the form
12477: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12478: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12479:
1.243 albertel 12480: =back
12481:
12482: =head2 User Roles
12483:
12484: =over 4
12485:
12486: =item *
12487:
1.810 raeburn 12488: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12489: F: full access
12490: U,I,K: authentication modes (cxx only)
12491: '': forbidden
12492: 1: user needs to choose course
12493: 2: browse allowed
1.766 albertel 12494: A: passphrase authentication needed
1.243 albertel 12495:
12496: =item *
12497:
1.1172.2.13 raeburn 12498: constructaccess($url,$setpriv) : check for access to construction space URL
12499:
12500: See if the owner domain and name in the URL match those in the
12501: expected environment. If so, return three element list
12502: ($ownername,$ownerdomain,$ownerhome).
12503:
12504: Otherwise return the null string.
12505:
12506: If second argument 'setpriv' is true, it assigns the privileges,
12507: and returns the same three element list, unless the owner has
12508: blocked "ad hoc" Domain Coordinator access to the Author Space,
12509: in which case the null string is returned.
12510:
12511: =item *
12512:
1.243 albertel 12513: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12514: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12515: and course level
12516:
12517: =item *
12518:
1.988 raeburn 12519: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12520: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12521: $type is Course (default) or Community.
1.988 raeburn 12522: If $forcedefault evaluates to true, text returned will be default
12523: text for $type. Otherwise, if this is a course, the text returned
12524: will be a custom name for the role (if defined in the course's
12525: environment). If no custom name is defined the default is returned.
12526:
1.832 raeburn 12527: =item *
12528:
1.1172.2.23 raeburn 12529: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12530: All arguments are optional. Returns a hash of a roles, either for
12531: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12532: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12533: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12534: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12535: For each key, value is set to colon-separated start and end times for
12536: the role. If no username and domain are specified, will default to
1.934 raeburn 12537: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12538: of role statuses (active, future or previous), roles
12539: (e.g., cc,in, st etc.) and domains of the roles which can be used
12540: to restrict the list of roles reported. If no array ref is
12541: provided for types, will default to return only active roles.
1.834 albertel 12542:
1.1172.2.13 raeburn 12543: =item *
12544:
12545: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12546: user: $uname:$udom has a role in the course: $cdom_$cnum.
12547:
12548: Additional optional arguments are: $type (if role checking is to be restricted
12549: to certain user status types -- previous (expired roles), active (currently
12550: available roles) or future (roles available in the future), and
12551: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12552: have active Domain Coordinator role in course's domain or in additional
12553: domains (specified in 'Domains to check for privileged users' in course
12554: environment -- set via: Course Settings -> Classlists and staff listing).
12555:
12556: =item *
12557:
12558: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12559: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12560: $possdomains and $possroles are optional array refs -- to domains to check and
12561: roles to check. If $possdomains is not specified, a dump will be done of the
12562: users' roles.db to check for a dc or su role in any domain. This can be
12563: time consuming if &privileged is called repeatedly (e.g., when displaying a
12564: classlist), so in such cases, supplying a $possdomains array is preferred, as
12565: this then allows &privileged_by_domain() to be used, which caches the identity
12566: of privileged users, eliminating the need for repeated calls to &dump().
12567:
12568: =item *
12569:
12570: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12571: where the outer hash keys are domains specified in the $possdomains array ref,
12572: next inner hash keys are privileged roles specified in the $roles array ref,
12573: and the innermost hash contains key = value pairs for username:domain = end:start
12574: for active or future "privileged" users with that role in that domain. To avoid
12575: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12576: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12577:
1.243 albertel 12578: =back
12579:
12580: =head2 User Modification
12581:
12582: =over 4
12583:
12584: =item *
12585:
1.957 raeburn 12586: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12587: user for the level given by URL. Optional start and end dates (leave empty
12588: string or zero for "no date")
1.191 harris41 12589:
12590: =item *
12591:
1.243 albertel 12592: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12593: change a users, password, possible return values are: ok,
12594: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12595: refused
1.191 harris41 12596:
12597: =item *
12598:
1.243 albertel 12599: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12600:
12601: =item *
12602:
1.1058 raeburn 12603: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12604: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12605:
12606: will update user information (firstname,middlename,lastname,generation,
12607: permanentemail), and if forceid is true, student/employee ID also.
12608: A user's institutional affiliation(s) can also be updated.
12609: User information fields will not be overwritten with empty entries
12610: unless the field is included in the $candelete array reference.
12611: This array is included when a single user is modified via "Manage Users",
12612: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12613:
12614: =item *
12615:
1.286 matthew 12616: modifystudent
12617:
1.957 raeburn 12618: modify a student's enrollment and identification information.
1.286 matthew 12619: The course id is resolved based on the current users environment.
12620: This means the envoking user must be a course coordinator or otherwise
12621: associated with a course.
12622:
1.297 matthew 12623: This call is essentially a wrapper for lonnet::modifyuser and
12624: lonnet::modify_student_enrollment
1.286 matthew 12625:
12626: Inputs:
12627:
12628: =over 4
12629:
1.957 raeburn 12630: =item B<$udom> Student's loncapa domain
1.286 matthew 12631:
1.957 raeburn 12632: =item B<$uname> Student's loncapa login name
1.286 matthew 12633:
1.964 bisitz 12634: =item B<$uid> Student/Employee ID
1.286 matthew 12635:
1.957 raeburn 12636: =item B<$umode> Student's authentication mode
1.286 matthew 12637:
1.957 raeburn 12638: =item B<$upass> Student's password
1.286 matthew 12639:
1.957 raeburn 12640: =item B<$first> Student's first name
1.286 matthew 12641:
1.957 raeburn 12642: =item B<$middle> Student's middle name
1.286 matthew 12643:
1.957 raeburn 12644: =item B<$last> Student's last name
1.286 matthew 12645:
1.957 raeburn 12646: =item B<$gene> Student's generation
1.286 matthew 12647:
1.957 raeburn 12648: =item B<$usec> Student's section in course
1.286 matthew 12649:
12650: =item B<$end> Unix time of the roles expiration
12651:
12652: =item B<$start> Unix time of the roles start date
12653:
12654: =item B<$forceid> If defined, allow $uid to be changed
12655:
12656: =item B<$desiredhome> server to use as home server for student
12657:
1.957 raeburn 12658: =item B<$email> Student's permanent e-mail address
12659:
12660: =item B<$type> Type of enrollment (auto or manual)
12661:
1.963 raeburn 12662: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12663:
12664: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12665:
1.963 raeburn 12666: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12667:
1.963 raeburn 12668: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12669:
1.1172.2.19 raeburn 12670: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12671:
12672: =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 12673:
1.286 matthew 12674: =back
1.297 matthew 12675:
12676: =item *
12677:
12678: modify_student_enrollment
12679:
12680: Change a students enrollment status in a class. The environment variable
12681: 'role.request.course' must be defined for this function to proceed.
12682:
12683: Inputs:
12684:
12685: =over 4
12686:
12687: =item $udom, students domain
12688:
12689: =item $uname, students name
12690:
12691: =item $uid, students user id
12692:
12693: =item $first, students first name
12694:
12695: =item $middle
12696:
12697: =item $last
12698:
12699: =item $gene
12700:
12701: =item $usec
12702:
12703: =item $end
12704:
12705: =item $start
12706:
1.957 raeburn 12707: =item $type
12708:
12709: =item $locktype
12710:
12711: =item $cid
12712:
12713: =item $selfenroll
12714:
12715: =item $context
12716:
1.1172.2.19 raeburn 12717: =item $credits, number of credits student will earn from this class
12718:
1.297 matthew 12719: =back
12720:
1.191 harris41 12721:
12722: =item *
12723:
1.243 albertel 12724: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12725: custom role; give a custom role to a user for the level given by URL. Specify
12726: name and domain of role author, and role name
1.191 harris41 12727:
12728: =item *
12729:
1.243 albertel 12730: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12731:
12732: =item *
12733:
1.243 albertel 12734: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12735:
12736: =back
12737:
12738: =head2 Course Infomation
12739:
12740: =over 4
1.191 harris41 12741:
12742: =item *
12743:
1.1118 foxr 12744: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12745: specified course id, including all environment settings for the
12746: course, the description of the course will be in the hash under the
12747: key 'description'
1.191 harris41 12748:
1.1118 foxr 12749: $options is an optional parameter that if supplied is a hash reference that controls
12750: what how this function works. It has the following key/values:
12751:
12752: =over 4
12753:
12754: =item freshen_cache
12755:
12756: If defined, and the environment cache for the course is valid, it is
12757: returned in the returned hash.
12758:
12759: =item one_time
12760:
12761: If defined, the last cache time is set to _now_
12762:
12763: =item user
12764:
12765: If defined, the supplied username is used instead of the current user.
12766:
12767:
12768: =back
12769:
1.191 harris41 12770: =item *
12771:
1.624 albertel 12772: resdata($name,$domain,$type,@which) : request for current parameter
12773: setting for a specific $type, where $type is either 'course' or 'user',
12774: @what should be a list of parameters to ask about. This routine caches
12775: answers for 5 minutes.
1.243 albertel 12776:
1.877 foxr 12777: =item *
12778:
12779: get_courseresdata($courseid, $domain) : dump the entire course resource
12780: data base, returning a hash that is keyed by the resource name and has
12781: values that are the resource value. I believe that the timestamps and
12782: versions are also returned.
12783:
1.243 albertel 12784: =back
12785:
12786: =head2 Course Modification
12787:
12788: =over 4
1.191 harris41 12789:
12790: =item *
12791:
1.243 albertel 12792: writecoursepref($courseid,%prefs) : write preferences (environment
12793: database) for a course
1.191 harris41 12794:
12795: =item *
12796:
1.1011 raeburn 12797: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12798:
12799: =item *
12800:
1.1038 raeburn 12801: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12802:
1.1167 droeschl 12803: =item *
12804:
12805: is_course($courseid), is_course($cdom, $cnum)
12806:
12807: Accepts either a combined $courseid (in the form of domain_courseid) or the
12808: two component version $cdom, $cnum. It checks if the specified course exists.
12809:
12810: Returns:
12811: undef if the course doesn't exist, otherwise
12812: in scalar context the combined courseid.
12813: in list context the two components of the course identifier, domain and
12814: courseid.
12815:
1.243 albertel 12816: =back
12817:
12818: =head2 Resource Subroutines
12819:
12820: =over 4
1.191 harris41 12821:
12822: =item *
12823:
1.243 albertel 12824: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12825:
12826: =item *
12827:
1.243 albertel 12828: repcopy($filename) : subscribes to the requested file, and attempts to
12829: replicate from the owning library server, Might return
1.607 raeburn 12830: 'unavailable', 'not_found', 'forbidden', 'ok', or
12831: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12832: resource. Expects the local filesystem pathname
12833: (/home/httpd/html/res/....)
12834:
12835: =back
12836:
12837: =head2 Resource Information
12838:
12839: =over 4
1.191 harris41 12840:
12841: =item *
12842:
1.1172.2.28 raeburn 12843: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
12844: and returns the value of a variety of different possible values,
12845: $varname should be a request string, and the other parameters can be
12846: used to specify who and what one is asking about. Ordinarily, $cid
12847: does not need to be specified, as it is retrived from
12848: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12849: within lonuserstate::loadmap() when initializing a course, before
12850: $env{'request.course.id'} has been set, so it needs to be provided
12851: in that one case.
1.243 albertel 12852:
12853: Possible values for $varname are environment.lastname (or other item
12854: from the envirnment hash), user.name (or someother aspect about the
12855: user), resource.0.maxtries (or some other part and parameter of a
12856: resource)
1.204 albertel 12857:
12858: =item *
12859:
1.243 albertel 12860: directcondval($number) : get current value of a condition; reads from a state
12861: string
1.204 albertel 12862:
12863: =item *
12864:
1.243 albertel 12865: condval($condidx) : value of condition index based on state
1.204 albertel 12866:
12867: =item *
12868:
1.243 albertel 12869: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12870: resource's metadata, $what should be either a specific key, or either
12871: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12872: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12873:
12874: this function automatically caches all requests
1.191 harris41 12875:
12876: =item *
12877:
1.243 albertel 12878: metadata_query($query,$custom,$customshow) : make a metadata query against the
12879: network of library servers; returns file handle of where SQL and regex results
12880: will be stored for query
1.191 harris41 12881:
12882: =item *
12883:
1.243 albertel 12884: symbread($filename) : return symbolic list entry (filename argument optional);
12885: returns the data handle
1.191 harris41 12886:
12887: =item *
12888:
1.1172.2.17 raeburn 12889: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 12890: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 12891: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 12892: on failure, user must be in a course, as it assumes the existence of
12893: the course initial hash, and uses $env('request.course.id'}. The third
12894: arg is an optional reference to a scalar. If this arg is passed in the
12895: call to symbverify, it will be set to 1 if the symb has been set to be
12896: encrypted; otherwise it will be null.
1.243 albertel 12897:
1.191 harris41 12898: =item *
12899:
1.243 albertel 12900: symbclean($symb) : removes versions numbers from a symb, returns the
12901: cleaned symb
1.191 harris41 12902:
12903: =item *
12904:
1.243 albertel 12905: is_on_map($uri) : checks if the $uri is somewhere on the current
12906: course map, user must be in a course for it to work.
1.191 harris41 12907:
12908: =item *
12909:
1.243 albertel 12910: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 12911:
12912: =item *
12913:
1.243 albertel 12914: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12915: a random seed, all arguments are optional, if they aren't sent it uses the
12916: environment to derive them. Note: if symb isn't sent and it can't get one
12917: from &symbread it will use the current time as its return value
1.191 harris41 12918:
12919: =item *
12920:
1.243 albertel 12921: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12922: unfakeable, receipt
1.191 harris41 12923:
12924: =item *
12925:
1.620 albertel 12926: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 12927:
12928: =item *
12929:
1.243 albertel 12930: countacc($url) : count the number of accesses to a given URL
1.191 harris41 12931:
12932: =item *
12933:
1.243 albertel 12934: 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 12935:
12936: =item *
12937:
1.243 albertel 12938: 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 12939:
12940: =item *
12941:
1.243 albertel 12942: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 12943:
12944: =item *
12945:
1.243 albertel 12946: devalidate($symb) : devalidate temporary spreadsheet calculations,
12947: forcing spreadsheet to reevaluate the resource scores next time.
12948:
1.1172.2.13 raeburn 12949: =item *
12950:
12951: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
12952: when viewing in course context.
12953:
12954: input: six args -- filename (decluttered), course number, course domain,
12955: url, symb (if registered) and group (if this is a
12956: group item -- e.g., bulletin board, group page etc.).
12957:
12958: output: array of five scalars --
12959: $cfile -- url for file editing if editable on current server
12960: $home -- homeserver of resource (i.e., for author if published,
12961: or course if uploaded.).
12962: $switchserver -- 1 if server switch will be needed.
12963: $forceedit -- 1 if icon/link should be to go to edit mode
12964: $forceview -- 1 if icon/link should be to go to view mode
12965:
12966: =item *
12967:
12968: is_course_upload($file,$cnum,$cdom)
12969:
12970: Used in course context to determine if current file was uploaded to
12971: the course (i.e., would be found in /userfiles/docs on the course's
12972: homeserver.
12973:
12974: input: 3 args -- filename (decluttered), course number and course domain.
12975: output: boolean -- 1 if file was uploaded.
12976:
1.243 albertel 12977: =back
12978:
12979: =head2 Storing/Retreiving Data
12980:
12981: =over 4
1.191 harris41 12982:
12983: =item *
12984:
1.243 albertel 12985: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12986: for this url; hashref needs to be given and should be a \%hashname; the
12987: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 12988: be derived from the env
1.191 harris41 12989:
12990: =item *
12991:
1.243 albertel 12992: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12993: uses critical subroutine
1.191 harris41 12994:
12995: =item *
12996:
1.243 albertel 12997: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12998: all args are optional
1.191 harris41 12999:
13000: =item *
13001:
1.717 albertel 13002: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13003: dumps the complete (or key matching regexp) namespace into a hash
13004: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13005: normally &store()ed into
13006:
13007: $range should be either an integer '100' (give me the first 100
13008: matching records)
13009: or be two integers sperated by a - with no spaces
13010: '30-50' (give me the 30th through the 50th matching
13011: records)
13012:
13013:
13014: =item *
13015:
13016: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13017: replaces a &store() version of data with a replacement set of data
13018: for a particular resource in a namespace passed in the $storehash hash
13019: reference
13020:
13021: =item *
13022:
1.243 albertel 13023: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13024: works very similar to store/cstore, but all data is stored in a
13025: temporary location and can be reset using tmpreset, $storehash should
13026: be a hash reference, returns nothing on success
1.191 harris41 13027:
13028: =item *
13029:
1.243 albertel 13030: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13031: similar to restore, but all data is stored in a temporary location and
13032: can be reset using tmpreset. Returns a hash of values on success,
13033: error string otherwise.
1.191 harris41 13034:
13035: =item *
13036:
1.243 albertel 13037: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13038: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13039:
13040: =item *
13041:
1.243 albertel 13042: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13043: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13044:
13045: =item *
13046:
1.243 albertel 13047: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13048: namesp ($udom and $uname are optional)
1.191 harris41 13049:
13050: =item *
13051:
1.702 albertel 13052: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13053: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13054: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13055:
1.702 albertel 13056: $range should be either an integer '100' (give me the first 100
13057: matching records)
13058: or be two integers sperated by a - with no spaces
13059: '30-50' (give me the 30th through the 50th matching
13060: records)
1.449 matthew 13061: =item *
13062:
13063: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13064: $store can be a scalar, an array reference, or if the amount to be
13065: incremented is > 1, a hash reference.
13066:
13067: ($udom and $uname are optional)
1.191 harris41 13068:
13069: =item *
13070:
1.243 albertel 13071: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13072: ($udom and $uname are optional)
1.191 harris41 13073:
13074: =item *
13075:
1.243 albertel 13076: cput($namespace,$storehash,$udom,$uname) : critical put
13077: ($udom and $uname are optional)
1.191 harris41 13078:
13079: =item *
13080:
1.748 albertel 13081: newput($namespace,$storehash,$udom,$uname) :
13082:
13083: Attempts to store the items in the $storehash, but only if they don't
13084: currently exist, if this succeeds you can be certain that you have
13085: successfully created a new key value pair in the $namespace db.
13086:
13087:
13088: Args:
13089: $namespace: name of database to store values to
13090: $storehash: hashref to store to the db
13091: $udom: (optional) domain of user containing the db
13092: $uname: (optional) name of user caontaining the db
13093:
13094: Returns:
13095: 'ok' -> succeeded in storing all keys of $storehash
13096: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13097: least <key> already existed in the db (other
13098: requested keys may also already exist)
1.967 bisitz 13099: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13100: 'con_lost' -> unable to contact request server
13101: 'refused' -> action was not allowed by remote machine
13102:
13103:
13104: =item *
13105:
1.243 albertel 13106: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13107: reference filled in from namesp (encrypts the return communication)
13108: ($udom and $uname are optional)
1.191 harris41 13109:
13110: =item *
13111:
1.243 albertel 13112: log($udom,$name,$home,$message) : write to permanent log for user; use
13113: critical subroutine
13114:
1.806 raeburn 13115: =item *
13116:
1.860 raeburn 13117: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13118: array reference filled in from namespace found in domain level on either
13119: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13120:
13121: =item *
13122:
1.860 raeburn 13123: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13124: domain level either on specified domain server ($uhome) or primary domain
13125: server ($udom and $uhome are optional)
1.806 raeburn 13126:
1.943 raeburn 13127: =item *
13128:
13129: get_domain_defaults($target_domain) : returns hash with defaults for
13130: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13131: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13132: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13133: Values are retrieved from cache (if current), or from domain's configuration.db
13134: (if available), or lastly from values in lonTabs/dns_domain,tab,
13135: or lonTabs/domain.tab.
13136:
13137: %domdefaults = &get_auth_defaults($target_domain);
13138:
1.243 albertel 13139: =back
13140:
13141: =head2 Network Status Functions
13142:
13143: =over 4
1.191 harris41 13144:
13145: =item *
13146:
1.1137 raeburn 13147: dirlist() : return directory list based on URI (first arg).
13148:
13149: Inputs: 1 required, 5 optional.
13150:
13151: =over
13152:
13153: =item
13154: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13155:
13156: =item
13157: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13158:
13159: =item
13160: $username - username of user/course to be listed. Extracted from $uri if absent.
13161:
13162: =item
13163: $getpropath - boolean: 1 if prepend path using &propath().
13164:
13165: =item
13166: $getuserdir - boolean: 1 if prepend path for "userfiles".
13167:
13168: =item
13169: $alternateRoot - path to prepend in place of path from $uri.
13170:
13171: =back
13172:
13173: Returns: Array of up to two items.
13174:
13175: =over
13176:
13177: a reference to an array of files/subdirectories
13178:
13179: =over
13180:
13181: Each element in the array of files/subdirectories is a & separated list of
13182: item name and the result of running stat on the item. If dirlist was requested
13183: for a file instead of a directory, the item name will be ''. For a directory
13184: listing, if the item is a metadata file, the element will end &N&M
13185: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13186: default copyright set (1).
13187:
13188: =back
13189:
13190: a scalar containing error condition (if encountered).
13191:
13192: =over
13193:
13194: =item
13195: no_host (no homeserver identified for $username:$domain).
13196:
13197: =item
13198: no_such_host (server contacted for listing not identified as valid host).
13199:
13200: =item
13201: con_lost (connection to remote server failed).
13202:
13203: =item
13204: refused (invalid $username:$domain received on lond side).
13205:
13206: =item
13207: no_such_dir (directory at specified path on lond side does not exist).
13208:
13209: =item
13210: empty (directory at specified path on lond side is empty).
13211:
13212: =over
13213:
13214: This is currently not encountered because the &ls3, &ls2,
13215: &ls (_handler) routines on the lond side do not filter out
13216: . and .. from a directory listing.
13217:
13218: =back
13219:
13220: =back
13221:
13222: =back
1.191 harris41 13223:
13224: =item *
13225:
1.243 albertel 13226: spareserver() : find server with least workload from spare.tab
13227:
1.986 foxr 13228:
13229: =item *
13230:
13231: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13232: if there is no corresponding loncapa host.
13233:
1.243 albertel 13234: =back
13235:
1.986 foxr 13236:
1.243 albertel 13237: =head2 Apache Request
13238:
13239: =over 4
1.191 harris41 13240:
13241: =item *
13242:
1.243 albertel 13243: ssi($url,%hash) : server side include, does a complete request cycle on url to
13244: localhost, posts hash
13245:
13246: =back
13247:
13248: =head2 Data to String to Data
13249:
13250: =over 4
1.191 harris41 13251:
13252: =item *
13253:
1.243 albertel 13254: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13255: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13256:
13257: =item *
13258:
1.243 albertel 13259: hashref2str($hashref) : convert a hashref into a string complete with
13260: escaping and '=' and '&' separators, supports elements that are
13261: arrayrefs and hashrefs
1.191 harris41 13262:
13263: =item *
13264:
1.243 albertel 13265: arrayref2str($arrayref) : convert an arrayref into a string complete
13266: with escaping and '&' separators, supports elements that are arrayrefs
13267: and hashrefs
1.191 harris41 13268:
13269: =item *
13270:
1.243 albertel 13271: str2hash($string) : convert string to hash using unescaping and
13272: splitting on '=' and '&', supports elements that are arrayrefs and
13273: hashrefs
1.191 harris41 13274:
13275: =item *
13276:
1.243 albertel 13277: str2array($string) : convert string to hash using unescaping and
13278: splitting on '&', supports elements that are arrayrefs and hashrefs
13279:
13280: =back
13281:
13282: =head2 Logging Routines
13283:
13284:
13285: These routines allow one to make log messages in the lonnet.log and
13286: lonnet.perm logfiles.
1.191 harris41 13287:
1.1119 foxr 13288: =over 4
13289:
1.191 harris41 13290: =item *
13291:
1.243 albertel 13292: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13293:
13294: =item *
13295:
1.243 albertel 13296: logthis() : append message to the normal lonnet.log file, it gets
13297: preiodically rolled over and deleted.
1.191 harris41 13298:
13299: =item *
13300:
1.243 albertel 13301: logperm() : append a permanent message to lonnet.perm.log, this log
13302: file never gets deleted by any automated portion of the system, only
13303: messages of critical importance should go in here.
13304:
1.1119 foxr 13305:
1.243 albertel 13306: =back
13307:
13308: =head2 General File Helper Routines
13309:
13310: =over 4
1.191 harris41 13311:
13312: =item *
13313:
1.481 raeburn 13314: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13315: (a) files in /uploaded
13316: (i) If a local copy of the file exists -
13317: compares modification date of local copy with last-modified date for
13318: definitive version stored on home server for course. If local copy is
13319: stale, requests a new version from the home server and stores it.
13320: If the original has been removed from the home server, then local copy
13321: is unlinked.
13322: (ii) If local copy does not exist -
13323: requests the file from the home server and stores it.
13324:
13325: If $caller is 'uploadrep':
13326: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13327: for request for files originally uploaded via DOCS.
13328: - returns 'ok' if fresh local copy now available, -1 otherwise.
13329:
13330: Otherwise:
13331: This indicates a call from the content generation phase of the request.
13332: - returns the entire contents of the file or -1.
13333:
13334: (b) files in /res
13335: - returns the entire contents of a file or -1;
13336: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13337:
1.712 albertel 13338:
13339: =item *
13340:
13341: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13342: reference
13343:
13344: returns either a stat() list of data about the file or an empty list
13345: if the file doesn't exist or couldn't find out about it (connection
13346: problems or user unknown)
13347:
1.191 harris41 13348: =item *
13349:
1.243 albertel 13350: filelocation($dir,$file) : returns file system location of a file
13351: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13352: directory that relative $file lookups are to looked in ($dir of /a/dir
13353: and a file of ../bob will become /a/bob)
1.191 harris41 13354:
13355: =item *
13356:
13357: hreflocation($dir,$file) : returns file system location or a URL; same as
13358: filelocation except for hrefs
13359:
13360: =item *
13361:
13362: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13363:
1.243 albertel 13364: =back
13365:
1.608 albertel 13366: =head2 Usererfile file routines (/uploaded*)
13367:
13368: =over 4
13369:
13370: =item *
13371:
13372: userfileupload(): main rotine for putting a file in a user or course's
13373: filespace, arguments are,
13374:
1.620 albertel 13375: formname - required - this is the name of the element in $env where the
1.608 albertel 13376: filename, and the contents of the file to create/modifed exist
1.620 albertel 13377: the filename is in $env{'form.'.$formname.'.filename'} and the
13378: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13379: context - if coursedoc, store the file in the course of the active role
13380: of the current user;
13381: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13382: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13383: subdir - required - subdirectory to put the file in under ../userfiles/
13384: if undefined, it will be placed in "unknown"
13385:
13386: (This routine calls clean_filename() to remove any dangerous
13387: characters from the filename, and then calls finuserfileupload() to
13388: complete the transaction)
13389:
13390: returns either the url of the uploaded file (/uploaded/....) if successful
13391: and /adm/notfound.html if unsuccessful
13392:
13393: =item *
13394:
13395: clean_filename(): routine for cleaing a filename up for storage in
13396: userfile space, argument is:
13397:
13398: filename - proposed filename
13399:
13400: returns: the new clean filename
13401:
13402: =item *
13403:
1.1090 raeburn 13404: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13405: userspace, probably shouldn't be called directly
13406:
13407: docuname: username or courseid of destination for the file
13408: docudom: domain of user/course of destination for the file
13409: formname: same as for userfileupload()
1.1090 raeburn 13410: fname: filename (including subdirectories) for the file
13411: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13412: allfiles: reference to hash used to store objects found by parser
13413: codebase: reference to hash used for codebases of java objects found by parser
13414: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13415: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13416: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13417: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13418: context: if 'overwrite', will move the uploaded file from its temporary location to
13419: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13420: mimetype: reference to scalar to accommodate mime type determined
13421: from File::MMagic if $parser = parse.
1.608 albertel 13422:
13423: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13424: and /adm/notfound.html if unsuccessful (or an error message if context
13425: was 'overwrite').
13426:
1.608 albertel 13427:
13428: =item *
13429:
13430: renameuserfile(): renames an existing userfile to a new name
13431:
13432: Args:
13433: docuname: username or courseid of destination for the file
13434: docudom: domain of user/course of destination for the file
13435: old: current file name (including any subdirs under userfiles)
13436: new: desired file name (including any subdirs under userfiles)
13437:
13438: =item *
13439:
13440: mkdiruserfile(): creates a directory is a userfiles dir
13441:
13442: Args:
13443: docuname: username or courseid of destination for the file
13444: docudom: domain of user/course of destination for the file
13445: dir: dir to create (including any subdirs under userfiles)
13446:
13447: =item *
13448:
13449: removeuserfile(): removes a file that exists in userfiles
13450:
13451: Args:
13452: docuname: username or courseid of destination for the file
13453: docudom: domain of user/course of destination for the file
13454: fname: filname to delete (including any subdirs under userfiles)
13455:
13456: =item *
13457:
13458: removeuploadedurl(): convience function for removeuserfile()
13459:
13460: Args:
13461: url: a full /uploaded/... url to delete
13462:
1.747 albertel 13463: =item *
13464:
13465: get_portfile_permissions():
13466: Args:
13467: domain: domain of user or course contain the portfolio files
13468: user: name of user or num of course contain the portfolio files
13469: Returns:
13470: hashref of a dump of the proper file_permissions.db
13471:
13472:
13473: =item *
13474:
13475: get_access_controls():
13476:
13477: Args:
13478: current_permissions: the hash ref returned from get_portfile_permissions()
13479: group: (optional) the group you want the files associated with
13480: file: (optional) the file you want access info on
13481:
13482: Returns:
1.749 raeburn 13483: a hash (keys are file names) of hashes containing
13484: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13485: values are XML containing access control settings (see below)
1.747 albertel 13486:
13487: Internal notes:
13488:
1.749 raeburn 13489: access controls are stored in file_permissions.db as key=value pairs.
13490: key -> path to file/file_name\0uniqueID:scope_end_start
13491: where scope -> public,guest,course,group,domains or users.
13492: end -> UNIX time for end of access (0 -> no end date)
13493: start -> UNIX time for start of access
13494:
13495: value -> XML description of access control
13496: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13497: <start></start>
13498: <end></end>
13499:
13500: <password></password> for scope type = guest
13501:
13502: <domain></domain> for scope type = course or group
13503: <number></number>
13504: <roles id="">
13505: <role></role>
13506: <access></access>
13507: <section></section>
13508: <group></group>
13509: </roles>
13510:
13511: <dom></dom> for scope type = domains
13512:
13513: <users> for scope type = users
13514: <user>
13515: <uname></uname>
13516: <udom></udom>
13517: </user>
13518: </users>
13519: </scope>
13520:
13521: Access data is also aggregated for each file in an additional key=value pair:
13522: key -> path to file/file_name\0accesscontrol
13523: value -> reference to hash
13524: hash contains key = value pairs
13525: where key = uniqueID:scope_end_start
13526: value = UNIX time record was last updated
13527:
13528: Used to improve speed of look-ups of access controls for each file.
13529:
13530: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13531:
1.1172.2.13 raeburn 13532: =item *
13533:
1.749 raeburn 13534: modify_access_controls():
13535:
13536: Modifies access controls for a portfolio file
13537: Args
13538: 1. file name
13539: 2. reference to hash of required changes,
13540: 3. domain
13541: 4. username
13542: where domain,username are the domain of the portfolio owner
13543: (either a user or a course)
13544:
13545: Returns:
13546: 1. result of additions or updates ('ok' or 'error', with error message).
13547: 2. result of deletions ('ok' or 'error', with error message).
13548: 3. reference to hash of any new or updated access controls.
13549: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13550: key = integer (inbound ID)
1.1172.2.13 raeburn 13551: value = uniqueID
13552:
13553: =item *
13554:
13555: get_timebased_id():
13556:
13557: Attempts to get a unique timestamp-based suffix for use with items added to a
13558: course via the Course Editor (e.g., folders, composite pages,
13559: group bulletin boards).
13560:
13561: Args: (first three required; six others optional)
13562:
13563: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13564: docssequence, or name of group
13565:
13566: 2. keyid (alphanumeric): name of temporary locking key in hash,
13567: e.g., num, boardids
13568:
13569: 3. namespace: name of gdbm file used to store suffixes already assigned;
13570: file will be named nohist_namespace.db
13571:
13572: 4. cdom: domain of course; default is current course domain from %env
13573:
13574: 5. cnum: course number; default is current course number from %env
13575:
13576: 6. idtype: set to concat if an additional digit is to be appended to the
13577: unix timestamp to form the suffix, if the plain timestamp is already
13578: in use. Default is to not do this, but simply increment the unix
13579: timestamp by 1 until a unique key is obtained.
13580:
13581: 7. who: holder of locking key; defaults to user:domain for user.
13582:
13583: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13584: retrying); default is 3.
13585:
13586: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13587:
13588: Returns:
13589:
13590: 1. suffix obtained (numeric)
13591:
13592: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13593:
13594: 3. error: contains (localized) error message if an error occurred.
13595:
1.747 albertel 13596:
1.608 albertel 13597: =back
13598:
1.243 albertel 13599: =head2 HTTP Helper Routines
13600:
13601: =over 4
13602:
1.191 harris41 13603: =item *
13604:
13605: escape() : unpack non-word characters into CGI-compatible hex codes
13606:
13607: =item *
13608:
13609: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13610:
1.243 albertel 13611: =back
13612:
13613: =head1 PRIVATE SUBROUTINES
13614:
13615: =head2 Underlying communication routines (Shouldn't call)
13616:
13617: =over 4
13618:
13619: =item *
13620:
13621: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13622:
13623: =item *
13624:
13625: reply() : uses subreply to send a message to remote machine, logs all failures
13626:
13627: =item *
13628:
13629: critical() : passes a critical message to another server; if cannot
13630: get through then place message in connection buffer directory and
13631: returns con_delayed, if incapable of saving message, returns
13632: con_failed
13633:
13634: =item *
13635:
13636: reconlonc() : tries to reconnect lonc client processes.
13637:
13638: =back
13639:
13640: =head2 Resource Access Logging
13641:
13642: =over 4
13643:
13644: =item *
13645:
13646: flushcourselogs() : flush (save) buffer logs and access logs
13647:
13648: =item *
13649:
13650: courselog($what) : save message for course in hash
13651:
13652: =item *
13653:
13654: courseacclog($what) : save message for course using &courselog(). Perform
13655: special processing for specific resource types (problems, exams, quizzes, etc).
13656:
1.191 harris41 13657: =item *
13658:
13659: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13660: as a PerlChildExitHandler
1.243 albertel 13661:
13662: =back
13663:
13664: =head2 Other
13665:
13666: =over 4
13667:
13668: =item *
13669:
13670: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13671:
13672: =back
13673:
13674: =cut
1.877 foxr 13675:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>