Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1230
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1230 ! raeburn 4: # $Id: lonnet.pm,v 1.1229 2013/07/02 19:04:56 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.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1213 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.539 albertel 95: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.550 foxr 108: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1187 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1187 raeburn 119: sub write_log {
1.1188 raeburn 120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1184 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 143: }
144: }
1.1 albertel 145:
1.163 harris41 146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
1.1 albertel 156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
1.448 albertel 161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
1.448 albertel 164: close($fh);
165: }
1.1 albertel 166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
1.448 albertel 174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
1.1 albertel 178: return 1;
179: }
180:
1.850 albertel 181: sub create_connection {
1.853 albertel 182: my ($hostname,$lonid) = @_;
1.851 albertel 183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
1.890 albertel 187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
1.983 raeburn 194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
1.850 albertel 208:
1.1106 raeburn 209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
1.993 raeburn 232: sub get_server_loncaparev {
1.1073 raeburn 233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
1.1073 raeburn 248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
1.1082 raeburn 267: $ua->timeout(4);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
359: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 360: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 361: return $response;
362: }
363:
1.1 albertel 364: # -------------------------------------------------- Non-critical communication
365: sub subreply {
366: my ($cmd,$server)=@_;
1.838 albertel 367: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 368: #
369: # With loncnew process trimming, there's a timing hole between lonc server
370: # process exit and the master server picking up the listen on the AF_UNIX
371: # socket. In that time interval, a lock file will exist:
372:
373: my $lockfile=$peerfile.".lock";
374: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
375: sleep(1);
376: }
377: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 378: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 379: #
1.550 foxr 380: # We'll give the connection a few tries before abandoning it. If
381: # connection is not possible, we'll con_lost back to the client.
382: #
383: my $client;
384: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
385: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
386: Type => SOCK_STREAM,
387: Timeout => 10);
1.869 albertel 388: if ($client) {
1.550 foxr 389: last; # Connected!
1.850 albertel 390: } else {
1.853 albertel 391: &create_connection(&hostname($server),$server);
1.550 foxr 392: }
1.850 albertel 393: sleep(1); # Try again later if failed connection.
1.550 foxr 394: }
395: my $answer;
396: if ($client) {
1.704 albertel 397: print $client "sethost:$server:$cmd\n";
1.550 foxr 398: $answer=<$client>;
399: if (!$answer) { $answer="con_lost"; }
400: chomp($answer);
401: } else {
402: $answer = 'con_lost'; # Failed connection.
403: }
1.1 albertel 404: return $answer;
405: }
406:
407: sub reply {
408: my ($cmd,$server)=@_;
1.838 albertel 409: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 410: my $answer=subreply($cmd,$server);
1.65 www 411: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 412: &logthis("<font color=\"blue\">WARNING:".
1.12 www 413: " $cmd to $server returned $answer</font>");
414: }
1.1 albertel 415: return $answer;
416: }
417:
418: # ----------------------------------------------------------- Send USR1 to lonc
419:
420: sub reconlonc {
1.891 albertel 421: my ($lonid) = @_;
422: my $hostname = &hostname($lonid);
423: if ($lonid) {
424: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
425: if ($hostname && -e $peerfile) {
426: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
427: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
428: Type => SOCK_STREAM,
429: Timeout => 10);
430: if ($client) {
431: print $client ("reset_retries\n");
432: my $answer=<$client>;
433: #reset just this one.
434: }
435: }
436: return;
437: }
438:
1.836 www 439: &logthis("Trying to reconnect lonc");
1.1 albertel 440: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 441: if (open(my $fh,"<$loncfile")) {
1.1 albertel 442: my $loncpid=<$fh>;
443: chomp($loncpid);
444: if (kill 0 => $loncpid) {
445: &logthis("lonc at pid $loncpid responding, sending USR1");
446: kill USR1 => $loncpid;
447: sleep 1;
1.836 www 448: } else {
1.12 www 449: &logthis(
1.672 albertel 450: "<font color=\"blue\">WARNING:".
1.12 www 451: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 452: }
453: } else {
1.836 www 454: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 455: }
456: }
457:
458: # ------------------------------------------------------ Critical communication
1.12 www 459:
1.1 albertel 460: sub critical {
461: my ($cmd,$server)=@_;
1.838 albertel 462: unless (&hostname($server)) {
1.672 albertel 463: &logthis("<font color=\"blue\">WARNING:".
1.89 www 464: " Critical message to unknown server ($server)</font>");
465: return 'no_such_host';
466: }
1.1 albertel 467: my $answer=reply($cmd,$server);
468: if ($answer eq 'con_lost') {
469: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 470: my $answer=reply($cmd,$server);
1.1 albertel 471: if ($answer eq 'con_lost') {
472: my $now=time;
473: my $middlename=$cmd;
1.5 www 474: $middlename=substr($middlename,0,16);
1.1 albertel 475: $middlename=~s/\W//g;
476: my $dfilename=
1.305 www 477: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
478: $dumpcount++;
1.1 albertel 479: {
1.448 albertel 480: my $dfh;
481: if (open($dfh,">$dfilename")) {
482: print $dfh "$cmd\n";
483: close($dfh);
484: }
1.1 albertel 485: }
486: sleep 2;
487: my $wcmd='';
488: {
1.448 albertel 489: my $dfh;
490: if (open($dfh,"<$dfilename")) {
491: $wcmd=<$dfh>;
492: close($dfh);
493: }
1.1 albertel 494: }
495: chomp($wcmd);
1.7 www 496: if ($wcmd eq $cmd) {
1.672 albertel 497: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 498: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 499: &logperm("D:$server:$cmd");
500: return 'con_delayed';
501: } else {
1.672 albertel 502: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 503: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 504: &logperm("F:$server:$cmd");
505: return 'con_failed';
506: }
507: }
508: }
509: return $answer;
1.405 albertel 510: }
511:
1.755 albertel 512: # ------------------------------------------- check if return value is an error
513:
514: sub error {
515: my ($result) = @_;
1.756 albertel 516: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 517: if ($2 == 2) { return undef; }
518: return $1;
519: }
520: return undef;
521: }
522:
1.783 albertel 523: sub convert_and_load_session_env {
524: my ($lonidsdir,$handle)=@_;
525: my @profile;
526: {
1.917 albertel 527: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
528: if (!$opened) {
1.915 albertel 529: return 0;
530: }
1.783 albertel 531: flock($idf,LOCK_SH);
532: @profile=<$idf>;
533: close($idf);
534: }
535: my %temp_env;
536: foreach my $line (@profile) {
1.786 albertel 537: if ($line !~ m/=/) {
538: return 0;
539: }
1.783 albertel 540: chomp($line);
541: my ($envname,$envvalue)=split(/=/,$line,2);
542: $temp_env{&unescape($envname)} = &unescape($envvalue);
543: }
544: unlink("$lonidsdir/$handle.id");
545: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
546: 0640)) {
547: %disk_env = %temp_env;
548: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
549: untie(%disk_env);
550: }
1.786 albertel 551: return 1;
1.783 albertel 552: }
553:
1.374 www 554: # ------------------------------------------- Transfer profile into environment
1.780 albertel 555: my $env_loaded;
556: sub transfer_profile_to_env {
1.788 albertel 557: my ($lonidsdir,$handle,$force_transfer) = @_;
558: if (!$force_transfer && $env_loaded) { return; }
1.374 www 559:
1.720 albertel 560: if (!defined($lonidsdir)) {
561: $lonidsdir = $perlvar{'lonIDsDir'};
562: }
563: if (!defined($handle)) {
564: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
565: }
566:
1.786 albertel 567: my $convert;
568: {
1.917 albertel 569: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
570: if (!$opened) {
1.915 albertel 571: return;
572: }
1.786 albertel 573: flock($idf,LOCK_SH);
574: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
575: &GDBM_READER(),0640)) {
576: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
577: untie(%disk_env);
578: } else {
579: $convert = 1;
580: }
581: }
582: if ($convert) {
583: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
584: &logthis("Failed to load session, or convert session.");
585: }
1.374 www 586: }
1.783 albertel 587:
1.786 albertel 588: my %remove;
1.783 albertel 589: while ( my $envname = each(%env) ) {
1.433 matthew 590: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
591: if ($time < time-300) {
1.783 albertel 592: $remove{$key}++;
1.433 matthew 593: }
594: }
595: }
1.783 albertel 596:
1.619 albertel 597: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 598: $env_loaded=1;
1.783 albertel 599: foreach my $expired_key (keys(%remove)) {
1.433 matthew 600: &delenv($expired_key);
1.374 www 601: }
1.1 albertel 602: }
603:
1.916 albertel 604: # ---------------------------------------------------- Check for valid session
605: sub check_for_valid_session {
1.1155 raeburn 606: my ($r,$name) = @_;
1.916 albertel 607: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 608: if ($name eq '') {
609: $name = 'lonID';
610: }
611: my $lonid=$cookies{$name};
1.916 albertel 612: return undef if (!$lonid);
613:
614: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 615: my $lonidsdir;
616: if ($name eq 'lonDAV') {
617: $lonidsdir=$r->dir_config('lonDAVsessDir');
618: } else {
619: $lonidsdir=$r->dir_config('lonIDsDir');
620: }
1.916 albertel 621: return undef if (!-e "$lonidsdir/$handle.id");
622:
1.917 albertel 623: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
624: return undef if (!$opened);
1.916 albertel 625:
626: flock($idf,LOCK_SH);
627: my %disk_env;
628: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
629: &GDBM_READER(),0640)) {
630: return undef;
631: }
632:
633: if (!defined($disk_env{'user.name'})
634: || !defined($disk_env{'user.domain'})) {
635: return undef;
636: }
1.1213 raeburn 637: if (($r->user() eq '') && ($apache >= 2.4)) {
1.1212 raeburn 638: if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
639: $r->user($disk_env{'user.name'});
640: } else {
641: $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
642: }
643: }
1.916 albertel 644: return $handle;
645: }
646:
1.830 albertel 647: sub timed_flock {
648: my ($file,$lock_type) = @_;
649: my $failed=0;
650: eval {
651: local $SIG{__DIE__}='DEFAULT';
652: local $SIG{ALRM}=sub {
653: $failed=1;
654: die("failed lock");
655: };
656: alarm(13);
657: flock($file,$lock_type);
658: alarm(0);
659: };
660: if ($failed) {
661: return undef;
662: } else {
663: return 1;
664: }
665: }
666:
1.5 www 667: # ---------------------------------------------------------- Append Environment
668:
669: sub appenv {
1.949 raeburn 670: my ($newenv,$roles) = @_;
671: if (ref($newenv) eq 'HASH') {
672: foreach my $key (keys(%{$newenv})) {
673: my $refused = 0;
674: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
675: $refused = 1;
676: if (ref($roles) eq 'ARRAY') {
677: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
678: if (grep(/^\Q$role\E$/,@{$roles})) {
679: $refused = 0;
680: }
681: }
682: }
683: if ($refused) {
684: &logthis("<font color=\"blue\">WARNING: ".
685: "Attempt to modify environment ".$key." to ".$newenv->{$key}
686: .'</font>');
687: delete($newenv->{$key});
688: } else {
689: $env{$key}=$newenv->{$key};
690: }
691: }
692: my $opened = open(my $env_file,'+<',$env{'user.environment'});
693: if ($opened
694: && &timed_flock($env_file,LOCK_EX)
695: &&
696: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
697: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
698: while (my ($key,$value) = each(%{$newenv})) {
699: $disk_env{$key} = $value;
700: }
701: untie(%disk_env);
1.35 www 702: }
1.191 harris41 703: }
1.56 www 704: return 'ok';
705: }
706: # ----------------------------------------------------- Delete from Environment
707:
708: sub delenv {
1.1104 raeburn 709: my ($delthis,$regexp,$roles) = @_;
710: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
711: my $refused = 1;
712: if (ref($roles) eq 'ARRAY') {
713: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
714: if (grep(/^\Q$role\E$/,@{$roles})) {
715: $refused = 0;
716: }
717: }
718: if ($refused) {
719: &logthis("<font color=\"blue\">WARNING: ".
720: "Attempt to delete from environment ".$delthis);
721: return 'error';
722: }
1.56 www 723: }
1.917 albertel 724: my $opened = open(my $env_file,'+<',$env{'user.environment'});
725: if ($opened
1.915 albertel 726: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 727: &&
728: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
729: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 730: foreach my $key (keys(%disk_env)) {
1.987 raeburn 731: if ($regexp) {
732: if ($key=~/^$delthis/) {
733: delete($env{$key});
734: delete($disk_env{$key});
735: }
736: } else {
737: if ($key=~/^\Q$delthis\E/) {
738: delete($env{$key});
739: delete($disk_env{$key});
740: }
741: }
1.448 albertel 742: }
1.783 albertel 743: untie(%disk_env);
1.5 www 744: }
745: return 'ok';
1.369 albertel 746: }
747:
1.790 albertel 748: sub get_env_multiple {
749: my ($name) = @_;
750: my @values;
751: if (defined($env{$name})) {
752: # exists is it an array
753: if (ref($env{$name})) {
754: @values=@{ $env{$name} };
755: } else {
756: $values[0]=$env{$name};
757: }
758: }
759: return(@values);
760: }
761:
1.958 www 762: # ------------------------------------------------------------------- Locking
763:
764: sub set_lock {
765: my ($text)=@_;
766: $locknum++;
767: my $id=$$.'-'.$locknum;
768: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
769: 'session.lock.'.$id => $text});
770: return $id;
771: }
772:
773: sub get_locks {
774: my $num=0;
775: my %texts=();
776: foreach my $lock (split(/\,/,$env{'session.locks'})) {
777: if ($lock=~/\w/) {
778: $num++;
779: $texts{$lock}=$env{'session.lock.'.$lock};
780: }
781: }
782: return ($num,%texts);
783: }
784:
785: sub remove_lock {
786: my ($id)=@_;
787: my $newlocks='';
788: foreach my $lock (split(/\,/,$env{'session.locks'})) {
789: if (($lock=~/\w/) && ($lock ne $id)) {
790: $newlocks.=','.$lock;
791: }
792: }
793: &appenv({'session.locks' => $newlocks});
794: &delenv('session.lock.'.$id);
795: }
796:
797: sub remove_all_locks {
798: my $activelocks=$env{'session.locks'};
799: foreach my $lock (split(/\,/,$env{'session.locks'})) {
800: if ($lock=~/\w/) {
801: &remove_lock($lock);
802: }
803: }
804: }
805:
806:
1.369 albertel 807: # ------------------------------------------ Find out current server userload
808: sub userload {
809: my $numusers=0;
810: {
811: opendir(LONIDS,$perlvar{'lonIDsDir'});
812: my $filename;
813: my $curtime=time;
814: while ($filename=readdir(LONIDS)) {
1.925 albertel 815: next if ($filename eq '.' || $filename eq '..');
816: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 817: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 818: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 819: }
820: closedir(LONIDS);
821: }
822: my $userloadpercent=0;
823: my $maxuserload=$perlvar{'lonUserLoadLim'};
824: if ($maxuserload) {
1.371 albertel 825: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 826: }
1.372 albertel 827: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 828: return $userloadpercent;
1.283 www 829: }
830:
1.1 albertel 831: # ------------------------------ Find server with least workload from spare.tab
1.11 www 832:
1.1 albertel 833: sub spareserver {
1.1083 raeburn 834: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 835: my $spare_server;
1.370 albertel 836: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 837: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
838: : $userloadpercent;
1.1083 raeburn 839: my ($uint_dom,$remotesessions);
840: if (($udom ne '') && (&domain($udom) ne '')) {
841: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
842: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
843: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
844: $remotesessions = $udomdefaults{'remotesessions'};
845: }
1.1123 raeburn 846: my $spareshash = &this_host_spares($udom);
847: if (ref($spareshash) eq 'HASH') {
848: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
849: foreach my $try_server (@{ $spareshash->{'primary'} }) {
850: if ($uint_dom) {
851: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
852: $try_server));
853: }
854: ($spare_server, $lowest_load) =
855: &compare_server_load($try_server, $spare_server, $lowest_load);
856: }
1.1083 raeburn 857: }
1.784 albertel 858:
1.1123 raeburn 859: my $found_server = ($spare_server ne '' && $lowest_load < 100);
860:
861: if (!$found_server) {
862: if (ref($spareshash->{'default'}) eq 'ARRAY') {
863: foreach my $try_server (@{ $spareshash->{'default'} }) {
864: if ($uint_dom) {
865: next unless (&spare_can_host($udom,$uint_dom,
866: $remotesessions,$try_server));
867: }
868: ($spare_server, $lowest_load) =
869: &compare_server_load($try_server, $spare_server, $lowest_load);
870: }
871: }
872: }
1.784 albertel 873: }
874:
875: if (!$want_server_name) {
1.968 raeburn 876: my $protocol = 'http';
877: if ($protocol{$spare_server} eq 'https') {
878: $protocol = $protocol{$spare_server};
879: }
1.1001 raeburn 880: if (defined($spare_server)) {
881: my $hostname = &hostname($spare_server);
1.1083 raeburn 882: if (defined($hostname)) {
1.1001 raeburn 883: $spare_server = $protocol.'://'.$hostname;
884: }
885: }
1.784 albertel 886: }
887: return $spare_server;
888: }
889:
890: sub compare_server_load {
891: my ($try_server, $spare_server, $lowest_load) = @_;
892:
893: my $loadans = &reply('load', $try_server);
894: my $userloadans = &reply('userload',$try_server);
895:
896: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 897: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 898: }
899:
900: my $load;
901: if ($loadans =~ /\d/) {
902: if ($userloadans =~ /\d/) {
903: #both are numbers, pick the bigger one
904: $load = ($loadans > $userloadans) ? $loadans
905: : $userloadans;
1.411 albertel 906: } else {
1.784 albertel 907: $load = $loadans;
1.411 albertel 908: }
1.784 albertel 909: } else {
910: $load = $userloadans;
911: }
912:
913: if (($load =~ /\d/) && ($load < $lowest_load)) {
914: $spare_server = $try_server;
915: $lowest_load = $load;
1.370 albertel 916: }
1.784 albertel 917: return ($spare_server,$lowest_load);
1.202 matthew 918: }
1.914 albertel 919:
920: # --------------------------- ask offload servers if user already has a session
921: sub find_existing_session {
922: my ($udom,$uname) = @_;
1.1123 raeburn 923: my $spareshash = &this_host_spares($udom);
924: if (ref($spareshash) eq 'HASH') {
925: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
926: foreach my $try_server (@{ $spareshash->{'primary'} }) {
927: return $try_server if (&has_user_session($try_server, $udom, $uname));
928: }
929: }
930: if (ref($spareshash->{'default'}) eq 'ARRAY') {
931: foreach my $try_server (@{ $spareshash->{'default'} }) {
932: return $try_server if (&has_user_session($try_server, $udom, $uname));
933: }
934: }
1.914 albertel 935: }
936: return;
937: }
938:
939: # -------------------------------- ask if server already has a session for user
940: sub has_user_session {
941: my ($lonid,$udom,$uname) = @_;
942: my $result = &reply(join(':','userhassession',
943: map {&escape($_)} ($udom,$uname)),$lonid);
944: return 1 if ($result eq 'ok');
945:
946: return 0;
947: }
948:
1.1076 raeburn 949: # --------- determine least loaded server in a user's domain which allows login
950:
951: sub choose_server {
1.1115 raeburn 952: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 953: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 954: my %servers = &get_servers($udom);
1.1076 raeburn 955: my $lowest_load = 30000;
1.1151 raeburn 956: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 957: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 958: my $loginvia;
959: if ($checkloginvia) {
960: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 961: if ($loginvia) {
962: my ($server,$path) = split(/:/,$loginvia);
963: ($login_host, $lowest_load) =
964: &compare_server_load($server, $login_host, $lowest_load);
965: if ($login_host eq $server) {
966: $portal_path = $path;
1.1151 raeburn 967: $isredirect = 1;
1.1116 raeburn 968: }
969: } else {
970: ($login_host, $lowest_load) =
971: &compare_server_load($lonhost, $login_host, $lowest_load);
972: if ($login_host eq $lonhost) {
973: $portal_path = '';
1.1151 raeburn 974: $isredirect = '';
1.1116 raeburn 975: }
976: }
977: } else {
1.1076 raeburn 978: ($login_host, $lowest_load) =
1.1116 raeburn 979: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 980: }
981: }
982: if ($login_host ne '') {
1.1116 raeburn 983: $hostname = &hostname($login_host);
1.1076 raeburn 984: }
1.1151 raeburn 985: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 986: }
987:
1.202 matthew 988: # --------------------------------------------- Try to change a user's password
989:
990: sub changepass {
1.799 raeburn 991: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 992: $currentpass = &escape($currentpass);
993: $newpass = &escape($newpass);
1.1030 raeburn 994: my $lonhost = $perlvar{'lonHostID'};
995: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 996: $server);
997: if (! $answer) {
998: &logthis("No reply on password change request to $server ".
999: "by $uname in domain $udom.");
1000: } elsif ($answer =~ "^ok") {
1001: &logthis("$uname in $udom successfully changed their password ".
1002: "on $server.");
1003: } elsif ($answer =~ "^pwchange_failure") {
1004: &logthis("$uname in $udom was unable to change their password ".
1005: "on $server. The action was blocked by either lcpasswd ".
1006: "or pwchange");
1007: } elsif ($answer =~ "^non_authorized") {
1008: &logthis("$uname in $udom did not get their password correct when ".
1009: "attempting to change it on $server.");
1010: } elsif ($answer =~ "^auth_mode_error") {
1011: &logthis("$uname in $udom attempted to change their password despite ".
1012: "not being locally or internally authenticated on $server.");
1013: } elsif ($answer =~ "^unknown_user") {
1014: &logthis("$uname in $udom attempted to change their password ".
1015: "on $server but were unable to because $server is not ".
1016: "their home server.");
1017: } elsif ($answer =~ "^refused") {
1018: &logthis("$server refused to change $uname in $udom password because ".
1019: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1020: } elsif ($answer =~ "invalid_client") {
1021: &logthis("$server refused to change $uname in $udom password because ".
1022: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1023: }
1024: return $answer;
1.1 albertel 1025: }
1026:
1.169 harris41 1027: # ----------------------- Try to determine user's current authentication scheme
1028:
1029: sub queryauthenticate {
1030: my ($uname,$udom)=@_;
1.456 albertel 1031: my $uhome=&homeserver($uname,$udom);
1032: if (!$uhome) {
1033: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1034: return 'no_host';
1035: }
1036: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1037: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1038: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1039: }
1.456 albertel 1040: return $answer;
1.169 harris41 1041: }
1042:
1.1 albertel 1043: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1044:
1.1 albertel 1045: sub authenticate {
1.1073 raeburn 1046: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1047: $upass=&escape($upass);
1048: $uname= &LONCAPA::clean_username($uname);
1.836 www 1049: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1050: my $newhome;
1.836 www 1051: if ((!$uhome) || ($uhome eq 'no_host')) {
1052: # Maybe the machine was offline and only re-appeared again recently?
1053: &reconlonc();
1054: # One more
1.952 raeburn 1055: $uhome=&homeserver($uname,$udom,1);
1056: if (($uhome eq 'no_host') && $checkdefauth) {
1057: if (defined(&domain($udom,'primary'))) {
1058: $newhome=&domain($udom,'primary');
1059: }
1060: if ($newhome ne '') {
1061: $uhome = $newhome;
1062: }
1063: }
1.836 www 1064: if ((!$uhome) || ($uhome eq 'no_host')) {
1065: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1066: return 'no_host';
1067: }
1.1 albertel 1068: }
1.1073 raeburn 1069: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1070: if ($answer eq 'authorized') {
1.952 raeburn 1071: if ($newhome) {
1072: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1073: return 'no_account_on_host';
1074: } else {
1075: &logthis("User $uname at $udom authorized by $uhome");
1076: return $uhome;
1077: }
1.471 albertel 1078: }
1079: if ($answer eq 'non_authorized') {
1080: &logthis("User $uname at $udom rejected by $uhome");
1081: return 'no_host';
1.9 www 1082: }
1.471 albertel 1083: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1084: return 'no_host';
1085: }
1086:
1.1073 raeburn 1087: sub can_host_session {
1.1074 raeburn 1088: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1089: my $canhost = 1;
1.1074 raeburn 1090: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1091: if (ref($remotesessions) eq 'HASH') {
1092: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1093: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1094: $canhost = 0;
1095: } else {
1096: $canhost = 1;
1097: }
1098: }
1099: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1100: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1101: $canhost = 1;
1102: } else {
1103: $canhost = 0;
1104: }
1105: }
1106: if ($canhost) {
1107: if ($remotesessions->{'version'} ne '') {
1108: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1109: if ($reqmajor ne '' && $reqminor ne '') {
1110: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1111: my $major = $1;
1112: my $minor = $2;
1113: if (($major < $reqmajor ) ||
1114: (($major == $reqmajor) && ($minor < $reqminor))) {
1115: $canhost = 0;
1116: }
1117: } else {
1118: $canhost = 0;
1119: }
1120: }
1121: }
1122: }
1123: }
1124: if ($canhost) {
1125: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1126: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1127: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1128: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1129: if (($uint_dom ne '') &&
1130: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1131: $canhost = 0;
1132: } else {
1133: $canhost = 1;
1134: }
1135: }
1136: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1137: if (($uint_dom ne '') &&
1138: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1139: $canhost = 1;
1140: } else {
1141: $canhost = 0;
1142: }
1143: }
1144: }
1145: }
1146: return $canhost;
1147: }
1148:
1.1083 raeburn 1149: sub spare_can_host {
1150: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1151: my $canhost=1;
1152: my @intdoms;
1153: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1154: if (ref($internet_names) eq 'ARRAY') {
1155: @intdoms = @{$internet_names};
1156: }
1157: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1158: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1159: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1160: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1161: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1162: $canhost = &can_host_session($udom,$try_server,$remoterev,
1163: $remotesessions,
1164: $defdomdefaults{'hostedsessions'});
1165: }
1166: return $canhost;
1167: }
1168:
1.1123 raeburn 1169: sub this_host_spares {
1170: my ($dom) = @_;
1.1126 raeburn 1171: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1172: my @hosts = ¤t_machine_ids();
1173: foreach my $lonhost (@hosts) {
1174: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1175: $dom_in_use = $dom;
1176: $lonhost_in_use = $lonhost;
1.1123 raeburn 1177: last;
1178: }
1179: }
1.1126 raeburn 1180: if ($dom_in_use ne '') {
1181: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1182: }
1183: if (ref($result) ne 'HASH') {
1184: $lonhost_in_use = $perlvar{'lonHostID'};
1185: $dom_in_use = &host_domain($lonhost_in_use);
1186: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1187: if (ref($result) ne 'HASH') {
1188: $result = \%spareid;
1189: }
1190: }
1191: return $result;
1192: }
1193:
1194: sub spares_for_offload {
1195: my ($dom_in_use,$lonhost_in_use) = @_;
1196: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1197: if (defined($cached)) {
1198: return $result;
1199: } else {
1.1126 raeburn 1200: my $cachetime = 60*60*24;
1201: my %domconfig =
1202: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1203: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1204: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1205: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1206: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1207: }
1208: }
1209: }
1210: }
1.1126 raeburn 1211: return;
1.1123 raeburn 1212: }
1213:
1.1129 raeburn 1214: sub get_lonbalancer_config {
1215: my ($servers) = @_;
1216: my ($currbalancer,$currtargets);
1217: if (ref($servers) eq 'HASH') {
1218: foreach my $server (keys(%{$servers})) {
1219: my %what = (
1220: spareid => 1,
1221: perlvar => 1,
1222: );
1223: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1224: if ($result eq 'ok') {
1225: if (ref($returnhash) eq 'HASH') {
1226: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1227: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1228: $currbalancer = $server;
1229: $currtargets = {};
1230: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1231: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1232: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1233: }
1234: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1235: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1236: }
1237: }
1238: last;
1239: }
1240: }
1241: }
1242: }
1243: }
1244: }
1245: return ($currbalancer,$currtargets);
1246: }
1247:
1248: sub check_loadbalancing {
1249: my ($uname,$udom) = @_;
1.1191 raeburn 1250: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1251: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1252: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1253: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1254: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1255: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1256: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1257: my $serverhomedom = &host_domain($lonhost);
1258:
1259: my $cachetime = 60*60*24;
1260:
1261: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1262: $dom_in_use = $udom;
1263: $homeintdom = 1;
1264: } else {
1265: $dom_in_use = $serverhomedom;
1266: }
1267: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1268: unless (defined($cached)) {
1269: my %domconfig =
1270: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1271: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1272: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1273: }
1274: }
1275: if (ref($result) eq 'HASH') {
1.1191 raeburn 1276: ($is_balancer,$currtargets,$currrules) =
1277: &check_balancer_result($result,@hosts);
1.1129 raeburn 1278: if ($is_balancer) {
1279: if (ref($currrules) eq 'HASH') {
1280: if ($homeintdom) {
1281: if ($uname ne '') {
1282: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1283: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1284: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1285: $rule_in_effect = $currrules->{'_LC_author'};
1286: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1287: $rule_in_effect = $currrules->{'_LC_adv'}
1288: }
1289: }
1290: if ($rule_in_effect eq '') {
1291: my %userenv = &userenvironment($udom,$uname,'inststatus');
1292: if ($userenv{'inststatus'} ne '') {
1293: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1294: my ($othertitle,$usertypes,$types) =
1295: &Apache::loncommon::sorted_inst_types($udom);
1296: if (ref($types) eq 'ARRAY') {
1297: foreach my $type (@{$types}) {
1298: if (grep(/^\Q$type\E$/,@statuses)) {
1299: if (exists($currrules->{$type})) {
1300: $rule_in_effect = $currrules->{$type};
1301: }
1302: }
1303: }
1304: }
1305: } else {
1306: if (exists($currrules->{'default'})) {
1307: $rule_in_effect = $currrules->{'default'};
1308: }
1309: }
1310: }
1311: } else {
1312: if (exists($currrules->{'default'})) {
1313: $rule_in_effect = $currrules->{'default'};
1314: }
1315: }
1316: } else {
1317: if ($currrules->{'_LC_external'} ne '') {
1318: $rule_in_effect = $currrules->{'_LC_external'};
1319: }
1320: }
1321: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1322: $uname,$udom);
1323: }
1324: }
1325: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1326: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1327: unless (defined($cached)) {
1328: my %domconfig =
1329: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1330: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1331: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1332: }
1333: }
1334: if (ref($result) eq 'HASH') {
1.1191 raeburn 1335: ($is_balancer,$currtargets,$currrules) =
1336: &check_balancer_result($result,@hosts);
1337: if ($is_balancer) {
1.1129 raeburn 1338: if (ref($currrules) eq 'HASH') {
1339: if ($currrules->{'_LC_internetdom'} ne '') {
1340: $rule_in_effect = $currrules->{'_LC_internetdom'};
1341: }
1342: }
1343: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1344: $uname,$udom);
1345: }
1346: } else {
1347: if ($perlvar{'lonBalancer'} eq 'yes') {
1348: $is_balancer = 1;
1349: $offloadto = &this_host_spares($dom_in_use);
1350: }
1351: }
1352: } else {
1353: if ($perlvar{'lonBalancer'} eq 'yes') {
1354: $is_balancer = 1;
1355: $offloadto = &this_host_spares($dom_in_use);
1356: }
1357: }
1.1176 raeburn 1358: if ($is_balancer) {
1359: my $lowest_load = 30000;
1360: if (ref($offloadto) eq 'HASH') {
1361: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1362: foreach my $try_server (@{$offloadto->{'primary'}}) {
1363: ($otherserver,$lowest_load) =
1364: &compare_server_load($try_server,$otherserver,$lowest_load);
1365: }
1.1129 raeburn 1366: }
1.1176 raeburn 1367: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1368:
1.1176 raeburn 1369: if (!$found_server) {
1370: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1371: foreach my $try_server (@{$offloadto->{'default'}}) {
1372: ($otherserver,$lowest_load) =
1373: &compare_server_load($try_server,$otherserver,$lowest_load);
1374: }
1375: }
1376: }
1377: } elsif (ref($offloadto) eq 'ARRAY') {
1378: if (@{$offloadto} == 1) {
1379: $otherserver = $offloadto->[0];
1380: } elsif (@{$offloadto} > 1) {
1381: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1382: ($otherserver,$lowest_load) =
1383: &compare_server_load($try_server,$otherserver,$lowest_load);
1384: }
1385: }
1386: }
1.1176 raeburn 1387: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1388: $is_balancer = 0;
1389: if ($uname ne '' && $udom ne '') {
1390: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1391:
1392: &appenv({'user.loadbalexempt' => $lonhost,
1393: 'user.loadbalcheck.time' => time});
1394: }
1.1129 raeburn 1395: }
1396: }
1397: }
1398: return ($is_balancer,$otherserver);
1399: }
1400:
1.1191 raeburn 1401: sub check_balancer_result {
1402: my ($result,@hosts) = @_;
1403: my ($is_balancer,$currtargets,$currrules);
1404: if (ref($result) eq 'HASH') {
1405: if ($result->{'lonhost'} ne '') {
1406: my $currbalancer = $result->{'lonhost'};
1407: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1408: $is_balancer = 1;
1409: $currtargets = $result->{'targets'};
1410: $currrules = $result->{'rules'};
1411: }
1412: } else {
1413: foreach my $key (keys(%{$result})) {
1414: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1415: (ref($result->{$key}) eq 'HASH')) {
1416: $is_balancer = 1;
1417: $currrules = $result->{$key}{'rules'};
1418: $currtargets = $result->{$key}{'targets'};
1419: last;
1420: }
1421: }
1422: }
1423: }
1424: return ($is_balancer,$currtargets,$currrules);
1425: }
1426:
1.1129 raeburn 1427: sub get_loadbalancer_targets {
1428: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1429: my $offloadto;
1.1175 raeburn 1430: if ($rule_in_effect eq 'none') {
1431: return [$perlvar{'lonHostID'}];
1432: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1433: $offloadto = $currtargets;
1434: } else {
1435: if ($rule_in_effect eq 'homeserver') {
1436: my $homeserver = &homeserver($uname,$udom);
1437: if ($homeserver ne 'no_host') {
1438: $offloadto = [$homeserver];
1439: }
1440: } elsif ($rule_in_effect eq 'externalbalancer') {
1441: my %domconfig =
1442: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1443: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1444: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1445: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1446: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1447: }
1448: }
1449: } else {
1.1178 raeburn 1450: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1451: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1452: if (&hostname($remotebalancer) ne '') {
1453: $offloadto = [$remotebalancer];
1454: }
1455: }
1456: } elsif (&hostname($rule_in_effect) ne '') {
1457: $offloadto = [$rule_in_effect];
1458: }
1459: }
1460: return $offloadto;
1461: }
1462:
1.1127 raeburn 1463: sub internet_dom_servers {
1464: my ($dom) = @_;
1465: my (%uniqservers,%servers);
1466: my $primaryserver = &hostname(&domain($dom,'primary'));
1467: my @machinedoms = &machine_domains($primaryserver);
1468: foreach my $mdom (@machinedoms) {
1469: my %currservers = %servers;
1470: my %server = &get_servers($mdom);
1471: %servers = (%currservers,%server);
1472: }
1473: my %by_hostname;
1474: foreach my $id (keys(%servers)) {
1475: push(@{$by_hostname{$servers{$id}}},$id);
1476: }
1477: foreach my $hostname (sort(keys(%by_hostname))) {
1478: if (@{$by_hostname{$hostname}} > 1) {
1479: my $match = 0;
1480: foreach my $id (@{$by_hostname{$hostname}}) {
1481: if (&host_domain($id) eq $dom) {
1482: $uniqservers{$id} = $hostname;
1483: $match = 1;
1484: }
1485: }
1486: unless ($match) {
1487: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1488: }
1489: } else {
1490: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1491: }
1492: }
1493: return %uniqservers;
1494: }
1495:
1.1 albertel 1496: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1497:
1.599 albertel 1498: my %homecache;
1.1 albertel 1499: sub homeserver {
1.230 stredwic 1500: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1501: my $index="$uname:$udom";
1.426 albertel 1502:
1.599 albertel 1503: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1504:
1505: my %servers = &get_servers($udom,'library');
1506: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1507: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1508: exists($badServerCache{$tryserver}));
1.841 albertel 1509:
1510: my $answer=reply("home:$udom:$uname",$tryserver);
1511: if ($answer eq 'found') {
1512: delete($badServerCache{$tryserver});
1513: return $homecache{$index}=$tryserver;
1514: } elsif ($answer eq 'no_host') {
1515: $badServerCache{$tryserver}=1;
1516: }
1.1 albertel 1517: }
1518: return 'no_host';
1.70 www 1519: }
1520:
1521: # ------------------------------------- Find the usernames behind a list of IDs
1522:
1523: sub idget {
1524: my ($udom,@ids)=@_;
1525: my %returnhash=();
1526:
1.841 albertel 1527: my %servers = &get_servers($udom,'library');
1528: foreach my $tryserver (keys(%servers)) {
1529: my $idlist=join('&',@ids);
1530: $idlist=~tr/A-Z/a-z/;
1531: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1532: my @answer=();
1533: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1534: @answer=split(/\&/,$reply);
1535: } ;
1536: my $i;
1537: for ($i=0;$i<=$#ids;$i++) {
1538: if ($answer[$i]) {
1539: $returnhash{$ids[$i]}=$answer[$i];
1540: }
1541: }
1542: }
1.70 www 1543: return %returnhash;
1544: }
1545:
1546: # ------------------------------------- Find the IDs behind a list of usernames
1547:
1548: sub idrget {
1549: my ($udom,@unames)=@_;
1550: my %returnhash=();
1.800 albertel 1551: foreach my $uname (@unames) {
1552: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1553: }
1.70 www 1554: return %returnhash;
1555: }
1556:
1557: # ------------------------------- Store away a list of names and associated IDs
1558:
1559: sub idput {
1560: my ($udom,%ids)=@_;
1561: my %servers=();
1.800 albertel 1562: foreach my $uname (keys(%ids)) {
1563: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1564: my $uhom=&homeserver($uname,$udom);
1.70 www 1565: if ($uhom ne 'no_host') {
1.800 albertel 1566: my $id=&escape($ids{$uname});
1.70 www 1567: $id=~tr/A-Z/a-z/;
1.800 albertel 1568: my $esc_unam=&escape($uname);
1.70 www 1569: if ($servers{$uhom}) {
1.800 albertel 1570: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1571: } else {
1.800 albertel 1572: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1573: }
1574: }
1.191 harris41 1575: }
1.800 albertel 1576: foreach my $server (keys(%servers)) {
1577: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1578: }
1.344 www 1579: }
1580:
1.1023 raeburn 1581: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1582: sub dump_dom {
1.1165 droeschl 1583: my ($namespace, $udom, $regexp) = @_;
1584:
1585: $udom ||= $env{'user.domain'};
1586:
1587: return () unless $udom;
1588:
1589: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1590: }
1591:
1.1023 raeburn 1592: # ------------------------------------------ get items from domain db files
1.806 raeburn 1593:
1594: sub get_dom {
1.860 raeburn 1595: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1596: my $items='';
1597: foreach my $item (@$storearr) {
1598: $items.=&escape($item).'&';
1599: }
1600: $items=~s/\&$//;
1.860 raeburn 1601: if (!$udom) {
1602: $udom=$env{'user.domain'};
1603: if (defined(&domain($udom,'primary'))) {
1604: $uhome=&domain($udom,'primary');
1605: } else {
1.874 albertel 1606: undef($uhome);
1.860 raeburn 1607: }
1608: } else {
1609: if (!$uhome) {
1610: if (defined(&domain($udom,'primary'))) {
1611: $uhome=&domain($udom,'primary');
1612: }
1613: }
1614: }
1615: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1616: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1617: my %returnhash;
1.875 albertel 1618: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1619: return %returnhash;
1620: }
1.806 raeburn 1621: my @pairs=split(/\&/,$rep);
1622: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1623: return @pairs;
1624: }
1625: my $i=0;
1626: foreach my $item (@$storearr) {
1627: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1628: $i++;
1629: }
1630: return %returnhash;
1631: } else {
1.880 banghart 1632: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1633: }
1634: }
1635:
1636: # -------------------------------------------- put items in domain db files
1637:
1638: sub put_dom {
1.860 raeburn 1639: my ($namespace,$storehash,$udom,$uhome)=@_;
1640: if (!$udom) {
1641: $udom=$env{'user.domain'};
1642: if (defined(&domain($udom,'primary'))) {
1643: $uhome=&domain($udom,'primary');
1644: } else {
1.874 albertel 1645: undef($uhome);
1.860 raeburn 1646: }
1647: } else {
1648: if (!$uhome) {
1649: if (defined(&domain($udom,'primary'))) {
1650: $uhome=&domain($udom,'primary');
1651: }
1652: }
1653: }
1654: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1655: my $items='';
1656: foreach my $item (keys(%$storehash)) {
1657: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1658: }
1659: $items=~s/\&$//;
1660: return &reply("putdom:$udom:$namespace:$items",$uhome);
1661: } else {
1.860 raeburn 1662: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1663: }
1664: }
1665:
1.1023 raeburn 1666: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1667: sub newput_dom {
1.1023 raeburn 1668: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1669: my $result;
1670: if (!$udom) {
1671: $udom=$env{'user.domain'};
1672: }
1.1023 raeburn 1673: if ($udom) {
1674: my $uname = &get_domainconfiguser($udom);
1675: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1676: }
1677: return $result;
1678: }
1679:
1.1023 raeburn 1680: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1681: sub del_dom {
1.1023 raeburn 1682: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1683: if (ref($storearr) eq 'ARRAY') {
1684: if (!$udom) {
1685: $udom=$env{'user.domain'};
1686: }
1.1023 raeburn 1687: if ($udom) {
1688: my $uname = &get_domainconfiguser($udom);
1689: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1690: }
1691: }
1692: }
1693:
1.1023 raeburn 1694: # ----------------------------------construct domainconfig user for a domain
1695: sub get_domainconfiguser {
1696: my ($udom) = @_;
1697: return $udom.'-domainconfig';
1698: }
1699:
1.837 raeburn 1700: sub retrieve_inst_usertypes {
1701: my ($udom) = @_;
1702: my (%returnhash,@order);
1.989 raeburn 1703: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1704: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1705: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1706: %returnhash = %{$domdefs{'inststatustypes'}};
1707: @order = @{$domdefs{'inststatusorder'}};
1708: } else {
1709: if (defined(&domain($udom,'primary'))) {
1710: my $uhome=&domain($udom,'primary');
1711: my $rep=&reply("inst_usertypes:$udom",$uhome);
1712: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1713: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1714: return (\%returnhash,\@order);
1715: }
1716: my ($hashitems,$orderitems) = split(/:/,$rep);
1717: my @pairs=split(/\&/,$hashitems);
1718: foreach my $item (@pairs) {
1719: my ($key,$value)=split(/=/,$item,2);
1720: $key = &unescape($key);
1721: next if ($key =~ /^error: 2 /);
1722: $returnhash{$key}=&thaw_unescape($value);
1723: }
1724: my @esc_order = split(/\&/,$orderitems);
1725: foreach my $item (@esc_order) {
1726: push(@order,&unescape($item));
1727: }
1728: } else {
1729: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1730: }
1731: }
1732: return (\%returnhash,\@order);
1733: }
1734:
1.868 raeburn 1735: sub is_domainimage {
1736: my ($url) = @_;
1737: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1738: if (&domain($1) ne '') {
1739: return '1';
1740: }
1741: }
1742: return;
1743: }
1744:
1.899 raeburn 1745: sub inst_directory_query {
1746: my ($srch) = @_;
1747: my $udom = $srch->{'srchdomain'};
1748: my %results;
1749: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1750: my $outcome;
1.899 raeburn 1751: if ($homeserver ne '') {
1.904 albertel 1752: my $queryid=&reply("querysend:instdirsearch:".
1753: &escape($srch->{'srchby'}).':'.
1754: &escape($srch->{'srchterm'}).':'.
1755: &escape($srch->{'srchtype'}),$homeserver);
1756: my $host=&hostname($homeserver);
1757: if ($queryid !~/^\Q$host\E\_/) {
1758: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1759: return;
1760: }
1761: my $response = &get_query_reply($queryid);
1762: my $maxtries = 5;
1763: my $tries = 1;
1764: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1765: $response = &get_query_reply($queryid);
1766: $tries ++;
1767: }
1768:
1769: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1770: if ($response eq 'unavailable') {
1771: $outcome = $response;
1772: } else {
1773: $outcome = 'ok';
1774: my @matches = split(/\n/,$response);
1775: foreach my $match (@matches) {
1776: my ($key,$value) = split(/=/,$match);
1777: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1778: }
1.899 raeburn 1779: }
1780: }
1781: }
1.909 raeburn 1782: return ($outcome,%results);
1.899 raeburn 1783: }
1784:
1785: sub usersearch {
1786: my ($srch) = @_;
1787: my $dom = $srch->{'srchdomain'};
1788: my %results;
1789: my %libserv = &all_library();
1790: my $query = 'usersearch';
1791: foreach my $tryserver (keys(%libserv)) {
1792: if (&host_domain($tryserver) eq $dom) {
1793: my $host=&hostname($tryserver);
1794: my $queryid=
1.911 raeburn 1795: &reply("querysend:".&escape($query).':'.
1796: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1797: &escape($srch->{'srchtype'}).':'.
1798: &escape($srch->{'srchterm'}),$tryserver);
1799: if ($queryid !~/^\Q$host\E\_/) {
1800: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1801: next;
1.899 raeburn 1802: }
1803: my $reply = &get_query_reply($queryid);
1804: my $maxtries = 1;
1805: my $tries = 1;
1806: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1807: $reply = &get_query_reply($queryid);
1808: $tries ++;
1809: }
1810: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1811: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1812: } else {
1.911 raeburn 1813: my @matches;
1814: if ($reply =~ /\n/) {
1815: @matches = split(/\n/,$reply);
1816: } else {
1817: @matches = split(/\&/,$reply);
1818: }
1.899 raeburn 1819: foreach my $match (@matches) {
1820: my ($uname,$udom,%userhash);
1.911 raeburn 1821: foreach my $entry (split(/:/,$match)) {
1822: my ($key,$value) =
1823: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1824: $userhash{$key} = $value;
1825: if ($key eq 'username') {
1826: $uname = $value;
1827: } elsif ($key eq 'domain') {
1828: $udom = $value;
1.911 raeburn 1829: }
1.899 raeburn 1830: }
1831: $results{$uname.':'.$udom} = \%userhash;
1832: }
1833: }
1834: }
1835: }
1836: return %results;
1837: }
1838:
1.912 raeburn 1839: sub get_instuser {
1840: my ($udom,$uname,$id) = @_;
1841: my $homeserver = &domain($udom,'primary');
1842: my ($outcome,%results);
1843: if ($homeserver ne '') {
1844: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1845: &escape($id).':'.&escape($udom),$homeserver);
1846: my $host=&hostname($homeserver);
1847: if ($queryid !~/^\Q$host\E\_/) {
1848: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1849: return;
1850: }
1851: my $response = &get_query_reply($queryid);
1852: my $maxtries = 5;
1853: my $tries = 1;
1854: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1855: $response = &get_query_reply($queryid);
1856: $tries ++;
1857: }
1858: if (!&error($response) && $response ne 'refused') {
1859: if ($response eq 'unavailable') {
1860: $outcome = $response;
1861: } else {
1862: $outcome = 'ok';
1863: my @matches = split(/\n/,$response);
1864: foreach my $match (@matches) {
1865: my ($key,$value) = split(/=/,$match);
1866: $results{&unescape($key)} = &thaw_unescape($value);
1867: }
1868: }
1869: }
1870: }
1871: my %userinfo;
1872: if (ref($results{$uname}) eq 'HASH') {
1873: %userinfo = %{$results{$uname}};
1874: }
1875: return ($outcome,%userinfo);
1876: }
1877:
1878: sub inst_rulecheck {
1.923 raeburn 1879: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1880: my %returnhash;
1881: if ($udom ne '') {
1882: if (ref($rules) eq 'ARRAY') {
1883: @{$rules} = map {&escape($_);} (@{$rules});
1884: my $rulestr = join(':',@{$rules});
1885: my $homeserver=&domain($udom,'primary');
1886: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1887: my $response;
1888: if ($item eq 'username') {
1889: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1890: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1891: $homeserver));
1.923 raeburn 1892: } elsif ($item eq 'id') {
1893: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1894: ':'.&escape($id).':'.$rulestr,
1895: $homeserver));
1.945 raeburn 1896: } elsif ($item eq 'selfcreate') {
1897: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1898: &escape($udom).':'.&escape($uname).
1899: ':'.$rulestr,$homeserver));
1.923 raeburn 1900: }
1.912 raeburn 1901: if ($response ne 'refused') {
1902: my @pairs=split(/\&/,$response);
1903: foreach my $item (@pairs) {
1904: my ($key,$value)=split(/=/,$item,2);
1905: $key = &unescape($key);
1906: next if ($key =~ /^error: 2 /);
1907: $returnhash{$key}=&thaw_unescape($value);
1908: }
1909: }
1910: }
1911: }
1912: }
1913: return %returnhash;
1914: }
1915:
1916: sub inst_userrules {
1.923 raeburn 1917: my ($udom,$check) = @_;
1.912 raeburn 1918: my (%ruleshash,@ruleorder);
1919: if ($udom ne '') {
1920: my $homeserver=&domain($udom,'primary');
1921: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1922: my $response;
1923: if ($check eq 'id') {
1924: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1925: $homeserver);
1.943 raeburn 1926: } elsif ($check eq 'email') {
1927: $response=&reply('instemailrules:'.&escape($udom),
1928: $homeserver);
1.923 raeburn 1929: } else {
1930: $response=&reply('instuserrules:'.&escape($udom),
1931: $homeserver);
1932: }
1.912 raeburn 1933: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1934: ($response ne 'unknown_cmd') &&
1.912 raeburn 1935: ($response ne 'no_such_host')) {
1936: my ($hashitems,$orderitems) = split(/:/,$response);
1937: my @pairs=split(/\&/,$hashitems);
1938: foreach my $item (@pairs) {
1939: my ($key,$value)=split(/=/,$item,2);
1940: $key = &unescape($key);
1941: next if ($key =~ /^error: 2 /);
1942: $ruleshash{$key}=&thaw_unescape($value);
1943: }
1944: my @esc_order = split(/\&/,$orderitems);
1945: foreach my $item (@esc_order) {
1946: push(@ruleorder,&unescape($item));
1947: }
1948: }
1949: }
1950: }
1951: return (\%ruleshash,\@ruleorder);
1952: }
1953:
1.976 raeburn 1954: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1955:
1956: sub get_domain_defaults {
1957: my ($domain) = @_;
1958: my $cachetime = 60*60*24;
1959: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1960: if (defined($cached)) {
1961: if (ref($result) eq 'HASH') {
1962: return %{$result};
1963: }
1964: }
1965: my %domdefaults;
1966: my %domconfig =
1.989 raeburn 1967: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1968: 'requestcourses','inststatus',
1.1183 raeburn 1969: 'coursedefaults','usersessions',
1970: 'requestauthor'],$domain);
1.943 raeburn 1971: if (ref($domconfig{'defaults'}) eq 'HASH') {
1972: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1973: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1974: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1975: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1976: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1977: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1978: } else {
1979: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1980: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1981: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1982: }
1.976 raeburn 1983: if (ref($domconfig{'quotas'}) eq 'HASH') {
1984: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1985: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1986: } else {
1987: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 1988: }
1.1177 raeburn 1989: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 1990: foreach my $item (@usertools) {
1991: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1992: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1993: }
1994: }
1.1229 raeburn 1995: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
1996: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
1997: }
1.976 raeburn 1998: }
1.985 raeburn 1999: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 2000: foreach my $item ('official','unofficial','community') {
1.985 raeburn 2001: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2002: }
2003: }
1.1183 raeburn 2004: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2005: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2006: }
1.989 raeburn 2007: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2008: foreach my $item ('inststatustypes','inststatusorder') {
2009: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2010: }
2011: }
1.1047 raeburn 2012: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 ! raeburn 2013: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1216 raeburn 2014: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2015: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2016: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
2017: }
1.1230 ! raeburn 2018: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
! 2019: $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
! 2020: $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
! 2021: $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
! 2022: }
1.1047 raeburn 2023: }
1.1073 raeburn 2024: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2025: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2026: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2027: }
2028: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2029: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2030: }
2031: }
1.1219 raeburn 2032: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2033: return %domdefaults;
2034: }
2035:
1.344 www 2036: # --------------------------------------------------- Assign a key to a student
2037:
2038: sub assign_access_key {
1.364 www 2039: #
2040: # a valid key looks like uname:udom#comments
2041: # comments are being appended
2042: #
1.498 www 2043: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2044: $kdom=
1.620 albertel 2045: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2046: $knum=
1.620 albertel 2047: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2048: $cdom=
1.620 albertel 2049: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2050: $cnum=
1.620 albertel 2051: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2052: $udom=$env{'user.name'} unless (defined($udom));
2053: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2054: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2055: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2056: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2057: # assigned to this person
2058: # - this should not happen,
1.345 www 2059: # unless something went wrong
2060: # the first time around
2061: # ready to assign
1.364 www 2062: $logentry=$1.'; '.$logentry;
1.496 www 2063: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2064: $kdom,$knum) eq 'ok') {
1.345 www 2065: # key now belongs to user
1.346 www 2066: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2067: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2068: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2069: return 'ok';
2070: } else {
2071: return
2072: 'error: Count not permanently assign key, will need to be re-entered later.';
2073: }
2074: } else {
2075: return 'error: Could not assign key, try again later.';
2076: }
1.364 www 2077: } elsif (!$existing{$ckey}) {
1.345 www 2078: # the key does not exist
2079: return 'error: The key does not exist';
2080: } else {
2081: # the key is somebody else's
2082: return 'error: The key is already in use';
2083: }
1.344 www 2084: }
2085:
1.364 www 2086: # ------------------------------------------ put an additional comment on a key
2087:
2088: sub comment_access_key {
2089: #
2090: # a valid key looks like uname:udom#comments
2091: # comments are being appended
2092: #
2093: my ($ckey,$cdom,$cnum,$logentry)=@_;
2094: $cdom=
1.620 albertel 2095: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2096: $cnum=
1.620 albertel 2097: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2098: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2099: if ($existing{$ckey}) {
2100: $existing{$ckey}.='; '.$logentry;
2101: # ready to assign
1.367 www 2102: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2103: $cdom,$cnum) eq 'ok') {
2104: return 'ok';
2105: } else {
2106: return 'error: Count not store comment.';
2107: }
2108: } else {
2109: # the key does not exist
2110: return 'error: The key does not exist';
2111: }
2112: }
2113:
1.344 www 2114: # ------------------------------------------------------ Generate a set of keys
2115:
2116: sub generate_access_keys {
1.364 www 2117: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2118: $cdom=
1.620 albertel 2119: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2120: $cnum=
1.620 albertel 2121: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2122: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2123: unless (($cdom) && ($cnum)) { return 0; }
2124: if ($number>10000) { return 0; }
2125: sleep(2); # make sure don't get same seed twice
2126: srand(time()^($$+($$<<15))); # from "Programming Perl"
2127: my $total=0;
2128: for (my $i=1;$i<=$number;$i++) {
2129: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2130: sprintf("%lx",int(100000*rand)).'-'.
2131: sprintf("%lx",int(100000*rand));
2132: $newkey=~s/1/g/g; # folks mix up 1 and l
2133: $newkey=~s/0/h/g; # and also 0 and O
2134: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2135: if ($existing{$newkey}) {
2136: $i--;
2137: } else {
1.364 www 2138: if (&put('accesskeys',
2139: { $newkey => '# generated '.localtime().
1.620 albertel 2140: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2141: '; '.$logentry },
2142: $cdom,$cnum) eq 'ok') {
1.344 www 2143: $total++;
2144: }
2145: }
2146: }
1.620 albertel 2147: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2148: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2149: return $total;
2150: }
2151:
2152: # ------------------------------------------------------- Validate an accesskey
2153:
2154: sub validate_access_key {
2155: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2156: $cdom=
1.620 albertel 2157: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2158: $cnum=
1.620 albertel 2159: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2160: $udom=$env{'user.domain'} unless (defined($udom));
2161: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2162: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2163: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2164: }
2165:
2166: # ------------------------------------- Find the section of student in a course
1.652 albertel 2167: sub devalidate_getsection_cache {
2168: my ($udom,$unam,$courseid)=@_;
2169: my $hashid="$udom:$unam:$courseid";
2170: &devalidate_cache_new('getsection',$hashid);
2171: }
1.298 matthew 2172:
1.815 albertel 2173: sub courseid_to_courseurl {
2174: my ($courseid) = @_;
2175: #already url style courseid
2176: return $courseid if ($courseid =~ m{^/});
2177:
2178: if (exists($env{'course.'.$courseid.'.num'})) {
2179: my $cnum = $env{'course.'.$courseid.'.num'};
2180: my $cdom = $env{'course.'.$courseid.'.domain'};
2181: return "/$cdom/$cnum";
2182: }
2183:
2184: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2185: if (exists($courseinfo{'num'})) {
2186: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2187: }
2188:
2189: return undef;
2190: }
2191:
1.298 matthew 2192: sub getsection {
2193: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2194: my $cachetime=1800;
1.551 albertel 2195:
2196: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2197: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2198: if (defined($cached)) { return $result; }
2199:
1.298 matthew 2200: my %Pending;
2201: my %Expired;
2202: #
2203: # Each role can either have not started yet (pending), be active,
2204: # or have expired.
2205: #
2206: # If there is an active role, we are done.
2207: #
2208: # If there is more than one role which has not started yet,
2209: # choose the one which will start sooner
2210: # If there is one role which has not started yet, return it.
2211: #
2212: # If there is more than one expired role, choose the one which ended last.
2213: # If there is a role which has expired, return it.
2214: #
1.815 albertel 2215: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2216: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2217: foreach my $key (keys(%roleshash)) {
1.479 albertel 2218: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2219: my $section=$1;
2220: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2221: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2222: my $now=time;
1.548 albertel 2223: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2224: $Expired{$end}=$section;
2225: next;
2226: }
1.548 albertel 2227: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2228: $Pending{$start}=$section;
2229: next;
2230: }
1.599 albertel 2231: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2232: }
2233: #
2234: # Presumedly there will be few matching roles from the above
2235: # loop and the sorting time will be negligible.
2236: if (scalar(keys(%Pending))) {
2237: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2238: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2239: }
2240: if (scalar(keys(%Expired))) {
2241: my @sorted = sort {$a <=> $b} keys(%Expired);
2242: my $time = pop(@sorted);
1.599 albertel 2243: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2244: }
1.599 albertel 2245: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2246: }
1.70 www 2247:
1.599 albertel 2248: sub save_cache {
2249: &purge_remembered();
1.722 albertel 2250: #&Apache::loncommon::validate_page();
1.620 albertel 2251: undef(%env);
1.780 albertel 2252: undef($env_loaded);
1.599 albertel 2253: }
1.452 albertel 2254:
1.599 albertel 2255: my $to_remember=-1;
2256: my %remembered;
2257: my %accessed;
2258: my $kicks=0;
2259: my $hits=0;
1.849 albertel 2260: sub make_key {
2261: my ($name,$id) = @_;
1.872 albertel 2262: if (length($id) > 65
2263: && length(&escape($id)) > 200) {
2264: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2265: }
1.849 albertel 2266: return &escape($name.':'.$id);
2267: }
2268:
1.599 albertel 2269: sub devalidate_cache_new {
2270: my ($name,$id,$debug) = @_;
2271: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2272: $id=&make_key($name,$id);
1.599 albertel 2273: $memcache->delete($id);
2274: delete($remembered{$id});
2275: delete($accessed{$id});
2276: }
2277:
2278: sub is_cached_new {
2279: my ($name,$id,$debug) = @_;
1.849 albertel 2280: $id=&make_key($name,$id);
1.599 albertel 2281: if (exists($remembered{$id})) {
1.1133 foxr 2282: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2283: $accessed{$id}=[&gettimeofday()];
2284: $hits++;
2285: return ($remembered{$id},1);
2286: }
2287: my $value = $memcache->get($id);
2288: if (!(defined($value))) {
2289: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2290: return (undef,undef);
1.416 albertel 2291: }
1.599 albertel 2292: if ($value eq '__undef__') {
2293: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2294: $value=undef;
2295: }
2296: &make_room($id,$value,$debug);
2297: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2298: return ($value,1);
2299: }
2300:
2301: sub do_cache_new {
2302: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2303: $id=&make_key($name,$id);
1.599 albertel 2304: my $setvalue=$value;
2305: if (!defined($setvalue)) {
2306: $setvalue='__undef__';
2307: }
1.623 albertel 2308: if (!defined($time) ) {
2309: $time=600;
2310: }
1.599 albertel 2311: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2312: my $result = $memcache->set($id,$setvalue,$time);
2313: if (! $result) {
1.872 albertel 2314: &logthis("caching of id -> $id failed");
1.910 albertel 2315: $memcache->disconnect_all();
1.872 albertel 2316: }
1.600 albertel 2317: # need to make a copy of $value
1.919 albertel 2318: &make_room($id,$value,$debug);
1.599 albertel 2319: return $value;
2320: }
2321:
2322: sub make_room {
2323: my ($id,$value,$debug)=@_;
1.919 albertel 2324:
2325: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2326: : $value;
1.599 albertel 2327: if ($to_remember<0) { return; }
2328: $accessed{$id}=[&gettimeofday()];
2329: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2330: my $to_kick;
2331: my $max_time=0;
2332: foreach my $other (keys(%accessed)) {
2333: if (&tv_interval($accessed{$other}) > $max_time) {
2334: $to_kick=$other;
2335: $max_time=&tv_interval($accessed{$other});
2336: }
2337: }
2338: delete($remembered{$to_kick});
2339: delete($accessed{$to_kick});
2340: $kicks++;
2341: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2342: return;
2343: }
2344:
1.599 albertel 2345: sub purge_remembered {
1.604 albertel 2346: #&logthis("Tossing ".scalar(keys(%remembered)));
2347: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2348: undef(%remembered);
2349: undef(%accessed);
1.428 albertel 2350: }
1.70 www 2351: # ------------------------------------- Read an entry from a user's environment
2352:
2353: sub userenvironment {
2354: my ($udom,$unam,@what)=@_;
1.976 raeburn 2355: my $items;
2356: foreach my $item (@what) {
2357: $items.=&escape($item).'&';
2358: }
2359: $items=~s/\&$//;
1.70 www 2360: my %returnhash=();
1.1009 raeburn 2361: my $uhome = &homeserver($unam,$udom);
2362: unless ($uhome eq 'no_host') {
2363: my @answer=split(/\&/,
2364: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2365: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2366: return %returnhash;
2367: }
1.1009 raeburn 2368: my $i;
2369: for ($i=0;$i<=$#what;$i++) {
2370: $returnhash{$what[$i]}=&unescape($answer[$i]);
2371: }
1.70 www 2372: }
2373: return %returnhash;
1.1 albertel 2374: }
2375:
1.617 albertel 2376: # ---------------------------------------------------------- Get a studentphoto
2377: sub studentphoto {
2378: my ($udom,$unam,$ext) = @_;
2379: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2380: if (defined($env{'request.course.id'})) {
1.708 raeburn 2381: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2382: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2383: return(&retrievestudentphoto($udom,$unam,$ext));
2384: } else {
2385: my ($result,$perm_reqd)=
1.707 albertel 2386: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2387: if ($result eq 'ok') {
2388: if (!($perm_reqd eq 'yes')) {
2389: return(&retrievestudentphoto($udom,$unam,$ext));
2390: }
2391: }
2392: }
2393: }
2394: } else {
2395: my ($result,$perm_reqd) =
1.707 albertel 2396: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2397: if ($result eq 'ok') {
2398: if (!($perm_reqd eq 'yes')) {
2399: return(&retrievestudentphoto($udom,$unam,$ext));
2400: }
2401: }
2402: }
2403: return '/adm/lonKaputt/lonlogo_broken.gif';
2404: }
2405:
2406: sub retrievestudentphoto {
2407: my ($udom,$unam,$ext,$type) = @_;
2408: my $home=&Apache::lonnet::homeserver($unam,$udom);
2409: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2410: if ($ret eq 'ok') {
2411: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2412: if ($type eq 'thumbnail') {
2413: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2414: }
2415: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2416: return $tokenurl;
2417: } else {
2418: if ($type eq 'thumbnail') {
2419: return '/adm/lonKaputt/genericstudent_tn.gif';
2420: } else {
2421: return '/adm/lonKaputt/lonlogo_broken.gif';
2422: }
1.617 albertel 2423: }
2424: }
2425:
1.263 www 2426: # -------------------------------------------------------------------- New chat
2427:
2428: sub chatsend {
1.724 raeburn 2429: my ($newentry,$anon,$group)=@_;
1.620 albertel 2430: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2431: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2432: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2433: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2434: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2435: &escape($newentry)).':'.$group,$chome);
1.292 www 2436: }
2437:
2438: # ------------------------------------------ Find current version of a resource
2439:
2440: sub getversion {
2441: my $fname=&clutter(shift);
1.1189 raeburn 2442: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2443: return ¤tversion(&filelocation('',$fname));
2444: }
2445:
2446: sub currentversion {
2447: my $fname=shift;
2448: my $author=$fname;
2449: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2450: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2451: my $home=&homeserver($uname,$udom);
1.292 www 2452: if ($home eq 'no_host') {
2453: return -1;
2454: }
1.1112 www 2455: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2456: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2457: return -1;
2458: }
1.1112 www 2459: return $answer;
1.263 www 2460: }
2461:
1.1111 www 2462: #
2463: # Return special version number of resource if set by override, empty otherwise
2464: #
2465: sub usedversion {
2466: my $fname=shift;
2467: unless ($fname) { $fname=$env{'request.uri'}; }
2468: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2469: if ($urlversion) { return $urlversion; }
2470: return '';
2471: }
2472:
1.1 albertel 2473: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2474:
1.1 albertel 2475: sub subscribe {
2476: my $fname=shift;
1.761 raeburn 2477: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2478: $fname=~s/[\n\r]//g;
1.1 albertel 2479: my $author=$fname;
2480: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2481: my ($udom,$uname)=split(/\//,$author);
2482: my $home=homeserver($uname,$udom);
1.335 albertel 2483: if ($home eq 'no_host') {
2484: return 'not_found';
1.1 albertel 2485: }
2486: my $answer=reply("sub:$fname",$home);
1.64 www 2487: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2488: $answer.=' by '.$home;
2489: }
1.1 albertel 2490: return $answer;
2491: }
2492:
1.8 www 2493: # -------------------------------------------------------------- Replicate file
2494:
2495: sub repcopy {
2496: my $filename=shift;
1.23 www 2497: $filename=~s/\/+/\//g;
1.1142 raeburn 2498: my $londocroot = $perlvar{'lonDocRoot'};
2499: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2500: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2501: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2502: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2503: return &repcopy_userfile($filename);
2504: }
1.532 albertel 2505: $filename=~s/[\n\r]//g;
1.8 www 2506: my $transname="$filename.in.transfer";
1.828 www 2507: # FIXME: this should flock
1.607 raeburn 2508: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2509: my $remoteurl=subscribe($filename);
1.64 www 2510: if ($remoteurl =~ /^con_lost by/) {
2511: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2512: return 'unavailable';
1.8 www 2513: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2514: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2515: return 'not_found';
1.64 www 2516: } elsif ($remoteurl =~ /^rejected by/) {
2517: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2518: return 'forbidden';
1.20 www 2519: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2520: return 'ok';
1.8 www 2521: } else {
1.290 www 2522: my $author=$filename;
2523: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2524: my ($udom,$uname)=split(/\//,$author);
2525: my $home=homeserver($uname,$udom);
2526: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2527: my @parts=split(/\//,$filename);
2528: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2529: if ($path ne "$londocroot/res") {
1.8 www 2530: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2531: return 'bad_request';
1.8 www 2532: }
2533: my $count;
2534: for ($count=5;$count<$#parts;$count++) {
2535: $path.="/$parts[$count]";
2536: if ((-e $path)!=1) {
2537: mkdir($path,0777);
2538: }
2539: }
2540: my $ua=new LWP::UserAgent;
2541: my $request=new HTTP::Request('GET',"$remoteurl");
2542: my $response=$ua->request($request,$transname);
2543: if ($response->is_error()) {
2544: unlink($transname);
2545: my $message=$response->status_line;
1.672 albertel 2546: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2547: ." LWP get: $message: $filename</font>");
1.607 raeburn 2548: return 'unavailable';
1.8 www 2549: } else {
1.16 www 2550: if ($remoteurl!~/\.meta$/) {
2551: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2552: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2553: if ($mresponse->is_error()) {
2554: unlink($filename.'.meta');
2555: &logthis(
1.672 albertel 2556: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2557: }
2558: }
1.8 www 2559: rename($transname,$filename);
1.607 raeburn 2560: return 'ok';
1.8 www 2561: }
1.290 www 2562: }
1.8 www 2563: }
1.330 www 2564: }
2565:
2566: # ------------------------------------------------ Get server side include body
2567: sub ssi_body {
1.381 albertel 2568: my ($filelink,%form)=@_;
1.606 matthew 2569: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2570: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2571: }
1.953 www 2572: my $output='';
2573: my $response;
1.980 raeburn 2574: if ($filelink=~/^https?\:/) {
1.954 raeburn 2575: ($output,$response)=&externalssi($filelink);
1.953 www 2576: } else {
1.1004 droeschl 2577: $filelink .= $filelink=~/\?/ ? '&' : '?';
2578: $filelink .= 'inhibitmenu=yes';
1.953 www 2579: ($output,$response)=&ssi($filelink,%form);
2580: }
1.778 albertel 2581: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2582: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2583: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2584: if (wantarray) {
2585: return ($output, $response);
2586: } else {
2587: return $output;
2588: }
1.8 www 2589: }
2590:
1.15 www 2591: # --------------------------------------------------------- Server Side Include
2592:
1.782 albertel 2593: sub absolute_url {
2594: my ($host_name) = @_;
2595: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2596: if ($host_name eq '') {
2597: $host_name = $ENV{'SERVER_NAME'};
2598: }
2599: return $protocol.$host_name;
2600: }
2601:
1.942 foxr 2602: #
2603: # Server side include.
2604: # Parameters:
2605: # fn Possibly encrypted resource name/id.
2606: # form Hash that describes how the rendering should be done
2607: # and other things.
1.944 foxr 2608: # Returns:
1.950 raeburn 2609: # Scalar context: The content of the response.
2610: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2611: #
1.15 www 2612: sub ssi {
2613:
1.944 foxr 2614: my ($fn,%form)=@_;
1.15 www 2615: my $ua=new LWP::UserAgent;
1.23 www 2616: my $request;
1.711 albertel 2617:
2618: $form{'no_update_last_known'}=1;
1.895 albertel 2619: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2620: if (%form) {
1.782 albertel 2621: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2622: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2623: } else {
1.782 albertel 2624: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2625: }
2626:
1.15 www 2627: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2628: my $response= $ua->request($request);
1.1182 foxr 2629: my $content = $response->content;
2630:
2631:
1.944 foxr 2632: if (wantarray) {
1.1173 foxr 2633: return ($content, $response);
1.944 foxr 2634: } else {
1.1173 foxr 2635: return $content;
1.942 foxr 2636: }
1.324 www 2637: }
2638:
2639: sub externalssi {
2640: my ($url)=@_;
2641: my $ua=new LWP::UserAgent;
2642: my $request=new HTTP::Request('GET',$url);
2643: my $response=$ua->request($request);
1.954 raeburn 2644: if (wantarray) {
2645: return ($response->content, $response);
2646: } else {
2647: return $response->content;
2648: }
1.15 www 2649: }
1.254 www 2650:
1.492 albertel 2651: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2652:
2653: sub allowuploaded {
2654: my ($srcurl,$url)=@_;
2655: $url=&clutter(&declutter($url));
2656: my $dir=$url;
2657: $dir=~s/\/[^\/]+$//;
2658: my %httpref=();
2659: my $httpurl=&hreflocation('',$url);
2660: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2661: &Apache::lonnet::appenv(\%httpref);
1.254 www 2662: }
1.477 raeburn 2663:
1.1193 raeburn 2664: #
2665: # Determine if the current user should be able to edit a particular resource,
2666: # when viewing in course context.
2667: # (a) When viewing resource used to determine if "Edit" item is included in
2668: # Functions.
2669: # (b) When displaying folder contents in course editor, used to determine if
2670: # "Edit" link will be displayed alongside resource.
2671: #
1.1196 raeburn 2672: # input: six args -- filename (decluttered), course number, course domain,
2673: # url, symb (if registered) and group (if this is a group
2674: # item -- e.g., bulletin board, group page etc.).
2675: # output: array of five scalars --
1.1193 raeburn 2676: # $cfile -- url for file editing if editable on current server
2677: # $home -- homeserver of resource (i.e., for author if published,
2678: # or course if uploaded.).
2679: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2680: # $forceedit -- 1 if icon/link should be to go to edit mode
2681: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2682: #
2683:
2684: sub can_edit_resource {
1.1194 raeburn 2685: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2686: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2687: #
2688: # For aboutme pages user can only edit his/her own.
2689: #
1.1199 raeburn 2690: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2691: my ($sdom,$sname) = ($1,$2);
2692: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2693: $home = $env{'user.home'};
2694: $cfile = $resurl;
2695: if ($env{'form.forceedit'}) {
2696: $forceview = 1;
2697: } else {
2698: $forceedit = 1;
2699: }
2700: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2701: } else {
2702: return;
2703: }
2704: }
2705:
2706: if ($env{'request.course.id'}) {
2707: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2708: if ($group ne '') {
2709: # if this is a group homepage or group bulletin board, check group privs
2710: my $allowed = 0;
1.1197 raeburn 2711: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2712: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2713: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2714: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2715: $allowed = 1;
2716: }
1.1197 raeburn 2717: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2718: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2719: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2720: $allowed = 1;
2721: }
2722: }
2723: if ($allowed) {
2724: $home=&homeserver($cnum,$cdom);
2725: if ($env{'form.forceedit'}) {
2726: $forceview = 1;
2727: } else {
2728: $forceedit = 1;
2729: }
2730: $cfile = $resurl;
2731: } else {
2732: return;
2733: }
2734: } else {
1.1208 raeburn 2735: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2736: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2737: return;
2738: }
2739: } elsif (!$crsedit) {
1.1194 raeburn 2740: #
2741: # No edit allowed where CC has switched to student role.
2742: #
2743: return;
2744: }
2745: }
2746: }
2747:
1.1193 raeburn 2748: if ($file ne '') {
2749: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2750: if (&is_course_upload($file,$cnum,$cdom)) {
2751: $uploaded = 1;
2752: $incourse = 1;
1.1193 raeburn 2753: if ($file =~/\.(htm|html|css|js|txt)$/) {
2754: $cfile = &hreflocation('',$file);
1.1201 raeburn 2755: if ($env{'form.forceedit'}) {
2756: $forceview = 1;
2757: } else {
2758: $forceedit = 1;
2759: }
1.1194 raeburn 2760: }
2761: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2762: $incourse = 1;
2763: if ($env{'form.forceedit'}) {
2764: $forceview = 1;
2765: } else {
2766: $forceedit = 1;
2767: }
2768: $cfile = $resurl;
2769: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2770: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2771: $incourse = 1;
2772: if ($env{'form.forceedit'}) {
2773: $forceview = 1;
2774: } else {
2775: $forceedit = 1;
2776: }
2777: $cfile = $resurl;
1.1199 raeburn 2778: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2779: $incourse = 1;
2780: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2781: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2782: $incourse = 1;
1.1199 raeburn 2783: if ($env{'form.forceedit'}) {
2784: $forceview = 1;
2785: } else {
2786: $forceedit = 1;
2787: }
2788: $cfile = $resurl;
1.1208 raeburn 2789: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2790: $incourse = 1;
2791: if ($env{'form.forceedit'}) {
2792: $forceview = 1;
2793: } else {
2794: $forceedit = 1;
2795: }
2796: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2797: }
2798: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2799: my $template = '/res/lib/templates/simpleproblem.problem';
2800: if (&is_on_map($template)) {
2801: $incourse = 1;
2802: $forceview = 1;
2803: $cfile = $template;
1.1193 raeburn 2804: }
1.1199 raeburn 2805: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2806: $incourse = 1;
2807: if ($env{'form.forceedit'}) {
2808: $forceview = 1;
2809: } else {
2810: $forceedit = 1;
2811: }
2812: $cfile = $resurl;
2813: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2814: $incourse = 1;
2815: $forceview = 1;
2816: if ($symb) {
2817: my ($map,$id,$res)=&decode_symb($symb);
2818: $env{'request.symb'} = $symb;
2819: $cfile = &clutter($res);
2820: } else {
2821: $cfile = $env{'form.suppurl'};
2822: $cfile =~ s{^http://}{};
2823: $cfile = '/adm/wrapper/ext/'.$cfile;
2824: }
1.1193 raeburn 2825: }
2826: }
1.1194 raeburn 2827: if ($uploaded || $incourse) {
2828: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2829: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2830: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2831: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2832: # Check that the user has permission to edit this resource
2833: my $setpriv = 1;
2834: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2835: if (defined($cfudom)) {
2836: $home=&homeserver($cfuname,$cfudom);
2837: $cfile=$file;
2838: }
2839: }
1.1194 raeburn 2840: if (($cfile ne '') && (!$incourse || $uploaded) &&
2841: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2842: my @ids=¤t_machine_ids();
2843: unless (grep(/^\Q$home\E$/,@ids)) {
2844: $switchserver=1;
2845: }
2846: }
2847: }
1.1194 raeburn 2848: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2849: }
2850:
2851: sub is_course_upload {
2852: my ($file,$cnum,$cdom) = @_;
2853: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2854: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2855: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2856: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2857: return 1;
2858: }
2859: return;
2860: }
2861:
1.1194 raeburn 2862: sub in_course {
1.1195 raeburn 2863: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2864: if ($hideprivileged) {
2865: my $skipuser;
1.1219 raeburn 2866: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2867: my @possdoms = ($cdom);
2868: if ($coursehash{'checkforpriv'}) {
2869: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2870: }
2871: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 2872: $skipuser = 1;
2873: if ($coursehash{'nothideprivileged'}) {
2874: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2875: my $user;
2876: if ($item =~ /:/) {
2877: $user = $item;
2878: } else {
2879: $user = join(':',split(/[\@]/,$item));
2880: }
2881: if ($user eq $uname.':'.$udom) {
2882: undef($skipuser);
2883: last;
2884: }
2885: }
2886: }
2887: if ($skipuser) {
2888: return 0;
2889: }
2890: }
2891: }
1.1194 raeburn 2892: $type ||= 'any';
2893: if (!defined($cdom) || !defined($cnum)) {
2894: my $cid = $env{'request.course.id'};
2895: $cdom = $env{'course.'.$cid.'.domain'};
2896: $cnum = $env{'course.'.$cid.'.num'};
2897: }
2898: my $typesref;
1.1195 raeburn 2899: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 2900: $typesref = ['active','previous','future'];
2901: } elsif ($type eq 'previous' || $type eq 'future') {
2902: $typesref = [$type];
2903: }
2904: my %roles = &get_my_roles($uname,$udom,'userroles',
2905: $typesref,undef,[$cdom]);
2906: my ($tmp) = keys(%roles);
2907: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2908: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2909: if (@course_roles > 0) {
2910: return 1;
2911: }
2912: return 0;
2913: }
2914:
1.478 albertel 2915: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2916: # input: action, courseID, current domain, intended
1.637 raeburn 2917: # path to file, source of file, instruction to parse file for objects,
2918: # ref to hash for embedded objects,
2919: # ref to hash for codebase of java objects.
1.1095 raeburn 2920: # reference to scalar to accommodate mime type determined
2921: # from File::MMagic if $parser = parse.
1.637 raeburn 2922: #
1.485 raeburn 2923: # output: url to file (if action was uploaddoc),
2924: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2925: #
1.478 albertel 2926: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2927: # course.
1.477 raeburn 2928: #
1.478 albertel 2929: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2930: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2931: # course's home server.
1.477 raeburn 2932: #
1.478 albertel 2933: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2934: # be copied from $source (current location) to
2935: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2936: # and will then be copied to
2937: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2938: # course's home server.
1.485 raeburn 2939: #
1.481 raeburn 2940: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2941: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2942: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2943: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2944: # in course's home server.
1.637 raeburn 2945: #
1.477 raeburn 2946:
2947: sub process_coursefile {
1.1095 raeburn 2948: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2949: $mimetype)=@_;
1.477 raeburn 2950: my $fetchresult;
1.638 albertel 2951: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2952: if ($action eq 'propagate') {
1.638 albertel 2953: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2954: $home);
1.481 raeburn 2955: } else {
1.477 raeburn 2956: my $fpath = '';
2957: my $fname = $file;
1.478 albertel 2958: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2959: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2960: my $filepath = &build_filepath($fpath);
1.481 raeburn 2961: if ($action eq 'copy') {
2962: if ($source eq '') {
2963: $fetchresult = 'no source file';
2964: return $fetchresult;
2965: } else {
2966: my $destination = $filepath.'/'.$fname;
2967: rename($source,$destination);
2968: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2969: $home);
1.481 raeburn 2970: }
2971: } elsif ($action eq 'uploaddoc') {
2972: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2973: print $fh $env{'form.'.$source};
1.481 raeburn 2974: close($fh);
1.637 raeburn 2975: if ($parser eq 'parse') {
1.1024 raeburn 2976: my $mm = new File::MMagic;
1.1095 raeburn 2977: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2978: if ($type eq 'text/html') {
1.1024 raeburn 2979: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2980: unless ($parse_result eq 'ok') {
2981: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2982: }
1.637 raeburn 2983: }
1.1095 raeburn 2984: if (ref($mimetype)) {
2985: $$mimetype = $type;
2986: }
1.637 raeburn 2987: }
1.477 raeburn 2988: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2989: $home);
1.481 raeburn 2990: if ($fetchresult eq 'ok') {
2991: return '/uploaded/'.$fpath.'/'.$fname;
2992: } else {
2993: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2994: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2995: return '/adm/notfound.html';
2996: }
1.477 raeburn 2997: }
2998: }
1.485 raeburn 2999: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3000: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3001: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3002: }
3003: return $fetchresult;
3004: }
3005:
1.637 raeburn 3006: sub build_filepath {
3007: my ($fpath) = @_;
3008: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3009: unless ($fpath eq '') {
3010: my @parts=split('/',$fpath);
3011: foreach my $part (@parts) {
3012: $filepath.= '/'.$part;
3013: if ((-e $filepath)!=1) {
3014: mkdir($filepath,0777);
3015: }
3016: }
3017: }
3018: return $filepath;
3019: }
3020:
3021: sub store_edited_file {
1.638 albertel 3022: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3023: my $file = $primary_url;
3024: $file =~ s#^/uploaded/$docudom/$docuname/##;
3025: my $fpath = '';
3026: my $fname = $file;
3027: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3028: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3029: my $filepath = &build_filepath($fpath);
3030: open(my $fh,'>'.$filepath.'/'.$fname);
3031: print $fh $content;
3032: close($fh);
1.638 albertel 3033: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3034: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3035: $home);
1.637 raeburn 3036: if ($$fetchresult eq 'ok') {
3037: return '/uploaded/'.$fpath.'/'.$fname;
3038: } else {
1.638 albertel 3039: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3040: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3041: return '/adm/notfound.html';
3042: }
3043: }
3044:
1.531 albertel 3045: sub clean_filename {
1.831 albertel 3046: my ($fname,$args)=@_;
1.315 www 3047: # Replace Windows backslashes by forward slashes
1.257 www 3048: $fname=~s/\\/\//g;
1.831 albertel 3049: if (!$args->{'keep_path'}) {
3050: # Get rid of everything but the actual filename
3051: $fname=~s/^.*\/([^\/]+)$/$1/;
3052: }
1.315 www 3053: # Replace spaces by underscores
3054: $fname=~s/\s+/\_/g;
3055: # Replace all other weird characters by nothing
1.831 albertel 3056: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3057: # Replace all .\d. sequences with _\d. so they no longer look like version
3058: # numbers
3059: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3060: return $fname;
3061: }
1.1051 raeburn 3062: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3063: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3064: # image with the same aspect ratio as the original, but with dimensions which do
3065: # not exceed $resizewidth and $resizeheight.
3066:
1.984 neumanie 3067: sub resizeImage {
1.1051 raeburn 3068: my ($img_path,$resizewidth,$resizeheight) = @_;
3069: my $ima = Image::Magick->new;
3070: my $resized;
3071: if (-e $img_path) {
3072: $ima->Read($img_path);
3073: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3074: my $width = $ima->Get('width');
3075: my $height = $ima->Get('height');
3076: if ($width > $resizewidth) {
3077: my $factor = $width/$resizewidth;
3078: my $newheight = $height/$factor;
3079: $ima->Scale(width=>$resizewidth,height=>$newheight);
3080: $resized = 1;
3081: }
3082: }
3083: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3084: my $width = $ima->Get('width');
3085: my $height = $ima->Get('height');
3086: if ($height > $resizeheight) {
3087: my $factor = $height/$resizeheight;
3088: my $newwidth = $width/$factor;
3089: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3090: $resized = 1;
3091: }
3092: }
3093: if ($resized) {
3094: $ima->Write($img_path);
3095: }
3096: }
3097: return;
1.977 amueller 3098: }
3099:
1.608 albertel 3100: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3101: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3102: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3103: # $context - possible values: coursedoc, existingfile, overwrite,
3104: # canceloverwrite, or ''.
3105: # if 'coursedoc': upload to the current course
3106: # if 'existingfile': write file to tmp/overwrites directory
3107: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3108: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3109: # $subdir - directory in userfile to store the file into
1.858 raeburn 3110: # $parser - instruction to parse file for objects ($parser = parse)
3111: # $allfiles - reference to hash for embedded objects
3112: # $codebase - reference to hash for codebase of java objects
3113: # $desuname - username for permanent storage of uploaded file
3114: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3115: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3116: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3117: # $resizewidth - width (pixels) to which to resize uploaded image
3118: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3119: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3120: # from File::MMagic.
1.858 raeburn 3121: #
1.686 albertel 3122: # output: url of file in userspace, or error: <message>
3123: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3124:
1.531 albertel 3125: sub userfileupload {
1.1090 raeburn 3126: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3127: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3128: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3129: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3130: $fname=&clean_filename($fname);
1.1090 raeburn 3131: # See if there is anything left
1.257 www 3132: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3133: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3134: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3135: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3136: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3137: my $now = time;
1.1090 raeburn 3138: my $filepath;
1.1095 raeburn 3139: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3140: $filepath = 'tmp/helprequests/'.$now;
3141: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3142: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3143: '_'.$env{'user.domain'}.'/pending';
3144: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3145: my ($docuname,$docudom);
3146: if ($destudom) {
3147: $docudom = $destudom;
3148: } else {
3149: $docudom = $env{'user.domain'};
3150: }
3151: if ($destuname) {
3152: $docuname = $destuname;
3153: } else {
3154: $docuname = $env{'user.name'};
3155: }
3156: if (exists($env{'form.group'})) {
3157: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3158: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3159: }
3160: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3161: if ($context eq 'canceloverwrite') {
3162: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3163: if (-e $tempfile) {
3164: my @info = stat($tempfile);
3165: if ($info[9] eq $env{'form.timestamp'}) {
3166: unlink($tempfile);
3167: }
3168: }
3169: return;
1.523 raeburn 3170: }
3171: }
1.1090 raeburn 3172: # Create the directory if not present
1.741 raeburn 3173: my @parts=split(/\//,$filepath);
3174: my $fullpath = $perlvar{'lonDaemons'};
3175: for (my $i=0;$i<@parts;$i++) {
3176: $fullpath .= '/'.$parts[$i];
3177: if ((-e $fullpath)!=1) {
3178: mkdir($fullpath,0777);
3179: }
3180: }
3181: open(my $fh,'>'.$fullpath.'/'.$fname);
3182: print $fh $env{'form.'.$formname};
3183: close($fh);
1.1090 raeburn 3184: if ($context eq 'existingfile') {
3185: my @info = stat($fullpath.'/'.$fname);
3186: return ($fullpath.'/'.$fname,$info[9]);
3187: } else {
3188: return $fullpath.'/'.$fname;
3189: }
1.523 raeburn 3190: }
1.995 raeburn 3191: if ($subdir eq 'scantron') {
3192: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3193: } else {
1.995 raeburn 3194: $fname="$subdir/$fname";
3195: }
1.1090 raeburn 3196: if ($context eq 'coursedoc') {
1.638 albertel 3197: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3198: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3199: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3200: return &finishuserfileupload($docuname,$docudom,
3201: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3202: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3203: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3204: } else {
1.1218 raeburn 3205: if ($env{'form.folder'}) {
3206: $fname=$env{'form.folder'}.'/'.$fname;
3207: }
1.638 albertel 3208: return &process_coursefile('uploaddoc',$docuname,$docudom,
3209: $fname,$formname,$parser,
1.1095 raeburn 3210: $allfiles,$codebase,$mimetype);
1.481 raeburn 3211: }
1.719 banghart 3212: } elsif (defined($destuname)) {
3213: my $docuname=$destuname;
3214: my $docudom=$destudom;
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: } else {
1.638 albertel 3220: my $docuname=$env{'user.name'};
3221: my $docudom=$env{'user.domain'};
1.1220 raeburn 3222: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3223: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3224: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3225: }
1.860 raeburn 3226: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3227: $parser,$allfiles,$codebase,
1.1051 raeburn 3228: $thumbwidth,$thumbheight,
1.1095 raeburn 3229: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3230: }
1.271 www 3231: }
3232:
3233: sub finishuserfileupload {
1.860 raeburn 3234: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3235: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3236: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3237: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3238:
1.860 raeburn 3239: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3240: $file=$fname;
3241: if ($fname=~m|/|) {
3242: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3243: $path.=$fnamepath.'/';
3244: }
1.259 www 3245: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3246: my $count;
3247: for ($count=4;$count<=$#parts;$count++) {
3248: $filepath.="/$parts[$count]";
3249: if ((-e $filepath)!=1) {
3250: mkdir($filepath,0777);
3251: }
3252: }
1.984 neumanie 3253:
1.258 www 3254: # Save the file
3255: {
1.701 albertel 3256: if (!open(FH,'>'.$filepath.'/'.$file)) {
3257: &logthis('Failed to create '.$filepath.'/'.$file);
3258: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3259: return '/adm/notfound.html';
3260: }
1.1090 raeburn 3261: if ($context eq 'overwrite') {
1.1117 foxr 3262: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3263: my $target = $filepath.'/'.$file;
3264: if (-e $source) {
3265: my @info = stat($source);
3266: if ($info[9] eq $env{'form.timestamp'}) {
3267: unless (&File::Copy::move($source,$target)) {
3268: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3269: return "Moving from $source failed";
3270: }
3271: } else {
3272: return "Temporary file: $source had unexpected date/time for last modification";
3273: }
3274: } else {
3275: return "Temporary file: $source missing";
3276: }
3277: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3278: &logthis('Failed to write to '.$filepath.'/'.$file);
3279: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3280: return '/adm/notfound.html';
3281: }
1.570 albertel 3282: close(FH);
1.1051 raeburn 3283: if ($resizewidth && $resizeheight) {
3284: my $mm = new File::MMagic;
3285: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3286: if ($mime_type =~ m{^image/}) {
3287: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3288: }
1.977 amueller 3289: }
1.258 www 3290: }
1.1152 raeburn 3291: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3292: if (ref($mimetype)) {
3293: if ($$mimetype eq '') {
3294: my $mm = new File::MMagic;
3295: my $type = $mm->checktype_filename($filepath.'/'.$file);
3296: $$mimetype = $type;
3297: }
3298: }
3299: }
1.637 raeburn 3300: if ($parser eq 'parse') {
1.1152 raeburn 3301: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3302: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3303: $allfiles,$codebase);
3304: unless ($parse_result eq 'ok') {
3305: &logthis('Failed to parse '.$filepath.$file.
3306: ' for embedded media: '.$parse_result);
3307: }
1.637 raeburn 3308: }
3309: }
1.860 raeburn 3310: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3311: my $input = $filepath.'/'.$file;
3312: my $output = $filepath.'/'.'tn-'.$file;
3313: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3314: system("convert -sample $thumbsize $input $output");
3315: if (-e $filepath.'/'.'tn-'.$file) {
3316: $fetchthumb = 1;
3317: }
3318: }
1.858 raeburn 3319:
1.259 www 3320: # Notify homeserver to grep it
3321: #
1.984 neumanie 3322: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3323: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3324: if ($fetchresult eq 'ok') {
1.860 raeburn 3325: if ($fetchthumb) {
3326: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3327: if ($thumbresult ne 'ok') {
3328: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3329: $docuhome.': '.$thumbresult);
3330: }
3331: }
1.259 www 3332: #
1.258 www 3333: # Return the URL to it
1.494 albertel 3334: return '/uploaded/'.$path.$file;
1.263 www 3335: } else {
1.494 albertel 3336: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3337: ': '.$fetchresult);
1.263 www 3338: return '/adm/notfound.html';
1.858 raeburn 3339: }
1.493 albertel 3340: }
3341:
1.637 raeburn 3342: sub extract_embedded_items {
1.961 raeburn 3343: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3344: my @state = ();
1.1164 raeburn 3345: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3346: my %javafiles = (
3347: codebase => '',
3348: code => '',
3349: archive => ''
3350: );
3351: my %mediafiles = (
3352: src => '',
3353: movie => '',
3354: );
1.648 raeburn 3355: my $p;
3356: if ($content) {
3357: $p = HTML::LCParser->new($content);
3358: } else {
1.961 raeburn 3359: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3360: }
1.641 albertel 3361: while (my $t=$p->get_token()) {
1.640 albertel 3362: if ($t->[0] eq 'S') {
3363: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3364: push(@state, $tagname);
1.648 raeburn 3365: if (lc($tagname) eq 'allow') {
3366: &add_filetype($allfiles,$attr->{'src'},'src');
3367: }
1.640 albertel 3368: if (lc($tagname) eq 'img') {
3369: &add_filetype($allfiles,$attr->{'src'},'src');
3370: }
1.886 albertel 3371: if (lc($tagname) eq 'a') {
1.1222 raeburn 3372: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3373: &add_filetype($allfiles,$attr->{'href'},'href');
3374: }
1.886 albertel 3375: }
1.645 raeburn 3376: if (lc($tagname) eq 'script') {
1.1164 raeburn 3377: my $src;
1.645 raeburn 3378: if ($attr->{'archive'} =~ /\.jar$/i) {
3379: &add_filetype($allfiles,$attr->{'archive'},'archive');
3380: } else {
1.1164 raeburn 3381: if ($attr->{'src'} ne '') {
3382: $src = $attr->{'src'};
3383: &add_filetype($allfiles,$src,'src');
3384: }
3385: }
3386: my $text = $p->get_trimmed_text();
3387: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3388: my @swfargs = split(/,/,$1);
3389: foreach my $item (@swfargs) {
3390: $item =~ s/["']//g;
3391: $item =~ s/^\s+//;
3392: $item =~ s/\s+$//;
3393: }
3394: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3395: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3396: push(@{$related{$swfargs[0]}},$swfargs[2]);
3397: } else {
3398: $related{$swfargs[0]} = [$swfargs[2]];
3399: }
3400: }
1.645 raeburn 3401: }
3402: }
3403: if (lc($tagname) eq 'link') {
3404: if (lc($attr->{'rel'}) eq 'stylesheet') {
3405: &add_filetype($allfiles,$attr->{'href'},'href');
3406: }
3407: }
1.640 albertel 3408: if (lc($tagname) eq 'object' ||
3409: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3410: foreach my $item (keys(%javafiles)) {
3411: $javafiles{$item} = '';
3412: }
1.1164 raeburn 3413: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3414: $lastids{lc($tagname)} = $attr->{'id'};
3415: }
1.640 albertel 3416: }
3417: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3418: my $name = lc($attr->{'name'});
3419: foreach my $item (keys(%javafiles)) {
3420: if ($name eq $item) {
3421: $javafiles{$item} = $attr->{'value'};
3422: last;
3423: }
3424: }
1.1164 raeburn 3425: my $pathfrom;
1.640 albertel 3426: foreach my $item (keys(%mediafiles)) {
3427: if ($name eq $item) {
1.1164 raeburn 3428: $pathfrom = $attr->{'value'};
3429: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3430: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3431: last;
3432: }
3433: }
1.1164 raeburn 3434: if ($name eq 'flashvars') {
3435: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3436: }
3437: if ($pathfrom ne '') {
3438: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3439: $pathfrom);
3440: }
1.640 albertel 3441: }
3442: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3443: foreach my $item (keys(%javafiles)) {
3444: if ($attr->{$item}) {
3445: $javafiles{$item} = $attr->{$item};
3446: last;
3447: }
3448: }
3449: foreach my $item (keys(%mediafiles)) {
3450: if ($attr->{$item}) {
3451: &add_filetype($allfiles,$attr->{$item},$item);
3452: last;
3453: }
3454: }
1.1164 raeburn 3455: if (lc($tagname) eq 'embed') {
3456: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3457: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3458: $attr->{'src'});
3459: }
3460: }
1.640 albertel 3461: }
1.1164 raeburn 3462: if ($t->[4] =~ m{/>$}) {
3463: pop(@state);
3464: }
1.640 albertel 3465: } elsif ($t->[0] eq 'E') {
3466: my ($tagname) = ($t->[1]);
3467: if ($javafiles{'codebase'} ne '') {
3468: $javafiles{'codebase'} .= '/';
3469: }
3470: if (lc($tagname) eq 'applet' ||
3471: lc($tagname) eq 'object' ||
3472: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3473: ) {
3474: foreach my $item (keys(%javafiles)) {
3475: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3476: my $file=$javafiles{'codebase'}.$javafiles{$item};
3477: &add_filetype($allfiles,$file,$item);
3478: }
3479: }
3480: }
3481: pop @state;
3482: }
3483: }
1.1164 raeburn 3484: foreach my $id (sort(keys(%flashvars))) {
3485: if ($shockwave{$id} ne '') {
3486: my @pairs = split(/\&/,$flashvars{$id});
3487: foreach my $pair (@pairs) {
3488: my ($key,$value) = split(/\=/,$pair);
3489: if ($key eq 'thumb') {
3490: &add_filetype($allfiles,$value,$key);
3491: } elsif ($key eq 'content') {
3492: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3493: my ($ext) = ($value =~ /\.([^.]+)$/);
3494: if ($ext ne '') {
3495: &add_filetype($allfiles,$path.$value,$ext);
3496: }
3497: }
3498: }
3499: }
3500: }
1.637 raeburn 3501: return 'ok';
3502: }
3503:
1.639 albertel 3504: sub add_filetype {
3505: my ($allfiles,$file,$type)=@_;
3506: if (exists($allfiles->{$file})) {
3507: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3508: push(@{$allfiles->{$file}}, &escape($type));
3509: }
3510: } else {
3511: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3512: }
3513: }
3514:
1.1164 raeburn 3515: sub embedded_dependency {
3516: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3517: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3518: if (($identifier ne '') &&
3519: (ref($related->{$identifier}) eq 'ARRAY') &&
3520: ($pathfrom ne '')) {
3521: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3522: foreach my $dep (@{$related->{$identifier}}) {
3523: &add_filetype($allfiles,$path.$dep,'object');
3524: }
3525: }
3526: }
3527: return;
3528: }
3529:
1.493 albertel 3530: sub removeuploadedurl {
1.984 neumanie 3531: my ($url)=@_;
3532: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3533: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3534: }
3535:
3536: sub removeuserfile {
3537: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3538: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3539: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3540: if ($result eq 'ok') {
1.798 raeburn 3541: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3542: my $metafile = $fname.'.meta';
3543: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3544: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3545: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3546: my $sqlresult =
1.823 albertel 3547: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3548: 'portfolio_metadata',$group,
3549: 'delete');
1.798 raeburn 3550: }
3551: }
3552: return $result;
1.257 www 3553: }
1.15 www 3554:
1.530 albertel 3555: sub mkdiruserfile {
3556: my ($docuname,$docudom,$dir)=@_;
3557: my $home=&homeserver($docuname,$docudom);
3558: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3559: }
3560:
1.531 albertel 3561: sub renameuserfile {
3562: my ($docuname,$docudom,$old,$new)=@_;
3563: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3564: my $result = &reply("renameuserfile:$docudom:$docuname:".
3565: &escape("$old").':'.&escape("$new"),$home);
3566: if ($result eq 'ok') {
3567: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3568: my $oldmeta = $old.'.meta';
3569: my $newmeta = $new.'.meta';
3570: my $metaresult =
3571: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3572: my $url = "/uploaded/$docudom/$docuname/$old";
3573: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3574: my $sqlresult =
1.823 albertel 3575: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3576: 'portfolio_metadata',$group,
3577: 'delete');
1.798 raeburn 3578: }
3579: }
3580: return $result;
1.531 albertel 3581: }
3582:
1.14 www 3583: # ------------------------------------------------------------------------- Log
3584:
3585: sub log {
3586: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3587: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3588: }
3589:
3590: # ------------------------------------------------------------------ Course Log
1.352 www 3591: #
3592: # This routine flushes several buffers of non-mission-critical nature
3593: #
1.157 www 3594:
3595: sub flushcourselogs {
1.352 www 3596: &logthis('Flushing log buffers');
3597: #
3598: # course logs
3599: # This is a log of all transactions in a course, which can be used
3600: # for data mining purposes
3601: #
3602: # It also collects the courseid database, which lists last transaction
3603: # times and course titles for all courseids
3604: #
3605: my %courseidbuffer=();
1.921 raeburn 3606: foreach my $crsid (keys(%courselogs)) {
1.352 www 3607: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3608: &escape($courselogs{$crsid}),
3609: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3610: delete $courselogs{$crsid};
3611: } else {
3612: &logthis('Failed to flush log buffer for '.$crsid);
3613: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3614: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3615: " exceeded maximum size, deleting.</font>");
3616: delete $courselogs{$crsid};
3617: }
1.352 www 3618: }
1.920 raeburn 3619: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3620: 'description' => $coursedescrbuf{$crsid},
3621: 'inst_code' => $courseinstcodebuf{$crsid},
3622: 'type' => $coursetypebuf{$crsid},
3623: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3624: };
1.191 harris41 3625: }
1.352 www 3626: #
3627: # Write course id database (reverse lookup) to homeserver of courses
3628: # Is used in pickcourse
3629: #
1.840 albertel 3630: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3631: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3632: $courseidbuffer{$crs_home},
3633: $crs_home,'timeonly');
1.352 www 3634: }
3635: #
3636: # File accesses
3637: # Writes to the dynamic metadata of resources to get hit counts, etc.
3638: #
1.449 matthew 3639: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3640: if ($entry =~ /___count$/) {
3641: my ($dom,$name);
1.807 albertel 3642: ($dom,$name,undef)=
1.811 albertel 3643: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3644: if (! defined($dom) || $dom eq '' ||
3645: ! defined($name) || $name eq '') {
1.620 albertel 3646: my $cid = $env{'request.course.id'};
3647: $dom = $env{'request.'.$cid.'.domain'};
3648: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3649: }
1.450 matthew 3650: my $value = $accesshash{$entry};
3651: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3652: my %temphash=($url => $value);
1.449 matthew 3653: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3654: if ($result eq 'ok') {
3655: delete $accesshash{$entry};
3656: }
3657: } else {
1.811 albertel 3658: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3659: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3660: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3661: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3662: delete $accesshash{$entry};
3663: }
1.185 www 3664: }
1.191 harris41 3665: }
1.352 www 3666: #
3667: # Roles
3668: # Reverse lookup of user roles for course faculty/staff and co-authorship
3669: #
1.800 albertel 3670: foreach my $entry (keys(%userrolehash)) {
1.351 www 3671: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3672: split(/\:/,$entry);
3673: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3674: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3675: $rudom,$runame) eq 'ok') {
3676: delete $userrolehash{$entry};
3677: }
3678: }
1.662 raeburn 3679: #
3680: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3681: #
3682: my %domrolebuffer = ();
1.1000 raeburn 3683: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3684: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3685: if ($domrolebuffer{$rudom}) {
3686: $domrolebuffer{$rudom}.='&'.&escape($entry).
3687: '='.&escape($domainrolehash{$entry});
3688: } else {
3689: $domrolebuffer{$rudom}.=&escape($entry).
3690: '='.&escape($domainrolehash{$entry});
3691: }
3692: delete $domainrolehash{$entry};
3693: }
3694: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3695: my %servers = &get_servers($dom,'library');
3696: foreach my $tryserver (keys(%servers)) {
3697: unless (&reply('domroleput:'.$dom.':'.
3698: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3699: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3700: }
1.662 raeburn 3701: }
3702: }
1.186 www 3703: $dumpcount++;
1.157 www 3704: }
3705:
3706: sub courselog {
3707: my $what=shift;
1.158 www 3708: $what=time.':'.$what;
1.620 albertel 3709: unless ($env{'request.course.id'}) { return ''; }
3710: $coursedombuf{$env{'request.course.id'}}=
3711: $env{'course.'.$env{'request.course.id'}.'.domain'};
3712: $coursenumbuf{$env{'request.course.id'}}=
3713: $env{'course.'.$env{'request.course.id'}.'.num'};
3714: $coursehombuf{$env{'request.course.id'}}=
3715: $env{'course.'.$env{'request.course.id'}.'.home'};
3716: $coursedescrbuf{$env{'request.course.id'}}=
3717: $env{'course.'.$env{'request.course.id'}.'.description'};
3718: $courseinstcodebuf{$env{'request.course.id'}}=
3719: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3720: $courseownerbuf{$env{'request.course.id'}}=
3721: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3722: $coursetypebuf{$env{'request.course.id'}}=
3723: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3724: if (defined $courselogs{$env{'request.course.id'}}) {
3725: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3726: } else {
1.620 albertel 3727: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3728: }
1.620 albertel 3729: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3730: &flushcourselogs();
3731: }
1.158 www 3732: }
3733:
3734: sub courseacclog {
3735: my $fnsymb=shift;
1.620 albertel 3736: unless ($env{'request.course.id'}) { return ''; }
3737: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3738: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3739: $what.=':POST';
1.583 matthew 3740: # FIXME: Probably ought to escape things....
1.800 albertel 3741: foreach my $key (keys(%env)) {
3742: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3743: my $formitem = $1;
3744: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3745: $what.=':'.$formitem.'='.$env{$key};
3746: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3747: $what.=':'.$formitem.'='.$env{$key};
3748: }
1.158 www 3749: }
1.191 harris41 3750: }
1.583 matthew 3751: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3752: # FIXME: We should not be depending on a form parameter that someone
3753: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3754: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3755: $what.= ':POST';
3756: # FIXME: Probably ought to escape things....
3757: foreach my $element ('courseexp','crsfulltext','crsrelated',
3758: 'crsdiscuss') {
1.620 albertel 3759: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3760: }
3761: }
1.158 www 3762: }
3763: &courselog($what);
1.149 www 3764: }
3765:
1.185 www 3766: sub countacc {
3767: my $url=&declutter(shift);
1.458 matthew 3768: return if (! defined($url) || $url eq '');
1.620 albertel 3769: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3770: #
3771: # Mark that this url was used in this course
3772: #
1.620 albertel 3773: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3774: #
3775: # Increase the access count for this resource in this child process
3776: #
1.281 www 3777: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3778: $accesshash{$key}++;
1.185 www 3779: }
1.349 www 3780:
1.361 www 3781: sub linklog {
3782: my ($from,$to)=@_;
3783: $from=&declutter($from);
3784: $to=&declutter($to);
3785: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3786: $accesshash{$to.'___'.$from.'___goto'}=1;
3787: }
1.1160 www 3788:
3789: sub statslog {
3790: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3791: if ($users<2) { return; }
3792: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3793: 'course' => $env{'request.course.id'},
3794: 'sections' => '"all"',
3795: 'num_students' => $users,
3796: 'part' => $part,
3797: 'symb' => $symb,
3798: 'mean_tries' => $av_attempts,
3799: 'deg_of_diff' => $degdiff});
3800: foreach my $key (keys(%dynstore)) {
3801: $accesshash{$key}=$dynstore{$key};
3802: }
3803: }
1.361 www 3804:
1.349 www 3805: sub userrolelog {
3806: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3807: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3808: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3809: $userrolehash
3810: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3811: =$tend.':'.$tstart;
1.662 raeburn 3812: }
1.1169 droeschl 3813: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3814: $userrolehash
3815: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3816: =$tend.':'.$tstart;
3817: }
1.1169 droeschl 3818: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3819: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3820: $domainrolehash
3821: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3822: = $tend.':'.$tstart;
3823: }
1.351 www 3824: }
3825:
1.957 raeburn 3826: sub courserolelog {
3827: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3828: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3829: my $cdom = $1;
3830: my $cnum = $2;
3831: my $sec = $3;
3832: my $namespace = 'rolelog';
3833: my %storehash = (
3834: role => $trole,
3835: start => $tstart,
3836: end => $tend,
3837: selfenroll => $selfenroll,
3838: context => $context,
3839: );
3840: if ($trole eq 'gr') {
3841: $namespace = 'groupslog';
3842: $storehash{'group'} = $sec;
3843: } else {
3844: $storehash{'section'} = $sec;
3845: }
1.1188 raeburn 3846: &write_log('course',$namespace,\%storehash,$delflag,$username,
3847: $domain,$cnum,$cdom);
1.1184 raeburn 3848: if (($trole ne 'st') || ($sec ne '')) {
3849: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3850: }
3851: }
3852: return;
3853: }
3854:
1.1184 raeburn 3855: sub domainrolelog {
3856: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3857: if ($area =~ m{^/($match_domain)/$}) {
3858: my $cdom = $1;
3859: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3860: my $namespace = 'rolelog';
3861: my %storehash = (
3862: role => $trole,
3863: start => $tstart,
3864: end => $tend,
3865: context => $context,
3866: );
1.1188 raeburn 3867: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3868: $domain,$domconfiguser,$cdom);
1.1184 raeburn 3869: }
3870: return;
3871:
3872: }
3873:
3874: sub coauthorrolelog {
3875: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3876: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3877: my $audom = $1;
3878: my $auname = $2;
3879: my $namespace = 'rolelog';
3880: my %storehash = (
3881: role => $trole,
3882: start => $tstart,
3883: end => $tend,
3884: context => $context,
3885: );
1.1188 raeburn 3886: &write_log('author',$namespace,\%storehash,$delflag,$username,
3887: $domain,$auname,$audom);
1.1184 raeburn 3888: }
3889: return;
3890: }
3891:
1.351 www 3892: sub get_course_adv_roles {
1.948 raeburn 3893: my ($cid,$codes) = @_;
1.620 albertel 3894: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3895: my %coursehash=&coursedescription($cid);
1.988 raeburn 3896: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3897: my %nothide=();
1.800 albertel 3898: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3899: if ($user !~ /:/) {
3900: $nothide{join(':',split(/[\@]/,$user))}=1;
3901: } else {
3902: $nothide{$user}=1;
3903: }
1.470 www 3904: }
1.1219 raeburn 3905: my @possdoms = ($coursehash{'domain'});
3906: if ($coursehash{'checkforpriv'}) {
3907: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3908: }
1.351 www 3909: my %returnhash=();
3910: my %dumphash=
3911: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3912: my $now=time;
1.997 raeburn 3913: my %privileged;
1.1000 raeburn 3914: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3915: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3916: if (($tstart) && ($tstart<0)) { next; }
3917: if (($tend) && ($tend<$now)) { next; }
3918: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3919: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3920: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 3921: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 3922: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3923: if ($role eq 'cr') { next; }
1.948 raeburn 3924: if ($codes) {
3925: if ($section) { $role .= ':'.$section; }
3926: if ($returnhash{$role}) {
3927: $returnhash{$role}.=','.$username.':'.$domain;
3928: } else {
3929: $returnhash{$role}=$username.':'.$domain;
3930: }
1.351 www 3931: } else {
1.988 raeburn 3932: my $key=&plaintext($role,$crstype);
1.973 bisitz 3933: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3934: if ($returnhash{$key}) {
3935: $returnhash{$key}.=','.$username.':'.$domain;
3936: } else {
3937: $returnhash{$key}=$username.':'.$domain;
3938: }
1.351 www 3939: }
1.948 raeburn 3940: }
1.400 www 3941: return %returnhash;
3942: }
3943:
3944: sub get_my_roles {
1.937 raeburn 3945: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3946: unless (defined($uname)) { $uname=$env{'user.name'}; }
3947: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3948: my (%dumphash,%nothide);
1.1086 raeburn 3949: if ($context eq 'userroles') {
1.1166 raeburn 3950: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 3951: } else {
1.1219 raeburn 3952: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3953: if ($hidepriv) {
3954: my %coursehash=&coursedescription($udom.'_'.$uname);
3955: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3956: if ($user !~ /:/) {
3957: $nothide{join(':',split(/[\@]/,$user))} = 1;
3958: } else {
3959: $nothide{$user} = 1;
3960: }
3961: }
3962: }
1.858 raeburn 3963: }
1.400 www 3964: my %returnhash=();
3965: my $now=time;
1.999 raeburn 3966: my %privileged;
1.800 albertel 3967: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3968: my ($role,$tend,$tstart);
3969: if ($context eq 'userroles') {
1.1149 raeburn 3970: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3971: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3972: } else {
3973: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3974: }
1.400 www 3975: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3976: my $status = 'active';
1.939 raeburn 3977: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3978: $status = 'previous';
3979: }
3980: if (($tstart) && ($now<$tstart)) {
3981: $status = 'future';
3982: }
3983: if (ref($types) eq 'ARRAY') {
3984: if (!grep(/^\Q$status\E$/,@{$types})) {
3985: next;
3986: }
3987: } else {
3988: if ($status ne 'active') {
3989: next;
3990: }
3991: }
1.867 raeburn 3992: my ($rolecode,$username,$domain,$section,$area);
3993: if ($context eq 'userroles') {
1.1186 raeburn 3994: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 3995: (undef,$domain,$username,$section) = split(/\//,$area);
3996: } else {
3997: ($role,$username,$domain,$section) = split(/\:/,$entry);
3998: }
1.832 raeburn 3999: if (ref($roledoms) eq 'ARRAY') {
4000: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4001: next;
4002: }
4003: }
4004: if (ref($roles) eq 'ARRAY') {
4005: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4006: if ($role =~ /^cr\//) {
4007: if (!grep(/^cr$/,@{$roles})) {
4008: next;
4009: }
1.1104 raeburn 4010: } elsif ($role =~ /^gr\//) {
4011: if (!grep(/^gr$/,@{$roles})) {
4012: next;
4013: }
1.922 raeburn 4014: } else {
4015: next;
4016: }
1.832 raeburn 4017: }
1.867 raeburn 4018: }
1.937 raeburn 4019: if ($hidepriv) {
1.1219 raeburn 4020: my @privroles = ('dc','su');
1.999 raeburn 4021: if ($context eq 'userroles') {
1.1219 raeburn 4022: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4023: } else {
1.1219 raeburn 4024: my $possdoms = [$domain];
4025: if (ref($roledoms) eq 'ARRAY') {
4026: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4027: }
1.1219 raeburn 4028: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4029: if (!$nothide{$username.':'.$domain}) {
4030: next;
4031: }
4032: }
1.937 raeburn 4033: }
4034: }
1.933 raeburn 4035: if ($withsec) {
4036: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4037: $tstart.':'.$tend;
4038: } else {
4039: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4040: }
1.832 raeburn 4041: }
1.373 www 4042: return %returnhash;
1.399 www 4043: }
4044:
4045: # ----------------------------------------------------- Frontpage Announcements
4046: #
4047: #
4048:
4049: sub postannounce {
4050: my ($server,$text)=@_;
1.844 albertel 4051: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4052: unless ($text=~/\w/) { $text=''; }
4053: return &reply('setannounce:'.&escape($text),$server);
4054: }
4055:
4056: sub getannounce {
1.448 albertel 4057:
4058: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4059: my $announcement='';
1.800 albertel 4060: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4061: close($fh);
1.399 www 4062: if ($announcement=~/\w/) {
4063: return
4064: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4065: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4066: } else {
4067: return '';
4068: }
4069: } else {
4070: return '';
4071: }
1.351 www 4072: }
1.353 www 4073:
4074: # ---------------------------------------------------------- Course ID routines
4075: # Deal with domain's nohist_courseid.db files
4076: #
4077:
4078: sub courseidput {
1.921 raeburn 4079: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4080: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4081: my $outcome;
4082: if ($caller eq 'timeonly') {
4083: my $cids = '';
4084: foreach my $item (keys(%$storehash)) {
4085: $cids.=&escape($item).'&';
4086: }
4087: $cids=~s/\&$//;
4088: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4089: $coursehome);
4090: } else {
4091: my $items = '';
4092: foreach my $item (keys(%$storehash)) {
4093: $items.= &escape($item).'='.
4094: &freeze_escape($$storehash{$item}).'&';
4095: }
4096: $items=~s/\&$//;
4097: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4098: $coursehome);
1.918 raeburn 4099: }
4100: if ($outcome eq 'unknown_cmd') {
4101: my $what;
4102: foreach my $cid (keys(%$storehash)) {
4103: $what .= &escape($cid).'=';
1.921 raeburn 4104: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4105: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4106: }
4107: $what =~ s/\:$/&/;
4108: }
4109: $what =~ s/\&$//;
4110: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4111: } else {
4112: return $outcome;
4113: }
1.353 www 4114: }
4115:
4116: sub courseiddump {
1.921 raeburn 4117: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4118: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4119: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 4120: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 4121: my $as_hash = 1;
4122: my %returnhash;
4123: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4124: my %libserv = &all_library();
4125: foreach my $tryserver (keys(%libserv)) {
4126: if ( ( $hostidflag == 1
4127: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4128: || (!defined($hostidflag)) ) {
4129:
1.918 raeburn 4130: if (($domfilter eq '') ||
4131: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4132: my $rep;
4133: if (grep { $_ eq $tryserver } current_machine_ids()) {
4134: $rep = LONCAPA::Lond::dump_course_id_handler(
4135: join(":", (&host_domain($tryserver), $sincefilter,
4136: &escape($descfilter), &escape($instcodefilter),
4137: &escape($ownerfilter), &escape($coursefilter),
4138: &escape($typefilter), &escape($regexp_ok),
4139: $as_hash, &escape($selfenrollonly),
4140: &escape($catfilter), $showhidden, $caller,
4141: &escape($cloner), &escape($cc_clone), $cloneonly,
4142: &escape($createdbefore), &escape($createdafter),
4143: &escape($creationcontext), $domcloner)));
4144: } else {
4145: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4146: $sincefilter.':'.&escape($descfilter).':'.
4147: &escape($instcodefilter).':'.&escape($ownerfilter).
4148: ':'.&escape($coursefilter).':'.&escape($typefilter).
4149: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4150: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4151: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4152: &escape($cc_clone).':'.$cloneonly.':'.
4153: &escape($createdbefore).':'.&escape($createdafter).':'.
4154: &escape($creationcontext).':'.$domcloner,
4155: $tryserver);
4156: }
4157:
1.918 raeburn 4158: my @pairs=split(/\&/,$rep);
4159: foreach my $item (@pairs) {
4160: my ($key,$value)=split(/\=/,$item,2);
4161: $key = &unescape($key);
4162: next if ($key =~ /^error: 2 /);
4163: my $result = &thaw_unescape($value);
4164: if (ref($result) eq 'HASH') {
4165: $returnhash{$key}=$result;
4166: } else {
1.921 raeburn 4167: my @responses = split(/:/,$value);
4168: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4169: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4170: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4171: }
1.1008 raeburn 4172: }
1.353 www 4173: }
4174: }
4175: }
4176: }
4177: return %returnhash;
4178: }
4179:
1.1055 raeburn 4180: sub courselastaccess {
4181: my ($cdom,$cnum,$hostidref) = @_;
4182: my %returnhash;
4183: if ($cdom && $cnum) {
4184: my $chome = &homeserver($cnum,$cdom);
4185: if ($chome ne 'no_host') {
4186: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4187: &extract_lastaccess(\%returnhash,$rep);
4188: }
4189: } else {
4190: if (!$cdom) { $cdom=''; }
4191: my %libserv = &all_library();
4192: foreach my $tryserver (keys(%libserv)) {
4193: if (ref($hostidref) eq 'ARRAY') {
4194: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4195: }
4196: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4197: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4198: &extract_lastaccess(\%returnhash,$rep);
4199: }
4200: }
4201: }
4202: return %returnhash;
4203: }
4204:
4205: sub extract_lastaccess {
4206: my ($returnhash,$rep) = @_;
4207: if (ref($returnhash) eq 'HASH') {
4208: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4209: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4210: $rep eq '') {
4211: my @pairs=split(/\&/,$rep);
4212: foreach my $item (@pairs) {
4213: my ($key,$value)=split(/\=/,$item,2);
4214: $key = &unescape($key);
4215: next if ($key =~ /^error: 2 /);
4216: $returnhash->{$key} = &thaw_unescape($value);
4217: }
4218: }
4219: }
4220: return;
4221: }
4222:
1.658 raeburn 4223: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4224:
4225: sub dcmailput {
1.685 raeburn 4226: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4227: my $status = &Apache::lonnet::critical(
1.740 www 4228: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4229: &escape($message),$server);
1.662 raeburn 4230: return $status;
4231: }
4232:
1.658 raeburn 4233: sub dcmaildump {
4234: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4235: my %returnhash=();
1.846 albertel 4236:
4237: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4238: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4239: &escape($enddate).':';
4240: my @esc_senders=map { &escape($_)} @$senders;
4241: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4242: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4243: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4244: if (($key) && ($value)) {
4245: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4246: }
4247: }
4248: }
4249: return %returnhash;
4250: }
1.662 raeburn 4251: # ---------------------------------------------------------- Domain roles
4252:
4253: sub get_domain_roles {
4254: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4255: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4256: $startdate = '.';
4257: }
1.1018 raeburn 4258: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4259: $enddate = '.';
4260: }
1.922 raeburn 4261: my $rolelist;
4262: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4263: $rolelist = join('&',@{$roles});
1.922 raeburn 4264: }
1.662 raeburn 4265: my %personnel = ();
1.841 albertel 4266:
4267: my %servers = &get_servers($dom,'library');
4268: foreach my $tryserver (keys(%servers)) {
4269: %{$personnel{$tryserver}}=();
4270: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4271: &escape($startdate).':'.
4272: &escape($enddate).':'.
4273: &escape($rolelist), $tryserver))) {
4274: my ($key,$value) = split(/\=/,$line,2);
4275: if (($key) && ($value)) {
4276: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4277: }
4278: }
1.662 raeburn 4279: }
4280: return %personnel;
4281: }
1.658 raeburn 4282:
1.1057 www 4283: # ----------------------------------------------------------- Interval timing
1.149 www 4284:
1.1153 www 4285: {
4286: # Caches needed for speedup of navmaps
4287: # We don't want to cache this for very long at all (5 seconds at most)
4288: #
4289: # The user for whom we cache
4290: my $cachedkey='';
4291: # The cached times for this user
4292: my %cachedtimes=();
4293: # When this was last done
4294: my $cachedtime=();
4295:
4296: sub load_all_first_access {
1.1154 raeburn 4297: my ($uname,$udom)=@_;
1.1156 www 4298: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4299: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4300: return;
4301: }
4302: $cachedtime=time;
4303: $cachedkey=$uname.':'.$udom;
4304: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4305: }
4306:
1.504 albertel 4307: sub get_first_access {
1.1162 raeburn 4308: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4309: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4310: if ($argsymb) { $symb=$argsymb; }
4311: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4312: if ($argmap) { $map = $argmap; }
1.926 albertel 4313: if ($type eq 'course') {
4314: $res='course';
4315: } elsif ($type eq 'map') {
1.588 albertel 4316: $res=&symbread($map);
4317: } else {
4318: $res=$symb;
4319: }
1.1153 www 4320: &load_all_first_access($uname,$udom);
4321: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4322: }
4323:
4324: sub set_first_access {
1.1162 raeburn 4325: my ($type,$interval)=@_;
1.790 albertel 4326: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4327: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4328: if ($type eq 'course') {
4329: $res='course';
4330: } elsif ($type eq 'map') {
1.588 albertel 4331: $res=&symbread($map);
4332: } else {
4333: $res=$symb;
4334: }
1.1153 www 4335: $cachedkey='';
1.1162 raeburn 4336: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4337: if (!$firstaccess) {
1.1162 raeburn 4338: my $start = time;
4339: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4340: $udom,$uname);
4341: if ($putres eq 'ok') {
4342: &put('timerinterval',{"$courseid\0$res"=>$interval},
4343: $udom,$uname);
4344: &appenv(
4345: {
4346: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4347: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4348: }
4349: );
4350: }
4351: return $putres;
1.505 albertel 4352: }
4353: return 'already_set';
1.504 albertel 4354: }
1.1153 www 4355: }
1.110 www 4356: # --------------------------------------------- Set Expire Date for Spreadsheet
4357:
4358: sub expirespread {
4359: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4360: my $cid=$env{'request.course.id'};
1.110 www 4361: if ($cid) {
4362: my $now=time;
4363: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4364: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4365: $env{'course.'.$cid.'.num'}.
1.110 www 4366: ':nohist_expirationdates:'.
4367: &escape($key).'='.$now,
1.620 albertel 4368: $env{'course.'.$cid.'.home'})
1.110 www 4369: }
4370: return 'ok';
1.14 www 4371: }
4372:
1.109 www 4373: # ----------------------------------------------------- Devalidate Spreadsheets
4374:
4375: sub devalidate {
1.325 www 4376: my ($symb,$uname,$udom)=@_;
1.620 albertel 4377: my $cid=$env{'request.course.id'};
1.109 www 4378: if ($cid) {
1.391 matthew 4379: # delete the stored spreadsheets for
4380: # - the student level sheet of this user in course's homespace
4381: # - the assessment level sheet for this resource
4382: # for this user in user's homespace
1.553 albertel 4383: # - current conditional state info
1.325 www 4384: my $key=$uname.':'.$udom.':';
1.109 www 4385: my $status=
1.299 matthew 4386: &del('nohist_calculatedsheets',
1.391 matthew 4387: [$key.'studentcalc:'],
1.620 albertel 4388: $env{'course.'.$cid.'.domain'},
4389: $env{'course.'.$cid.'.num'})
1.133 albertel 4390: .' '.
4391: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4392: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4393: unless ($status eq 'ok ok') {
4394: &logthis('Could not devalidate spreadsheet '.
1.325 www 4395: $uname.' at '.$udom.' for '.
1.109 www 4396: $symb.': '.$status);
1.133 albertel 4397: }
1.553 albertel 4398: &delenv('user.state.'.$cid);
1.109 www 4399: }
4400: }
4401:
1.265 albertel 4402: sub get_scalar {
4403: my ($string,$end) = @_;
4404: my $value;
4405: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4406: $value = $1;
4407: } elsif ($$string =~ s/^([^&]*?)&//) {
4408: $value = $1;
4409: }
4410: return &unescape($value);
4411: }
4412:
4413: sub array2str {
4414: my (@array) = @_;
4415: my $result=&arrayref2str(\@array);
4416: $result=~s/^__ARRAY_REF__//;
4417: $result=~s/__END_ARRAY_REF__$//;
4418: return $result;
4419: }
4420:
1.204 albertel 4421: sub arrayref2str {
4422: my ($arrayref) = @_;
1.265 albertel 4423: my $result='__ARRAY_REF__';
1.204 albertel 4424: foreach my $elem (@$arrayref) {
1.265 albertel 4425: if(ref($elem) eq 'ARRAY') {
4426: $result.=&arrayref2str($elem).'&';
4427: } elsif(ref($elem) eq 'HASH') {
4428: $result.=&hashref2str($elem).'&';
4429: } elsif(ref($elem)) {
4430: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4431: } else {
4432: $result.=&escape($elem).'&';
4433: }
4434: }
4435: $result=~s/\&$//;
1.265 albertel 4436: $result .= '__END_ARRAY_REF__';
1.204 albertel 4437: return $result;
4438: }
4439:
1.168 albertel 4440: sub hash2str {
1.204 albertel 4441: my (%hash) = @_;
4442: my $result=&hashref2str(\%hash);
1.265 albertel 4443: $result=~s/^__HASH_REF__//;
4444: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4445: return $result;
4446: }
4447:
4448: sub hashref2str {
4449: my ($hashref)=@_;
1.265 albertel 4450: my $result='__HASH_REF__';
1.800 albertel 4451: foreach my $key (sort(keys(%$hashref))) {
4452: if (ref($key) eq 'ARRAY') {
4453: $result.=&arrayref2str($key).'=';
4454: } elsif (ref($key) eq 'HASH') {
4455: $result.=&hashref2str($key).'=';
4456: } elsif (ref($key)) {
1.265 albertel 4457: $result.='=';
1.800 albertel 4458: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4459: } else {
1.1132 raeburn 4460: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4461: }
4462:
1.800 albertel 4463: if(ref($hashref->{$key}) eq 'ARRAY') {
4464: $result.=&arrayref2str($hashref->{$key}).'&';
4465: } elsif(ref($hashref->{$key}) eq 'HASH') {
4466: $result.=&hashref2str($hashref->{$key}).'&';
4467: } elsif(ref($hashref->{$key})) {
1.265 albertel 4468: $result.='&';
1.800 albertel 4469: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4470: } else {
1.800 albertel 4471: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4472: }
4473: }
1.168 albertel 4474: $result=~s/\&$//;
1.265 albertel 4475: $result .= '__END_HASH_REF__';
1.168 albertel 4476: return $result;
4477: }
4478:
4479: sub str2hash {
1.265 albertel 4480: my ($string)=@_;
4481: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4482: return %$hash;
4483: }
4484:
4485: sub str2hashref {
1.168 albertel 4486: my ($string) = @_;
1.265 albertel 4487:
4488: my %hash;
4489:
4490: if($string !~ /^__HASH_REF__/) {
4491: if (! ($string eq '' || !defined($string))) {
4492: $hash{'error'}='Not hash reference';
4493: }
4494: return (\%hash, $string);
4495: }
4496:
4497: $string =~ s/^__HASH_REF__//;
4498:
4499: while($string !~ /^__END_HASH_REF__/) {
4500: #key
4501: my $key='';
4502: if($string =~ /^__HASH_REF__/) {
4503: ($key, $string)=&str2hashref($string);
4504: if(defined($key->{'error'})) {
4505: $hash{'error'}='Bad data';
4506: return (\%hash, $string);
4507: }
4508: } elsif($string =~ /^__ARRAY_REF__/) {
4509: ($key, $string)=&str2arrayref($string);
4510: if($key->[0] eq 'Array reference error') {
4511: $hash{'error'}='Bad data';
4512: return (\%hash, $string);
4513: }
4514: } else {
4515: $string =~ s/^(.*?)=//;
1.267 albertel 4516: $key=&unescape($1);
1.265 albertel 4517: }
4518: $string =~ s/^=//;
4519:
4520: #value
4521: my $value='';
4522: if($string =~ /^__HASH_REF__/) {
4523: ($value, $string)=&str2hashref($string);
4524: if(defined($value->{'error'})) {
4525: $hash{'error'}='Bad data';
4526: return (\%hash, $string);
4527: }
4528: } elsif($string =~ /^__ARRAY_REF__/) {
4529: ($value, $string)=&str2arrayref($string);
4530: if($value->[0] eq 'Array reference error') {
4531: $hash{'error'}='Bad data';
4532: return (\%hash, $string);
4533: }
4534: } else {
4535: $value=&get_scalar(\$string,'__END_HASH_REF__');
4536: }
4537: $string =~ s/^&//;
4538:
4539: $hash{$key}=$value;
1.204 albertel 4540: }
1.265 albertel 4541:
4542: $string =~ s/^__END_HASH_REF__//;
4543:
4544: return (\%hash, $string);
1.204 albertel 4545: }
4546:
4547: sub str2array {
1.265 albertel 4548: my ($string)=@_;
4549: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4550: return @$array;
4551: }
4552:
4553: sub str2arrayref {
1.204 albertel 4554: my ($string) = @_;
1.265 albertel 4555: my @array;
4556:
4557: if($string !~ /^__ARRAY_REF__/) {
4558: if (! ($string eq '' || !defined($string))) {
4559: $array[0]='Array reference error';
4560: }
4561: return (\@array, $string);
4562: }
4563:
4564: $string =~ s/^__ARRAY_REF__//;
4565:
4566: while($string !~ /^__END_ARRAY_REF__/) {
4567: my $value='';
4568: if($string =~ /^__HASH_REF__/) {
4569: ($value, $string)=&str2hashref($string);
4570: if(defined($value->{'error'})) {
4571: $array[0] ='Array reference error';
4572: return (\@array, $string);
4573: }
4574: } elsif($string =~ /^__ARRAY_REF__/) {
4575: ($value, $string)=&str2arrayref($string);
4576: if($value->[0] eq 'Array reference error') {
4577: $array[0] ='Array reference error';
4578: return (\@array, $string);
4579: }
4580: } else {
4581: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4582: }
4583: $string =~ s/^&//;
4584:
4585: push(@array, $value);
1.191 harris41 4586: }
1.265 albertel 4587:
4588: $string =~ s/^__END_ARRAY_REF__//;
4589:
4590: return (\@array, $string);
1.168 albertel 4591: }
4592:
1.167 albertel 4593: # -------------------------------------------------------------------Temp Store
4594:
1.168 albertel 4595: sub tmpreset {
4596: my ($symb,$namespace,$domain,$stuname) = @_;
4597: if (!$symb) {
4598: $symb=&symbread();
1.620 albertel 4599: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4600: }
4601: $symb=escape($symb);
4602:
1.620 albertel 4603: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4604: $namespace=~s/\//\_/g;
4605: $namespace=~s/\W//g;
4606:
1.620 albertel 4607: if (!$domain) { $domain=$env{'user.domain'}; }
4608: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4609: if ($domain eq 'public' && $stuname eq 'public') {
4610: $stuname=$ENV{'REMOTE_ADDR'};
4611: }
1.1117 foxr 4612: my $path=LONCAPA::tempdir();
1.168 albertel 4613: my %hash;
4614: if (tie(%hash,'GDBM_File',
4615: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4616: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4617: foreach my $key (keys(%hash)) {
1.180 albertel 4618: if ($key=~ /:$symb/) {
1.168 albertel 4619: delete($hash{$key});
4620: }
4621: }
4622: }
4623: }
4624:
1.167 albertel 4625: sub tmpstore {
1.168 albertel 4626: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4627:
4628: if (!$symb) {
4629: $symb=&symbread();
1.620 albertel 4630: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4631: }
4632: $symb=escape($symb);
4633:
4634: if (!$namespace) {
4635: # I don't think we would ever want to store this for a course.
4636: # it seems this will only be used if we don't have a course.
1.620 albertel 4637: #$namespace=$env{'request.course.id'};
1.168 albertel 4638: #if (!$namespace) {
1.620 albertel 4639: $namespace=$env{'request.state'};
1.168 albertel 4640: #}
4641: }
4642: $namespace=~s/\//\_/g;
4643: $namespace=~s/\W//g;
1.620 albertel 4644: if (!$domain) { $domain=$env{'user.domain'}; }
4645: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4646: if ($domain eq 'public' && $stuname eq 'public') {
4647: $stuname=$ENV{'REMOTE_ADDR'};
4648: }
1.168 albertel 4649: my $now=time;
4650: my %hash;
1.1117 foxr 4651: my $path=LONCAPA::tempdir();
1.168 albertel 4652: if (tie(%hash,'GDBM_File',
4653: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4654: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4655: $hash{"version:$symb"}++;
4656: my $version=$hash{"version:$symb"};
4657: my $allkeys='';
4658: foreach my $key (keys(%$storehash)) {
4659: $allkeys.=$key.':';
1.591 albertel 4660: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4661: }
4662: $hash{"$version:$symb:timestamp"}=$now;
4663: $allkeys.='timestamp';
4664: $hash{"$version:keys:$symb"}=$allkeys;
4665: if (untie(%hash)) {
4666: return 'ok';
4667: } else {
4668: return "error:$!";
4669: }
4670: } else {
4671: return "error:$!";
4672: }
4673: }
1.167 albertel 4674:
1.168 albertel 4675: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4676:
1.168 albertel 4677: sub tmprestore {
4678: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4679:
1.168 albertel 4680: if (!$symb) {
4681: $symb=&symbread();
1.620 albertel 4682: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4683: }
4684: $symb=escape($symb);
4685:
1.620 albertel 4686: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4687:
1.620 albertel 4688: if (!$domain) { $domain=$env{'user.domain'}; }
4689: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4690: if ($domain eq 'public' && $stuname eq 'public') {
4691: $stuname=$ENV{'REMOTE_ADDR'};
4692: }
1.168 albertel 4693: my %returnhash;
4694: $namespace=~s/\//\_/g;
4695: $namespace=~s/\W//g;
4696: my %hash;
1.1117 foxr 4697: my $path=LONCAPA::tempdir();
1.168 albertel 4698: if (tie(%hash,'GDBM_File',
4699: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4700: &GDBM_READER(),0640)) {
1.168 albertel 4701: my $version=$hash{"version:$symb"};
4702: $returnhash{'version'}=$version;
4703: my $scope;
4704: for ($scope=1;$scope<=$version;$scope++) {
4705: my $vkeys=$hash{"$scope:keys:$symb"};
4706: my @keys=split(/:/,$vkeys);
4707: my $key;
4708: $returnhash{"$scope:keys"}=$vkeys;
4709: foreach $key (@keys) {
1.591 albertel 4710: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4711: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4712: }
4713: }
1.168 albertel 4714: if (!(untie(%hash))) {
4715: return "error:$!";
4716: }
4717: } else {
4718: return "error:$!";
4719: }
4720: return %returnhash;
1.167 albertel 4721: }
4722:
1.9 www 4723: # ----------------------------------------------------------------------- Store
4724:
4725: sub store {
1.124 www 4726: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4727: my $home='';
4728:
1.168 albertel 4729: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4730:
1.213 www 4731: $symb=&symbclean($symb);
1.122 albertel 4732: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4733:
1.620 albertel 4734: if (!$domain) { $domain=$env{'user.domain'}; }
4735: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4736:
4737: &devalidate($symb,$stuname,$domain);
1.109 www 4738:
4739: $symb=escape($symb);
1.187 www 4740: if (!$namespace) {
1.620 albertel 4741: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4742: return '';
4743: }
4744: }
1.620 albertel 4745: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4746:
4747: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4748: $$storehash{'host'}=$perlvar{'lonHostID'};
4749:
1.12 www 4750: my $namevalue='';
1.800 albertel 4751: foreach my $key (keys(%$storehash)) {
4752: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4753: }
1.12 www 4754: $namevalue=~s/\&$//;
1.187 www 4755: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4756: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4757: }
4758:
1.47 www 4759: # -------------------------------------------------------------- Critical Store
4760:
4761: sub cstore {
1.124 www 4762: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4763: my $home='';
4764:
1.168 albertel 4765: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4766:
1.213 www 4767: $symb=&symbclean($symb);
1.122 albertel 4768: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4769:
1.620 albertel 4770: if (!$domain) { $domain=$env{'user.domain'}; }
4771: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4772:
4773: &devalidate($symb,$stuname,$domain);
1.109 www 4774:
4775: $symb=escape($symb);
1.187 www 4776: if (!$namespace) {
1.620 albertel 4777: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4778: return '';
4779: }
4780: }
1.620 albertel 4781: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4782:
4783: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4784: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4785:
1.47 www 4786: my $namevalue='';
1.800 albertel 4787: foreach my $key (keys(%$storehash)) {
4788: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4789: }
1.47 www 4790: $namevalue=~s/\&$//;
1.187 www 4791: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4792: return critical
4793: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4794: }
4795:
1.9 www 4796: # --------------------------------------------------------------------- Restore
4797:
4798: sub restore {
1.124 www 4799: my ($symb,$namespace,$domain,$stuname) = @_;
4800: my $home='';
4801:
1.168 albertel 4802: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4803:
1.122 albertel 4804: if (!$symb) {
1.1224 raeburn 4805: return if ($namespace eq 'courserequests');
4806: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4807: } else {
1.1224 raeburn 4808: unless ($namespace eq 'courserequests') {
4809: $symb=&escape(&symbclean($symb));
4810: }
1.122 albertel 4811: }
1.188 www 4812: if (!$namespace) {
1.620 albertel 4813: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4814: return '';
4815: }
4816: }
1.620 albertel 4817: if (!$domain) { $domain=$env{'user.domain'}; }
4818: if (!$stuname) { $stuname=$env{'user.name'}; }
4819: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4820: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4821:
1.12 www 4822: my %returnhash=();
1.800 albertel 4823: foreach my $line (split(/\&/,$answer)) {
4824: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4825: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4826: }
1.75 www 4827: my $version;
4828: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4829: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4830: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4831: }
1.75 www 4832: }
1.13 www 4833: return %returnhash;
1.34 www 4834: }
4835:
4836: # ---------------------------------------------------------- Course Description
1.1118 foxr 4837: #
4838: #
1.34 www 4839:
4840: sub coursedescription {
1.731 albertel 4841: my ($courseid,$args)=@_;
1.34 www 4842: $courseid=~s/^\///;
1.49 www 4843: $courseid=~s/\_/\//g;
1.34 www 4844: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4845: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4846: my $normalid=$cdomain.'_'.$cnum;
4847: # need to always cache even if we get errors otherwise we keep
4848: # trying and trying and trying to get the course description.
4849: my %envhash=();
4850: my %returnhash=();
1.731 albertel 4851:
4852: my $expiretime=600;
4853: if ($env{'request.course.id'} eq $normalid) {
4854: $expiretime=120;
4855: }
4856:
4857: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4858: if (!$args->{'freshen_cache'}
4859: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4860: foreach my $key (keys(%env)) {
4861: next if ($key !~ /^\Q$prefix\E(.*)/);
4862: my ($setting) = $1;
4863: $returnhash{$setting} = $env{$key};
4864: }
4865: return %returnhash;
4866: }
4867:
1.1118 foxr 4868: # get the data again
4869:
1.731 albertel 4870: if (!$args->{'one_time'}) {
4871: $envhash{'course.'.$normalid.'.last_cache'}=time;
4872: }
1.811 albertel 4873:
1.34 www 4874: if ($chome ne 'no_host') {
1.302 albertel 4875: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4876: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4877: my $username = $env{'user.name'}; # Defult username
4878: if(defined $args->{'user'}) {
4879: $username = $args->{'user'};
4880: }
1.129 albertel 4881: $returnhash{'home'}= $chome;
4882: $returnhash{'domain'} = $cdomain;
4883: $returnhash{'num'} = $cnum;
1.741 raeburn 4884: if (!defined($returnhash{'type'})) {
4885: $returnhash{'type'} = 'Course';
4886: }
1.130 albertel 4887: while (my ($name,$value) = each %returnhash) {
1.53 www 4888: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4889: }
1.270 www 4890: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4891: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4892: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4893: $envhash{'course.'.$normalid.'.home'}=$chome;
4894: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4895: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4896: }
4897: }
1.731 albertel 4898: if (!$args->{'one_time'}) {
1.949 raeburn 4899: &appenv(\%envhash);
1.731 albertel 4900: }
1.302 albertel 4901: return %returnhash;
1.461 www 4902: }
4903:
1.1080 raeburn 4904: sub update_released_required {
4905: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4906: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4907: $cid = $env{'request.course.id'};
4908: $cdom = $env{'course.'.$cid.'.domain'};
4909: $cnum = $env{'course.'.$cid.'.num'};
4910: $chome = $env{'course.'.$cid.'.home'};
4911: }
4912: if ($needsrelease) {
4913: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4914: my $needsupdate;
4915: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4916: $needsupdate = 1;
4917: } else {
4918: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4919: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4920: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4921: $needsupdate = 1;
4922: }
4923: }
4924: if ($needsupdate) {
4925: my %needshash = (
4926: 'internal.releaserequired' => $needsrelease,
4927: );
4928: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4929: if ($putresult eq 'ok') {
4930: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4931: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4932: if (ref($crsinfo{$cid}) eq 'HASH') {
4933: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4934: &courseidput($cdom,\%crsinfo,$chome,'notime');
4935: }
4936: }
4937: }
4938: }
4939: return;
4940: }
4941:
1.461 www 4942: # -------------------------------------------------See if a user is privileged
4943:
4944: sub privileged {
1.1219 raeburn 4945: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 4946: my $now = time;
1.1219 raeburn 4947: my $roles;
4948: if (ref($possroles) eq 'ARRAY') {
4949: $roles = $possroles;
4950: } else {
4951: $roles = ['dc','su'];
4952: }
4953: if (ref($possdomains) eq 'ARRAY') {
4954: my %privileged = &privileged_by_domain($possdomains,$roles);
4955: foreach my $dom (@{$possdomains}) {
4956: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
4957: (ref($privileged{$dom}) eq 'HASH')) {
4958: foreach my $role (@{$roles}) {
4959: if (ref($privileged{$dom}{$role}) eq 'HASH') {
4960: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
4961: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
4962: return 1 unless (($end && $end < $now) ||
4963: ($start && $start > $now));
4964: }
4965: }
4966: }
4967: }
4968: }
4969: } else {
4970: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4971: my $now = time;
1.1170 droeschl 4972:
1.1219 raeburn 4973: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 4974: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 4975: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 4976: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 4977: or ($tstart && $tstart > $now);
1.1170 droeschl 4978: }
1.1219 raeburn 4979: }
4980: }
4981: return 0;
4982: }
1.1170 droeschl 4983:
1.1219 raeburn 4984: sub privileged_by_domain {
4985: my ($domains,$roles) = @_;
4986: my %privileged = ();
4987: my $cachetime = 60*60*24;
4988: my $now = time;
4989: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
4990: return %privileged;
4991: }
4992: foreach my $dom (@{$domains}) {
4993: next if (ref($privileged{$dom}) eq 'HASH');
4994: my $needroles;
4995: foreach my $role (@{$roles}) {
4996: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
4997: if (defined($cached)) {
4998: if (ref($result) eq 'HASH') {
4999: $privileged{$dom}{$role} = $result;
5000: }
5001: } else {
5002: $needroles = 1;
5003: }
5004: }
5005: if ($needroles) {
5006: my %dompersonnel = &get_domain_roles($dom,$roles);
5007: $privileged{$dom} = {};
5008: foreach my $server (keys(%dompersonnel)) {
5009: if (ref($dompersonnel{$server}) eq 'HASH') {
5010: foreach my $item (keys(%{$dompersonnel{$server}})) {
5011: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5012: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5013: next if ($end && $end < $now);
5014: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5015: $dompersonnel{$server}{$item};
5016: }
5017: }
5018: }
5019: if (ref($privileged{$dom}) eq 'HASH') {
5020: foreach my $role (@{$roles}) {
5021: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5022: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5023: } else {
5024: my %hash = ();
5025: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5026: }
5027: }
5028: }
5029: }
5030: }
5031: return %privileged;
1.9 www 5032: }
1.1 albertel 5033:
1.103 harris41 5034: # -------------------------------------------------------- Get user privileges
1.11 www 5035:
5036: sub rolesinit {
1.1169 droeschl 5037: my ($domain, $username) = @_;
5038: my %userroles = ('user.login.time' => time);
5039: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5040:
5041: # firstaccess and timerinterval are related to timed maps/resources.
5042: # also, blocking can be triggered by an activating timer
5043: # it's saved in the user's %env.
5044: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5045: my %timerinterval = &dump('timerinterval', $domain, $username);
5046: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5047: %timerintchk, %timerintenv);
5048:
1.1162 raeburn 5049: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5050: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5051: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5052: }
1.1169 droeschl 5053:
1.1162 raeburn 5054: foreach my $key (keys(%timerinterval)) {
5055: my ($cid,$rest) = split(/\0/,$key);
5056: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5057: }
1.1169 droeschl 5058:
1.11 www 5059: my %allroles=();
1.1162 raeburn 5060: my %allgroups=();
1.11 www 5061:
1.1169 droeschl 5062: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5063: my $role = $rolesdump{$area};
5064: $area =~ s/\_\w\w$//;
5065:
5066: my ($trole, $tend, $tstart, $group_privs);
5067:
5068: if ($role =~ /^cr/) {
5069: # Custom role, defined by a user
5070: # e.g., user.role.cr/msu/smith/mynewrole
5071: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5072: $trole = $1;
5073: ($tend, $tstart) = split('_', $2);
5074: } else {
5075: $trole = $role;
5076: }
5077: } elsif ($role =~ m|^gr/|) {
5078: # Role of member in a group, defined within a course/community
5079: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5080: ($trole, $tend, $tstart) = split(/_/, $role);
5081: next if $tstart eq '-1';
5082: ($trole, $group_privs) = split(/\//, $trole);
5083: $group_privs = &unescape($group_privs);
5084: } else {
5085: # Just a normal role, defined in roles.tab
5086: ($trole, $tend, $tstart) = split(/_/,$role);
5087: }
5088:
5089: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5090: $username);
5091: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5092:
5093: # role expired or not available yet?
5094: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5095: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5096:
5097: next if $area eq '' or $trole eq '';
5098:
5099: my $spec = "$trole.$area";
5100: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5101:
5102: if ($trole =~ /^cr\//) {
5103: # Custom role, defined by a user
5104: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5105: } elsif ($trole eq 'gr') {
5106: # Role of a member in a group, defined within a course/community
5107: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5108: next;
5109: } else {
5110: # Normal role, defined in roles.tab
5111: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5112: }
5113:
5114: my $cid = $tdomain.'_'.$trest;
5115: unless ($firstaccchk{$cid}) {
5116: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5117: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5118: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5119: $coursetimerstarts{$cid}{$item};
5120: }
5121: }
5122: $firstaccchk{$cid} = 1;
5123: }
5124: unless ($timerintchk{$cid}) {
5125: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5126: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5127: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5128: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5129: }
1.12 www 5130: }
1.1169 droeschl 5131: $timerintchk{$cid} = 1;
1.191 harris41 5132: }
1.11 www 5133: }
1.1169 droeschl 5134:
5135: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5136: \%allroles, \%allgroups);
5137: $env{'user.adv'} = $userroles{'user.adv'};
5138:
1.1162 raeburn 5139: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5140: }
5141:
1.567 raeburn 5142: sub set_arearole {
1.1215 raeburn 5143: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5144: unless ($nolog) {
1.567 raeburn 5145: # log the associated role with the area
1.1215 raeburn 5146: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5147: }
1.743 albertel 5148: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5149: }
5150:
5151: sub custom_roleprivs {
5152: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5153: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5154: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 5155: if (&hostname($homsvr) ne '') {
1.567 raeburn 5156: my ($rdummy,$roledef)=
5157: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5158: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5159: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5160: if (defined($syspriv)) {
1.1043 raeburn 5161: if ($trest =~ /^$match_community$/) {
5162: $syspriv =~ s/bre\&S//;
5163: }
1.567 raeburn 5164: $$allroles{'cm./'}.=':'.$syspriv;
5165: $$allroles{$spec.'./'}.=':'.$syspriv;
5166: }
5167: if ($tdomain ne '') {
5168: if (defined($dompriv)) {
5169: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5170: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5171: }
5172: if (($trest ne '') && (defined($coursepriv))) {
5173: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5174: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5175: }
5176: }
5177: }
5178: }
5179: }
5180:
1.678 raeburn 5181: sub group_roleprivs {
5182: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5183: my $access = 1;
5184: my $now = time;
5185: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5186: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5187: if ($access) {
1.811 albertel 5188: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5189: $$allgroups{$course}{$group} .=':'.$group_privs;
5190: }
5191: }
1.567 raeburn 5192:
5193: sub standard_roleprivs {
5194: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5195: if (defined($pr{$trole.':s'})) {
5196: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5197: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5198: }
5199: if ($tdomain ne '') {
5200: if (defined($pr{$trole.':d'})) {
5201: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5202: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5203: }
5204: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5205: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5206: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5207: }
5208: }
5209: }
5210:
5211: sub set_userprivs {
1.1064 raeburn 5212: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5213: my $author=0;
5214: my $adv=0;
1.678 raeburn 5215: my %grouproles = ();
5216: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5217: my @groupkeys;
1.1000 raeburn 5218: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5219: push(@groupkeys,$role);
5220: }
5221: if (ref($groups_roles) eq 'HASH') {
5222: foreach my $key (keys(%{$groups_roles})) {
5223: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5224: push(@groupkeys,$key);
5225: }
5226: }
5227: }
5228: if (@groupkeys > 0) {
5229: foreach my $role (@groupkeys) {
5230: my ($trole,$area,$sec,$extendedarea);
5231: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5232: $trole = $1;
5233: $area = $2;
5234: $sec = $3;
5235: $extendedarea = $area.$sec;
5236: if (exists($$allgroups{$area})) {
5237: foreach my $group (keys(%{$$allgroups{$area}})) {
5238: my $spec = $trole.'.'.$extendedarea;
5239: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5240: $$allgroups{$area}{$group};
1.1064 raeburn 5241: }
1.678 raeburn 5242: }
5243: }
5244: }
5245: }
5246: }
1.800 albertel 5247: foreach my $group (keys(%grouproles)) {
5248: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5249: }
1.800 albertel 5250: foreach my $role (keys(%{$allroles})) {
5251: my %thesepriv;
1.941 raeburn 5252: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5253: foreach my $item (split(/:/,$$allroles{$role})) {
5254: if ($item ne '') {
5255: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5256: if ($restrictions eq '') {
5257: $thesepriv{$privilege}='F';
5258: } elsif ($thesepriv{$privilege} ne 'F') {
5259: $thesepriv{$privilege}.=$restrictions;
5260: }
5261: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5262: }
5263: }
5264: my $thesestr='';
1.1104 raeburn 5265: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5266: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5267: }
5268: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5269: }
5270: return ($author,$adv);
5271: }
5272:
1.994 raeburn 5273: sub role_status {
1.1104 raeburn 5274: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5275: my @pwhere = ();
5276: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5277: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5278: unless (!defined($$role) || $$role eq '') {
5279: $$where=join('.',@pwhere);
5280: $$trolecode=$$role.'.'.$$where;
5281: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5282: $$tstatus='is';
1.1104 raeburn 5283: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5284: $$tstatus='future';
1.1034 raeburn 5285: if ($$tstart<$now) {
5286: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5287: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5288: my (%allroles,%allgroups,$group_privs,
5289: %groups_roles,@rolecodes);
1.1002 raeburn 5290: my %userroles = (
5291: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5292: );
1.1064 raeburn 5293: @rolecodes = ('cm');
1.1002 raeburn 5294: my $spec=$$role.'.'.$$where;
5295: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5296: if ($$role =~ /^cr\//) {
5297: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5298: push(@rolecodes,'cr');
1.1002 raeburn 5299: } elsif ($$role eq 'gr') {
1.1064 raeburn 5300: push(@rolecodes,$$role);
1.1002 raeburn 5301: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5302: $env{'user.name'});
1.1064 raeburn 5303: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5304: (undef,my $group_privs) = split(/\//,$trole);
5305: $group_privs = &unescape($group_privs);
5306: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5307: 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 5308: &get_groups_roles($tdomain,$trest,
5309: \%course_roles,\@rolecodes,
5310: \%groups_roles);
1.1002 raeburn 5311: } else {
1.1064 raeburn 5312: push(@rolecodes,$$role);
1.1002 raeburn 5313: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5314: }
1.1064 raeburn 5315: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5316: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5317: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5318: }
5319: }
1.1034 raeburn 5320: $$tstatus = 'is';
1.1002 raeburn 5321: }
1.994 raeburn 5322: }
5323: if ($$tend) {
1.1104 raeburn 5324: if ($$tend<$update) {
1.994 raeburn 5325: $$tstatus='expired';
5326: } elsif ($$tend<$now) {
5327: $$tstatus='will_not';
5328: }
5329: }
5330: }
5331: }
5332: }
5333:
1.1104 raeburn 5334: sub get_groups_roles {
5335: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5336: return unless((ref($cdom_courseroles) eq 'HASH') &&
5337: (ref($rolecodes) eq 'ARRAY') &&
5338: (ref($groups_roles) eq 'HASH'));
5339: if (keys(%{$cdom_courseroles}) > 0) {
5340: my ($cnum) = ($rest =~ /^($match_courseid)/);
5341: if ($cdom ne '' && $cnum ne '') {
5342: foreach my $key (keys(%{$cdom_courseroles})) {
5343: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5344: my $crsrole = $1;
5345: my $crssec = $2;
5346: if ($crsrole =~ /^cr/) {
5347: unless (grep(/^cr$/,@{$rolecodes})) {
5348: push(@{$rolecodes},'cr');
5349: }
5350: } else {
5351: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5352: push(@{$rolecodes},$crsrole);
5353: }
5354: }
5355: my $rolekey = "$crsrole./$cdom/$cnum";
5356: if ($crssec ne '') {
5357: $rolekey .= "/$crssec";
5358: }
5359: $rolekey .= './';
5360: $groups_roles->{$rolekey} = $rolecodes;
5361: }
5362: }
5363: }
5364: }
5365: return;
5366: }
5367:
5368: sub delete_env_groupprivs {
5369: my ($where,$courseroles,$possroles) = @_;
5370: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5371: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5372: unless (ref($courseroles->{$udom}) eq 'HASH') {
5373: %{$courseroles->{$udom}} =
5374: &get_my_roles('','','userroles',['active'],
5375: $possroles,[$udom],1);
5376: }
5377: if (ref($courseroles->{$udom}) eq 'HASH') {
5378: foreach my $item (keys(%{$courseroles->{$udom}})) {
5379: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5380: my $area = '/'.$cdom.'/'.$cnum;
5381: my $privkey = "user.priv.$crsrole.$area";
5382: if ($crssec ne '') {
5383: $privkey .= '/'.$crssec;
5384: }
5385: $privkey .= ".$area/$group";
5386: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5387: }
5388: }
5389: return;
5390: }
5391:
1.994 raeburn 5392: sub check_adhoc_privs {
1.1104 raeburn 5393: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5394: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5395: my $setprivs;
1.994 raeburn 5396: if ($env{$cckey}) {
5397: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5398: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5399: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5400: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5401: $setprivs = 1;
1.994 raeburn 5402: }
5403: } else {
1.1088 raeburn 5404: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5405: $setprivs = 1;
1.994 raeburn 5406: }
1.1185 raeburn 5407: return $setprivs;
1.994 raeburn 5408: }
5409:
5410: sub set_adhoc_privileges {
5411: # role can be cc or ca
1.1088 raeburn 5412: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5413: my $area = '/'.$dcdom.'/'.$pickedcourse;
5414: my $spec = $role.'.'.$area;
5415: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5416: $env{'user.name'},1);
1.994 raeburn 5417: my %ccrole = ();
5418: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5419: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5420: &appenv(\%userroles,[$role,'cm']);
5421: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5422: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5423: &appenv( {'request.role' => $spec,
5424: 'request.role.domain' => $dcdom,
5425: 'request.course.sec' => ''
5426: }
5427: );
5428: my $tadv=0;
5429: if (&allowed('adv') eq 'F') { $tadv=1; }
5430: &appenv({'request.role.adv' => $tadv});
5431: }
1.994 raeburn 5432: }
5433:
1.12 www 5434: # --------------------------------------------------------------- get interface
5435:
5436: sub get {
1.131 albertel 5437: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5438: my $items='';
1.800 albertel 5439: foreach my $item (@$storearr) {
5440: $items.=&escape($item).'&';
1.191 harris41 5441: }
1.12 www 5442: $items=~s/\&$//;
1.620 albertel 5443: if (!$udomain) { $udomain=$env{'user.domain'}; }
5444: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5445: my $uhome=&homeserver($uname,$udomain);
5446:
1.133 albertel 5447: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5448: my @pairs=split(/\&/,$rep);
1.273 albertel 5449: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5450: return @pairs;
5451: }
1.15 www 5452: my %returnhash=();
1.42 www 5453: my $i=0;
1.800 albertel 5454: foreach my $item (@$storearr) {
5455: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5456: $i++;
1.191 harris41 5457: }
1.15 www 5458: return %returnhash;
1.27 www 5459: }
5460:
5461: # --------------------------------------------------------------- del interface
5462:
5463: sub del {
1.133 albertel 5464: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5465: my $items='';
1.800 albertel 5466: foreach my $item (@$storearr) {
5467: $items.=&escape($item).'&';
1.191 harris41 5468: }
1.984 neumanie 5469:
1.27 www 5470: $items=~s/\&$//;
1.620 albertel 5471: if (!$udomain) { $udomain=$env{'user.domain'}; }
5472: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5473: my $uhome=&homeserver($uname,$udomain);
5474: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5475: }
5476:
5477: # -------------------------------------------------------------- dump interface
5478:
1.1180 droeschl 5479: sub unserialize {
5480: my ($rep, $escapedkeys) = @_;
5481:
5482: return {} if $rep =~ /^error/;
5483:
5484: my %returnhash=();
5485: foreach my $item (split /\&/, $rep) {
5486: my ($key, $value) = split(/=/, $item, 2);
5487: $key = unescape($key) unless $escapedkeys;
5488: next if $key =~ /^error: 2 /;
5489: $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
5490: }
5491: #return %returnhash;
5492: return \%returnhash;
5493: }
5494:
5495: # see Lond::dump_with_regexp
5496: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5497: sub dump {
1.1180 droeschl 5498: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5499: if (!$udomain) { $udomain=$env{'user.domain'}; }
5500: if (!$uname) { $uname=$env{'user.name'}; }
5501: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5502:
1.1180 droeschl 5503: my $reply;
5504: if (grep { $_ eq $uhome } current_machine_ids()) {
5505: # user is hosted on this machine
5506: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5507: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5508: return %{unserialize($reply, $escapedkeys)};
5509: }
1.755 albertel 5510: if ($regexp) {
5511: $regexp=&escape($regexp);
5512: } else {
5513: $regexp='.';
5514: }
1.1166 raeburn 5515: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5516: my @pairs=split(/\&/,$rep);
5517: my %returnhash=();
1.1098 foxr 5518: if (!($rep =~ /^error/ )) {
5519: foreach my $item (@pairs) {
5520: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5521: $key = unescape($key) unless $escapedkeys;
5522: #$key = &unescape($key);
1.1098 foxr 5523: next if ($key =~ /^error: 2 /);
5524: $returnhash{$key}=&thaw_unescape($value);
5525: }
1.755 albertel 5526: }
5527: return %returnhash;
1.407 www 5528: }
5529:
1.1098 foxr 5530:
1.717 albertel 5531: # --------------------------------------------------------- dumpstore interface
5532:
5533: sub dumpstore {
5534: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5535: # same as dump but keys must be escaped. They may contain colon separated
5536: # lists of values that may themself contain colons (e.g. symbs).
5537: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5538: }
5539:
1.407 www 5540: # -------------------------------------------------------------- keys interface
5541:
5542: sub getkeys {
5543: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5544: if (!$udomain) { $udomain=$env{'user.domain'}; }
5545: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5546: my $uhome=&homeserver($uname,$udomain);
5547: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5548: my @keyarray=();
1.800 albertel 5549: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5550: next if ($key =~ /^error: 2 /);
1.800 albertel 5551: push(@keyarray,&unescape($key));
1.407 www 5552: }
5553: return @keyarray;
1.318 matthew 5554: }
5555:
1.319 matthew 5556: # --------------------------------------------------------------- currentdump
5557: sub currentdump {
1.328 matthew 5558: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5559: $courseid = $env{'request.course.id'} if (! defined($courseid));
5560: $sdom = $env{'user.domain'} if (! defined($sdom));
5561: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5562: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5563: my $rep;
5564:
5565: if (grep { $_ eq $uhome } current_machine_ids()) {
5566: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5567: $courseid)));
5568: } else {
5569: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5570: }
5571:
1.318 matthew 5572: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5573: #
1.318 matthew 5574: my %returnhash=();
1.319 matthew 5575: #
5576: if ($rep eq "unknown_cmd") {
5577: # an old lond will not know currentdump
5578: # Do a dump and make it look like a currentdump
1.822 albertel 5579: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5580: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5581: my %hash = @tmp;
5582: @tmp=();
1.424 matthew 5583: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5584: } else {
5585: my @pairs=split(/\&/,$rep);
1.800 albertel 5586: foreach my $pair (@pairs) {
5587: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5588: my ($symb,$param) = split(/:/,$key);
5589: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5590: &thaw_unescape($value);
1.319 matthew 5591: }
1.191 harris41 5592: }
1.12 www 5593: return %returnhash;
1.424 matthew 5594: }
5595:
5596: sub convert_dump_to_currentdump{
5597: my %hash = %{shift()};
5598: my %returnhash;
5599: # Code ripped from lond, essentially. The only difference
5600: # here is the unescaping done by lonnet::dump(). Conceivably
5601: # we might run in to problems with parameter names =~ /^v\./
5602: while (my ($key,$value) = each(%hash)) {
5603: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5604: $symb = &unescape($symb);
5605: $param = &unescape($param);
1.424 matthew 5606: next if ($v eq 'version' || $symb eq 'keys');
5607: next if (exists($returnhash{$symb}) &&
5608: exists($returnhash{$symb}->{$param}) &&
5609: $returnhash{$symb}->{'v.'.$param} > $v);
5610: $returnhash{$symb}->{$param}=$value;
5611: $returnhash{$symb}->{'v.'.$param}=$v;
5612: }
5613: #
5614: # Remove all of the keys in the hashes which keep track of
5615: # the version of the parameter.
5616: while (my ($symb,$param_hash) = each(%returnhash)) {
5617: # use a foreach because we are going to delete from the hash.
5618: foreach my $key (keys(%$param_hash)) {
5619: delete($param_hash->{$key}) if ($key =~ /^v\./);
5620: }
5621: }
5622: return \%returnhash;
1.12 www 5623: }
5624:
1.627 albertel 5625: # ------------------------------------------------------ critical inc interface
5626:
5627: sub cinc {
5628: return &inc(@_,'critical');
5629: }
5630:
1.449 matthew 5631: # --------------------------------------------------------------- inc interface
5632:
5633: sub inc {
1.627 albertel 5634: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5635: if (!$udomain) { $udomain=$env{'user.domain'}; }
5636: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5637: my $uhome=&homeserver($uname,$udomain);
5638: my $items='';
5639: if (! ref($store)) {
5640: # got a single value, so use that instead
5641: $items = &escape($store).'=&';
5642: } elsif (ref($store) eq 'SCALAR') {
5643: $items = &escape($$store).'=&';
5644: } elsif (ref($store) eq 'ARRAY') {
5645: $items = join('=&',map {&escape($_);} @{$store});
5646: } elsif (ref($store) eq 'HASH') {
5647: while (my($key,$value) = each(%{$store})) {
5648: $items.= &escape($key).'='.&escape($value).'&';
5649: }
5650: }
5651: $items=~s/\&$//;
1.627 albertel 5652: if ($critical) {
5653: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5654: } else {
5655: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5656: }
1.449 matthew 5657: }
5658:
1.12 www 5659: # --------------------------------------------------------------- put interface
5660:
5661: sub put {
1.134 albertel 5662: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5663: if (!$udomain) { $udomain=$env{'user.domain'}; }
5664: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5665: my $uhome=&homeserver($uname,$udomain);
1.12 www 5666: my $items='';
1.800 albertel 5667: foreach my $item (keys(%$storehash)) {
5668: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5669: }
1.12 www 5670: $items=~s/\&$//;
1.134 albertel 5671: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5672: }
5673:
1.631 albertel 5674: # ------------------------------------------------------------ newput interface
5675:
5676: sub newput {
5677: my ($namespace,$storehash,$udomain,$uname)=@_;
5678: if (!$udomain) { $udomain=$env{'user.domain'}; }
5679: if (!$uname) { $uname=$env{'user.name'}; }
5680: my $uhome=&homeserver($uname,$udomain);
5681: my $items='';
5682: foreach my $key (keys(%$storehash)) {
5683: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5684: }
5685: $items=~s/\&$//;
5686: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5687: }
5688:
5689: # --------------------------------------------------------- putstore interface
5690:
1.524 raeburn 5691: sub putstore {
1.715 albertel 5692: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5693: if (!$udomain) { $udomain=$env{'user.domain'}; }
5694: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5695: my $uhome=&homeserver($uname,$udomain);
5696: my $items='';
1.715 albertel 5697: foreach my $key (keys(%$storehash)) {
5698: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5699: }
1.715 albertel 5700: $items=~s/\&$//;
1.716 albertel 5701: my $esc_symb=&escape($symb);
5702: my $esc_v=&escape($version);
1.715 albertel 5703: my $reply =
1.716 albertel 5704: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5705: $uhome);
5706: if ($reply eq 'unknown_cmd') {
1.716 albertel 5707: # gfall back to way things use to be done
1.715 albertel 5708: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5709: $uname);
1.524 raeburn 5710: }
1.715 albertel 5711: return $reply;
5712: }
5713:
5714: sub old_putstore {
1.716 albertel 5715: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5716: if (!$udomain) { $udomain=$env{'user.domain'}; }
5717: if (!$uname) { $uname=$env{'user.name'}; }
5718: my $uhome=&homeserver($uname,$udomain);
5719: my %newstorehash;
1.800 albertel 5720: foreach my $item (keys(%$storehash)) {
5721: my $key = $version.':'.&escape($symb).':'.$item;
5722: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5723: }
5724: my $items='';
5725: my %allitems = ();
1.800 albertel 5726: foreach my $item (keys(%newstorehash)) {
5727: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5728: my $key = $1.':keys:'.$2;
5729: $allitems{$key} .= $3.':';
5730: }
1.800 albertel 5731: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5732: }
1.800 albertel 5733: foreach my $item (keys(%allitems)) {
5734: $allitems{$item} =~ s/\:$//;
5735: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5736: }
5737: $items=~s/\&$//;
5738: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5739: }
5740:
1.47 www 5741: # ------------------------------------------------------ critical put interface
5742:
5743: sub cput {
1.134 albertel 5744: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5745: if (!$udomain) { $udomain=$env{'user.domain'}; }
5746: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5747: my $uhome=&homeserver($uname,$udomain);
1.47 www 5748: my $items='';
1.800 albertel 5749: foreach my $item (keys(%$storehash)) {
5750: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5751: }
1.47 www 5752: $items=~s/\&$//;
1.134 albertel 5753: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5754: }
5755:
5756: # -------------------------------------------------------------- eget interface
5757:
5758: sub eget {
1.133 albertel 5759: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5760: my $items='';
1.800 albertel 5761: foreach my $item (@$storearr) {
5762: $items.=&escape($item).'&';
1.191 harris41 5763: }
1.12 www 5764: $items=~s/\&$//;
1.620 albertel 5765: if (!$udomain) { $udomain=$env{'user.domain'}; }
5766: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5767: my $uhome=&homeserver($uname,$udomain);
5768: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5769: my @pairs=split(/\&/,$rep);
5770: my %returnhash=();
1.42 www 5771: my $i=0;
1.800 albertel 5772: foreach my $item (@$storearr) {
5773: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5774: $i++;
1.191 harris41 5775: }
1.12 www 5776: return %returnhash;
5777: }
5778:
1.667 albertel 5779: # ------------------------------------------------------------ tmpput interface
5780: sub tmpput {
1.802 raeburn 5781: my ($storehash,$server,$context)=@_;
1.667 albertel 5782: my $items='';
1.800 albertel 5783: foreach my $item (keys(%$storehash)) {
5784: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5785: }
5786: $items=~s/\&$//;
1.802 raeburn 5787: if (defined($context)) {
5788: $items .= ':'.&escape($context);
5789: }
1.667 albertel 5790: return &reply("tmpput:$items",$server);
5791: }
5792:
5793: # ------------------------------------------------------------ tmpget interface
5794: sub tmpget {
1.688 albertel 5795: my ($token,$server)=@_;
5796: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5797: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5798: my %returnhash;
5799: foreach my $item (split(/\&/,$rep)) {
5800: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5801: next if ($key =~ /^error: 2 /);
1.667 albertel 5802: $returnhash{&unescape($key)}=&thaw_unescape($value);
5803: }
5804: return %returnhash;
5805: }
5806:
1.1113 raeburn 5807: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5808: sub tmpdel {
5809: my ($token,$server)=@_;
5810: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5811: return &reply("tmpdel:$token",$server);
5812: }
5813:
1.1198 raeburn 5814: # ------------------------------------------------------------ get_timebased_id
5815:
5816: sub get_timebased_id {
5817: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5818: $maxtries) = @_;
5819: my ($newid,$error,$dellock);
5820: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5821: return ('','ok','invalid call to get suffix');
5822: }
5823:
5824: # set defaults for any optional args for which values were not supplied
5825: if ($who eq '') {
5826: $who = $env{'user.name'}.':'.$env{'user.domain'};
5827: }
5828: if (!$locktries) {
5829: $locktries = 3;
5830: }
5831: if (!$maxtries) {
5832: $maxtries = 10;
5833: }
5834:
5835: if (($cdom eq '') || ($cnum eq '')) {
5836: if ($env{'request.course.id'}) {
5837: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5838: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5839: }
5840: if (($cdom eq '') || ($cnum eq '')) {
5841: return ('','ok','call to get suffix not in course context');
5842: }
5843: }
5844:
5845: # construct locking item
5846: my $lockhash = {
5847: $prefix."\0".'locked_'.$keyid => $who,
5848: };
5849: my $tries = 0;
5850:
5851: # attempt to get lock on nohist_$namespace file
5852: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5853: while (($gotlock ne 'ok') && $tries <$locktries) {
5854: $tries ++;
5855: sleep 1;
5856: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5857: }
5858:
5859: # attempt to get unique identifier, based on current timestamp
5860: if ($gotlock eq 'ok') {
5861: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5862: my $id = time;
5863: $newid = $id;
5864: my $idtries = 0;
5865: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5866: if ($idtype eq 'concat') {
5867: $newid = $id.$idtries;
5868: } else {
5869: $newid ++;
5870: }
5871: $idtries ++;
5872: }
5873: if (!exists($inuse{$prefix."\0".$newid})) {
5874: my %new_item = (
5875: $prefix."\0".$newid => $who,
5876: );
5877: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5878: $cdom,$cnum);
5879: if ($putresult ne 'ok') {
5880: undef($newid);
5881: $error = 'error saving new item: '.$putresult;
5882: }
5883: } else {
5884: $error = ('error: no unique suffix available for the new item ');
5885: }
5886: # remove lock
5887: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5888: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5889: } else {
5890: $error = "error: could not obtain lockfile\n";
5891: $dellock = 'ok';
5892: }
5893: return ($newid,$dellock,$error);
5894: }
5895:
1.765 albertel 5896: # -------------------------------------------------- portfolio access checking
5897:
5898: sub portfolio_access {
1.766 albertel 5899: my ($requrl) = @_;
1.765 albertel 5900: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5901: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5902: if ($result) {
5903: my %setters;
5904: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5905: my ($startblock,$endblock) =
5906: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5907: if ($startblock && $endblock) {
5908: return 'B';
5909: }
5910: } else {
5911: my ($startblock,$endblock) =
5912: &Apache::loncommon::blockcheck(\%setters,'port');
5913: if ($startblock && $endblock) {
5914: return 'B';
5915: }
5916: }
5917: }
1.765 albertel 5918: if ($result eq 'ok') {
1.766 albertel 5919: return 'F';
1.765 albertel 5920: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5921: return 'A';
1.765 albertel 5922: }
1.766 albertel 5923: return '';
1.765 albertel 5924: }
5925:
5926: sub get_portfolio_access {
1.767 albertel 5927: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5928:
5929: if (!ref($access_hash)) {
5930: my $current_perms = &get_portfile_permissions($udom,$unum);
5931: my %access_controls = &get_access_controls($current_perms,$group,
5932: $file_name);
5933: $access_hash = $access_controls{$file_name};
5934: }
5935:
1.765 albertel 5936: my ($public,$guest,@domains,@users,@courses,@groups);
5937: my $now = time;
5938: if (ref($access_hash) eq 'HASH') {
5939: foreach my $key (keys(%{$access_hash})) {
5940: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5941: if ($start > $now) {
5942: next;
5943: }
5944: if ($end && $end<$now) {
5945: next;
5946: }
5947: if ($scope eq 'public') {
5948: $public = $key;
5949: last;
5950: } elsif ($scope eq 'guest') {
5951: $guest = $key;
5952: } elsif ($scope eq 'domains') {
5953: push(@domains,$key);
5954: } elsif ($scope eq 'users') {
5955: push(@users,$key);
5956: } elsif ($scope eq 'course') {
5957: push(@courses,$key);
5958: } elsif ($scope eq 'group') {
5959: push(@groups,$key);
5960: }
5961: }
5962: if ($public) {
5963: return 'ok';
5964: }
5965: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5966: if ($guest) {
5967: return $guest;
5968: }
5969: } else {
5970: if (@domains > 0) {
5971: foreach my $domkey (@domains) {
5972: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5973: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5974: return 'ok';
5975: }
5976: }
5977: }
5978: }
5979: if (@users > 0) {
5980: foreach my $userkey (@users) {
1.865 raeburn 5981: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5982: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5983: if (ref($item) eq 'HASH') {
5984: if (($item->{'uname'} eq $env{'user.name'}) &&
5985: ($item->{'udom'} eq $env{'user.domain'})) {
5986: return 'ok';
5987: }
5988: }
5989: }
5990: }
1.765 albertel 5991: }
5992: }
5993: my %roleshash;
5994: my @courses_and_groups = @courses;
5995: push(@courses_and_groups,@groups);
5996: if (@courses_and_groups > 0) {
5997: my (%allgroups,%allroles);
5998: my ($start,$end,$role,$sec,$group);
5999: foreach my $envkey (%env) {
1.1060 raeburn 6000: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6001: my $cid = $2.'_'.$3;
6002: if ($1 eq 'gr') {
6003: $group = $4;
6004: $allgroups{$cid}{$group} = $env{$envkey};
6005: } else {
6006: if ($4 eq '') {
6007: $sec = 'none';
6008: } else {
6009: $sec = $4;
6010: }
6011: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6012: }
1.811 albertel 6013: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6014: my $cid = $2.'_'.$3;
6015: if ($4 eq '') {
6016: $sec = 'none';
6017: } else {
6018: $sec = $4;
6019: }
6020: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6021: }
6022: }
6023: if (keys(%allroles) == 0) {
6024: return;
6025: }
6026: foreach my $key (@courses_and_groups) {
6027: my %content = %{$$access_hash{$key}};
6028: my $cnum = $content{'number'};
6029: my $cdom = $content{'domain'};
6030: my $cid = $cdom.'_'.$cnum;
6031: if (!exists($allroles{$cid})) {
6032: next;
6033: }
6034: foreach my $role_id (keys(%{$content{'roles'}})) {
6035: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6036: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6037: my @status = @{$content{'roles'}{$role_id}{'access'}};
6038: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6039: foreach my $role (keys(%{$allroles{$cid}})) {
6040: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6041: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6042: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6043: if (grep/^all$/,@sections) {
6044: return 'ok';
6045: } else {
6046: if (grep/^$sec$/,@sections) {
6047: return 'ok';
6048: }
6049: }
6050: }
6051: }
6052: if (keys(%{$allgroups{$cid}}) == 0) {
6053: if (grep/^none$/,@groups) {
6054: return 'ok';
6055: }
6056: } else {
6057: if (grep/^all$/,@groups) {
6058: return 'ok';
6059: }
6060: foreach my $group (keys(%{$allgroups{$cid}})) {
6061: if (grep/^$group$/,@groups) {
6062: return 'ok';
6063: }
6064: }
6065: }
6066: }
6067: }
6068: }
6069: }
6070: }
6071: if ($guest) {
6072: return $guest;
6073: }
6074: }
6075: }
6076: return;
6077: }
6078:
6079: sub course_group_datechecker {
6080: my ($dates,$now,$status) = @_;
6081: my ($start,$end) = split(/\./,$dates);
6082: if (!$start && !$end) {
6083: return 'ok';
6084: }
6085: if (grep/^active$/,@{$status}) {
6086: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6087: return 'ok';
6088: }
6089: }
6090: if (grep/^previous$/,@{$status}) {
6091: if ($end > $now ) {
6092: return 'ok';
6093: }
6094: }
6095: if (grep/^future$/,@{$status}) {
6096: if ($start > $now) {
6097: return 'ok';
6098: }
6099: }
6100: return;
6101: }
6102:
6103: sub parse_portfolio_url {
6104: my ($url) = @_;
6105:
6106: my ($type,$udom,$unum,$group,$file_name);
6107:
1.823 albertel 6108: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6109: $type = 1;
6110: $udom = $1;
6111: $unum = $2;
6112: $file_name = $3;
1.823 albertel 6113: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6114: $type = 2;
6115: $udom = $1;
6116: $unum = $2;
6117: $group = $3;
6118: $file_name = $3.'/'.$4;
6119: }
6120: if (wantarray) {
6121: return ($type,$udom,$unum,$file_name,$group);
6122: }
6123: return $type;
6124: }
6125:
6126: sub is_portfolio_url {
6127: my ($url) = @_;
6128: return scalar(&parse_portfolio_url($url));
6129: }
6130:
1.798 raeburn 6131: sub is_portfolio_file {
6132: my ($file) = @_;
1.820 raeburn 6133: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6134: return 1;
6135: }
6136: return;
6137: }
6138:
1.976 raeburn 6139: sub usertools_access {
1.1084 raeburn 6140: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6141: my ($access,%tools);
6142: if ($context eq '') {
6143: $context = 'tools';
6144: }
6145: if ($context eq 'requestcourses') {
6146: %tools = (
6147: official => 1,
6148: unofficial => 1,
1.1006 raeburn 6149: community => 1,
1.985 raeburn 6150: );
1.1183 raeburn 6151: } elsif ($context eq 'requestauthor') {
6152: %tools = (
6153: requestauthor => 1,
6154: );
1.985 raeburn 6155: } else {
6156: %tools = (
6157: aboutme => 1,
6158: blog => 1,
1.1177 raeburn 6159: webdav => 1,
1.985 raeburn 6160: portfolio => 1,
6161: );
6162: }
1.976 raeburn 6163: return if (!defined($tools{$tool}));
6164:
6165: if ((!defined($udom)) || (!defined($uname))) {
6166: $udom = $env{'user.domain'};
6167: $uname = $env{'user.name'};
6168: }
6169:
1.978 raeburn 6170: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6171: if ($action ne 'reload') {
1.985 raeburn 6172: if ($context eq 'requestcourses') {
6173: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6174: } elsif ($context eq 'requestauthor') {
6175: return $env{'environment.canrequest.author'};
1.985 raeburn 6176: } else {
6177: return $env{'environment.availabletools.'.$tool};
6178: }
6179: }
1.976 raeburn 6180: }
6181:
1.1183 raeburn 6182: my ($toolstatus,$inststatus,$envkey);
6183: if ($context eq 'requestauthor') {
6184: $envkey = $context;
6185: } else {
6186: $envkey = $context.'.'.$tool;
6187: }
1.976 raeburn 6188:
1.985 raeburn 6189: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6190: ($action ne 'reload')) {
1.1183 raeburn 6191: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6192: $inststatus = $env{'environment.inststatus'};
6193: } else {
1.1084 raeburn 6194: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6195: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6196: $inststatus = $userenvref->{'inststatus'};
6197: } else {
1.1183 raeburn 6198: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6199: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6200: $inststatus = $userenv{'inststatus'};
6201: }
1.976 raeburn 6202: }
6203:
6204: if ($toolstatus ne '') {
6205: if ($toolstatus) {
6206: $access = 1;
6207: } else {
6208: $access = 0;
6209: }
6210: return $access;
6211: }
6212:
1.1084 raeburn 6213: my ($is_adv,%domdef);
6214: if (ref($is_advref) eq 'HASH') {
6215: $is_adv = $is_advref->{'is_adv'};
6216: } else {
6217: $is_adv = &is_advanced_user($udom,$uname);
6218: }
6219: if (ref($domdefref) eq 'HASH') {
6220: %domdef = %{$domdefref};
6221: } else {
6222: %domdef = &get_domain_defaults($udom);
6223: }
1.976 raeburn 6224: if (ref($domdef{$tool}) eq 'HASH') {
6225: if ($is_adv) {
6226: if ($domdef{$tool}{'_LC_adv'} ne '') {
6227: if ($domdef{$tool}{'_LC_adv'}) {
6228: $access = 1;
6229: } else {
6230: $access = 0;
6231: }
6232: return $access;
6233: }
6234: }
6235: if ($inststatus ne '') {
6236: my ($hasaccess,$hasnoaccess);
6237: foreach my $affiliation (split(/:/,$inststatus)) {
6238: if ($domdef{$tool}{$affiliation} ne '') {
6239: if ($domdef{$tool}{$affiliation}) {
6240: $hasaccess = 1;
6241: } else {
6242: $hasnoaccess = 1;
6243: }
6244: }
6245: }
6246: if ($hasaccess || $hasnoaccess) {
6247: if ($hasaccess) {
6248: $access = 1;
6249: } elsif ($hasnoaccess) {
6250: $access = 0;
6251: }
6252: return $access;
6253: }
6254: } else {
6255: if ($domdef{$tool}{'default'} ne '') {
6256: if ($domdef{$tool}{'default'}) {
6257: $access = 1;
6258: } elsif ($domdef{$tool}{'default'} == 0) {
6259: $access = 0;
6260: }
6261: return $access;
6262: }
6263: }
6264: } else {
1.1177 raeburn 6265: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6266: $access = 1;
6267: } else {
6268: $access = 0;
6269: }
1.976 raeburn 6270: return $access;
6271: }
6272: }
6273:
1.1050 raeburn 6274: sub is_course_owner {
6275: my ($cdom,$cnum,$udom,$uname) = @_;
6276: if (($udom eq '') || ($uname eq '')) {
6277: $udom = $env{'user.domain'};
6278: $uname = $env{'user.name'};
6279: }
6280: unless (($udom eq '') || ($uname eq '')) {
6281: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6282: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6283: return 1;
6284: } else {
6285: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6286: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6287: return 1;
6288: }
6289: }
6290: }
6291: }
6292: return;
6293: }
6294:
1.976 raeburn 6295: sub is_advanced_user {
6296: my ($udom,$uname) = @_;
1.1085 raeburn 6297: if ($udom ne '' && $uname ne '') {
6298: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6299: if (wantarray) {
6300: return ($env{'user.adv'},$env{'user.author'});
6301: } else {
6302: return $env{'user.adv'};
6303: }
1.1085 raeburn 6304: }
6305: }
1.976 raeburn 6306: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6307: my %allroles;
1.1128 raeburn 6308: my ($is_adv,$is_author);
1.976 raeburn 6309: foreach my $role (keys(%roleshash)) {
6310: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6311: my $area = '/'.$tdomain.'/'.$trest;
6312: if ($sec ne '') {
6313: $area .= '/'.$sec;
6314: }
6315: if (($area ne '') && ($trole ne '')) {
6316: my $spec=$trole.'.'.$area;
6317: if ($trole =~ /^cr\//) {
6318: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6319: } elsif ($trole ne 'gr') {
6320: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6321: }
1.1128 raeburn 6322: if ($trole eq 'au') {
6323: $is_author = 1;
6324: }
1.976 raeburn 6325: }
6326: }
6327: foreach my $role (keys(%allroles)) {
6328: last if ($is_adv);
6329: foreach my $item (split(/:/,$allroles{$role})) {
6330: if ($item ne '') {
6331: my ($privilege,$restrictions)=split(/&/,$item);
6332: if ($privilege eq 'adv') {
6333: $is_adv = 1;
6334: last;
6335: }
6336: }
6337: }
6338: }
1.1128 raeburn 6339: if (wantarray) {
6340: return ($is_adv,$is_author);
6341: }
1.976 raeburn 6342: return $is_adv;
6343: }
1.798 raeburn 6344:
1.1035 raeburn 6345: sub check_can_request {
1.1036 raeburn 6346: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6347: my $canreq = 0;
6348: my ($types,$typename) = &Apache::loncommon::course_types();
6349: my @options = ('approval','validate','autolimit');
6350: my $optregex = join('|',@options);
6351: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6352: foreach my $type (@{$types}) {
6353: if (&usertools_access($env{'user.name'},
6354: $env{'user.domain'},
6355: $type,undef,'requestcourses')) {
6356: $canreq ++;
1.1036 raeburn 6357: if (ref($request_domains) eq 'HASH') {
6358: push(@{$request_domains->{$type}},$env{'user.domain'});
6359: }
1.1035 raeburn 6360: if ($dom eq $env{'user.domain'}) {
6361: $can_request->{$type} = 1;
6362: }
6363: }
6364: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6365: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6366: if (@curr > 0) {
1.1036 raeburn 6367: foreach my $item (@curr) {
6368: if (ref($request_domains) eq 'HASH') {
6369: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6370: if ($otherdom ne '') {
6371: if (ref($request_domains->{$type}) eq 'ARRAY') {
6372: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6373: push(@{$request_domains->{$type}},$otherdom);
6374: }
6375: } else {
6376: push(@{$request_domains->{$type}},$otherdom);
6377: }
6378: }
6379: }
6380: }
6381: unless($dom eq $env{'user.domain'}) {
6382: $canreq ++;
1.1035 raeburn 6383: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6384: $can_request->{$type} = 1;
6385: }
6386: }
6387: }
6388: }
6389: }
6390: }
6391: return $canreq;
6392: }
6393:
1.341 www 6394: # ---------------------------------------------- Custom access rule evaluation
6395:
6396: sub customaccess {
6397: my ($priv,$uri)=@_;
1.807 albertel 6398: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6399: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6400: $udom = &LONCAPA::clean_domain($udom);
6401: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6402: my $access=0;
1.800 albertel 6403: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6404: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6405: if ($type eq 'user') {
6406: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6407: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6408: if ($tdom) {
6409: if ($tdom ne $env{'user.domain'}) { next; }
6410: }
1.896 albertel 6411: if ($tuname) {
6412: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6413: }
6414: $access=($effect eq 'allow');
6415: last;
6416: }
6417: } else {
6418: if ($role) {
6419: if ($role ne $urole) { next; }
6420: }
6421: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6422: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6423: if ($tdom) {
6424: if ($tdom ne $udom) { next; }
6425: }
6426: if ($tcrs) {
6427: if ($tcrs ne $ucrs) { next; }
6428: }
6429: if ($tsec) {
6430: if ($tsec ne $usec) { next; }
6431: }
6432: $access=($effect eq 'allow');
6433: last;
6434: }
6435: if ($realm eq '' && $role eq '') {
6436: $access=($effect eq 'allow');
6437: }
1.402 bowersj2 6438: }
1.341 www 6439: }
6440: return $access;
6441: }
6442:
1.103 harris41 6443: # ------------------------------------------------- Check for a user privilege
1.12 www 6444:
6445: sub allowed {
1.810 raeburn 6446: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6447: my $ver_orguri=$uri;
1.439 www 6448: $uri=&deversion($uri);
1.152 www 6449: my $orguri=$uri;
1.52 www 6450: $uri=&declutter($uri);
1.809 raeburn 6451:
1.810 raeburn 6452: if ($priv eq 'evb') {
6453: # Evade communication block restrictions for specified role in a course
6454: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6455: return $1;
6456: } else {
6457: return;
6458: }
6459: }
6460:
1.620 albertel 6461: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6462: # Free bre access to adm and meta resources
1.775 albertel 6463: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6464: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6465: && ($priv eq 'bre')) {
1.14 www 6466: return 'F';
1.159 www 6467: }
6468:
1.545 banghart 6469: # Free bre access to user's own portfolio contents
1.714 raeburn 6470: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6471: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6472: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6473: my %setters;
6474: my ($startblock,$endblock) =
6475: &Apache::loncommon::blockcheck(\%setters,'port');
6476: if ($startblock && $endblock) {
6477: return 'B';
6478: } else {
6479: return 'F';
6480: }
1.545 banghart 6481: }
6482:
1.762 raeburn 6483: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6484: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6485: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6486: if (exists($env{'request.course.id'})) {
6487: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6488: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6489: if (($domain eq $cdom) && ($name eq $cnum)) {
6490: my $courseprivid=$env{'request.course.id'};
6491: $courseprivid=~s/\_/\//;
6492: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6493: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6494: return $1;
1.762 raeburn 6495: } else {
6496: if ($env{'request.course.sec'}) {
6497: $courseprivid.='/'.$env{'request.course.sec'};
6498: }
6499: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6500: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6501: return $2;
6502: }
1.714 raeburn 6503: }
6504: }
6505: }
6506: }
6507:
1.159 www 6508: # Free bre to public access
6509:
6510: if ($priv eq 'bre') {
1.238 www 6511: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6512: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6513: return 'F';
6514: }
1.238 www 6515: if ($copyright eq 'priv') {
6516: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6517: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6518: return '';
6519: }
6520: }
6521: if ($copyright eq 'domain') {
6522: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6523: unless (($env{'user.domain'} eq $1) ||
6524: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6525: return '';
6526: }
1.262 matthew 6527: }
1.620 albertel 6528: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6529: # Library role, so allow browsing of resources in this domain.
6530: return 'F';
1.238 www 6531: }
1.341 www 6532: if ($copyright eq 'custom') {
6533: unless (&customaccess($priv,$uri)) { return ''; }
6534: }
1.14 www 6535: }
1.264 matthew 6536: # Domain coordinator is trying to create a course
1.620 albertel 6537: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6538: # uri is the requested domain in this case.
6539: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6540: # a role of dc for the domain in question.
1.620 albertel 6541: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6542: }
1.29 www 6543:
1.52 www 6544: my $thisallowed='';
6545: my $statecond=0;
6546: my $courseprivid='';
6547:
1.1039 raeburn 6548: my $ownaccess;
1.1043 raeburn 6549: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6550: if (($priv eq 'bro') && ($env{'user.author'})) {
6551: if ($uri eq '') {
6552: $ownaccess = 1;
6553: } else {
6554: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6555: my $udom = $env{'user.domain'};
6556: my $uname = $env{'user.name'};
6557: if ($uri =~ m{^\Q$udom\E/?$}) {
6558: $ownaccess = 1;
1.1040 raeburn 6559: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6560: unless ($uri =~ m{\.\./}) {
6561: $ownaccess = 1;
6562: }
6563: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6564: my $now = time;
6565: if ($uri =~ m{^([^/]+)/?$}) {
6566: my $adom = $1;
6567: foreach my $key (keys(%env)) {
1.1042 raeburn 6568: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6569: my ($start,$end) = split('.',$env{$key});
6570: if (($now >= $start) && (!$end || $end < $now)) {
6571: $ownaccess = 1;
6572: last;
6573: }
6574: }
6575: }
6576: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6577: my $adom = $1;
6578: my $aname = $2;
1.1042 raeburn 6579: foreach my $role ('ca','aa') {
6580: if ($env{"user.role.$role./$adom/$aname"}) {
6581: my ($start,$end) =
6582: split('.',$env{"user.role.$role./$adom/$aname"});
6583: if (($now >= $start) && (!$end || $end < $now)) {
6584: $ownaccess = 1;
6585: last;
6586: }
1.1039 raeburn 6587: }
6588: }
6589: }
6590: }
6591: }
6592: }
6593: }
6594:
1.52 www 6595: # Course
6596:
1.620 albertel 6597: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6598: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6599: $thisallowed.=$1;
6600: }
1.52 www 6601: }
1.29 www 6602:
1.52 www 6603: # Domain
6604:
1.620 albertel 6605: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
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.52 www 6611:
1.1141 raeburn 6612: # User who is not author or co-author might still be able to edit
6613: # resource of an author in the domain (e.g., if Domain Coordinator).
6614: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6615: (&allowed('mdc',$env{'request.course.id'}))) {
6616: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6617: $thisallowed.=$1;
6618: }
6619: }
6620:
1.52 www 6621: # Course: uri itself is a course
1.66 www 6622: my $courseuri=$uri;
6623: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6624: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6625:
1.620 albertel 6626: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6627: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6628: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6629: $thisallowed.=$1;
6630: }
1.12 www 6631: }
1.29 www 6632:
1.665 albertel 6633: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6634: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6635: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6636: $thisallowed='';
1.671 raeburn 6637: my ($match)=&is_on_map($uri);
6638: if ($match) {
6639: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6640: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6641: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6642: if (@blockers > 0) {
6643: $thisallowed = 'B';
6644: } else {
6645: $thisallowed.=$1;
6646: }
1.671 raeburn 6647: }
6648: } else {
1.705 albertel 6649: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6650: if ($refuri) {
6651: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6652: $thisallowed='F';
1.671 raeburn 6653: } else {
6654: $refuri=&declutter($refuri);
6655: my ($match) = &is_on_map($refuri);
6656: if ($match) {
1.1162 raeburn 6657: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6658: if (@blockers > 0) {
6659: $thisallowed = 'B';
6660: } else {
6661: $thisallowed='F';
6662: }
1.671 raeburn 6663: }
1.669 raeburn 6664: }
1.671 raeburn 6665: }
6666: }
1.314 www 6667: }
1.492 albertel 6668:
1.766 albertel 6669: if ($priv eq 'bre'
6670: && $thisallowed ne 'F'
6671: && $thisallowed ne '2'
6672: && &is_portfolio_url($uri)) {
6673: $thisallowed = &portfolio_access($uri);
6674: }
6675:
1.52 www 6676: # Full access at system, domain or course-wide level? Exit.
1.29 www 6677: if ($thisallowed=~/F/) {
6678: return 'F';
6679: }
6680:
1.52 www 6681: # If this is generating or modifying users, exit with special codes
1.29 www 6682:
1.643 www 6683: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6684: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6685: my ($audom,$auname)=split('/',$uri);
1.643 www 6686: # no author name given, so this just checks on the general right to make a co-author in this domain
6687: unless ($auname) { return $thisallowed; }
6688: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6689: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6690: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6691: ($audom ne $env{'request.role.domain'}))) { return ''; }
6692: }
1.52 www 6693: return $thisallowed;
6694: }
6695: #
1.103 harris41 6696: # Gathered so far: system, domain and course wide privileges
1.52 www 6697: #
6698: # Course: See if uri or referer is an individual resource that is part of
6699: # the course
6700:
1.620 albertel 6701: if ($env{'request.course.id'}) {
1.232 www 6702:
1.620 albertel 6703: $courseprivid=$env{'request.course.id'};
6704: if ($env{'request.course.sec'}) {
6705: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6706: }
6707: $courseprivid=~s/\_/\//;
6708: my $checkreferer=1;
1.232 www 6709: my ($match,$cond)=&is_on_map($uri);
6710: if ($match) {
6711: $statecond=$cond;
1.620 albertel 6712: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6713: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6714: my $value = $1;
6715: if ($priv eq 'bre') {
6716: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6717: if (@blockers > 0) {
6718: $thisallowed = 'B';
6719: } else {
6720: $thisallowed.=$value;
6721: }
6722: } else {
6723: $thisallowed.=$value;
6724: }
1.52 www 6725: $checkreferer=0;
6726: }
1.29 www 6727: }
1.83 www 6728:
1.148 www 6729: if ($checkreferer) {
1.620 albertel 6730: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6731: unless ($refuri) {
1.800 albertel 6732: foreach my $key (keys(%env)) {
6733: if ($key=~/^httpref\..*\*/) {
6734: my $pattern=$key;
1.156 www 6735: $pattern=~s/^httpref\.\/res\///;
1.148 www 6736: $pattern=~s/\*/\[\^\/\]\+/g;
6737: $pattern=~s/\//\\\//g;
1.152 www 6738: if ($orguri=~/$pattern/) {
1.800 albertel 6739: $refuri=$env{$key};
1.148 www 6740: }
6741: }
1.191 harris41 6742: }
1.148 www 6743: }
1.232 www 6744:
1.148 www 6745: if ($refuri) {
1.152 www 6746: $refuri=&declutter($refuri);
1.232 www 6747: my ($match,$cond)=&is_on_map($refuri);
6748: if ($match) {
6749: my $refstatecond=$cond;
1.620 albertel 6750: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6751: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6752: my $value = $1;
6753: if ($priv eq 'bre') {
6754: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6755: if (@blockers > 0) {
6756: $thisallowed = 'B';
6757: } else {
6758: $thisallowed.=$value;
6759: }
6760: } else {
6761: $thisallowed.=$value;
6762: }
1.53 www 6763: $uri=$refuri;
6764: $statecond=$refstatecond;
1.52 www 6765: }
6766: }
1.148 www 6767: }
1.29 www 6768: }
1.52 www 6769: }
1.29 www 6770:
1.52 www 6771: #
1.103 harris41 6772: # Gathered now: all privileges that could apply, and condition number
1.52 www 6773: #
6774: #
6775: # Full or no access?
6776: #
1.29 www 6777:
1.52 www 6778: if ($thisallowed=~/F/) {
6779: return 'F';
6780: }
1.29 www 6781:
1.52 www 6782: unless ($thisallowed) {
6783: return '';
6784: }
1.29 www 6785:
1.52 www 6786: # Restrictions exist, deal with them
6787: #
6788: # C:according to course preferences
6789: # R:according to resource settings
6790: # L:unless locked
6791: # X:according to user session state
6792: #
6793:
6794: # Possibly locked functionality, check all courses
1.54 www 6795: # Locks might take effect only after 10 minutes cache expiration for other
6796: # courses, and 2 minutes for current course
1.52 www 6797:
6798: my $envkey;
6799: if ($thisallowed=~/L/) {
1.1000 raeburn 6800: foreach $envkey (keys(%env)) {
1.54 www 6801: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6802: my $courseid=$2;
6803: my $roleid=$1.'.'.$2;
1.92 www 6804: $courseid=~s/^\///;
1.54 www 6805: my $expiretime=600;
1.620 albertel 6806: if ($env{'request.role'} eq $roleid) {
1.54 www 6807: $expiretime=120;
6808: }
6809: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6810: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6811: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6812: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6813: }
1.620 albertel 6814: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6815: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6816: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6817: &log($env{'user.domain'},$env{'user.name'},
6818: $env{'user.home'},
1.57 www 6819: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6820: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6821: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6822: return '';
6823: }
6824: }
1.620 albertel 6825: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6826: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6827: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6828: &log($env{'user.domain'},$env{'user.name'},
6829: $env{'user.home'},
1.57 www 6830: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6831: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6832: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6833: return '';
6834: }
6835: }
6836: }
1.29 www 6837: }
1.52 www 6838: }
6839:
6840: #
6841: # Rest of the restrictions depend on selected course
6842: #
6843:
1.620 albertel 6844: unless ($env{'request.course.id'}) {
1.766 albertel 6845: if ($thisallowed eq 'A') {
6846: return 'A';
1.814 raeburn 6847: } elsif ($thisallowed eq 'B') {
6848: return 'B';
1.766 albertel 6849: } else {
6850: return '1';
6851: }
1.52 www 6852: }
1.29 www 6853:
1.52 www 6854: #
6855: # Now user is definitely in a course
6856: #
1.53 www 6857:
6858:
6859: # Course preferences
6860:
6861: if ($thisallowed=~/C/) {
1.620 albertel 6862: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6863: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6864: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6865: =~/\Q$rolecode\E/) {
1.1103 raeburn 6866: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6867: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6868: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6869: $env{'request.course.id'});
6870: }
1.237 www 6871: return '';
6872: }
6873:
1.620 albertel 6874: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6875: =~/\Q$unamedom\E/) {
1.1103 raeburn 6876: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6877: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6878: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6879: $env{'request.course.id'});
6880: }
1.54 www 6881: return '';
6882: }
1.53 www 6883: }
6884:
6885: # Resource preferences
6886:
6887: if ($thisallowed=~/R/) {
1.620 albertel 6888: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6889: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6890: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6891: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6892: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6893: }
6894: return '';
1.54 www 6895: }
1.53 www 6896: }
1.30 www 6897:
1.246 www 6898: # Restricted by state or randomout?
1.30 www 6899:
1.52 www 6900: if ($thisallowed=~/X/) {
1.620 albertel 6901: if ($env{'acc.randomout'}) {
1.579 albertel 6902: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6903: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6904: return '';
6905: }
1.247 www 6906: }
6907: if (&condval($statecond)) {
1.52 www 6908: return '2';
6909: } else {
6910: return '';
6911: }
6912: }
1.30 www 6913:
1.766 albertel 6914: if ($thisallowed eq 'A') {
6915: return 'A';
1.814 raeburn 6916: } elsif ($thisallowed eq 'B') {
6917: return 'B';
1.766 albertel 6918: }
1.52 www 6919: return 'F';
1.232 www 6920: }
1.1162 raeburn 6921:
1.1192 raeburn 6922: # ------------------------------------------- Check construction space access
6923:
6924: sub constructaccess {
6925: my ($url,$setpriv)=@_;
6926:
6927: # We do not allow editing of previous versions of files
6928: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
6929:
6930: # Get username and domain from URL
6931: my ($ownername,$ownerdomain,$ownerhome);
6932:
6933: ($ownerdomain,$ownername) =
6934: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
6935:
6936: # The URL does not really point to any authorspace, forget it
6937: unless (($ownername) && ($ownerdomain)) { return ''; }
6938:
6939: # Now we need to see if the user has access to the authorspace of
6940: # $ownername at $ownerdomain
6941:
6942: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
6943: # Real author for this?
6944: $ownerhome = $env{'user.home'};
6945: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
6946: return ($ownername,$ownerdomain,$ownerhome);
6947: }
6948: } else {
6949: # Co-author for this?
6950: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
6951: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
6952: $ownerhome = &homeserver($ownername,$ownerdomain);
6953: return ($ownername,$ownerdomain,$ownerhome);
6954: }
6955: }
6956:
6957: # We don't have any access right now. If we are not possibly going to do anything about this,
6958: # we might as well leave
6959: unless ($setpriv) { return ''; }
6960:
6961: # Backdoor access?
6962: my $allowed=&allowed('eco',$ownerdomain);
6963: # Nope
6964: unless ($allowed) { return ''; }
6965: # Looks like we may have access, but could be locked by the owner of the construction space
6966: if ($allowed eq 'U') {
6967: my %blocked=&get('environment',['domcoord.author'],
6968: $ownerdomain,$ownername);
6969: # Is blocked by owner
6970: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
6971: }
6972: if (($allowed eq 'F') || ($allowed eq 'U')) {
6973: # Grant temporary access
6974: my $then=$env{'user.login.time'};
1.1209 raeburn 6975: my $update=$env{'user.update.time'};
1.1192 raeburn 6976: if (!$update) { $update = $then; }
6977: my $refresh=$env{'user.refresh.time'};
6978: if (!$refresh) { $refresh = $update; }
6979: my $now = time;
6980: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
6981: $now,'ca','constructaccess');
6982: $ownerhome = &homeserver($ownername,$ownerdomain);
6983: return($ownername,$ownerdomain,$ownerhome);
6984: }
6985: # No business here
6986: return '';
6987: }
6988:
1.1162 raeburn 6989: sub get_comm_blocks {
6990: my ($cdom,$cnum) = @_;
6991: if ($cdom eq '' || $cnum eq '') {
6992: return unless ($env{'request.course.id'});
6993: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6994: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6995: }
6996: my %commblocks;
6997: my $hashid=$cdom.'_'.$cnum;
6998: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6999: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7000: %commblocks = %{$blocksref};
7001: } else {
7002: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7003: my $cachetime = 600;
7004: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7005: }
7006: return %commblocks;
7007: }
7008:
7009: sub has_comm_blocking {
7010: my ($priv,$symb,$uri,$blocks) = @_;
7011: return unless ($env{'request.course.id'});
7012: return unless ($priv eq 'bre');
7013: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7014: my %commblocks;
7015: if (ref($blocks) eq 'HASH') {
7016: %commblocks = %{$blocks};
7017: } else {
7018: %commblocks = &get_comm_blocks();
7019: }
7020: return unless (keys(%commblocks) > 0);
7021: if (!$symb) { $symb=&symbread($uri,1); }
7022: my ($map,$resid,undef)=&decode_symb($symb);
7023: my %tocheck = (
7024: maps => $map,
7025: resources => $symb,
7026: );
7027: my @blockers;
7028: my $now = time;
1.1163 raeburn 7029: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7030: foreach my $block (keys(%commblocks)) {
7031: if ($block =~ /^(\d+)____(\d+)$/) {
7032: my ($start,$end) = ($1,$2);
7033: if ($start <= $now && $end >= $now) {
7034: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7035: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7036: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7037: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7038: unless (grep(/^\Q$block\E$/,@blockers)) {
7039: push(@blockers,$block);
7040: }
7041: }
7042: }
7043: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7044: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7045: unless (grep(/^\Q$block\E$/,@blockers)) {
7046: push(@blockers,$block);
7047: }
7048: }
7049: }
7050: }
7051: }
7052: }
7053: } elsif ($block =~ /^firstaccess____(.+)$/) {
7054: my $item = $1;
1.1163 raeburn 7055: my @to_test;
1.1162 raeburn 7056: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7057: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7058: my $check_interval;
7059: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7060: my @interval;
7061: my $type = 'map';
7062: if ($item eq 'course') {
7063: $type = 'course';
7064: @interval=&EXT("resource.0.interval");
7065: } else {
7066: if ($item =~ /___\d+___/) {
7067: $type = 'resource';
7068: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7069: if (ref($navmap)) {
7070: my $res = $navmap->getBySymb($item);
7071: push(@to_test,$res);
7072: }
1.1162 raeburn 7073: } else {
7074: my $mapsymb = &symbread($item,1);
7075: if ($mapsymb) {
7076: if (ref($navmap)) {
7077: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7078: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7079: foreach my $res (@to_test) {
1.1162 raeburn 7080: my $symb = $res->symb();
7081: next if ($symb eq $mapsymb);
7082: if ($symb ne '') {
7083: @interval=&EXT("resource.0.interval",$symb);
7084: last;
7085: }
7086: }
7087: }
7088: }
7089: }
7090: }
7091: if ($interval[0] =~ /\d+/) {
7092: my $first_access;
7093: if ($type eq 'resource') {
7094: $first_access=&get_first_access($interval[1],$item);
7095: } elsif ($type eq 'map') {
7096: $first_access=&get_first_access($interval[1],undef,$item);
7097: } else {
7098: $first_access=&get_first_access($interval[1]);
7099: }
7100: if ($first_access) {
7101: my $timesup = $first_access+$interval[0];
7102: if ($timesup > $now) {
1.1163 raeburn 7103: foreach my $res (@to_test) {
7104: if ($res->is_problem()) {
7105: if ($res->completable()) {
7106: unless (grep(/^\Q$block\E$/,@blockers)) {
7107: push(@blockers,$block);
7108: }
7109: last;
7110: }
7111: }
1.1162 raeburn 7112: }
7113: }
7114: }
7115: }
7116: }
7117: }
7118: }
7119: }
7120: }
7121: return @blockers;
7122: }
7123:
7124: sub check_docs_block {
7125: my ($docsblock,$tocheck) =@_;
7126: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7127: return;
7128: }
7129: if (ref($docsblock->{'maps'}) eq 'HASH') {
7130: if ($tocheck->{'maps'}) {
7131: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7132: return 1;
7133: }
7134: }
7135: }
7136: if (ref($docsblock->{'resources'}) eq 'HASH') {
7137: if ($tocheck->{'resources'}) {
7138: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7139: return 1;
7140: }
7141: }
7142: }
7143: return;
7144: }
7145:
1.1133 foxr 7146: #
7147: # Removes the versino from a URI and
7148: # splits it in to its filename and path to the filename.
7149: # Seems like File::Basename could have done this more clearly.
7150: # Parameters:
7151: # $uri - input URI
7152: # Returns:
7153: # Two element list consisting of
7154: # $pathname - the URI up to and excluding the trailing /
7155: # $filename - The part of the URI following the last /
7156: # NOTE:
7157: # Another realization of this is simply:
7158: # use File::Basename;
7159: # ...
7160: # $uri = shift;
7161: # $filename = basename($uri);
7162: # $path = dirname($uri);
7163: # return ($filename, $path);
7164: #
7165: # The implementation below is probably faster however.
7166: #
1.710 albertel 7167: sub split_uri_for_cond {
7168: my $uri=&deversion(&declutter(shift));
7169: my @uriparts=split(/\//,$uri);
7170: my $filename=pop(@uriparts);
7171: my $pathname=join('/',@uriparts);
7172: return ($pathname,$filename);
7173: }
1.232 www 7174: # --------------------------------------------------- Is a resource on the map?
7175:
7176: sub is_on_map {
1.710 albertel 7177: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7178: #Trying to find the conditional for the file
1.620 albertel 7179: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7180: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7181: if ($match) {
1.289 bowersj2 7182: return (1,$1);
7183: } else {
1.434 www 7184: return (0,0);
1.289 bowersj2 7185: }
1.12 www 7186: }
7187:
1.427 www 7188: # --------------------------------------------------------- Get symb from alias
7189:
7190: sub get_symb_from_alias {
7191: my $symb=shift;
7192: my ($map,$resid,$url)=&decode_symb($symb);
7193: # Already is a symb
7194: if ($url) { return $symb; }
7195: # Must be an alias
7196: my $aliassymb='';
7197: my %bighash;
1.620 albertel 7198: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7199: &GDBM_READER(),0640)) {
7200: my $rid=$bighash{'mapalias_'.$symb};
7201: if ($rid) {
7202: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7203: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7204: $resid,$bighash{'src_'.$rid});
1.427 www 7205: }
7206: untie %bighash;
7207: }
7208: return $aliassymb;
7209: }
7210:
1.12 www 7211: # ----------------------------------------------------------------- Define Role
7212:
7213: sub definerole {
7214: if (allowed('mcr','/')) {
7215: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7216: foreach my $role (split(':',$sysrole)) {
7217: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7218: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7219: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7220: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7221: return "refused:s:$crole&$cqual";
7222: }
7223: }
1.191 harris41 7224: }
1.800 albertel 7225: foreach my $role (split(':',$domrole)) {
7226: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7227: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7228: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7229: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7230: return "refused:d:$crole&$cqual";
7231: }
7232: }
1.191 harris41 7233: }
1.800 albertel 7234: foreach my $role (split(':',$courole)) {
7235: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7236: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7237: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7238: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7239: return "refused:c:$crole&$cqual";
7240: }
7241: }
1.191 harris41 7242: }
1.620 albertel 7243: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7244: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7245: "rolesdef_$rolename=".
7246: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7247: return reply($command,$env{'user.home'});
1.12 www 7248: } else {
7249: return 'refused';
7250: }
1.105 harris41 7251: }
7252:
7253: # ---------------- Make a metadata query against the network of library servers
7254:
7255: sub metadata_query {
1.244 matthew 7256: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 7257: my %rhash;
1.845 albertel 7258: my %libserv = &all_library();
1.244 matthew 7259: my @server_list = (defined($server_array) ? @$server_array
7260: : keys(%libserv) );
7261: for my $server (@server_list) {
1.118 harris41 7262: unless ($custom or $customshow) {
7263: my $reply=&reply("querysend:".&escape($query),$server);
7264: $rhash{$server}=$reply;
7265: }
7266: else {
7267: my $reply=&reply("querysend:".&escape($query).':'.
7268: &escape($custom).':'.&escape($customshow),
7269: $server);
7270: $rhash{$server}=$reply;
7271: }
1.112 harris41 7272: }
1.118 harris41 7273: return \%rhash;
1.240 www 7274: }
7275:
7276: # ----------------------------------------- Send log queries and wait for reply
7277:
7278: sub log_query {
7279: my ($uname,$udom,$query,%filters)=@_;
7280: my $uhome=&homeserver($uname,$udom);
7281: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7282: my $uhost=&hostname($uhome);
1.800 albertel 7283: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7284: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7285: $uhome);
1.479 albertel 7286: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7287: return get_query_reply($queryid);
7288: }
7289:
1.818 raeburn 7290: # -------------------------- Update MySQL table for portfolio file
7291:
7292: sub update_portfolio_table {
1.821 raeburn 7293: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7294: if ($group ne '') {
7295: $file_name =~s /^\Q$group\E//;
7296: }
1.818 raeburn 7297: my $homeserver = &homeserver($uname,$udom);
7298: my $queryid=
1.821 raeburn 7299: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7300: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7301: my $reply = &get_query_reply($queryid);
7302: return $reply;
7303: }
7304:
1.899 raeburn 7305: # -------------------------- Update MySQL allusers table
7306:
7307: sub update_allusers_table {
7308: my ($uname,$udom,$names) = @_;
7309: my $homeserver = &homeserver($uname,$udom);
7310: my $queryid=
7311: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7312: 'lastname='.&escape($names->{'lastname'}).'%%'.
7313: 'firstname='.&escape($names->{'firstname'}).'%%'.
7314: 'middlename='.&escape($names->{'middlename'}).'%%'.
7315: 'generation='.&escape($names->{'generation'}).'%%'.
7316: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7317: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7318: return;
1.899 raeburn 7319: }
7320:
1.508 raeburn 7321: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7322:
7323: sub fetch_enrollment_query {
1.511 raeburn 7324: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7325: my $homeserver;
1.547 raeburn 7326: my $maxtries = 1;
1.508 raeburn 7327: if ($context eq 'automated') {
7328: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7329: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7330: } else {
7331: $homeserver = &homeserver($cnum,$dom);
7332: }
1.838 albertel 7333: my $host=&hostname($homeserver);
1.506 raeburn 7334: my $cmd = '';
1.1000 raeburn 7335: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7336: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7337: }
7338: $cmd =~ s/%%$//;
7339: $cmd = &escape($cmd);
7340: my $query = 'fetchenrollment';
1.620 albertel 7341: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7342: unless ($queryid=~/^\Q$host\E\_/) {
7343: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7344: return 'error: '.$queryid;
7345: }
1.506 raeburn 7346: my $reply = &get_query_reply($queryid);
1.547 raeburn 7347: my $tries = 1;
7348: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7349: $reply = &get_query_reply($queryid);
7350: $tries ++;
7351: }
1.526 raeburn 7352: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7353: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7354: } else {
1.901 albertel 7355: my @responses = split(/:/,$reply);
1.515 raeburn 7356: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7357: foreach my $line (@responses) {
7358: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7359: $$replyref{$key} = $value;
7360: }
7361: } else {
1.1117 foxr 7362: my $pathname = LONCAPA::tempdir();
1.800 albertel 7363: foreach my $line (@responses) {
7364: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7365: $$replyref{$key} = $value;
7366: if ($value > 0) {
1.800 albertel 7367: foreach my $item (@{$$affiliatesref{$key}}) {
7368: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7369: my $destname = $pathname.'/'.$filename;
7370: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7371: if ($xml_classlist =~ /^error/) {
7372: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7373: } else {
1.506 raeburn 7374: if ( open(FILE,">$destname") ) {
7375: print FILE &unescape($xml_classlist);
7376: close(FILE);
1.526 raeburn 7377: } else {
7378: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7379: }
7380: }
7381: }
7382: }
7383: }
7384: }
7385: return 'ok';
7386: }
7387: return 'error';
7388: }
7389:
1.242 www 7390: sub get_query_reply {
7391: my $queryid=shift;
1.1117 foxr 7392: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7393: my $reply='';
7394: for (1..100) {
7395: sleep 2;
7396: if (-e $replyfile.'.end') {
1.448 albertel 7397: if (open(my $fh,$replyfile)) {
1.904 albertel 7398: $reply = join('',<$fh>);
7399: close($fh);
1.240 www 7400: } else { return 'error: reply_file_error'; }
1.242 www 7401: return &unescape($reply);
7402: }
1.240 www 7403: }
1.242 www 7404: return 'timeout:'.$queryid;
1.240 www 7405: }
7406:
7407: sub courselog_query {
1.241 www 7408: #
7409: # possible filters:
7410: # url: url or symb
7411: # username
7412: # domain
7413: # action: view, submit, grade
7414: # start: timestamp
7415: # end: timestamp
7416: #
1.240 www 7417: my (%filters)=@_;
1.620 albertel 7418: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7419: if ($filters{'url'}) {
7420: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7421: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7422: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7423: }
1.620 albertel 7424: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7425: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7426: return &log_query($cname,$cdom,'courselog',%filters);
7427: }
7428:
7429: sub userlog_query {
1.858 raeburn 7430: #
7431: # possible filters:
7432: # action: log check role
7433: # start: timestamp
7434: # end: timestamp
7435: #
1.240 www 7436: my ($uname,$udom,%filters)=@_;
7437: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7438: }
7439:
1.506 raeburn 7440: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7441:
7442: sub auto_run {
1.508 raeburn 7443: my ($cnum,$cdom) = @_;
1.876 raeburn 7444: my $response = 0;
7445: my $settings;
7446: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7447: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7448: $settings = $domconfig{'autoenroll'};
7449: if ($settings->{'run'} eq '1') {
7450: $response = 1;
7451: }
7452: } else {
1.934 raeburn 7453: my $homeserver;
7454: if (&is_course($cdom,$cnum)) {
7455: $homeserver = &homeserver($cnum,$cdom);
7456: } else {
7457: $homeserver = &domain($cdom,'primary');
7458: }
7459: if ($homeserver ne 'no_host') {
7460: $response = &reply('autorun:'.$cdom,$homeserver);
7461: }
1.876 raeburn 7462: }
1.506 raeburn 7463: return $response;
7464: }
1.776 albertel 7465:
1.506 raeburn 7466: sub auto_get_sections {
1.508 raeburn 7467: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7468: my $homeserver;
7469: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7470: $homeserver = &homeserver($cnum,$cdom);
7471: }
7472: if (!defined($homeserver)) {
7473: if ($cdom =~ /^$match_domain$/) {
7474: $homeserver = &domain($cdom,'primary');
7475: }
7476: }
7477: my @secs;
7478: if (defined($homeserver)) {
7479: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7480: unless ($response eq 'refused') {
7481: @secs = split(/:/,$response);
7482: }
1.506 raeburn 7483: }
7484: return @secs;
7485: }
1.776 albertel 7486:
1.506 raeburn 7487: sub auto_new_course {
1.1099 raeburn 7488: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7489: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7490: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7491: return $response;
7492: }
1.776 albertel 7493:
1.506 raeburn 7494: sub auto_validate_courseID {
1.508 raeburn 7495: my ($cnum,$cdom,$inst_course_id) = @_;
7496: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7497: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7498: return $response;
7499: }
1.776 albertel 7500:
1.1007 raeburn 7501: sub auto_validate_instcode {
1.1020 raeburn 7502: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7503: my ($homeserver,$response);
7504: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7505: $homeserver = &homeserver($cnum,$cdom);
7506: }
7507: if (!defined($homeserver)) {
7508: if ($cdom =~ /^$match_domain$/) {
7509: $homeserver = &domain($cdom,'primary');
7510: }
7511: }
1.1065 raeburn 7512: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7513: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7514: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7515: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7516: }
7517:
1.506 raeburn 7518: sub auto_create_password {
1.873 raeburn 7519: my ($cnum,$cdom,$authparam,$udom) = @_;
7520: my ($homeserver,$response);
1.506 raeburn 7521: my $create_passwd = 0;
7522: my $authchk = '';
1.873 raeburn 7523: if ($udom =~ /^$match_domain$/) {
7524: $homeserver = &domain($udom,'primary');
7525: }
7526: if ($homeserver eq '') {
7527: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7528: $homeserver = &homeserver($cnum,$cdom);
7529: }
7530: }
7531: if ($homeserver eq '') {
7532: $authchk = 'nodomain';
1.506 raeburn 7533: } else {
1.873 raeburn 7534: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7535: if ($response eq 'refused') {
7536: $authchk = 'refused';
7537: } else {
1.901 albertel 7538: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7539: }
1.506 raeburn 7540: }
7541: return ($authparam,$create_passwd,$authchk);
7542: }
7543:
1.706 raeburn 7544: sub auto_photo_permission {
7545: my ($cnum,$cdom,$students) = @_;
7546: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7547: my ($outcome,$perm_reqd,$conditions) =
7548: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7549: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7550: return (undef,undef);
7551: }
1.706 raeburn 7552: return ($outcome,$perm_reqd,$conditions);
7553: }
7554:
7555: sub auto_checkphotos {
7556: my ($uname,$udom,$pid) = @_;
7557: my $homeserver = &homeserver($uname,$udom);
7558: my ($result,$resulttype);
7559: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7560: &escape($uname).':'.&escape($pid),
7561: $homeserver));
1.709 albertel 7562: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7563: return (undef,undef);
7564: }
1.706 raeburn 7565: if ($outcome) {
7566: ($result,$resulttype) = split(/:/,$outcome);
7567: }
7568: return ($result,$resulttype);
7569: }
7570:
7571: sub auto_photochoice {
7572: my ($cnum,$cdom) = @_;
7573: my $homeserver = &homeserver($cnum,$cdom);
7574: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7575: &escape($cdom),
7576: $homeserver)));
1.709 albertel 7577: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7578: return (undef,undef);
7579: }
1.706 raeburn 7580: return ($update,$comment);
7581: }
7582:
7583: sub auto_photoupdate {
7584: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7585: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7586: my $host=&hostname($homeserver);
1.706 raeburn 7587: my $cmd = '';
7588: my $maxtries = 1;
1.800 albertel 7589: foreach my $affiliate (keys(%{$affiliatesref})) {
7590: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7591: }
7592: $cmd =~ s/%%$//;
7593: $cmd = &escape($cmd);
7594: my $query = 'institutionalphotos';
7595: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7596: unless ($queryid=~/^\Q$host\E\_/) {
7597: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7598: return 'error: '.$queryid;
7599: }
7600: my $reply = &get_query_reply($queryid);
7601: my $tries = 1;
7602: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7603: $reply = &get_query_reply($queryid);
7604: $tries ++;
7605: }
7606: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7607: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7608: } else {
7609: my @responses = split(/:/,$reply);
7610: my $outcome = shift(@responses);
7611: foreach my $item (@responses) {
7612: my ($key,$value) = split(/=/,$item);
7613: $$photo{$key} = $value;
7614: }
7615: return $outcome;
7616: }
7617: return 'error';
7618: }
7619:
1.521 raeburn 7620: sub auto_instcode_format {
1.793 albertel 7621: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7622: $cat_order) = @_;
1.521 raeburn 7623: my $courses = '';
1.772 raeburn 7624: my @homeservers;
1.521 raeburn 7625: if ($caller eq 'global') {
1.841 albertel 7626: my %servers = &get_servers($codedom,'library');
7627: foreach my $tryserver (keys(%servers)) {
7628: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7629: push(@homeservers,$tryserver);
7630: }
1.584 raeburn 7631: }
1.1022 raeburn 7632: } elsif ($caller eq 'requests') {
7633: if ($codedom =~ /^$match_domain$/) {
7634: my $chome = &domain($codedom,'primary');
7635: unless ($chome eq 'no_host') {
7636: push(@homeservers,$chome);
7637: }
7638: }
1.521 raeburn 7639: } else {
1.772 raeburn 7640: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7641: }
1.793 albertel 7642: foreach my $code (keys(%{$instcodes})) {
7643: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7644: }
7645: chop($courses);
1.772 raeburn 7646: my $ok_response = 0;
7647: my $response;
7648: while (@homeservers > 0 && $ok_response == 0) {
7649: my $server = shift(@homeservers);
7650: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7651: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7652: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7653: split(/:/,$response);
1.772 raeburn 7654: %{$codes} = (%{$codes},&str2hash($codes_str));
7655: push(@{$codetitles},&str2array($codetitles_str));
7656: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7657: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7658: $ok_response = 1;
7659: }
7660: }
7661: if ($ok_response) {
1.521 raeburn 7662: return 'ok';
1.772 raeburn 7663: } else {
7664: return $response;
1.521 raeburn 7665: }
7666: }
7667:
1.792 raeburn 7668: sub auto_instcode_defaults {
7669: my ($domain,$returnhash,$code_order) = @_;
7670: my @homeservers;
1.841 albertel 7671:
7672: my %servers = &get_servers($domain,'library');
7673: foreach my $tryserver (keys(%servers)) {
7674: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7675: push(@homeservers,$tryserver);
7676: }
1.792 raeburn 7677: }
1.841 albertel 7678:
1.792 raeburn 7679: my $response;
1.841 albertel 7680: foreach my $server (@homeservers) {
1.792 raeburn 7681: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7682: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7683:
7684: foreach my $pair (split(/\&/,$response)) {
7685: my ($name,$value)=split(/\=/,$pair);
7686: if ($name eq 'code_order') {
7687: @{$code_order} = split(/\&/,&unescape($value));
7688: } else {
7689: $returnhash->{&unescape($name)}=&unescape($value);
7690: }
7691: }
7692: return 'ok';
1.792 raeburn 7693: }
1.841 albertel 7694:
7695: return $response;
1.1003 raeburn 7696: }
7697:
7698: sub auto_possible_instcodes {
1.1007 raeburn 7699: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7700: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7701: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7702: return;
7703: }
1.1003 raeburn 7704: my (@homeservers,$uhome);
7705: if (defined(&domain($domain,'primary'))) {
7706: $uhome=&domain($domain,'primary');
7707: push(@homeservers,&domain($domain,'primary'));
7708: } else {
7709: my %servers = &get_servers($domain,'library');
7710: foreach my $tryserver (keys(%servers)) {
7711: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7712: push(@homeservers,$tryserver);
7713: }
7714: }
7715: }
7716: my $response;
7717: foreach my $server (@homeservers) {
7718: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7719: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7720: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7721: split(':',$response);
7722: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7723: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7724: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7725: my ($name,$value)=split('=',$item);
7726: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7727: }
7728: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7729: my ($name,$value)=split('=',$item);
7730: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7731: }
7732: return 'ok';
7733: }
7734: return $response;
7735: }
1.792 raeburn 7736:
1.1010 raeburn 7737: sub auto_courserequest_checks {
7738: my ($dom) = @_;
1.1020 raeburn 7739: my ($homeserver,%validations);
7740: if ($dom =~ /^$match_domain$/) {
7741: $homeserver = &domain($dom,'primary');
7742: }
7743: unless ($homeserver eq 'no_host') {
7744: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7745: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7746: my @items = split(/&/,$response);
7747: foreach my $item (@items) {
7748: my ($key,$value) = split('=',$item);
7749: $validations{&unescape($key)} = &thaw_unescape($value);
7750: }
7751: }
7752: }
1.1010 raeburn 7753: return %validations;
7754: }
7755:
1.1020 raeburn 7756: sub auto_courserequest_validation {
7757: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7758: my ($homeserver,$response);
7759: if ($dom =~ /^$match_domain$/) {
7760: $homeserver = &domain($dom,'primary');
7761: }
7762: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7763:
1.1020 raeburn 7764: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7765: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7766: ':'.&escape($instcode).':'.&escape($instseclist),
7767: $homeserver));
7768: }
7769: return $response;
7770: }
7771:
1.777 albertel 7772: sub auto_validate_class_sec {
1.918 raeburn 7773: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7774: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7775: my $ownerlist;
7776: if (ref($owners) eq 'ARRAY') {
7777: $ownerlist = join(',',@{$owners});
7778: } else {
7779: $ownerlist = $owners;
7780: }
1.773 raeburn 7781: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7782: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7783: return $response;
7784: }
7785:
1.679 raeburn 7786: # ------------------------------------------------------- Course Group routines
7787:
7788: sub get_coursegroups {
1.809 raeburn 7789: my ($cdom,$cnum,$group,$namespace) = @_;
7790: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7791: }
7792:
1.679 raeburn 7793: sub modify_coursegroup {
7794: my ($cdom,$cnum,$groupsettings) = @_;
7795: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7796: }
7797:
1.809 raeburn 7798: sub toggle_coursegroup_status {
7799: my ($cdom,$cnum,$group,$action) = @_;
7800: my ($from_namespace,$to_namespace);
7801: if ($action eq 'delete') {
7802: $from_namespace = 'coursegroups';
7803: $to_namespace = 'deleted_groups';
7804: } else {
7805: $from_namespace = 'deleted_groups';
7806: $to_namespace = 'coursegroups';
7807: }
7808: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7809: if (my $tmp = &error(%curr_group)) {
7810: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7811: return ('read error',$tmp);
7812: } else {
7813: my %savedsettings = %curr_group;
1.809 raeburn 7814: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7815: my $deloutcome;
7816: if ($result eq 'ok') {
1.809 raeburn 7817: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7818: } else {
7819: return ('write error',$result);
7820: }
7821: if ($deloutcome eq 'ok') {
7822: return 'ok';
7823: } else {
7824: return ('delete error',$deloutcome);
7825: }
7826: }
7827: }
7828:
1.679 raeburn 7829: sub modify_group_roles {
1.957 raeburn 7830: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7831: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7832: my $role = 'gr/'.&escape($userprivs);
7833: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7834: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7835: if ($result eq 'ok') {
7836: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7837: }
1.679 raeburn 7838: return $result;
7839: }
7840:
7841: sub modify_coursegroup_membership {
7842: my ($cdom,$cnum,$membership) = @_;
7843: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7844: return $result;
7845: }
7846:
1.682 raeburn 7847: sub get_active_groups {
7848: my ($udom,$uname,$cdom,$cnum) = @_;
7849: my $now = time;
7850: my %groups = ();
7851: foreach my $key (keys(%env)) {
1.811 albertel 7852: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7853: my ($start,$end) = split(/\./,$env{$key});
7854: if (($end!=0) && ($end<$now)) { next; }
7855: if (($start!=0) && ($start>$now)) { next; }
7856: if ($1 eq $cdom && $2 eq $cnum) {
7857: $groups{$3} = $env{$key} ;
7858: }
7859: }
7860: }
7861: return %groups;
7862: }
7863:
1.683 raeburn 7864: sub get_group_membership {
7865: my ($cdom,$cnum,$group) = @_;
7866: return(&dump('groupmembership',$cdom,$cnum,$group));
7867: }
7868:
7869: sub get_users_groups {
7870: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7871: my @usersgroups;
1.683 raeburn 7872: my $cachetime=1800;
7873:
7874: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7875: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7876: if (defined($cached)) {
1.734 albertel 7877: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7878: } else {
7879: $grouplist = '';
1.816 raeburn 7880: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7881: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7882: my $access_end = $env{'course.'.$courseid.
7883: '.default_enrollment_end_date'};
7884: my $now = time;
7885: foreach my $key (keys(%roleshash)) {
7886: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7887: my $group = $1;
7888: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7889: my $start = $2;
7890: my $end = $1;
7891: if ($start == -1) { next; } # deleted from group
7892: if (($start!=0) && ($start>$now)) { next; }
7893: if (($end!=0) && ($end<$now)) {
7894: if ($access_end && $access_end < $now) {
7895: if ($access_end - $end < 86400) {
7896: push(@usersgroups,$group);
1.733 raeburn 7897: }
7898: }
1.817 raeburn 7899: next;
1.733 raeburn 7900: }
1.817 raeburn 7901: push(@usersgroups,$group);
1.683 raeburn 7902: }
7903: }
7904: }
1.817 raeburn 7905: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7906: $grouplist = join(':',@usersgroups);
7907: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7908: }
1.733 raeburn 7909: return @usersgroups;
1.683 raeburn 7910: }
7911:
7912: sub devalidate_getgroups_cache {
7913: my ($udom,$uname,$cdom,$cnum)=@_;
7914: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7915:
1.683 raeburn 7916: my $hashid="$udom:$uname:$courseid";
7917: &devalidate_cache_new('getgroups',$hashid);
7918: }
7919:
1.12 www 7920: # ------------------------------------------------------------------ Plain Text
7921:
7922: sub plaintext {
1.988 raeburn 7923: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7924: if ($short =~ m{^cr/}) {
1.758 albertel 7925: return (split('/',$short))[-1];
7926: }
1.742 raeburn 7927: if (!defined($cid)) {
7928: $cid = $env{'request.course.id'};
7929: }
7930: my %rolenames = (
1.1008 raeburn 7931: Course => 'std',
7932: Community => 'alt1',
1.742 raeburn 7933: );
1.1037 raeburn 7934: if ($cid ne '') {
7935: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7936: unless ($forcedefault) {
7937: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7938: &Apache::lonlocal::mt_escape(\$roletext);
7939: return &Apache::lonlocal::mt($roletext);
7940: }
7941: }
7942: }
7943: if ((defined($type)) && (defined($rolenames{$type})) &&
7944: (defined($rolenames{$type})) &&
7945: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7946: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7947: } elsif ($cid ne '') {
7948: my $crstype = $env{'course.'.$cid.'.type'};
7949: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7950: (defined($prp{$short}{$rolenames{$crstype}}))) {
7951: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7952: }
1.742 raeburn 7953: }
1.1037 raeburn 7954: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7955: }
7956:
7957: # ----------------------------------------------------------------- Assign Role
7958:
7959: sub assignrole {
1.957 raeburn 7960: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7961: $context)=@_;
1.21 www 7962: my $mrole;
7963: if ($role =~ /^cr\//) {
1.393 www 7964: my $cwosec=$url;
1.811 albertel 7965: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7966: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7967: my $refused = 1;
7968: if ($context eq 'requestcourses') {
7969: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7970: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7971: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7972: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7973: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7974: if ($crsenv{'internal.courseowner'} eq
7975: $env{'user.name'}.':'.$env{'user.domain'}) {
7976: $refused = '';
7977: }
7978: }
7979: }
7980: }
7981: }
7982: if ($refused) {
7983: &logthis('Refused custom assignrole: '.
7984: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7985: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7986: return 'refused';
7987: }
1.104 www 7988: }
1.21 www 7989: $mrole='cr';
1.678 raeburn 7990: } elsif ($role =~ /^gr\//) {
7991: my $cwogrp=$url;
1.811 albertel 7992: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7993: unless (&allowed('mdg',$cwogrp)) {
7994: &logthis('Refused group assignrole: '.
7995: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7996: $env{'user.name'}.' at '.$env{'user.domain'});
7997: return 'refused';
7998: }
7999: $mrole='gr';
1.21 www 8000: } else {
1.82 www 8001: my $cwosec=$url;
1.811 albertel 8002: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8003: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8004: my $refused;
8005: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8006: if (!(&allowed('c'.$role,$url))) {
8007: $refused = 1;
8008: }
8009: } else {
8010: $refused = 1;
8011: }
1.947 raeburn 8012: if ($refused) {
1.1045 raeburn 8013: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8014: if (!$selfenroll && $context eq 'course') {
8015: my %crsenv;
8016: if ($role eq 'cc' || $role eq 'co') {
8017: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8018: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8019: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8020: if ($crsenv{'internal.courseowner'} eq
8021: $env{'user.name'}.':'.$env{'user.domain'}) {
8022: $refused = '';
8023: }
8024: }
8025: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8026: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8027: if ($crsenv{'internal.courseowner'} eq
8028: $env{'user.name'}.':'.$env{'user.domain'}) {
8029: $refused = '';
8030: }
8031: }
8032: }
8033: }
8034: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8035: $refused = '';
1.1017 raeburn 8036: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8037: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8038: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8039: my $wrongcc;
8040: if ($cnum =~ /^$match_community$/) {
8041: $wrongcc = 1 if ($role eq 'cc');
8042: } else {
8043: $wrongcc = 1 if ($role eq 'co');
8044: }
8045: unless ($wrongcc) {
8046: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8047: if ($crsenv{'internal.courseowner'} eq
8048: $env{'user.name'}.':'.$env{'user.domain'}) {
8049: $refused = '';
8050: }
1.1017 raeburn 8051: }
8052: }
1.1183 raeburn 8053: } elsif ($context eq 'requestauthor') {
8054: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8055: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8056: if ($env{'environment.requestauthor'} eq 'automatic') {
8057: $refused = '';
8058: } else {
8059: my %domdefaults = &get_domain_defaults($udom);
8060: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8061: my $checkbystatus;
8062: if ($env{'user.adv'}) {
8063: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8064: if ($disposition eq 'automatic') {
8065: $refused = '';
8066: } elsif ($disposition eq '') {
8067: $checkbystatus = 1;
8068: }
8069: } else {
8070: $checkbystatus = 1;
8071: }
8072: if ($checkbystatus) {
8073: if ($env{'environment.inststatus'}) {
8074: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8075: foreach my $type (@inststatuses) {
8076: if (($type ne '') &&
8077: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8078: $refused = '';
8079: }
8080: }
8081: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8082: $refused = '';
8083: }
8084: }
8085: }
8086: }
8087: }
1.1017 raeburn 8088: }
8089: if ($refused) {
1.947 raeburn 8090: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8091: ' '.$role.' '.$end.' '.$start.' by '.
8092: $env{'user.name'}.' at '.$env{'user.domain'});
8093: return 'refused';
8094: }
1.932 raeburn 8095: }
1.1131 raeburn 8096: } elsif ($role eq 'au') {
8097: if ($url ne '/'.$udom.'/') {
8098: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8099: ' to assign author role for '.$uname.':'.$udom.
8100: ' in domain: '.$url.' refused (wrong domain).');
8101: return 'refused';
8102: }
1.104 www 8103: }
1.21 www 8104: $mrole=$role;
8105: }
1.620 albertel 8106: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8107: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8108: if ($end) { $command.='_'.$end; }
1.21 www 8109: if ($start) {
8110: if ($end) {
1.81 www 8111: $command.='_'.$start;
1.21 www 8112: } else {
1.81 www 8113: $command.='_0_'.$start;
1.21 www 8114: }
8115: }
1.739 raeburn 8116: my $origstart = $start;
8117: my $origend = $end;
1.957 raeburn 8118: my $delflag;
1.357 www 8119: # actually delete
8120: if ($deleteflag) {
1.373 www 8121: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8122: # modify command to delete the role
1.620 albertel 8123: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8124: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8125: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8126: # set start and finish to negative values for userrolelog
8127: $start=-1;
8128: $end=-1;
1.957 raeburn 8129: $delflag = 1;
1.357 www 8130: }
8131: }
8132: # send command
1.349 www 8133: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8134: # log new user role if status is ok
1.349 www 8135: if ($answer eq 'ok') {
1.663 raeburn 8136: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8137: if (($role eq 'cc') || ($role eq 'in') ||
8138: ($role eq 'ep') || ($role eq 'ad') ||
8139: ($role eq 'ta') || ($role eq 'st') ||
8140: ($role=~/^cr/) || ($role eq 'gr') ||
8141: ($role eq 'co')) {
1.1200 raeburn 8142: # for course roles, perform group memberships changes triggered by role change.
8143: unless ($role =~ /^gr/) {
8144: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8145: $origstart,$selfenroll,$context);
8146: }
1.1184 raeburn 8147: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8148: $selfenroll,$context);
8149: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8150: ($role eq 'au') || ($role eq 'dc')) {
8151: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8152: $context);
8153: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8154: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8155: $context);
8156: }
1.1053 raeburn 8157: if ($role eq 'cc') {
8158: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8159: }
1.349 www 8160: }
8161: return $answer;
1.169 harris41 8162: }
8163:
1.1053 raeburn 8164: sub autoupdate_coowners {
8165: my ($url,$end,$start,$uname,$udom) = @_;
8166: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8167: if (($cdom ne '') && ($cnum ne '')) {
8168: my $now = time;
8169: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8170: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8171: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8172: my $instcode = $coursehash{'internal.coursecode'};
8173: if ($instcode ne '') {
1.1056 raeburn 8174: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8175: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8176: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8177: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8178: if ($result eq 'valid') {
8179: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8180: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8181: push(@newcoowners,$coowner);
8182: }
8183: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8184: push(@newcoowners,$uname.':'.$udom);
8185: }
8186: @newcoowners = sort(@newcoowners);
8187: } else {
8188: push(@newcoowners,$uname.':'.$udom);
8189: }
8190: } else {
8191: if ($coursehash{'internal.co-owners'}) {
8192: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8193: unless ($coowner eq $uname.':'.$udom) {
8194: push(@newcoowners,$coowner);
8195: }
8196: }
8197: unless (@newcoowners > 0) {
8198: $delcoowners = 1;
8199: $coowners = '';
8200: }
8201: }
8202: }
8203: if (@newcoowners || $delcoowners) {
8204: &store_coowners($cdom,$cnum,$coursehash{'home'},
8205: $delcoowners,@newcoowners);
8206: }
8207: }
8208: }
8209: }
8210: }
8211: }
8212: }
8213:
8214: sub store_coowners {
8215: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8216: my $cid = $cdom.'_'.$cnum;
8217: my ($coowners,$delresult,$putresult);
8218: if (@newcoowners) {
8219: $coowners = join(',',@newcoowners);
8220: my %coownershash = (
8221: 'internal.co-owners' => $coowners,
8222: );
8223: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8224: if ($putresult eq 'ok') {
8225: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8226: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8227: }
8228: }
8229: }
8230: if ($delcoowners) {
8231: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8232: if ($delresult eq 'ok') {
8233: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8234: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8235: }
8236: }
8237: }
8238: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8239: my %crsinfo =
8240: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8241: if (ref($crsinfo{$cid}) eq 'HASH') {
8242: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8243: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8244: }
8245: }
8246: }
8247:
1.169 harris41 8248: # -------------------------------------------------- Modify user authentication
1.197 www 8249: # Overrides without validation
8250:
1.169 harris41 8251: sub modifyuserauth {
8252: my ($udom,$uname,$umode,$upass)=@_;
8253: my $uhome=&homeserver($uname,$udom);
1.197 www 8254: unless (&allowed('mau',$udom)) { return 'refused'; }
8255: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8256: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8257: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8258: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8259: &escape($upass),$uhome);
1.620 albertel 8260: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8261: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8262: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8263: &log($udom,,$uname,$uhome,
1.620 albertel 8264: 'Authentication changed by '.$env{'user.domain'}.', '.
8265: $env{'user.name'}.', '.$umode.
1.197 www 8266: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8267: unless ($reply eq 'ok') {
1.197 www 8268: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8269: return 'error: '.$reply;
8270: }
1.170 harris41 8271: return 'ok';
1.80 www 8272: }
8273:
1.81 www 8274: # --------------------------------------------------------------- Modify a user
1.80 www 8275:
1.81 www 8276: sub modifyuser {
1.206 matthew 8277: my ($udom, $uname, $uid,
8278: $umode, $upass, $first,
8279: $middle, $last, $gene,
1.1058 raeburn 8280: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8281: $udom= &LONCAPA::clean_domain($udom);
8282: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8283: my $showcandelete = 'none';
8284: if (ref($candelete) eq 'ARRAY') {
8285: if (@{$candelete} > 0) {
8286: $showcandelete = join(', ',@{$candelete});
8287: }
8288: }
1.81 www 8289: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8290: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8291: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8292: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8293: ' desiredhome not specified').
1.620 albertel 8294: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8295: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8296: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8297: my $newuser;
8298: if ($uhome eq 'no_host') {
8299: $newuser = 1;
8300: }
1.80 www 8301: # ----------------------------------------------------------------- Create User
1.406 albertel 8302: if (($uhome eq 'no_host') &&
8303: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8304: my $unhome='';
1.844 albertel 8305: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8306: $unhome = $desiredhome;
1.620 albertel 8307: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8308: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8309: } else { # load balancing routine for determining $unhome
1.81 www 8310: my $loadm=10000000;
1.841 albertel 8311: my %servers = &get_servers($udom,'library');
8312: foreach my $tryserver (keys(%servers)) {
8313: my $answer=reply('load',$tryserver);
8314: if (($answer=~/\d+/) && ($answer<$loadm)) {
8315: $loadm=$answer;
8316: $unhome=$tryserver;
8317: }
1.80 www 8318: }
8319: }
8320: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8321: return 'error: unable to find a home server for '.$uname.
8322: ' in domain '.$udom;
1.80 www 8323: }
8324: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8325: &escape($upass),$unhome);
8326: unless ($reply eq 'ok') {
8327: return 'error: '.$reply;
8328: }
1.230 stredwic 8329: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8330: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8331: return 'error: unable verify users home machine.';
1.80 www 8332: }
1.209 matthew 8333: } # End of creation of new user
1.80 www 8334: # ---------------------------------------------------------------------- Add ID
8335: if ($uid) {
8336: $uid=~tr/A-Z/a-z/;
8337: my %uidhash=&idrget($udom,$uname);
1.196 www 8338: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8339: && (!$forceid)) {
1.80 www 8340: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8341: return 'error: user id "'.$uid.'" does not match '.
8342: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8343: }
8344: } else {
8345: &idput($udom,($uname => $uid));
8346: }
8347: }
8348: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8349: my @tmp=&get('environment',
1.899 raeburn 8350: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8351: 'permanentemail','inststatus'],
1.134 albertel 8352: $udom,$uname);
1.1075 raeburn 8353: my (%names,%oldnames);
1.313 matthew 8354: if ($tmp[0] =~ m/^error:.*/) {
8355: %names=();
8356: } else {
8357: %names = @tmp;
1.1075 raeburn 8358: %oldnames = %names;
1.313 matthew 8359: }
1.388 www 8360: #
1.1058 raeburn 8361: # If name, email and/or uid are blank (e.g., because an uploaded file
8362: # of users did not contain them), do not overwrite existing values
8363: # unless field is in $candelete array ref.
8364: #
8365:
8366: my @fields = ('firstname','middlename','lastname','generation',
8367: 'permanentemail','id');
8368: my %newvalues;
8369: if (ref($candelete) eq 'ARRAY') {
8370: foreach my $field (@fields) {
8371: if (grep(/^\Q$field\E$/,@{$candelete})) {
8372: if ($field eq 'firstname') {
8373: $names{$field} = $first;
8374: } elsif ($field eq 'middlename') {
8375: $names{$field} = $middle;
8376: } elsif ($field eq 'lastname') {
8377: $names{$field} = $last;
8378: } elsif ($field eq 'generation') {
8379: $names{$field} = $gene;
8380: } elsif ($field eq 'permanentemail') {
8381: $names{$field} = $email;
8382: } elsif ($field eq 'id') {
8383: $names{$field} = $uid;
8384: }
8385: }
8386: }
8387: }
1.388 www 8388: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8389: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8390: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8391: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8392: if ($email) {
8393: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8394: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8395: }
1.899 raeburn 8396: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8397: if (defined($inststatus)) {
8398: $names{'inststatus'} = '';
8399: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8400: if (ref($usertypes) eq 'HASH') {
8401: my @okstatuses;
8402: foreach my $item (split(/:/,$inststatus)) {
8403: if (defined($usertypes->{$item})) {
8404: push(@okstatuses,$item);
8405: }
8406: }
8407: if (@okstatuses) {
8408: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8409: }
8410: }
8411: }
1.1075 raeburn 8412: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8413: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8414: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8415: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8416: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8417: } else {
8418: $logmsg .= ' during self creation';
8419: }
1.1075 raeburn 8420: my $changed;
8421: if ($newuser) {
8422: $changed = 1;
8423: } else {
8424: foreach my $field (@fields) {
8425: if ($names{$field} ne $oldnames{$field}) {
8426: $changed = 1;
8427: last;
8428: }
8429: }
8430: }
8431: unless ($changed) {
8432: $logmsg = 'No changes in user information needed for: '.$logmsg;
8433: &logthis($logmsg);
8434: return 'ok';
8435: }
8436: my $reply = &put('environment', \%names, $udom,$uname);
8437: if ($reply ne 'ok') {
8438: return 'error: '.$reply;
8439: }
1.1087 raeburn 8440: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8441: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8442: }
1.1075 raeburn 8443: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8444: &devalidate_cache_new('namescache',$uname.':'.$udom);
8445: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8446: &logthis($logmsg);
1.134 albertel 8447: return 'ok';
1.80 www 8448: }
8449:
1.81 www 8450: # -------------------------------------------------------------- Modify student
1.80 www 8451:
1.81 www 8452: sub modifystudent {
8453: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8454: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8455: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8456: if (!$cid) {
1.620 albertel 8457: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8458: return 'not_in_class';
8459: }
1.80 www 8460: }
8461: # --------------------------------------------------------------- Make the user
1.81 www 8462: my $reply=&modifyuser
1.209 matthew 8463: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8464: $desiredhome,$email,$inststatus);
1.80 www 8465: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8466: # This will cause &modify_student_enrollment to get the uid from the
8467: # students environment
8468: $uid = undef if (!$forceid);
1.455 albertel 8469: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8470: $gene,$usec,$end,$start,$type,$locktype,
8471: $cid,$selfenroll,$context,$credits);
1.297 matthew 8472: return $reply;
8473: }
8474:
8475: sub modify_student_enrollment {
1.1216 raeburn 8476: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8477: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8478: my ($cdom,$cnum,$chome);
8479: if (!$cid) {
1.620 albertel 8480: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8481: return 'not_in_class';
8482: }
1.620 albertel 8483: $cdom=$env{'course.'.$cid.'.domain'};
8484: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8485: } else {
8486: ($cdom,$cnum)=split(/_/,$cid);
8487: }
1.620 albertel 8488: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8489: if (!$chome) {
1.457 raeburn 8490: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8491: }
1.455 albertel 8492: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8493: # Make sure the user exists
1.81 www 8494: my $uhome=&homeserver($uname,$udom);
8495: if (($uhome eq '') || ($uhome eq 'no_host')) {
8496: return 'error: no such user';
8497: }
1.297 matthew 8498: # Get student data if we were not given enough information
8499: if (!defined($first) || $first eq '' ||
8500: !defined($last) || $last eq '' ||
8501: !defined($uid) || $uid eq '' ||
8502: !defined($middle) || $middle eq '' ||
8503: !defined($gene) || $gene eq '') {
1.294 matthew 8504: # They did not supply us with enough data to enroll the student, so
8505: # we need to pick up more information.
1.297 matthew 8506: my %tmp = &get('environment',
1.294 matthew 8507: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8508: ,$udom,$uname);
8509:
1.800 albertel 8510: #foreach my $key (keys(%tmp)) {
8511: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8512: #}
1.294 matthew 8513: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8514: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8515: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8516: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8517: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8518: }
1.556 albertel 8519: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8520: my $user = "$uname:$udom";
8521: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8522: my $reply=cput('classlist',
1.1148 raeburn 8523: {$user =>
1.1216 raeburn 8524: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8525: $cdom,$cnum);
1.1148 raeburn 8526: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8527: &devalidate_getsection_cache($udom,$uname,$cid);
8528: } else {
1.81 www 8529: return 'error: '.$reply;
8530: }
1.297 matthew 8531: # Add student role to user
1.83 www 8532: my $uurl='/'.$cid;
1.81 www 8533: $uurl=~s/\_/\//g;
8534: if ($usec) {
8535: $uurl.='/'.$usec;
8536: }
1.1148 raeburn 8537: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8538: $selfenroll,$context);
8539: if ($result ne 'ok') {
8540: if ($old_entry{$user} ne '') {
8541: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8542: } else {
8543: $reply = &del('classlist',[$user],$cdom,$cnum);
8544: }
8545: }
8546: return $result;
1.21 www 8547: }
8548:
1.556 albertel 8549: sub format_name {
8550: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8551: my $name;
8552: if ($first ne 'lastname') {
8553: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8554: } else {
8555: if ($lastname=~/\S/) {
8556: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8557: $name=~s/\s+,/,/;
8558: } else {
8559: $name.= $firstname.' '.$middlename.' '.$generation;
8560: }
8561: }
8562: $name=~s/^\s+//;
8563: $name=~s/\s+$//;
8564: $name=~s/\s+/ /g;
8565: return $name;
8566: }
8567:
1.84 www 8568: # ------------------------------------------------- Write to course preferences
8569:
8570: sub writecoursepref {
8571: my ($courseid,%prefs)=@_;
8572: $courseid=~s/^\///;
8573: $courseid=~s/\_/\//g;
8574: my ($cdomain,$cnum)=split(/\//,$courseid);
8575: my $chome=homeserver($cnum,$cdomain);
8576: if (($chome eq '') || ($chome eq 'no_host')) {
8577: return 'error: no such course';
8578: }
8579: my $cstring='';
1.800 albertel 8580: foreach my $pref (keys(%prefs)) {
8581: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8582: }
1.84 www 8583: $cstring=~s/\&$//;
8584: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8585: }
8586:
8587: # ---------------------------------------------------------- Make/modify course
8588:
8589: sub createcourse {
1.741 raeburn 8590: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8591: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8592: $url=&declutter($url);
8593: my $cid='';
1.1028 raeburn 8594: if ($context eq 'requestcourses') {
8595: my $can_create = 0;
8596: my ($ownername,$ownerdom) = split(':',$course_owner);
8597: if ($udom eq $ownerdom) {
8598: if (&usertools_access($ownername,$ownerdom,$category,undef,
8599: $context)) {
8600: $can_create = 1;
8601: }
8602: } else {
8603: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8604: $category);
8605: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8606: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8607: if (@curr > 0) {
8608: my @options = qw(approval validate autolimit);
8609: my $optregex = join('|',@options);
8610: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8611: $can_create = 1;
8612: }
8613: }
8614: }
8615: }
8616: if ($can_create) {
8617: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8618: unless (&allowed('ccc',$udom)) {
8619: return 'refused';
8620: }
1.1017 raeburn 8621: }
8622: } else {
8623: return 'refused';
8624: }
1.1028 raeburn 8625: } elsif (!&allowed('ccc',$udom)) {
8626: return 'refused';
1.84 www 8627: }
1.1011 raeburn 8628: # --------------------------------------------------------------- Get Unique ID
8629: my $uname;
8630: if ($cnum =~ /^$match_courseid$/) {
8631: my $chome=&homeserver($cnum,$udom,'true');
8632: if (($chome eq '') || ($chome eq 'no_host')) {
8633: $uname = $cnum;
8634: } else {
1.1038 raeburn 8635: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8636: }
8637: } else {
1.1038 raeburn 8638: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8639: }
8640: return $uname if ($uname =~ /^error/);
8641: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8642: if (!defined($course_server)) {
8643: if (defined(&domain($udom,'primary'))) {
8644: $course_server = &domain($udom,'primary');
8645: } else {
8646: $course_server = $env{'user.home'};
8647: }
8648: }
8649: my %host_servers =
8650: &Apache::lonnet::get_servers($udom,'library');
8651: unless ($host_servers{$course_server}) {
8652: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8653: }
1.84 www 8654: # ------------------------------------------------------------- Make the course
8655: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8656: $course_server);
1.84 www 8657: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8658: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8659: if (($uhome eq '') || ($uhome eq 'no_host')) {
8660: return 'error: no such course';
8661: }
1.271 www 8662: # ----------------------------------------------------------------- Course made
1.516 raeburn 8663: # log existence
1.1029 raeburn 8664: my $now = time;
1.918 raeburn 8665: my $newcourse = {
8666: $udom.'_'.$uname => {
1.921 raeburn 8667: description => $description,
8668: inst_code => $inst_code,
8669: owner => $course_owner,
8670: type => $crstype,
1.1029 raeburn 8671: creator => $env{'user.name'}.':'.
8672: $env{'user.domain'},
8673: created => $now,
8674: context => $context,
1.918 raeburn 8675: },
8676: };
1.921 raeburn 8677: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8678: # set toplevel url
1.271 www 8679: my $topurl=$url;
8680: unless ($nonstandard) {
8681: # ------------------------------------------ For standard courses, make top url
8682: my $mapurl=&clutter($url);
1.278 www 8683: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8684: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8685: <map>
8686: <resource id="1" type="start"></resource>
8687: <resource id="2" src="$mapurl"></resource>
8688: <resource id="3" type="finish"></resource>
8689: <link index="1" from="1" to="2"></link>
8690: <link index="2" from="2" to="3"></link>
8691: </map>
8692: ENDINITMAP
8693: $topurl=&declutter(
1.638 albertel 8694: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8695: );
8696: }
8697: # ----------------------------------------------------------- Write preferences
1.84 www 8698: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8699: ('description' => $description,
8700: 'url' => $topurl,
8701: 'internal.creator' => $env{'user.name'}.':'.
8702: $env{'user.domain'},
8703: 'internal.created' => $now,
8704: 'internal.creationcontext' => $context)
8705: );
1.84 www 8706: return '/'.$udom.'/'.$uname;
8707: }
8708:
1.1011 raeburn 8709: # ------------------------------------------------------------------- Create ID
8710: sub generate_coursenum {
1.1038 raeburn 8711: my ($udom,$crstype) = @_;
1.1011 raeburn 8712: my $domdesc = &domain($udom);
8713: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8714: my $first;
8715: if ($crstype eq 'Community') {
8716: $first = '0';
8717: } else {
8718: $first = int(1+rand(9));
8719: }
8720: my $uname=$first.
1.1011 raeburn 8721: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8722: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8723: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8724: # ----------------------------------------------- Make sure that does not exist
8725: my $uhome=&homeserver($uname,$udom,'true');
8726: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8727: if ($crstype eq 'Community') {
8728: $first = '0';
8729: } else {
8730: $first = int(1+rand(9));
8731: }
8732: $uname=$first.
1.1011 raeburn 8733: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8734: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8735: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8736: $uhome=&homeserver($uname,$udom,'true');
8737: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8738: return 'error: unable to generate unique course-ID';
8739: }
8740: }
8741: return $uname;
8742: }
8743:
1.813 albertel 8744: sub is_course {
1.1167 droeschl 8745: my ($cdom, $cnum) = scalar(@_) == 1 ?
8746: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8747:
8748: return unless $cdom and $cnum;
8749:
8750: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8751: '.');
8752:
1.1219 raeburn 8753: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8754: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8755: }
8756:
1.1015 raeburn 8757: sub store_userdata {
8758: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8759: my $result;
1.1016 raeburn 8760: if ($datakey ne '') {
1.1013 raeburn 8761: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8762: if ($udom eq '' || $uname eq '') {
8763: $udom = $env{'user.domain'};
8764: $uname = $env{'user.name'};
8765: }
8766: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8767: if (($uhome eq '') || ($uhome eq 'no_host')) {
8768: $result = 'error: no_host';
8769: } else {
8770: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8771: $storehash->{'host'} = $perlvar{'lonHostID'};
8772:
8773: my $namevalue='';
8774: foreach my $key (keys(%{$storehash})) {
8775: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8776: }
8777: $namevalue=~s/\&$//;
1.1224 raeburn 8778: unless ($namespace eq 'courserequests') {
8779: $datakey = &escape($datakey);
8780: }
1.1105 raeburn 8781: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8782: $namevalue,$uhome);
1.1013 raeburn 8783: }
8784: } else {
8785: $result = 'error: data to store was not a hash reference';
8786: }
8787: } else {
8788: $result= 'error: invalid requestkey';
8789: }
8790: return $result;
8791: }
8792:
1.21 www 8793: # ---------------------------------------------------------- Assign Custom Role
8794:
8795: sub assigncustomrole {
1.957 raeburn 8796: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8797: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8798: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8799: }
8800:
8801: # ----------------------------------------------------------------- Revoke Role
8802:
8803: sub revokerole {
1.957 raeburn 8804: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8805: my $now=time;
1.965 raeburn 8806: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8807: }
8808:
8809: # ---------------------------------------------------------- Revoke Custom Role
8810:
8811: sub revokecustomrole {
1.957 raeburn 8812: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8813: my $now=time;
1.357 www 8814: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8815: $deleteflag,$selfenroll,$context);
1.17 www 8816: }
8817:
1.533 banghart 8818: # ------------------------------------------------------------ Disk usage
1.535 albertel 8819: sub diskusage {
1.955 raeburn 8820: my ($udom,$uname,$directorypath,$getpropath)=@_;
8821: $directorypath =~ s/\/$//;
8822: my $listing=&reply('du2:'.&escape($directorypath).':'
8823: .&escape($getpropath).':'.&escape($uname).':'
8824: .&escape($udom),homeserver($uname,$udom));
8825: if ($listing eq 'unknown_cmd') {
8826: if ($getpropath) {
8827: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8828: }
8829: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8830: }
1.514 albertel 8831: return $listing;
1.512 banghart 8832: }
8833:
1.566 banghart 8834: sub is_locked {
1.1096 raeburn 8835: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8836: my @check;
8837: my $is_locked;
1.1093 raeburn 8838: push (@check,$file_name);
1.613 albertel 8839: my %locked = &get('file_permissions',\@check,
1.620 albertel 8840: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8841: my ($tmp)=keys(%locked);
8842: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8843:
1.566 banghart 8844: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8845: $is_locked = 'false';
8846: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8847: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8848: $is_locked = 'true';
1.1096 raeburn 8849: if (ref($which) eq 'ARRAY') {
8850: push(@{$which},$entry);
8851: } else {
8852: last;
8853: }
1.745 raeburn 8854: }
8855: }
1.566 banghart 8856: } else {
8857: $is_locked = 'false';
8858: }
1.1093 raeburn 8859: return $is_locked;
1.566 banghart 8860: }
8861:
1.759 albertel 8862: sub declutter_portfile {
8863: my ($file) = @_;
1.833 albertel 8864: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8865: return $file;
8866: }
8867:
1.559 banghart 8868: # ------------------------------------------------------------- Mark as Read Only
8869:
8870: sub mark_as_readonly {
8871: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8872: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8873: my ($tmp)=keys(%current_permissions);
8874: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8875: foreach my $file (@{$files}) {
1.759 albertel 8876: $file = &declutter_portfile($file);
1.561 banghart 8877: push(@{$current_permissions{$file}},$what);
1.559 banghart 8878: }
1.613 albertel 8879: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8880: return;
8881: }
8882:
1.572 banghart 8883: # ------------------------------------------------------------Save Selected Files
8884:
8885: sub save_selected_files {
8886: my ($user, $path, @files) = @_;
8887: my $filename = $user."savedfiles";
1.573 banghart 8888: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8889: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8890: foreach my $file (@files) {
1.620 albertel 8891: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8892: }
8893: foreach my $file (@other_files) {
1.574 banghart 8894: print (OUT $file."\n");
1.572 banghart 8895: }
1.574 banghart 8896: close (OUT);
1.572 banghart 8897: return 'ok';
8898: }
8899:
1.574 banghart 8900: sub clear_selected_files {
8901: my ($user) = @_;
8902: my $filename = $user."savedfiles";
1.1117 foxr 8903: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8904: print (OUT undef);
8905: close (OUT);
8906: return ("ok");
8907: }
8908:
1.572 banghart 8909: sub files_in_path {
8910: my ($user, $path) = @_;
8911: my $filename = $user."savedfiles";
8912: my %return_files;
1.1117 foxr 8913: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8914: while (my $line_in = <IN>) {
1.574 banghart 8915: chomp ($line_in);
8916: my @paths_and_file = split (m!/!, $line_in);
8917: my $file_part = pop (@paths_and_file);
8918: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8919: $path_part.='/';
8920: my $path_and_file = $path_part.$file_part;
8921: if ($path_part eq $path) {
8922: $return_files{$file_part}= 'selected';
8923: }
8924: }
1.574 banghart 8925: close (IN);
8926: return (\%return_files);
1.572 banghart 8927: }
8928:
8929: # called in portfolio select mode, to show files selected NOT in current directory
8930: sub files_not_in_path {
8931: my ($user, $path) = @_;
8932: my $filename = $user."savedfiles";
8933: my @return_files;
8934: my $path_part;
1.1117 foxr 8935: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8936: while (my $line = <IN>) {
1.572 banghart 8937: #ok, I know it's clunky, but I want it to work
1.800 albertel 8938: my @paths_and_file = split(m|/|, $line);
8939: my $file_part = pop(@paths_and_file);
8940: chomp($file_part);
8941: my $path_part = join('/', @paths_and_file);
1.572 banghart 8942: $path_part .= '/';
8943: my $path_and_file = $path_part.$file_part;
8944: if ($path_part ne $path) {
1.800 albertel 8945: push(@return_files, ($path_and_file));
1.572 banghart 8946: }
8947: }
1.800 albertel 8948: close(OUT);
1.574 banghart 8949: return (@return_files);
1.572 banghart 8950: }
8951:
1.745 raeburn 8952: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8953:
1.745 raeburn 8954: sub get_portfile_permissions {
8955: my ($domain,$user) = @_;
1.613 albertel 8956: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8957: my ($tmp)=keys(%current_permissions);
8958: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8959: return \%current_permissions;
8960: }
8961:
8962: #---------------------------------------------Get portfolio file access controls
8963:
1.749 raeburn 8964: sub get_access_controls {
1.745 raeburn 8965: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8966: my %access;
8967: my $real_file = $file;
8968: $file =~ s/\.meta$//;
1.745 raeburn 8969: if (defined($file)) {
1.749 raeburn 8970: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8971: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8972: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8973: }
8974: }
1.745 raeburn 8975: } else {
1.749 raeburn 8976: foreach my $key (keys(%{$current_permissions})) {
8977: if ($key =~ /\0accesscontrol$/) {
8978: if (defined($group)) {
8979: if ($key !~ m-^\Q$group\E/-) {
8980: next;
8981: }
8982: }
8983: my ($fullpath) = split(/\0/,$key);
8984: if (ref($$current_permissions{$key}) eq 'HASH') {
8985: foreach my $control (keys(%{$$current_permissions{$key}})) {
8986: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8987: }
8988: }
8989: }
8990: }
8991: }
8992: return %access;
8993: }
8994:
8995: sub modify_access_controls {
8996: my ($file_name,$changes,$domain,$user)=@_;
8997: my ($outcome,$deloutcome);
8998: my %store_permissions;
8999: my %new_values;
9000: my %new_control;
9001: my %translation;
9002: my @deletions = ();
9003: my $now = time;
9004: if (exists($$changes{'activate'})) {
9005: if (ref($$changes{'activate'}) eq 'HASH') {
9006: my @newitems = sort(keys(%{$$changes{'activate'}}));
9007: my $numnew = scalar(@newitems);
9008: for (my $i=0; $i<$numnew; $i++) {
9009: my $newkey = $newitems[$i];
9010: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9011: if ($newkey =~ /^\d+:/) {
9012: $newkey =~ s/^(\d+)/$newid/;
9013: $translation{$1} = $newid;
9014: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9015: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9016: $translation{$1} = $newid;
9017: }
1.749 raeburn 9018: $new_values{$file_name."\0".$newkey} =
9019: $$changes{'activate'}{$newitems[$i]};
9020: $new_control{$newkey} = $now;
9021: }
9022: }
9023: }
9024: my %todelete;
9025: my %changed_items;
9026: foreach my $action ('delete','update') {
9027: if (exists($$changes{$action})) {
9028: if (ref($$changes{$action}) eq 'HASH') {
9029: foreach my $key (keys(%{$$changes{$action}})) {
9030: my ($itemnum) = ($key =~ /^([^:]+):/);
9031: if ($action eq 'delete') {
9032: $todelete{$itemnum} = 1;
9033: } else {
9034: $changed_items{$itemnum} = $key;
9035: }
9036: }
1.745 raeburn 9037: }
9038: }
1.749 raeburn 9039: }
9040: # get lock on access controls for file.
9041: my $lockhash = {
9042: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9043: ':'.$env{'user.domain'},
9044: };
9045: my $tries = 0;
9046: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9047:
9048: while (($gotlock ne 'ok') && $tries <3) {
9049: $tries ++;
9050: sleep 1;
9051: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9052: }
9053: if ($gotlock eq 'ok') {
9054: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9055: my ($tmp)=keys(%curr_permissions);
9056: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9057: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9058: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9059: if (ref($curr_controls) eq 'HASH') {
9060: foreach my $control_item (keys(%{$curr_controls})) {
9061: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9062: if (defined($todelete{$itemnum})) {
9063: push(@deletions,$file_name."\0".$control_item);
9064: } else {
9065: if (defined($changed_items{$itemnum})) {
9066: $new_control{$changed_items{$itemnum}} = $now;
9067: push(@deletions,$file_name."\0".$control_item);
9068: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9069: } else {
9070: $new_control{$control_item} = $$curr_controls{$control_item};
9071: }
9072: }
1.745 raeburn 9073: }
9074: }
9075: }
1.970 raeburn 9076: my ($group);
9077: if (&is_course($domain,$user)) {
9078: ($group,my $file) = split(/\//,$file_name,2);
9079: }
1.749 raeburn 9080: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9081: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9082: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9083: # remove lock
9084: my @del_lock = ($file_name."\0".'locked_access_records');
9085: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9086: my $sqlresult =
1.970 raeburn 9087: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9088: $group);
1.749 raeburn 9089: } else {
9090: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9091: }
1.749 raeburn 9092: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9093: }
9094:
1.827 raeburn 9095: sub make_public_indefinitely {
9096: my ($requrl) = @_;
9097: my $now = time;
9098: my $action = 'activate';
9099: my $aclnum = 0;
9100: if (&is_portfolio_url($requrl)) {
9101: my (undef,$udom,$unum,$file_name,$group) =
9102: &parse_portfolio_url($requrl);
9103: my $current_perms = &get_portfile_permissions($udom,$unum);
9104: my %access_controls = &get_access_controls($current_perms,
9105: $group,$file_name);
9106: foreach my $key (keys(%{$access_controls{$file_name}})) {
9107: my ($num,$scope,$end,$start) =
9108: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9109: if ($scope eq 'public') {
9110: if ($start <= $now && $end == 0) {
9111: $action = 'none';
9112: } else {
9113: $action = 'update';
9114: $aclnum = $num;
9115: }
9116: last;
9117: }
9118: }
9119: if ($action eq 'none') {
9120: return 'ok';
9121: } else {
9122: my %changes;
9123: my $newend = 0;
9124: my $newstart = $now;
9125: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9126: $changes{$action}{$newkey} = {
9127: type => 'public',
9128: time => {
9129: start => $newstart,
9130: end => $newend,
9131: },
9132: };
9133: my ($outcome,$deloutcome,$new_values,$translation) =
9134: &modify_access_controls($file_name,\%changes,$udom,$unum);
9135: return $outcome;
9136: }
9137: } else {
9138: return 'invalid';
9139: }
9140: }
9141:
1.745 raeburn 9142: #------------------------------------------------------Get Marked as Read Only
9143:
9144: sub get_marked_as_readonly {
9145: my ($domain,$user,$what,$group) = @_;
9146: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9147: my @readonly_files;
1.629 banghart 9148: my $cmp1=$what;
9149: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9150: while (my ($file_name,$value) = each(%{$current_permissions})) {
9151: if (defined($group)) {
9152: if ($file_name !~ m-^\Q$group\E/-) {
9153: next;
9154: }
9155: }
1.561 banghart 9156: if (ref($value) eq "ARRAY"){
9157: foreach my $stored_what (@{$value}) {
1.629 banghart 9158: my $cmp2=$stored_what;
1.759 albertel 9159: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9160: $cmp2=join('',@{$stored_what});
1.745 raeburn 9161: }
1.629 banghart 9162: if ($cmp1 eq $cmp2) {
1.561 banghart 9163: push(@readonly_files, $file_name);
1.745 raeburn 9164: last;
1.563 banghart 9165: } elsif (!defined($what)) {
9166: push(@readonly_files, $file_name);
1.745 raeburn 9167: last;
1.561 banghart 9168: }
9169: }
1.745 raeburn 9170: }
1.561 banghart 9171: }
9172: return @readonly_files;
9173: }
1.577 banghart 9174: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9175:
1.577 banghart 9176: sub get_marked_as_readonly_hash {
1.745 raeburn 9177: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9178: my %readonly_files;
1.745 raeburn 9179: while (my ($file_name,$value) = each(%{$current_permissions})) {
9180: if (defined($group)) {
9181: if ($file_name !~ m-^\Q$group\E/-) {
9182: next;
9183: }
9184: }
1.577 banghart 9185: if (ref($value) eq "ARRAY"){
9186: foreach my $stored_what (@{$value}) {
1.745 raeburn 9187: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9188: foreach my $lock_descriptor(@{$stored_what}) {
9189: if ($lock_descriptor eq 'graded') {
9190: $readonly_files{$file_name} = 'graded';
9191: } elsif ($lock_descriptor eq 'handback') {
9192: $readonly_files{$file_name} = 'handback';
9193: } else {
9194: if (!exists($readonly_files{$file_name})) {
9195: $readonly_files{$file_name} = 'locked';
9196: }
9197: }
1.745 raeburn 9198: }
1.750 banghart 9199: }
1.577 banghart 9200: }
9201: }
9202: }
9203: return %readonly_files;
9204: }
1.559 banghart 9205: # ------------------------------------------------------------ Unmark as Read Only
9206:
9207: sub unmark_as_readonly {
1.629 banghart 9208: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9209: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9210: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9211: $file_name = &declutter_portfile($file_name);
1.634 albertel 9212: my $symb_crs = $what;
9213: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9214: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9215: my ($tmp)=keys(%current_permissions);
9216: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9217: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9218: foreach my $file (@readonly_files) {
1.759 albertel 9219: my $clean_file = &declutter_portfile($file);
9220: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9221: my $current_locks = $current_permissions{$file};
1.563 banghart 9222: my @new_locks;
9223: my @del_keys;
9224: if (ref($current_locks) eq "ARRAY"){
9225: foreach my $locker (@{$current_locks}) {
1.632 albertel 9226: my $compare=$locker;
1.749 raeburn 9227: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9228: $compare=join('',@{$locker});
1.746 raeburn 9229: if ($compare ne $symb_crs) {
9230: push(@new_locks, $locker);
9231: }
1.563 banghart 9232: }
9233: }
1.650 albertel 9234: if (scalar(@new_locks) > 0) {
1.563 banghart 9235: $current_permissions{$file} = \@new_locks;
9236: } else {
9237: push(@del_keys, $file);
1.613 albertel 9238: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9239: delete($current_permissions{$file});
1.563 banghart 9240: }
9241: }
1.561 banghart 9242: }
1.613 albertel 9243: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9244: return;
9245: }
1.512 banghart 9246:
1.17 www 9247: # ------------------------------------------------------------ Directory lister
9248:
9249: sub dirlist {
1.955 raeburn 9250: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9251: $uri=~s/^\///;
9252: $uri=~s/\/$//;
1.253 stredwic 9253: my ($udom, $uname);
1.955 raeburn 9254: if ($getuserdir) {
1.253 stredwic 9255: $udom = $userdomain;
9256: $uname = $username;
1.955 raeburn 9257: } else {
9258: (undef,$udom,$uname)=split(/\//,$uri);
9259: if(defined($userdomain)) {
9260: $udom = $userdomain;
9261: }
9262: if(defined($username)) {
9263: $uname = $username;
9264: }
1.253 stredwic 9265: }
1.955 raeburn 9266: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9267:
1.955 raeburn 9268: $dirRoot = $perlvar{'lonDocRoot'};
9269: if (defined($getpropath)) {
9270: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9271: $dirRoot =~ s/\/$//;
1.955 raeburn 9272: } elsif (defined($getuserdir)) {
9273: my $subdir=$uname.'__';
9274: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9275: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9276: ."/$udom/$subdir/$uname";
9277: } elsif (defined($alternateRoot)) {
9278: $dirRoot = $alternateRoot;
1.751 banghart 9279: }
1.253 stredwic 9280:
9281: if($udom) {
9282: if($uname) {
1.1135 raeburn 9283: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9284: if ($uhome eq 'no_host') {
9285: return ([],'no_host');
9286: }
1.955 raeburn 9287: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9288: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9289: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9290: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9291: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9292: } else {
9293: @listing_results = map { &unescape($_); } split(/:/,$listing);
9294: }
1.605 matthew 9295: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9296: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9297: @listing_results = split(/:/,$listing);
9298: } else {
9299: @listing_results = map { &unescape($_); } split(/:/,$listing);
9300: }
1.1135 raeburn 9301: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9302: ($listing eq 'rejected') || ($listing eq 'refused') ||
9303: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9304: return ([],$listing);
9305: } else {
9306: return (\@listing_results);
1.1135 raeburn 9307: }
1.955 raeburn 9308: } elsif(!$alternateRoot) {
1.1136 raeburn 9309: my (%allusers,%listerror);
1.841 albertel 9310: my %servers = &get_servers($udom,'library');
1.955 raeburn 9311: foreach my $tryserver (keys(%servers)) {
9312: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9313: &escape($udom),$tryserver);
9314: if ($listing eq 'unknown_cmd') {
9315: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9316: $udom, $tryserver);
9317: } else {
9318: @listing_results = map { &unescape($_); } split(/:/,$listing);
9319: }
1.841 albertel 9320: if ($listing eq 'unknown_cmd') {
9321: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9322: $udom, $tryserver);
9323: @listing_results = split(/:/,$listing);
9324: } else {
9325: @listing_results =
9326: map { &unescape($_); } split(/:/,$listing);
9327: }
1.1136 raeburn 9328: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9329: ($listing eq 'rejected') || ($listing eq 'refused') ||
9330: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9331: $listerror{$tryserver} = $listing;
9332: } else {
1.841 albertel 9333: foreach my $line (@listing_results) {
9334: my ($entry) = split(/&/,$line,2);
9335: $allusers{$entry} = 1;
9336: }
9337: }
1.253 stredwic 9338: }
1.1136 raeburn 9339: my @alluserslist=();
1.800 albertel 9340: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9341: push(@alluserslist,$user.'&user');
1.253 stredwic 9342: }
1.1136 raeburn 9343: return (\@alluserslist);
1.253 stredwic 9344: } else {
1.1136 raeburn 9345: return ([],'missing username');
1.253 stredwic 9346: }
1.955 raeburn 9347: } elsif(!defined($getpropath)) {
1.1136 raeburn 9348: my $path = $perlvar{'lonDocRoot'}.'/res/';
9349: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9350: return (\@all_domains);
1.955 raeburn 9351: } else {
1.1136 raeburn 9352: return ([],'missing domain');
1.275 stredwic 9353: }
9354: }
9355:
9356: # --------------------------------------------- GetFileTimestamp
9357: # This function utilizes dirlist and returns the date stamp for
9358: # when it was last modified. It will also return an error of -1
9359: # if an error occurs
9360:
9361: sub GetFileTimestamp {
1.955 raeburn 9362: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9363: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9364: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9365: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9366: undef,$getuserdir);
9367: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9368: return -1;
9369: }
9370: if (ref($fileref) eq 'ARRAY') {
9371: my @stats = split('&',$fileref->[0]);
1.375 matthew 9372: # @stats contains first the filename, then the stat output
9373: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9374: } else {
9375: return -1;
1.253 stredwic 9376: }
1.26 www 9377: }
9378:
1.712 albertel 9379: sub stat_file {
9380: my ($uri) = @_;
1.787 albertel 9381: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9382:
1.955 raeburn 9383: my ($udom,$uname,$file);
1.712 albertel 9384: if ($uri =~ m-^/(uploaded|editupload)/-) {
9385: ($udom,$uname,$file) =
1.811 albertel 9386: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9387: $file = 'userfiles/'.$file;
9388: }
9389: if ($uri =~ m-^/res/-) {
9390: ($udom,$uname) =
1.807 albertel 9391: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9392: $file = $uri;
9393: }
9394:
9395: if (!$udom || !$uname || !$file) {
9396: # unable to handle the uri
9397: return ();
9398: }
1.956 raeburn 9399: my $getpropath;
9400: if ($file =~ /^userfiles\//) {
9401: $getpropath = 1;
9402: }
1.1136 raeburn 9403: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9404: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9405: return ();
9406: } else {
9407: if (ref($listref) eq 'ARRAY') {
9408: my @stats = split('&',$listref->[0]);
9409: shift(@stats); #filename is first
9410: return @stats;
9411: }
1.712 albertel 9412: }
9413: return ();
9414: }
9415:
1.26 www 9416: # -------------------------------------------------------- Value of a Condition
9417:
1.713 albertel 9418: # gets the value of a specific preevaluated condition
9419: # stored in the string $env{user.state.<cid>}
9420: # or looks up a condition reference in the bighash and if if hasn't
9421: # already been evaluated recurses into docondval to get the value of
9422: # the condition, then memoizing it to
9423: # $env{user.state.<cid>.<condition>}
1.40 www 9424: sub directcondval {
9425: my $number=shift;
1.620 albertel 9426: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9427: &Apache::lonuserstate::evalstate();
9428: }
1.713 albertel 9429: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9430: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9431: } elsif ($number =~ /^_/) {
9432: my $sub_condition;
9433: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9434: &GDBM_READER(),0640)) {
9435: $sub_condition=$bighash{'conditions'.$number};
9436: untie(%bighash);
9437: }
9438: my $value = &docondval($sub_condition);
1.949 raeburn 9439: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9440: return $value;
9441: }
1.620 albertel 9442: if ($env{'user.state.'.$env{'request.course.id'}}) {
9443: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9444: } else {
9445: return 2;
9446: }
9447: }
9448:
1.713 albertel 9449: # get the collection of conditions for this resource
1.26 www 9450: sub condval {
9451: my $condidx=shift;
1.54 www 9452: my $allpathcond='';
1.713 albertel 9453: foreach my $cond (split(/\|/,$condidx)) {
9454: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9455: $allpathcond.=
9456: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9457: }
1.191 harris41 9458: }
1.54 www 9459: $allpathcond=~s/\|$//;
1.713 albertel 9460: return &docondval($allpathcond);
9461: }
9462:
9463: #evaluates an expression of conditions
9464: sub docondval {
9465: my ($allpathcond) = @_;
9466: my $result=0;
9467: if ($env{'request.course.id'}
9468: && defined($allpathcond)) {
9469: my $operand='|';
9470: my @stack;
9471: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9472: if ($chunk eq '(') {
9473: push @stack,($operand,$result);
9474: } elsif ($chunk eq ')') {
9475: my $before=pop @stack;
9476: if (pop @stack eq '&') {
9477: $result=$result>$before?$before:$result;
9478: } else {
9479: $result=$result>$before?$result:$before;
9480: }
9481: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9482: $operand=$chunk;
9483: } else {
9484: my $new=directcondval($chunk);
9485: if ($operand eq '&') {
9486: $result=$result>$new?$new:$result;
9487: } else {
9488: $result=$result>$new?$result:$new;
9489: }
9490: }
9491: }
1.26 www 9492: }
9493: return $result;
1.421 albertel 9494: }
9495:
9496: # ---------------------------------------------------- Devalidate courseresdata
9497:
9498: sub devalidatecourseresdata {
9499: my ($coursenum,$coursedomain)=@_;
9500: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9501: &devalidate_cache_new('courseres',$hashid);
1.28 www 9502: }
9503:
1.763 www 9504:
1.200 www 9505: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9506: #
9507: # Parameters:
9508: # $coursenum - Number of the course.
9509: # $coursedomain - Domain at which the course was created.
9510: # Returns:
9511: # A hash of the course parameters along (I think) with timestamps
9512: # and version info.
1.877 foxr 9513:
1.624 albertel 9514: sub get_courseresdata {
9515: my ($coursenum,$coursedomain)=@_;
1.200 www 9516: my $coursehom=&homeserver($coursenum,$coursedomain);
9517: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9518: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9519: my %dumpreply;
1.417 albertel 9520: unless (defined($cached)) {
1.624 albertel 9521: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9522: $result=\%dumpreply;
1.251 albertel 9523: my ($tmp) = keys(%dumpreply);
9524: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9525: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9526: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9527: return $tmp;
1.416 albertel 9528: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9529: $result=undef;
1.599 albertel 9530: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9531: }
9532: }
1.624 albertel 9533: return $result;
9534: }
9535:
1.633 albertel 9536: sub devalidateuserresdata {
9537: my ($uname,$udom)=@_;
9538: my $hashid="$udom:$uname";
9539: &devalidate_cache_new('userres',$hashid);
9540: }
9541:
1.624 albertel 9542: sub get_userresdata {
9543: my ($uname,$udom)=@_;
9544: #most student don\'t have any data set, check if there is some data
9545: if (&EXT_cache_status($udom,$uname)) { return undef; }
9546:
9547: my $hashid="$udom:$uname";
9548: my ($result,$cached)=&is_cached_new('userres',$hashid);
9549: if (!defined($cached)) {
9550: my %resourcedata=&dump('resourcedata',$udom,$uname);
9551: $result=\%resourcedata;
9552: &do_cache_new('userres',$hashid,$result,600);
9553: }
9554: my ($tmp)=keys(%$result);
9555: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9556: return $result;
9557: }
9558: #error 2 occurs when the .db doesn't exist
9559: if ($tmp!~/error: 2 /) {
1.672 albertel 9560: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9561: " Trying to get resource data for ".
9562: $uname." at ".$udom.": ".
9563: $tmp."</font>");
9564: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9565: #&EXT_cache_set($udom,$uname);
9566: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9567: undef($tmp); # not really an error so don't send it back
1.624 albertel 9568: }
9569: return $tmp;
9570: }
1.879 foxr 9571: #----------------------------------------------- resdata - return resource data
9572: # Purpose:
9573: # Return resource data for either users or for a course.
9574: # Parameters:
9575: # $name - Course/user name.
9576: # $domain - Name of the domain the user/course is registered on.
9577: # $type - Type of thing $name is (must be 'course' or 'user'
9578: # @which - Array of names of resources desired.
9579: # Returns:
9580: # The value of the first reasource in @which that is found in the
9581: # resource hash.
9582: # Exceptional Conditions:
9583: # If the $type passed in is not valid (not the string 'course' or
9584: # 'user', an undefined reference is returned.
9585: # If none of the resources are found, an undef is returned
1.624 albertel 9586: sub resdata {
9587: my ($name,$domain,$type,@which)=@_;
9588: my $result;
9589: if ($type eq 'course') {
9590: $result=&get_courseresdata($name,$domain);
9591: } elsif ($type eq 'user') {
9592: $result=&get_userresdata($name,$domain);
9593: }
9594: if (!ref($result)) { return $result; }
1.251 albertel 9595: foreach my $item (@which) {
1.927 albertel 9596: if (defined($result->{$item->[0]})) {
9597: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9598: }
1.250 albertel 9599: }
1.291 albertel 9600: return undef;
1.200 www 9601: }
9602:
1.379 matthew 9603: #
9604: # EXT resource caching routines
9605: #
9606:
9607: sub clear_EXT_cache_status {
1.383 albertel 9608: &delenv('cache.EXT.');
1.379 matthew 9609: }
9610:
9611: sub EXT_cache_status {
9612: my ($target_domain,$target_user) = @_;
1.383 albertel 9613: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9614: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9615: # We know already the user has no data
9616: return 1;
9617: } else {
9618: return 0;
9619: }
9620: }
9621:
9622: sub EXT_cache_set {
9623: my ($target_domain,$target_user) = @_;
1.383 albertel 9624: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9625: #&appenv({$cachename => time});
1.379 matthew 9626: }
9627:
1.28 www 9628: # --------------------------------------------------------- Value of a Variable
1.58 www 9629: sub EXT {
1.715 albertel 9630:
1.1228 raeburn 9631: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9632: unless ($varname) { return ''; }
1.218 albertel 9633: #get real user name/domain, courseid and symb
9634: my $courseid;
1.359 albertel 9635: my $publicuser;
1.427 www 9636: if ($symbparm) {
9637: $symbparm=&get_symb_from_alias($symbparm);
9638: }
1.218 albertel 9639: if (!($uname && $udom)) {
1.790 albertel 9640: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9641: if (!$symbparm) { $symbparm=$cursymb; }
9642: } else {
1.620 albertel 9643: $courseid=$env{'request.course.id'};
1.218 albertel 9644: }
1.48 www 9645: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9646: my $rest;
1.320 albertel 9647: if (defined($therest[0])) {
1.48 www 9648: $rest=join('.',@therest);
9649: } else {
9650: $rest='';
9651: }
1.320 albertel 9652:
1.57 www 9653: my $qualifierrest=$qualifier;
9654: if ($rest) { $qualifierrest.='.'.$rest; }
9655: my $spacequalifierrest=$space;
9656: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9657: if ($realm eq 'user') {
1.48 www 9658: # --------------------------------------------------------------- user.resource
9659: if ($space eq 'resource') {
1.651 albertel 9660: if ( (defined($Apache::lonhomework::parsing_a_problem)
9661: || defined($Apache::lonhomework::parsing_a_task))
9662: &&
1.744 albertel 9663: ($symbparm eq &symbread()) ) {
9664: # if we are in the middle of processing the resource the
9665: # get the value we are planning on committing
9666: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9667: return $Apache::lonhomework::results{$qualifierrest};
9668: } else {
9669: return $Apache::lonhomework::history{$qualifierrest};
9670: }
1.335 albertel 9671: } else {
1.359 albertel 9672: my %restored;
1.620 albertel 9673: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9674: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9675: } else {
9676: %restored=&restore($symbparm,$courseid,$udom,$uname);
9677: }
1.335 albertel 9678: return $restored{$qualifierrest};
9679: }
1.48 www 9680: # ----------------------------------------------------------------- user.access
9681: } elsif ($space eq 'access') {
1.218 albertel 9682: # FIXME - not supporting calls for a specific user
1.48 www 9683: return &allowed($qualifier,$rest);
9684: # ------------------------------------------ user.preferences, user.environment
9685: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9686: if (($uname eq $env{'user.name'}) &&
9687: ($udom eq $env{'user.domain'})) {
9688: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9689: } else {
1.359 albertel 9690: my %returnhash;
9691: if (!$publicuser) {
9692: %returnhash=&userenvironment($udom,$uname,
9693: $qualifierrest);
9694: }
1.218 albertel 9695: return $returnhash{$qualifierrest};
9696: }
1.48 www 9697: # ----------------------------------------------------------------- user.course
9698: } elsif ($space eq 'course') {
1.218 albertel 9699: # FIXME - not supporting calls for a specific user
1.620 albertel 9700: return $env{join('.',('request.course',$qualifier))};
1.48 www 9701: # ------------------------------------------------------------------- user.role
9702: } elsif ($space eq 'role') {
1.218 albertel 9703: # FIXME - not supporting calls for a specific user
1.620 albertel 9704: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9705: if ($qualifier eq 'value') {
9706: return $role;
9707: } elsif ($qualifier eq 'extent') {
9708: return $where;
9709: }
9710: # ----------------------------------------------------------------- user.domain
9711: } elsif ($space eq 'domain') {
1.218 albertel 9712: return $udom;
1.48 www 9713: # ------------------------------------------------------------------- user.name
9714: } elsif ($space eq 'name') {
1.218 albertel 9715: return $uname;
1.48 www 9716: # ---------------------------------------------------- Any other user namespace
1.29 www 9717: } else {
1.359 albertel 9718: my %reply;
9719: if (!$publicuser) {
9720: %reply=&get($space,[$qualifierrest],$udom,$uname);
9721: }
9722: return $reply{$qualifierrest};
1.48 www 9723: }
1.236 www 9724: } elsif ($realm eq 'query') {
9725: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9726: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9727: [$spacequalifierrest]);
1.620 albertel 9728: return $env{'form.'.$spacequalifierrest};
1.236 www 9729: } elsif ($realm eq 'request') {
1.48 www 9730: # ------------------------------------------------------------- request.browser
9731: if ($space eq 'browser') {
1.1145 bisitz 9732: return $env{'browser.'.$qualifier};
1.57 www 9733: # ------------------------------------------------------------ request.filename
9734: } else {
1.620 albertel 9735: return $env{'request.'.$spacequalifierrest};
1.29 www 9736: }
1.28 www 9737: } elsif ($realm eq 'course') {
1.48 www 9738: # ---------------------------------------------------------- course.description
1.620 albertel 9739: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9740: } elsif ($realm eq 'resource') {
1.165 www 9741:
1.620 albertel 9742: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9743: if (!$symbparm) { $symbparm=&symbread(); }
9744: }
1.693 albertel 9745:
9746: if ($space eq 'title') {
9747: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9748: return &gettitle($symbparm);
9749: }
9750:
9751: if ($space eq 'map') {
9752: my ($map) = &decode_symb($symbparm);
9753: return &symbread($map);
9754: }
1.905 albertel 9755: if ($space eq 'filename') {
9756: if ($symbparm) {
9757: return &clutter((&decode_symb($symbparm))[2]);
9758: }
9759: return &hreflocation('',$env{'request.filename'});
9760: }
1.693 albertel 9761:
9762: my ($section, $group, @groups);
1.593 albertel 9763: my ($courselevelm,$courselevel);
1.1228 raeburn 9764: if (($courseid eq '') && ($cid)) {
9765: $courseid = $cid;
9766: }
9767: if (($symbparm && $courseid) &&
9768: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9769:
1.218 albertel 9770: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9771:
1.60 www 9772: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9773: my $symbp=$symbparm;
1.735 albertel 9774: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9775:
9776: my $symbparm=$symbp.'.'.$spacequalifierrest;
9777: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9778:
1.620 albertel 9779: if (($env{'user.name'} eq $uname) &&
9780: ($env{'user.domain'} eq $udom)) {
9781: $section=$env{'request.course.sec'};
1.733 raeburn 9782: @groups = split(/:/,$env{'request.course.groups'});
9783: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9784: } else {
1.539 albertel 9785: if (! defined($usection)) {
1.551 albertel 9786: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9787: } else {
9788: $section = $usection;
9789: }
1.733 raeburn 9790: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9791: }
9792:
9793: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9794: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9795: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9796:
1.593 albertel 9797: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9798: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9799: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9800:
1.60 www 9801: # ----------------------------------------------------------- first, check user
1.624 albertel 9802:
9803: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9804: ([$courselevelr,'resource'],
9805: [$courselevelm,'map' ],
9806: [$courselevel, 'course' ]));
1.931 albertel 9807: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9808:
1.594 albertel 9809: # ------------------------------------------------ second, check some of course
1.684 raeburn 9810: my $coursereply;
1.691 raeburn 9811: if (@groups > 0) {
9812: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9813: $mapparm,$spacequalifierrest);
1.927 albertel 9814: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9815: }
1.96 www 9816:
1.684 raeburn 9817: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9818: $env{'course.'.$courseid.'.domain'},
9819: 'course',
9820: ([$seclevelr, 'resource'],
9821: [$seclevelm, 'map' ],
9822: [$seclevel, 'course' ],
9823: [$courselevelr,'resource']));
9824: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9825:
1.60 www 9826: # ------------------------------------------------------ third, check map parms
1.218 albertel 9827: my %parmhash=();
9828: my $thisparm='';
9829: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9830: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9831: &GDBM_READER(),0640)) {
1.218 albertel 9832: $thisparm=$parmhash{$symbparm};
9833: untie(%parmhash);
9834: }
1.927 albertel 9835: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9836: }
1.594 albertel 9837: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9838:
1.218 albertel 9839: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9840: my $filename;
9841: if (!$symbparm) { $symbparm=&symbread(); }
9842: if ($symbparm) {
1.409 www 9843: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9844: } else {
1.620 albertel 9845: $filename=$env{'request.filename'};
1.282 albertel 9846: }
9847: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9848: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9849: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9850: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9851:
1.927 albertel 9852: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9853: if ($symbparm && defined($courseid) &&
1.620 albertel 9854: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9855: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9856: $env{'course.'.$courseid.'.domain'},
9857: 'course',
1.927 albertel 9858: ([$courselevelm,'map' ],
9859: [$courselevel, 'course']));
9860: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9861: }
1.145 www 9862: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9863: unless ($space eq '0') {
1.336 albertel 9864: my @parts=split(/_/,$space);
9865: my $id=pop(@parts);
9866: my $part=join('_',@parts);
9867: if ($part eq '') { $part='0'; }
1.927 albertel 9868: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9869: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9870: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9871: }
1.395 albertel 9872: if ($recurse) { return undef; }
9873: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9874: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9875: # ---------------------------------------------------- Any other user namespace
9876: } elsif ($realm eq 'environment') {
9877: # ----------------------------------------------------------------- environment
1.620 albertel 9878: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9879: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9880: } else {
1.770 albertel 9881: if ($uname eq 'anonymous' && $udom eq '') {
9882: return '';
9883: }
1.219 albertel 9884: my %returnhash=&userenvironment($udom,$uname,
9885: $spacequalifierrest);
9886: return $returnhash{$spacequalifierrest};
9887: }
1.28 www 9888: } elsif ($realm eq 'system') {
1.48 www 9889: # ----------------------------------------------------------------- system.time
9890: if ($space eq 'time') {
9891: return time;
9892: }
1.696 albertel 9893: } elsif ($realm eq 'server') {
9894: # ----------------------------------------------------------------- system.time
9895: if ($space eq 'name') {
9896: return $ENV{'SERVER_NAME'};
9897: }
1.28 www 9898: }
1.48 www 9899: return '';
1.61 www 9900: }
9901:
1.927 albertel 9902: sub get_reply {
9903: my ($reply_value) = @_;
1.940 raeburn 9904: if (ref($reply_value) eq 'ARRAY') {
9905: if (wantarray) {
9906: return @$reply_value;
9907: }
9908: return $reply_value->[0];
9909: } else {
9910: return $reply_value;
1.927 albertel 9911: }
9912: }
9913:
1.691 raeburn 9914: sub check_group_parms {
9915: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9916: my @groupitems = ();
9917: my $resultitem;
1.927 albertel 9918: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9919: foreach my $group (@{$groups}) {
9920: foreach my $level (@levels) {
1.927 albertel 9921: my $item = $courseid.'.['.$group.'].'.$level->[0];
9922: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9923: }
9924: }
9925: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9926: $env{'course.'.$courseid.'.domain'},
9927: 'course',@groupitems);
9928: return $coursereply;
9929: }
9930:
9931: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9932: my ($courseid,@groups) = @_;
9933: @groups = sort(@groups);
1.691 raeburn 9934: return @groups;
9935: }
9936:
1.395 albertel 9937: sub packages_tab_default {
9938: my ($uri,$varname)=@_;
9939: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 9940:
9941: my (@extension,@specifics,$do_default);
9942: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 9943: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 9944: if ($pack_type eq 'default') {
9945: $do_default=1;
9946: } elsif ($pack_type eq 'extension') {
9947: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 9948: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 9949: # only look at packages defaults for packages that this id is
1.738 albertel 9950: push(@specifics,[$package,$pack_type,$pack_part]);
9951: }
9952: }
9953: # first look for a package that matches the requested part id
9954: foreach my $package (@specifics) {
9955: my (undef,$pack_type,$pack_part)=@{$package};
9956: next if ($pack_part ne $part);
9957: if (defined($packagetab{"$pack_type&$name&default"})) {
9958: return $packagetab{"$pack_type&$name&default"};
9959: }
9960: }
9961: # look for any possible matching non extension_ package
9962: foreach my $package (@specifics) {
9963: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 9964: if (defined($packagetab{"$pack_type&$name&default"})) {
9965: return $packagetab{"$pack_type&$name&default"};
9966: }
1.585 albertel 9967: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 9968: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9969: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 9970: }
9971: }
1.738 albertel 9972: # look for any posible extension_ match
9973: foreach my $package (@extension) {
9974: my ($package,$pack_type)=@{$package};
9975: if (defined($packagetab{"$pack_type&$name&default"})) {
9976: return $packagetab{"$pack_type&$name&default"};
9977: }
9978: if (defined($packagetab{$package."&$name&default"})) {
9979: return $packagetab{$package."&$name&default"};
9980: }
9981: }
9982: # look for a global default setting
9983: if ($do_default && defined($packagetab{"default&$name&default"})) {
9984: return $packagetab{"default&$name&default"};
9985: }
1.395 albertel 9986: return undef;
9987: }
9988:
1.334 albertel 9989: sub add_prefix_and_part {
9990: my ($prefix,$part)=@_;
9991: my $keyroot;
9992: if (defined($prefix) && $prefix !~ /^__/) {
9993: # prefix that has a part already
9994: $keyroot=$prefix;
9995: } elsif (defined($prefix)) {
9996: # prefix that is missing a part
9997: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9998: } else {
9999: # no prefix at all
10000: if (defined($part)) { $keyroot='_'.$part; }
10001: }
10002: return $keyroot;
10003: }
10004:
1.71 www 10005: # ---------------------------------------------------------------- Get metadata
10006:
1.599 albertel 10007: my %metaentry;
1.1070 www 10008: my %importedpartids;
1.71 www 10009: sub metadata {
1.176 www 10010: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10011: $uri=&declutter($uri);
1.288 albertel 10012: # if it is a non metadata possible uri return quickly
1.529 albertel 10013: if (($uri eq '') ||
10014: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10015: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10016: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10017: return undef;
10018: }
1.1140 www 10019: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10020: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10021: return undef;
1.288 albertel 10022: }
1.73 www 10023: my $filename=$uri;
10024: $uri=~s/\.meta$//;
1.172 www 10025: #
10026: # Is the metadata already cached?
1.177 www 10027: # Look at timestamp of caching
1.172 www 10028: # Everything is cached by the main uri, libraries are never directly cached
10029: #
1.428 albertel 10030: if (!defined($liburi)) {
1.599 albertel 10031: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10032: if (defined($cached)) { return $result->{':'.$what}; }
10033: }
10034: {
1.1069 www 10035: # Imported parts would go here
1.1070 www 10036: my %importedids=();
10037: my @origfileimportpartids=();
1.1069 www 10038: my $importedparts=0;
1.172 www 10039: #
10040: # Is this a recursive call for a library?
10041: #
1.599 albertel 10042: # if (! exists($metacache{$uri})) {
10043: # $metacache{$uri}={};
10044: # }
1.924 albertel 10045: my $cachetime = 60*60;
1.171 www 10046: if ($liburi) {
10047: $liburi=&declutter($liburi);
10048: $filename=$liburi;
1.401 bowersj2 10049: } else {
1.599 albertel 10050: &devalidate_cache_new('meta',$uri);
10051: undef(%metaentry);
1.401 bowersj2 10052: }
1.140 www 10053: my %metathesekeys=();
1.73 www 10054: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10055: my $metastring;
1.1140 www 10056: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10057: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10058: $metastring =
1.929 albertel 10059: &Apache::lonnet::ssi_body($which,
1.924 albertel 10060: ('grade_target' => 'meta'));
10061: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10062: } elsif (($uri !~ m -^(editupload)/-) &&
10063: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10064: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10065: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10066: $metastring=&getfile($file);
1.489 albertel 10067: }
1.208 albertel 10068: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10069: my $token;
1.140 www 10070: undef %metathesekeys;
1.71 www 10071: while ($token=$parser->get_token) {
1.339 albertel 10072: if ($token->[0] eq 'S') {
10073: if (defined($token->[2]->{'package'})) {
1.172 www 10074: #
10075: # This is a package - get package info
10076: #
1.339 albertel 10077: my $package=$token->[2]->{'package'};
10078: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10079: if (defined($token->[2]->{'id'})) {
10080: $keyroot.='_'.$token->[2]->{'id'};
10081: }
1.599 albertel 10082: if ($metaentry{':packages'}) {
10083: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10084: } else {
1.599 albertel 10085: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10086: }
1.736 albertel 10087: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10088: my $part=$keyroot;
10089: $part=~s/^\_//;
1.736 albertel 10090: if ($pack_entry=~/^\Q$package\E\&/ ||
10091: $pack_entry=~/^\Q$package\E_0\&/) {
10092: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10093: # ignore package.tab specified default values
10094: # here &package_tab_default() will fetch those
10095: if ($subp eq 'default') { next; }
1.736 albertel 10096: my $value=$packagetab{$pack_entry};
1.432 albertel 10097: my $unikey;
10098: if ($pack =~ /_0$/) {
10099: $unikey='parameter_0_'.$name;
10100: $part=0;
10101: } else {
10102: $unikey='parameter'.$keyroot.'_'.$name;
10103: }
1.339 albertel 10104: if ($subp eq 'display') {
10105: $value.=' [Part: '.$part.']';
10106: }
1.599 albertel 10107: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10108: $metathesekeys{$unikey}=1;
1.599 albertel 10109: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10110: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10111: }
1.599 albertel 10112: if (defined($metaentry{':'.$unikey.'.default'})) {
10113: $metaentry{':'.$unikey}=
10114: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10115: }
1.339 albertel 10116: }
10117: }
10118: } else {
1.172 www 10119: #
10120: # This is not a package - some other kind of start tag
1.339 albertel 10121: #
10122: my $entry=$token->[1];
1.1068 www 10123: my $unikey='';
1.175 www 10124:
1.339 albertel 10125: if ($entry eq 'import') {
1.175 www 10126: #
10127: # Importing a library here
1.339 albertel 10128: #
1.1067 www 10129: my $location=$parser->get_text('/import');
10130: my $dir=$filename;
10131: $dir=~s|[^/]*$||;
10132: $location=&filelocation($dir,$location);
1.1069 www 10133:
1.1068 www 10134: my $importmode=$token->[2]->{'importmode'};
10135: if ($importmode eq 'problem') {
1.1069 www 10136: # Import as problem/response
1.1068 www 10137: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10138: } elsif ($importmode eq 'part') {
10139: # Import as part(s)
1.1069 www 10140: $importedparts=1;
10141: # We need to get the original file and the imported file to get the part order correct
10142: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10143: # Load and inspect original file
1.1070 www 10144: if ($#origfileimportpartids<0) {
10145: undef(%importedpartids);
10146: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10147: my $origfile=&getfile($origfilelocation);
10148: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10149: }
10150:
1.1069 www 10151: # Load and inspect imported file
10152: my $impfile=&getfile($location);
10153: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10154: if ($#impfilepartids>=0) {
10155: # This problem had parts
1.1070 www 10156: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10157: } else {
10158: # Importing by turning a single problem into a problem part
10159: # It gets the import-tags ID as part-ID
10160: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10161: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10162: }
1.1068 www 10163: } else {
10164: # Normal import
10165: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10166: if (defined($token->[2]->{'id'})) {
10167: $unikey.='_'.$token->[2]->{'id'};
10168: }
1.1067 www 10169: }
10170:
1.339 albertel 10171: if ($depthcount<20) {
1.736 albertel 10172: my $metadata =
10173: &metadata($uri,'keys', $location,$unikey,
10174: $depthcount+1);
10175: foreach my $meta (split(',',$metadata)) {
10176: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10177: $metathesekeys{$meta}=1;
1.339 albertel 10178: }
1.1068 www 10179:
10180: }
1.1067 www 10181: } else {
10182: #
10183: # Not importing, some other kind of non-package, non-library start tag
10184: #
10185: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10186: if (defined($token->[2]->{'id'})) {
10187: $unikey.='_'.$token->[2]->{'id'};
10188: }
1.339 albertel 10189: if (defined($token->[2]->{'name'})) {
10190: $unikey.='_'.$token->[2]->{'name'};
10191: }
10192: $metathesekeys{$unikey}=1;
1.736 albertel 10193: foreach my $param (@{$token->[3]}) {
10194: $metaentry{':'.$unikey.'.'.$param} =
10195: $token->[2]->{$param};
1.339 albertel 10196: }
10197: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10198: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10199: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10200: # only ws inside the tag, and not in default, so use default
10201: # as value
1.599 albertel 10202: $metaentry{':'.$unikey}=$default;
1.908 albertel 10203: } elsif ( $internaltext =~ /\S/ ) {
10204: # something interesting inside the tag
10205: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10206: } else {
1.908 albertel 10207: # no interesting values, don't set a default
1.339 albertel 10208: }
1.172 www 10209: # end of not-a-package not-a-library import
1.339 albertel 10210: }
1.172 www 10211: # end of not-a-package start tag
1.339 albertel 10212: }
1.172 www 10213: # the next is the end of "start tag"
1.339 albertel 10214: }
10215: }
1.483 albertel 10216: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10217: $extension = lc($extension);
10218: if ($extension eq 'htm') { $extension='html'; }
10219:
1.737 albertel 10220: foreach my $key (keys(%packagetab)) {
1.483 albertel 10221: #no specific packages #how's our extension
10222: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10223: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10224: \%metathesekeys);
10225: }
1.883 albertel 10226:
10227: if (!exists($metaentry{':packages'})
10228: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10229: foreach my $key (keys(%packagetab)) {
1.483 albertel 10230: #no specific packages well let's get default then
10231: if ($key!~/^default&/) { next; }
1.488 albertel 10232: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10233: \%metathesekeys);
10234: }
10235: }
1.338 www 10236: # are there custom rights to evaluate
1.599 albertel 10237: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10238:
1.338 www 10239: #
10240: # Importing a rights file here
1.339 albertel 10241: #
10242: unless ($depthcount) {
1.599 albertel 10243: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10244: my $dir=$filename;
10245: $dir=~s|[^/]*$||;
10246: $location=&filelocation($dir,$location);
1.736 albertel 10247: my $rights_metadata =
10248: &metadata($uri,'keys',$location,'_rights',
10249: $depthcount+1);
10250: foreach my $rights (split(',',$rights_metadata)) {
10251: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10252: $metathesekeys{$rights}=1;
1.339 albertel 10253: }
10254: }
10255: }
1.737 albertel 10256: # uniqifiy package listing
10257: my %seen;
10258: my @uniq_packages =
10259: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10260: $metaentry{':packages'} = join(',',@uniq_packages);
10261:
1.1070 www 10262: if ($importedparts) {
10263: # We had imported parts and need to rebuild partorder
10264: $metaentry{':partorder'}='';
10265: $metathesekeys{'partorder'}=1;
10266: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10267: if ($origfileimportpartids[$index] eq 'part') {
10268: # original part, part of the problem
10269: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10270: } else {
10271: # we have imported parts at this position
10272: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10273: }
10274: }
10275: $metaentry{':partorder'}=~s/^\,//;
10276: }
10277:
1.737 albertel 10278: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10279: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10280: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10281: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10282: # this is the end of "was not already recently cached
1.71 www 10283: }
1.599 albertel 10284: return $metaentry{':'.$what};
1.261 albertel 10285: }
10286:
1.488 albertel 10287: sub metadata_create_package_def {
1.483 albertel 10288: my ($uri,$key,$package,$metathesekeys)=@_;
10289: my ($pack,$name,$subp)=split(/\&/,$key);
10290: if ($subp eq 'default') { next; }
10291:
1.599 albertel 10292: if (defined($metaentry{':packages'})) {
10293: $metaentry{':packages'}.=','.$package;
1.483 albertel 10294: } else {
1.599 albertel 10295: $metaentry{':packages'}=$package;
1.483 albertel 10296: }
10297: my $value=$packagetab{$key};
10298: my $unikey;
10299: $unikey='parameter_0_'.$name;
1.599 albertel 10300: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10301: $$metathesekeys{$unikey}=1;
1.599 albertel 10302: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10303: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10304: }
1.599 albertel 10305: if (defined($metaentry{':'.$unikey.'.default'})) {
10306: $metaentry{':'.$unikey}=
10307: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10308: }
10309: }
10310:
1.261 albertel 10311: sub metadata_generate_part0 {
10312: my ($metadata,$metacache,$uri) = @_;
10313: my %allnames;
1.737 albertel 10314: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10315: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10316: my $part=$$metacache{':'.$metakey.'.part'};
10317: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10318: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10319: $allnames{$name}=$part;
10320: }
10321: }
10322: }
10323: foreach my $name (keys(%allnames)) {
10324: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10325: my $key=":parameter_0_$name";
1.261 albertel 10326: $$metacache{"$key.part"}='0';
10327: $$metacache{"$key.name"}=$name;
1.428 albertel 10328: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10329: $allnames{$name}.'_'.$name.
10330: '.type'};
1.428 albertel 10331: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10332: '.display'};
1.644 www 10333: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10334: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10335: $$metacache{"$key.display"}=$olddis;
10336: }
1.71 www 10337: }
10338:
1.764 albertel 10339: # ------------------------------------------------------ Devalidate title cache
10340:
10341: sub devalidate_title_cache {
10342: my ($url)=@_;
10343: if (!$env{'request.course.id'}) { return; }
10344: my $symb=&symbread($url);
10345: if (!$symb) { return; }
10346: my $key=$env{'request.course.id'}."\0".$symb;
10347: &devalidate_cache_new('title',$key);
10348: }
10349:
1.1014 droeschl 10350: # ------------------------------------------------- Get the title of a course
10351:
10352: sub current_course_title {
10353: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10354: }
1.301 www 10355: # ------------------------------------------------- Get the title of a resource
10356:
10357: sub gettitle {
10358: my $urlsymb=shift;
10359: my $symb=&symbread($urlsymb);
1.534 albertel 10360: if ($symb) {
1.620 albertel 10361: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10362: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10363: if (defined($cached)) {
10364: return $result;
10365: }
1.534 albertel 10366: my ($map,$resid,$url)=&decode_symb($symb);
10367: my $title='';
1.907 albertel 10368: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10369: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10370: } else {
10371: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10372: &GDBM_READER(),0640)) {
10373: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10374: $title=$bighash{'title_'.$mapid.'.'.$resid};
10375: untie(%bighash);
10376: }
1.534 albertel 10377: }
10378: $title=~s/\&colon\;/\:/gs;
10379: if ($title) {
1.1159 www 10380: # Remember both $symb and $title for dynamic metadata
10381: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10382: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10383: # Cache this title and then return it
1.599 albertel 10384: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10385: }
10386: $urlsymb=$url;
10387: }
10388: my $title=&metadata($urlsymb,'title');
10389: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10390: return $title;
1.301 www 10391: }
1.613 albertel 10392:
1.614 albertel 10393: sub get_slot {
10394: my ($which,$cnum,$cdom)=@_;
10395: if (!$cnum || !$cdom) {
1.790 albertel 10396: (undef,my $courseid)=&whichuser();
1.620 albertel 10397: $cdom=$env{'course.'.$courseid.'.domain'};
10398: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10399: }
1.703 albertel 10400: my $key=join("\0",'slots',$cdom,$cnum,$which);
10401: my %slotinfo;
10402: if (exists($remembered{$key})) {
10403: $slotinfo{$which} = $remembered{$key};
10404: } else {
10405: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10406: &Apache::lonhomework::showhash(%slotinfo);
10407: my ($tmp)=keys(%slotinfo);
10408: if ($tmp=~/^error:/) { return (); }
10409: $remembered{$key} = $slotinfo{$which};
10410: }
1.616 albertel 10411: if (ref($slotinfo{$which}) eq 'HASH') {
10412: return %{$slotinfo{$which}};
10413: }
10414: return $slotinfo{$which};
1.614 albertel 10415: }
1.1150 raeburn 10416:
10417: sub get_reservable_slots {
10418: my ($cnum,$cdom,$uname,$udom) = @_;
10419: my $now = time;
10420: my $reservable_info;
10421: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10422: if (exists($remembered{$key})) {
10423: $reservable_info = $remembered{$key};
10424: } else {
10425: my %resv;
10426: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10427: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10428: $reservable_info = \%resv;
10429: $remembered{$key} = $reservable_info;
10430: }
10431: return $reservable_info;
10432: }
10433:
10434: sub get_course_slots {
10435: my ($cnum,$cdom) = @_;
10436: my $hashid=$cnum.':'.$cdom;
10437: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10438: if (defined($cached)) {
10439: if (ref($result) eq 'HASH') {
10440: return %{$result};
10441: }
10442: } else {
10443: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10444: my ($tmp) = keys(%slots);
10445: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10446: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10447: return %slots;
10448: }
10449: }
10450: return;
10451: }
10452:
10453: sub devalidate_slots_cache {
10454: my ($cnum,$cdom)=@_;
10455: my $hashid=$cnum.':'.$cdom;
10456: &devalidate_cache_new('allslots',$hashid);
10457: }
10458:
1.1181 raeburn 10459: sub get_coursechange {
10460: my ($cdom,$cnum) = @_;
10461: if ($cdom eq '' || $cnum eq '') {
10462: return unless ($env{'request.course.id'});
10463: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10464: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10465: }
10466: my $hashid=$cdom.'_'.$cnum;
10467: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10468: if ((defined($cached)) && ($change ne '')) {
10469: return $change;
10470: } else {
10471: my %crshash;
10472: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10473: if ($crshash{'internal.contentchange'} eq '') {
10474: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10475: if ($change eq '') {
10476: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10477: $change = $crshash{'internal.created'};
10478: }
10479: } else {
10480: $change = $crshash{'internal.contentchange'};
10481: }
10482: my $cachetime = 600;
10483: &do_cache_new('crschange',$hashid,$change,$cachetime);
10484: }
10485: return $change;
10486: }
10487:
10488: sub devalidate_coursechange_cache {
10489: my ($cnum,$cdom)=@_;
10490: my $hashid=$cnum.':'.$cdom;
10491: &devalidate_cache_new('crschange',$hashid);
10492: }
10493:
1.31 www 10494: # ------------------------------------------------- Update symbolic store links
10495:
10496: sub symblist {
10497: my ($mapname,%newhash)=@_;
1.438 www 10498: $mapname=&deversion(&declutter($mapname));
1.31 www 10499: my %hash;
1.620 albertel 10500: if (($env{'request.course.fn'}) && (%newhash)) {
10501: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10502: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10503: foreach my $url (keys(%newhash)) {
1.711 albertel 10504: next if ($url eq 'last_known'
10505: && $env{'form.no_update_last_known'});
10506: $hash{declutter($url)}=&encode_symb($mapname,
10507: $newhash{$url}->[1],
10508: $newhash{$url}->[0]);
1.191 harris41 10509: }
1.31 www 10510: if (untie(%hash)) {
10511: return 'ok';
10512: }
10513: }
10514: }
10515: return 'error';
1.212 www 10516: }
10517:
10518: # --------------------------------------------------------------- Verify a symb
10519:
10520: sub symbverify {
1.1190 raeburn 10521: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10522: my $thisfn=$thisurl;
1.439 www 10523: $thisfn=&declutter($thisfn);
1.215 www 10524: # direct jump to resource in page or to a sequence - will construct own symbs
10525: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10526: # check URL part
1.409 www 10527: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10528:
1.431 www 10529: unless ($url eq $thisfn) { return 0; }
1.213 www 10530:
1.216 www 10531: $symb=&symbclean($symb);
1.510 www 10532: $thisurl=&deversion($thisurl);
1.439 www 10533: $thisfn=&deversion($thisfn);
1.213 www 10534:
10535: my %bighash;
10536: my $okay=0;
1.431 www 10537:
1.620 albertel 10538: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10539: &GDBM_READER(),0640)) {
1.1204 raeburn 10540: my $noclutter;
1.1032 raeburn 10541: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10542: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10543: if ($map =~ m{^uploaded/.+\.page$}) {
10544: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10545: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10546: $noclutter = 1;
10547: }
10548: }
10549: my $ids;
10550: if ($noclutter) {
10551: $ids=$bighash{'ids_'.$thisurl};
10552: } else {
10553: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10554: }
1.1102 raeburn 10555: unless ($ids) {
10556: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10557: $ids=$bighash{$idkey};
1.216 www 10558: }
10559: if ($ids) {
10560: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10561: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10562: $symb =~ s/\?.+$//;
1.1202 raeburn 10563: }
1.800 albertel 10564: foreach my $id (split(/\,/,$ids)) {
10565: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10566: if (
10567: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 10568: eq $symb) {
10569: if (ref($encstate)) {
10570: $$encstate = $bighash{'encrypted_'.$id};
10571: }
1.620 albertel 10572: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10573: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10574: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 10575: $okay=1;
1.1202 raeburn 10576: last;
1.582 albertel 10577: }
10578: }
1.216 www 10579: }
10580: }
1.213 www 10581: untie(%bighash);
10582: }
10583: return $okay;
1.31 www 10584: }
10585:
1.210 www 10586: # --------------------------------------------------------------- Clean-up symb
10587:
10588: sub symbclean {
10589: my $symb=shift;
1.568 albertel 10590: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10591: # remove version from map
10592: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10593:
1.210 www 10594: # remove version from URL
10595: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10596:
1.507 www 10597: # remove wrapper
10598:
1.510 www 10599: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10600: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10601: return $symb;
1.409 www 10602: }
10603:
10604: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10605:
10606: sub encode_symb {
10607: my ($map,$resid,$url)=@_;
10608: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10609: }
1.409 www 10610:
10611: sub decode_symb {
1.568 albertel 10612: my $symb=shift;
10613: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10614: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10615: return (&fixversion($map),$resid,&fixversion($url));
10616: }
10617:
10618: sub fixversion {
10619: my $fn=shift;
1.609 banghart 10620: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10621: my %bighash;
10622: my $uri=&clutter($fn);
1.620 albertel 10623: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10624: # is this cached?
1.599 albertel 10625: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10626: if (defined($cached)) { return $result; }
10627: # unfortunately not cached, or expired
1.620 albertel 10628: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10629: &GDBM_READER(),0640)) {
10630: if ($bighash{'version_'.$uri}) {
10631: my $version=$bighash{'version_'.$uri};
1.444 www 10632: unless (($version eq 'mostrecent') ||
10633: ($version==&getversion($uri))) {
1.440 www 10634: $uri=~s/\.(\w+)$/\.$version\.$1/;
10635: }
10636: }
10637: untie %bighash;
1.413 www 10638: }
1.599 albertel 10639: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10640: }
10641:
10642: sub deversion {
10643: my $url=shift;
10644: $url=~s/\.\d+\.(\w+)$/\.$1/;
10645: return $url;
1.210 www 10646: }
10647:
1.31 www 10648: # ------------------------------------------------------ Return symb list entry
10649:
10650: sub symbread {
1.249 www 10651: my ($thisfn,$donotrecurse)=@_;
1.1206 raeburn 10652: my $cache_str;
10653: if ($thisfn ne '') {
10654: $cache_str='request.symbread.cached.'.$thisfn;
10655: if ($env{$cache_str} ne '') {
1.1179 raeburn 10656: return $env{$cache_str};
10657: }
1.1206 raeburn 10658: } else {
1.242 www 10659: # no filename provided? try from environment
1.620 albertel 10660: if ($env{'request.symb'}) {
10661: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10662: }
1.620 albertel 10663: $thisfn=$env{'request.filename'};
1.44 www 10664: }
1.569 albertel 10665: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10666: # is that filename actually a symb? Verify, clean, and return
10667: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10668: if (&symbverify($thisfn,$1)) {
1.620 albertel 10669: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10670: }
1.242 www 10671: }
1.44 www 10672: $thisfn=declutter($thisfn);
1.31 www 10673: my %hash;
1.37 www 10674: my %bighash;
10675: my $syval='';
1.620 albertel 10676: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10677: my $targetfn = $thisfn;
1.609 banghart 10678: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10679: $targetfn = 'adm/wrapper/'.$thisfn;
10680: }
1.687 albertel 10681: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10682: $targetfn=$1;
10683: }
1.620 albertel 10684: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10685: &GDBM_READER(),0640)) {
1.481 raeburn 10686: $syval=$hash{$targetfn};
1.37 www 10687: untie(%hash);
10688: }
10689: # ---------------------------------------------------------- There was an entry
10690: if ($syval) {
1.601 albertel 10691: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10692: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10693: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10694: #return $env{$cache_str}='';
1.601 albertel 10695: #}
10696: #$syval.=$1;
10697: #}
1.37 www 10698: } else {
10699: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10700: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10701: &GDBM_READER(),0640)) {
1.37 www 10702: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10703: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10704: unless ($ids) {
10705: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10706: }
10707: unless ($ids) {
10708: # alias?
10709: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10710: }
1.37 www 10711: if ($ids) {
10712: # ------------------------------------------------------------------- Has ID(s)
10713: my @possibilities=split(/\,/,$ids);
1.39 www 10714: if ($#possibilities==0) {
10715: # ----------------------------------------------- There is only one possibility
1.37 www 10716: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10717: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10718: $resid,$thisfn);
1.249 www 10719: } elsif (!$donotrecurse) {
1.39 www 10720: # ------------------------------------------ There is more than one possibility
10721: my $realpossible=0;
1.800 albertel 10722: foreach my $id (@possibilities) {
10723: my $file=$bighash{'src_'.$id};
1.39 www 10724: if (&allowed('bre',$file)) {
1.800 albertel 10725: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10726: if ($bighash{'map_type_'.$mapid} ne 'page') {
10727: $realpossible++;
1.626 albertel 10728: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10729: $resid,$thisfn);
1.39 www 10730: }
10731: }
1.191 harris41 10732: }
1.39 www 10733: if ($realpossible!=1) { $syval=''; }
1.249 www 10734: } else {
10735: $syval='';
1.37 www 10736: }
10737: }
10738: untie(%bighash)
1.481 raeburn 10739: }
1.31 www 10740: }
1.62 www 10741: if ($syval) {
1.620 albertel 10742: return $env{$cache_str}=$syval;
1.62 www 10743: }
1.31 www 10744: }
1.949 raeburn 10745: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10746: return $env{$cache_str}='';
1.31 www 10747: }
10748:
10749: # ---------------------------------------------------------- Return random seed
10750:
1.32 www 10751: sub numval {
10752: my $txt=shift;
10753: $txt=~tr/A-J/0-9/;
10754: $txt=~tr/a-j/0-9/;
10755: $txt=~tr/K-T/0-9/;
10756: $txt=~tr/k-t/0-9/;
10757: $txt=~tr/U-Z/0-5/;
10758: $txt=~tr/u-z/0-5/;
10759: $txt=~s/\D//g;
1.564 albertel 10760: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10761: return int($txt);
1.368 albertel 10762: }
10763:
1.484 albertel 10764: sub numval2 {
10765: my $txt=shift;
10766: $txt=~tr/A-J/0-9/;
10767: $txt=~tr/a-j/0-9/;
10768: $txt=~tr/K-T/0-9/;
10769: $txt=~tr/k-t/0-9/;
10770: $txt=~tr/U-Z/0-5/;
10771: $txt=~tr/u-z/0-5/;
10772: $txt=~s/\D//g;
10773: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10774: my $total;
10775: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10776: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10777: return int($total);
10778: }
10779:
1.575 albertel 10780: sub numval3 {
10781: use integer;
10782: my $txt=shift;
10783: $txt=~tr/A-J/0-9/;
10784: $txt=~tr/a-j/0-9/;
10785: $txt=~tr/K-T/0-9/;
10786: $txt=~tr/k-t/0-9/;
10787: $txt=~tr/U-Z/0-5/;
10788: $txt=~tr/u-z/0-5/;
10789: $txt=~s/\D//g;
10790: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10791: my $total;
10792: foreach my $val (@txts) { $total+=$val; }
10793: if ($_64bit) { $total=(($total<<32)>>32); }
10794: return $total;
10795: }
10796:
1.675 albertel 10797: sub digest {
10798: my ($data)=@_;
10799: my $digest=&Digest::MD5::md5($data);
10800: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10801: my ($e,$f);
10802: {
10803: use integer;
10804: $e=($a+$b);
10805: $f=($c+$d);
10806: if ($_64bit) {
10807: $e=(($e<<32)>>32);
10808: $f=(($f<<32)>>32);
10809: }
10810: }
10811: if (wantarray) {
10812: return ($e,$f);
10813: } else {
10814: my $g;
10815: {
10816: use integer;
10817: $g=($e+$f);
10818: if ($_64bit) {
10819: $g=(($g<<32)>>32);
10820: }
10821: }
10822: return $g;
10823: }
10824: }
10825:
1.368 albertel 10826: sub latest_rnd_algorithm_id {
1.675 albertel 10827: return '64bit5';
1.366 albertel 10828: }
1.32 www 10829:
1.503 albertel 10830: sub get_rand_alg {
10831: my ($courseid)=@_;
1.790 albertel 10832: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10833: if ($courseid) {
1.620 albertel 10834: return $env{"course.$courseid.rndseed"};
1.503 albertel 10835: }
10836: return &latest_rnd_algorithm_id();
10837: }
10838:
1.562 albertel 10839: sub validCODE {
10840: my ($CODE)=@_;
10841: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10842: return 0;
10843: }
10844:
1.491 albertel 10845: sub getCODE {
1.620 albertel 10846: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10847: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10848: defined($Apache::lonhomework::parsing_a_task) ) &&
10849: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10850: return $Apache::lonhomework::history{'resource.CODE'};
10851: }
10852: return undef;
10853: }
1.1133 foxr 10854: #
10855: # Determines the random seed for a specific context:
10856: #
10857: # parameters:
10858: # symb - in course context the symb for the seed.
10859: # course_id - The course id of the form domain_coursenum.
10860: # domain - Domain for the user.
10861: # course - Course for the user.
10862: # cenv - environment of the course.
10863: #
10864: # NOTE:
10865: # All parameters are picked out of the environment if missing
10866: # or not defined.
10867: # If a symb cannot be determined the current time is used instead.
10868: #
10869: # For a given well defined symb, courside, domain, username,
10870: # and course environment, the seed is reproducible.
10871: #
1.31 www 10872: sub rndseed {
1.1133 foxr 10873: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10874: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10875: if (!defined($symb)) {
1.366 albertel 10876: unless ($symb=$wsymb) { return time; }
10877: }
1.1146 foxr 10878: if (!defined $courseid) {
10879: $courseid=$wcourseid;
10880: }
10881: if (!defined $domain) { $domain=$wdomain; }
10882: if (!defined $username) { $username=$wusername }
1.1133 foxr 10883:
10884: my $which;
10885: if (defined($cenv->{'rndseed'})) {
10886: $which = $cenv->{'rndseed'};
10887: } else {
10888: $which =&get_rand_alg($courseid);
10889: }
1.491 albertel 10890: if (defined(&getCODE())) {
1.1133 foxr 10891:
1.675 albertel 10892: if ($which eq '64bit5') {
10893: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10894: } elsif ($which eq '64bit4') {
1.575 albertel 10895: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10896: } else {
10897: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10898: }
1.675 albertel 10899: } elsif ($which eq '64bit5') {
10900: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10901: } elsif ($which eq '64bit4') {
10902: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10903: } elsif ($which eq '64bit3') {
10904: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10905: } elsif ($which eq '64bit2') {
10906: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10907: } elsif ($which eq '64bit') {
10908: return &rndseed_64bit($symb,$courseid,$domain,$username);
10909: }
10910: return &rndseed_32bit($symb,$courseid,$domain,$username);
10911: }
10912:
10913: sub rndseed_32bit {
10914: my ($symb,$courseid,$domain,$username)=@_;
10915: {
10916: use integer;
10917: my $symbchck=unpack("%32C*",$symb) << 27;
10918: my $symbseed=numval($symb) << 22;
10919: my $namechck=unpack("%32C*",$username) << 17;
10920: my $nameseed=numval($username) << 12;
10921: my $domainseed=unpack("%32C*",$domain) << 7;
10922: my $courseseed=unpack("%32C*",$courseid);
10923: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10924: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10925: #&logthis("rndseed :$num:$symb");
1.564 albertel 10926: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10927: return $num;
10928: }
10929: }
10930:
10931: sub rndseed_64bit {
10932: my ($symb,$courseid,$domain,$username)=@_;
10933: {
10934: use integer;
10935: my $symbchck=unpack("%32S*",$symb) << 21;
10936: my $symbseed=numval($symb) << 10;
10937: my $namechck=unpack("%32S*",$username);
10938:
10939: my $nameseed=numval($username) << 21;
10940: my $domainseed=unpack("%32S*",$domain) << 10;
10941: my $courseseed=unpack("%32S*",$courseid);
10942:
10943: my $num1=$symbchck+$symbseed+$namechck;
10944: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10945: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10946: #&logthis("rndseed :$num:$symb");
1.564 albertel 10947: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 10948: return "$num1,$num2";
1.155 albertel 10949: }
1.366 albertel 10950: }
10951:
1.443 albertel 10952: sub rndseed_64bit2 {
10953: my ($symb,$courseid,$domain,$username)=@_;
10954: {
10955: use integer;
10956: # strings need to be an even # of cahracters long, it it is odd the
10957: # last characters gets thrown away
10958: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10959: my $symbseed=numval($symb) << 10;
10960: my $namechck=unpack("%32S*",$username.' ');
10961:
10962: my $nameseed=numval($username) << 21;
1.501 albertel 10963: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10964: my $courseseed=unpack("%32S*",$courseid.' ');
10965:
10966: my $num1=$symbchck+$symbseed+$namechck;
10967: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10968: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10969: #&logthis("rndseed :$num:$symb");
1.803 albertel 10970: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 10971: return "$num1,$num2";
10972: }
10973: }
10974:
10975: sub rndseed_64bit3 {
10976: my ($symb,$courseid,$domain,$username)=@_;
10977: {
10978: use integer;
10979: # strings need to be an even # of cahracters long, it it is odd the
10980: # last characters gets thrown away
10981: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10982: my $symbseed=numval2($symb) << 10;
10983: my $namechck=unpack("%32S*",$username.' ');
10984:
10985: my $nameseed=numval2($username) << 21;
1.443 albertel 10986: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10987: my $courseseed=unpack("%32S*",$courseid.' ');
10988:
10989: my $num1=$symbchck+$symbseed+$namechck;
10990: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10991: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10992: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 10993: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10994:
1.503 albertel 10995: return "$num1:$num2";
1.443 albertel 10996: }
10997: }
10998:
1.575 albertel 10999: sub rndseed_64bit4 {
11000: my ($symb,$courseid,$domain,$username)=@_;
11001: {
11002: use integer;
11003: # strings need to be an even # of cahracters long, it it is odd the
11004: # last characters gets thrown away
11005: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11006: my $symbseed=numval3($symb) << 10;
11007: my $namechck=unpack("%32S*",$username.' ');
11008:
11009: my $nameseed=numval3($username) << 21;
11010: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11011: my $courseseed=unpack("%32S*",$courseid.' ');
11012:
11013: my $num1=$symbchck+$symbseed+$namechck;
11014: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11015: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11016: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11017: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11018:
1.575 albertel 11019: return "$num1:$num2";
11020: }
11021: }
11022:
1.675 albertel 11023: sub rndseed_64bit5 {
11024: my ($symb,$courseid,$domain,$username)=@_;
11025: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11026: return "$num1:$num2";
11027: }
11028:
1.366 albertel 11029: sub rndseed_CODE_64bit {
11030: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11031: {
1.366 albertel 11032: use integer;
1.443 albertel 11033: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11034: my $symbseed=numval2($symb);
1.491 albertel 11035: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11036: my $CODEseed=numval(&getCODE());
1.443 albertel 11037: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11038: my $num1=$symbseed+$CODEchck;
11039: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11040: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11041: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11042: if ($_64bit) { $num1=(($num1<<32)>>32); }
11043: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11044: return "$num1:$num2";
1.366 albertel 11045: }
11046: }
11047:
1.575 albertel 11048: sub rndseed_CODE_64bit4 {
11049: my ($symb,$courseid,$domain,$username)=@_;
11050: {
11051: use integer;
11052: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11053: my $symbseed=numval3($symb);
11054: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11055: my $CODEseed=numval3(&getCODE());
11056: my $courseseed=unpack("%32S*",$courseid.' ');
11057: my $num1=$symbseed+$CODEchck;
11058: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11059: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11060: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11061: if ($_64bit) { $num1=(($num1<<32)>>32); }
11062: if ($_64bit) { $num2=(($num2<<32)>>32); }
11063: return "$num1:$num2";
11064: }
11065: }
11066:
1.675 albertel 11067: sub rndseed_CODE_64bit5 {
11068: my ($symb,$courseid,$domain,$username)=@_;
11069: my $code = &getCODE();
11070: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11071: return "$num1:$num2";
11072: }
11073:
1.366 albertel 11074: sub setup_random_from_rndseed {
11075: my ($rndseed)=@_;
1.503 albertel 11076: if ($rndseed =~/([,:])/) {
11077: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11078: &Math::Random::random_set_seed(abs($num1),abs($num2));
11079: } else {
11080: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11081: }
1.36 albertel 11082: }
11083:
1.474 albertel 11084: sub latest_receipt_algorithm_id {
1.835 albertel 11085: return 'receipt3';
1.474 albertel 11086: }
11087:
1.480 www 11088: sub recunique {
11089: my $fucourseid=shift;
11090: my $unique;
1.835 albertel 11091: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11092: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11093: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11094: } else {
11095: $unique=$perlvar{'lonReceipt'};
11096: }
11097: return unpack("%32C*",$unique);
11098: }
11099:
11100: sub recprefix {
11101: my $fucourseid=shift;
11102: my $prefix;
1.835 albertel 11103: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11104: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11105: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11106: } else {
11107: $prefix=$perlvar{'lonHostID'};
11108: }
11109: return unpack("%32C*",$prefix);
11110: }
11111:
1.76 www 11112: sub ireceipt {
1.474 albertel 11113: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11114:
11115: my $return =&recprefix($fucourseid).'-';
11116:
11117: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11118: $env{'request.state'} eq 'construct') {
11119: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11120: return $return;
11121: }
11122:
1.76 www 11123: my $cuname=unpack("%32C*",$funame);
11124: my $cudom=unpack("%32C*",$fudom);
11125: my $cucourseid=unpack("%32C*",$fucourseid);
11126: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11127: my $cunique=&recunique($fucourseid);
1.474 albertel 11128: my $cpart=unpack("%32S*",$part);
1.835 albertel 11129: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11130:
1.790 albertel 11131: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11132:
11133: $return.= ($cunique%$cuname+
11134: $cunique%$cudom+
11135: $cusymb%$cuname+
11136: $cusymb%$cudom+
11137: $cucourseid%$cuname+
11138: $cucourseid%$cudom+
11139: $cpart%$cuname+
11140: $cpart%$cudom);
11141: } else {
11142: $return.= ($cunique%$cuname+
11143: $cunique%$cudom+
11144: $cusymb%$cuname+
11145: $cusymb%$cudom+
11146: $cucourseid%$cuname+
11147: $cucourseid%$cudom);
11148: }
11149: return $return;
1.76 www 11150: }
11151:
11152: sub receipt {
1.474 albertel 11153: my ($part)=@_;
1.790 albertel 11154: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11155: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11156: }
1.260 ng 11157:
1.790 albertel 11158: sub whichuser {
11159: my ($passedsymb)=@_;
11160: my ($symb,$courseid,$domain,$name,$publicuser);
11161: if (defined($env{'form.grade_symb'})) {
11162: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11163: my $allowed=&allowed('vgr',$tmp_courseid);
11164: if (!$allowed &&
11165: exists($env{'request.course.sec'}) &&
11166: $env{'request.course.sec'} !~ /^\s*$/) {
11167: $allowed=&allowed('vgr',$tmp_courseid.
11168: '/'.$env{'request.course.sec'});
11169: }
11170: if ($allowed) {
11171: ($symb)=&get_env_multiple('form.grade_symb');
11172: $courseid=$tmp_courseid;
11173: ($domain)=&get_env_multiple('form.grade_domain');
11174: ($name)=&get_env_multiple('form.grade_username');
11175: return ($symb,$courseid,$domain,$name,$publicuser);
11176: }
11177: }
11178: if (!$passedsymb) {
11179: $symb=&symbread();
11180: } else {
11181: $symb=$passedsymb;
11182: }
11183: $courseid=$env{'request.course.id'};
11184: $domain=$env{'user.domain'};
11185: $name=$env{'user.name'};
11186: if ($name eq 'public' && $domain eq 'public') {
11187: if (!defined($env{'form.username'})) {
11188: $env{'form.username'}.=time.rand(10000000);
11189: }
11190: $name.=$env{'form.username'};
11191: }
11192: return ($symb,$courseid,$domain,$name,$publicuser);
11193:
11194: }
11195:
1.36 albertel 11196: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11197: # returns either the contents of the file or
11198: # -1 if the file doesn't exist
1.481 raeburn 11199: #
11200: # if the target is a file that was uploaded via DOCS,
11201: # a check will be made to see if a current copy exists on the local server,
11202: # if it does this will be served, otherwise a copy will be retrieved from
11203: # the home server for the course and stored in /home/httpd/html/userfiles on
11204: # the local server.
1.472 albertel 11205:
1.36 albertel 11206: sub getfile {
1.538 albertel 11207: my ($file) = @_;
1.609 banghart 11208: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11209: &repcopy($file);
11210: return &readfile($file);
11211: }
11212:
11213: sub repcopy_userfile {
11214: my ($file)=@_;
1.1142 raeburn 11215: my $londocroot = $perlvar{'lonDocRoot'};
11216: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11217: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11218: my ($cdom,$cnum,$filename) =
1.811 albertel 11219: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11220: my $uri="/uploaded/$cdom/$cnum/$filename";
11221: if (-e "$file") {
1.828 www 11222: # we already have a local copy, check it out
1.538 albertel 11223: my @fileinfo = stat($file);
1.828 www 11224: my $rtncode;
11225: my $info;
1.538 albertel 11226: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11227: if ($lwpresp ne 'ok') {
1.828 www 11228: # there is no such file anymore, even though we had a local copy
1.482 albertel 11229: if ($rtncode eq '404') {
1.538 albertel 11230: unlink($file);
1.482 albertel 11231: }
11232: return -1;
11233: }
11234: if ($info < $fileinfo[9]) {
1.828 www 11235: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11236: return 'ok';
1.828 www 11237: } else {
11238: # the file is outdated, get rid of it
11239: unlink($file);
1.482 albertel 11240: }
1.828 www 11241: }
11242: # one way or the other, at this point, we don't have the file
11243: # construct the correct path for the file
11244: my @parts = ($cdom,$cnum);
11245: if ($filename =~ m|^(.+)/[^/]+$|) {
11246: push @parts, split(/\//,$1);
11247: }
11248: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11249: foreach my $part (@parts) {
11250: $path .= '/'.$part;
11251: if (!-e $path) {
11252: mkdir($path,0770);
1.482 albertel 11253: }
11254: }
1.828 www 11255: # now the path exists for sure
11256: # get a user agent
11257: my $ua=new LWP::UserAgent;
11258: my $transferfile=$file.'.in.transfer';
11259: # FIXME: this should flock
11260: if (-e $transferfile) { return 'ok'; }
11261: my $request;
11262: $uri=~s/^\///;
1.980 raeburn 11263: my $homeserver = &homeserver($cnum,$cdom);
11264: my $protocol = $protocol{$homeserver};
11265: $protocol = 'http' if ($protocol ne 'https');
11266: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11267: my $response=$ua->request($request,$transferfile);
11268: # did it work?
11269: if ($response->is_error()) {
11270: unlink($transferfile);
11271: &logthis("Userfile repcopy failed for $uri");
11272: return -1;
11273: }
11274: # worked, rename the transfer file
11275: rename($transferfile,$file);
1.607 raeburn 11276: return 'ok';
1.481 raeburn 11277: }
11278:
1.517 albertel 11279: sub tokenwrapper {
11280: my $uri=shift;
1.980 raeburn 11281: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11282: $uri=~s|^/||;
1.620 albertel 11283: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11284: my $token=$1;
1.552 albertel 11285: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11286: if ($udom && $uname && $file) {
11287: $file=~s|(\?\.*)*$||;
1.949 raeburn 11288: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11289: my $homeserver = &homeserver($uname,$udom);
11290: my $protocol = $protocol{$homeserver};
11291: $protocol = 'http' if ($protocol ne 'https');
11292: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11293: (($uri=~/\?/)?'&':'?').'token='.$token.
11294: '&tokenissued='.$perlvar{'lonHostID'};
11295: } else {
11296: return '/adm/notfound.html';
11297: }
11298: }
11299:
1.828 www 11300: # call with reqtype HEAD: get last modification time
11301: # call with reqtype GET: get the file contents
11302: # Do not call this with reqtype GET for large files! It loads everything into memory
11303: #
1.481 raeburn 11304: sub getuploaded {
11305: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11306: $uri=~s/^\///;
1.980 raeburn 11307: my $homeserver = &homeserver($cnum,$cdom);
11308: my $protocol = $protocol{$homeserver};
11309: $protocol = 'http' if ($protocol ne 'https');
11310: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11311: my $ua=new LWP::UserAgent;
11312: my $request=new HTTP::Request($reqtype,$uri);
11313: my $response=$ua->request($request);
11314: $$rtncode = $response->code;
1.482 albertel 11315: if (! $response->is_success()) {
11316: return 'failed';
11317: }
11318: if ($reqtype eq 'HEAD') {
1.486 www 11319: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11320: } elsif ($reqtype eq 'GET') {
11321: $$info = $response->content;
1.472 albertel 11322: }
1.482 albertel 11323: return 'ok';
1.36 albertel 11324: }
11325:
1.481 raeburn 11326: sub readfile {
11327: my $file = shift;
11328: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11329: my $fh;
11330: open($fh,"<$file");
11331: my $a='';
1.800 albertel 11332: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11333: return $a;
11334: }
11335:
1.36 albertel 11336: sub filelocation {
1.590 banghart 11337: my ($dir,$file) = @_;
11338: my $location;
11339: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11340:
11341: if ($file =~ m-^/adm/-) {
11342: $file=~s-^/adm/wrapper/-/-;
11343: $file=~s-^/adm/coursedocs/showdoc/-/-;
11344: }
1.882 albertel 11345:
1.1139 www 11346: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11347: $location = $file;
1.609 banghart 11348: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11349: my ($udom,$uname,$filename)=
1.811 albertel 11350: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11351: my $home=&homeserver($uname,$udom);
11352: my $is_me=0;
11353: my @ids=¤t_machine_ids();
11354: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11355: if ($is_me) {
1.1117 foxr 11356: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11357: } else {
11358: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11359: $udom.'/'.$uname.'/'.$filename;
11360: }
1.882 albertel 11361: } elsif ($file =~ m-^/adm/-) {
11362: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11363: } else {
11364: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11365: $file=~s:^/(res|priv)/:/:;
11366: my $space=$1;
1.590 banghart 11367: if ( !( $file =~ m:^/:) ) {
11368: $location = $dir. '/'.$file;
11369: } else {
1.1142 raeburn 11370: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11371: }
1.59 albertel 11372: }
1.590 banghart 11373: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11374: while ($location=~m{/\.\./}) {
11375: if ($location =~ m{/[^/]+/\.\./}) {
11376: $location=~ s{/[^/]+/\.\./}{/}g;
11377: } else {
11378: $location=~ s{/\.\./}{/}g;
11379: }
11380: } #remove dir/..
1.590 banghart 11381: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11382: return $location;
1.46 www 11383: }
1.36 albertel 11384:
1.46 www 11385: sub hreflocation {
11386: my ($dir,$file)=@_;
1.980 raeburn 11387: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11388: $file=filelocation($dir,$file);
1.700 albertel 11389: } elsif ($file=~m-^/adm/-) {
11390: $file=~s-^/adm/wrapper/-/-;
11391: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11392: }
11393: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11394: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11395: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11396: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11397: {/uploaded/$1/$2/}x;
1.46 www 11398: }
1.913 albertel 11399: if ($file=~ m{^/userfiles/}) {
11400: $file =~ s{^/userfiles/}{/uploaded/};
11401: }
1.462 albertel 11402: return $file;
1.465 albertel 11403: }
11404:
1.1139 www 11405:
11406:
11407:
11408:
1.465 albertel 11409: sub current_machine_domains {
1.853 albertel 11410: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11411: }
11412:
11413: sub machine_domains {
11414: my ($hostname) = @_;
1.465 albertel 11415: my @domains;
1.838 albertel 11416: my %hostname = &all_hostnames();
1.465 albertel 11417: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11418: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11419: if ($hostname eq $name) {
1.844 albertel 11420: push(@domains,&host_domain($id));
1.465 albertel 11421: }
11422: }
11423: return @domains;
11424: }
11425:
11426: sub current_machine_ids {
1.853 albertel 11427: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11428: }
11429:
11430: sub machine_ids {
11431: my ($hostname) = @_;
11432: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11433: my @ids;
1.888 albertel 11434: my %name_to_host = &all_names();
1.889 albertel 11435: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11436: return @{ $name_to_host{$hostname} };
11437: }
11438: return;
1.31 www 11439: }
11440:
1.824 raeburn 11441: sub additional_machine_domains {
11442: my @domains;
11443: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11444: while( my $line = <$fh>) {
11445: $line =~ s/\s//g;
11446: push(@domains,$line);
11447: }
11448: return @domains;
11449: }
11450:
11451: sub default_login_domain {
11452: my $domain = $perlvar{'lonDefDomain'};
11453: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11454: foreach my $posdom (¤t_machine_domains(),
11455: &additional_machine_domains()) {
11456: if (lc($posdom) eq lc($testdomain)) {
11457: $domain=$posdom;
11458: last;
11459: }
11460: }
11461: return $domain;
11462: }
11463:
1.31 www 11464: # ------------------------------------------------------------- Declutters URLs
11465:
11466: sub declutter {
11467: my $thisfn=shift;
1.569 albertel 11468: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11469: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11470: $thisfn=~s/^\///;
1.697 albertel 11471: $thisfn=~s|^adm/wrapper/||;
11472: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11473: $thisfn=~s/^res\///;
1.1172 bisitz 11474: $thisfn=~s/^priv\///;
1.1032 raeburn 11475: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11476: $thisfn=~s/\?.+$//;
11477: }
1.268 www 11478: return $thisfn;
11479: }
11480:
11481: # ------------------------------------------------------------- Clutter up URLs
11482:
11483: sub clutter {
11484: my $thisfn='/'.&declutter(shift);
1.887 albertel 11485: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11486: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11487: $thisfn='/res'.$thisfn;
11488: }
1.1031 raeburn 11489: if ($thisfn !~m|^/adm|) {
11490: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11491: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11492: } else {
11493: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11494: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11495: if ($embstyle eq 'ssi'
11496: || ($embstyle eq 'hdn')
11497: || ($embstyle eq 'rat')
11498: || ($embstyle eq 'prv')
11499: || ($embstyle eq 'ign')) {
11500: #do nothing with these
11501: } elsif (($embstyle eq 'img')
1.695 albertel 11502: || ($embstyle eq 'emb')
11503: || ($embstyle eq 'wrp')) {
11504: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11505: } elsif ($embstyle eq 'unk'
11506: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11507: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11508: } else {
1.718 www 11509: # &logthis("Got a blank emb style");
1.695 albertel 11510: }
1.694 albertel 11511: }
11512: }
1.31 www 11513: return $thisfn;
1.12 www 11514: }
11515:
1.787 albertel 11516: sub clutter_with_no_wrapper {
11517: my $uri = &clutter(shift);
11518: if ($uri =~ m-^/adm/-) {
11519: $uri =~ s-^/adm/wrapper/-/-;
11520: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11521: }
11522: return $uri;
11523: }
11524:
1.557 albertel 11525: sub freeze_escape {
11526: my ($value)=@_;
11527: if (ref($value)) {
11528: $value=&nfreeze($value);
11529: return '__FROZEN__'.&escape($value);
11530: }
11531: return &escape($value);
11532: }
11533:
1.11 www 11534:
1.557 albertel 11535: sub thaw_unescape {
11536: my ($value)=@_;
11537: if ($value =~ /^__FROZEN__/) {
11538: substr($value,0,10,undef);
11539: $value=&unescape($value);
11540: return &thaw($value);
11541: }
11542: return &unescape($value);
11543: }
11544:
1.436 albertel 11545: sub correct_line_ends {
11546: my ($result)=@_;
11547: $$result =~s/\r\n/\n/mg;
11548: $$result =~s/\r/\n/mg;
1.415 albertel 11549: }
1.1 albertel 11550: # ================================================================ Main Program
11551:
1.184 www 11552: sub goodbye {
1.204 albertel 11553: &logthis("Starting Shut down");
1.443 albertel 11554: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11555: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11556: #converted
1.599 albertel 11557: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11558: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11559: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11560: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11561: #1.1 only
1.870 albertel 11562: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11563: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11564: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11565: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11566: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11567: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11568: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11569: &flushcourselogs();
11570: &logthis("Shutting down");
11571: }
11572:
1.852 albertel 11573: sub get_dns {
1.1210 raeburn 11574: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11575: if (!$ignore_cache) {
11576: my ($content,$cached)=
11577: &Apache::lonnet::is_cached_new('dns',$url);
11578: if ($cached) {
1.1210 raeburn 11579: &$func($content,$hashref);
1.869 albertel 11580: return;
11581: }
11582: }
11583:
11584: my %alldns;
1.852 albertel 11585: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11586: foreach my $dns (<$config>) {
11587: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11588: my $line = $1;
11589: my ($host,$protocol) = split(/:/,$line);
11590: if ($protocol ne 'https') {
11591: $protocol = 'http';
11592: }
11593: $alldns{$host} = $protocol;
1.869 albertel 11594: }
11595: while (%alldns) {
11596: my ($dns) = keys(%alldns);
1.852 albertel 11597: my $ua=new LWP::UserAgent;
1.1134 raeburn 11598: $ua->timeout(30);
1.979 raeburn 11599: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11600: my $response=$ua->request($request);
1.979 raeburn 11601: delete($alldns{$dns});
1.852 albertel 11602: next if ($response->is_error());
11603: my @content = split("\n",$response->content);
1.1210 raeburn 11604: unless ($nocache) {
1.1219 raeburn 11605: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 11606: }
11607: &$func(\@content,$hashref);
1.869 albertel 11608: return;
1.852 albertel 11609: }
11610: close($config);
1.871 albertel 11611: my $which = (split('/',$url))[3];
11612: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11613: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11614: my @content = <$config>;
1.1210 raeburn 11615: &$func(\@content,$hashref);
11616: return;
11617: }
11618:
11619: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 11620: sub parse_dns_checksums_tab {
1.1210 raeburn 11621: my ($lines,$hashref) = @_;
11622: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11623: my $loncaparev = &get_server_loncaparev($machine_dom);
11624: my ($release,$timestamp) = split(/\-/,$loncaparev);
11625: my (%chksum,%revnum);
11626: if (ref($lines) eq 'ARRAY') {
11627: chomp(@{$lines});
11628: my $versions = shift(@{$lines});
11629: my %supported;
11630: if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
11631: my $releaseslist = $1;
11632: if ($releaseslist =~ /,/) {
11633: map { $supported{$_} = 1; } split(/,/,$releaseslist);
11634: } elsif ($releaseslist) {
11635: $supported{$releaseslist} = 1;
11636: }
11637: }
11638: if ($supported{$release}) {
11639: my $matchthis = 0;
11640: foreach my $line (@{$lines}) {
11641: if ($line =~ /^(\d[\w\.]+)$/) {
11642: if ($matchthis) {
11643: last;
11644: } elsif ($1 eq $release) {
11645: $matchthis = 1;
11646: }
11647: } elsif ($matchthis) {
11648: my ($file,$version,$shasum) = split(/,/,$line);
11649: $chksum{$file} = $shasum;
11650: $revnum{$file} = $version;
11651: }
11652: }
11653: if (ref($hashref) eq 'HASH') {
11654: %{$hashref} = (
11655: sums => \%chksum,
11656: versions => \%revnum,
11657: );
11658: }
11659: }
11660: }
1.869 albertel 11661: return;
1.852 albertel 11662: }
1.1210 raeburn 11663:
11664: sub fetch_dns_checksums {
11665: my %checksums;
1.1211 raeburn 11666: &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
11667: \%checksums);
1.1210 raeburn 11668: return \%checksums;
11669: }
11670:
1.327 albertel 11671: # ------------------------------------------------------------ Read domain file
11672: {
1.852 albertel 11673: my $loaded;
1.846 albertel 11674: my %domain;
11675:
1.852 albertel 11676: sub parse_domain_tab {
11677: my ($lines) = @_;
11678: foreach my $line (@$lines) {
11679: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11680:
1.846 albertel 11681: chomp($line);
1.852 albertel 11682: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11683: my %this_domain;
11684: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11685: 'lang_def', 'city', 'longi', 'lati',
11686: 'primary') {
11687: $this_domain{$field} = shift(@elements);
11688: }
11689: $domain{$name} = \%this_domain;
1.852 albertel 11690: }
11691: }
1.864 albertel 11692:
11693: sub reset_domain_info {
11694: undef($loaded);
11695: undef(%domain);
11696: }
11697:
1.852 albertel 11698: sub load_domain_tab {
1.869 albertel 11699: my ($ignore_cache) = @_;
11700: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11701: my $fh;
11702: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11703: my @lines = <$fh>;
11704: &parse_domain_tab(\@lines);
1.448 albertel 11705: }
1.852 albertel 11706: close($fh);
11707: $loaded = 1;
1.327 albertel 11708: }
1.846 albertel 11709:
11710: sub domain {
1.852 albertel 11711: &load_domain_tab() if (!$loaded);
11712:
1.846 albertel 11713: my ($name,$what) = @_;
11714: return if ( !exists($domain{$name}) );
11715:
11716: if (!$what) {
11717: return $domain{$name}{'description'};
11718: }
11719: return $domain{$name}{$what};
11720: }
1.974 raeburn 11721:
11722: sub domain_info {
11723: &load_domain_tab() if (!$loaded);
11724: return %domain;
11725: }
11726:
1.327 albertel 11727: }
11728:
11729:
1.1 albertel 11730: # ------------------------------------------------------------- Read hosts file
11731: {
1.838 albertel 11732: my %hostname;
1.844 albertel 11733: my %hostdom;
1.845 albertel 11734: my %libserv;
1.852 albertel 11735: my $loaded;
1.888 albertel 11736: my %name_to_host;
1.1074 raeburn 11737: my %internetdom;
1.1107 raeburn 11738: my %LC_dns_serv;
1.852 albertel 11739:
11740: sub parse_hosts_tab {
11741: my ($file) = @_;
11742: foreach my $configline (@$file) {
11743: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11744: chomp($configline);
11745: if ($configline =~ /^\^/) {
11746: if ($configline =~ /^\^([\w.\-]+)/) {
11747: $LC_dns_serv{$1} = 1;
11748: }
11749: next;
11750: }
1.1074 raeburn 11751: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11752: $name=~s/\s//g;
11753: if ($id && $domain && $role && $name) {
11754: $hostname{$id}=$name;
1.888 albertel 11755: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11756: $hostdom{$id}=$domain;
11757: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11758: if (defined($protocol)) {
11759: if ($protocol eq 'https') {
11760: $protocol{$id} = $protocol;
11761: } else {
11762: $protocol{$id} = 'http';
11763: }
1.968 raeburn 11764: } else {
1.969 raeburn 11765: $protocol{$id} = 'http';
1.968 raeburn 11766: }
1.1074 raeburn 11767: if (defined($intdom)) {
11768: $internetdom{$id} = $intdom;
11769: }
1.852 albertel 11770: }
11771: }
11772: }
1.864 albertel 11773:
11774: sub reset_hosts_info {
1.897 albertel 11775: &purge_remembered();
1.864 albertel 11776: &reset_domain_info();
11777: &reset_hosts_ip_info();
1.892 albertel 11778: undef(%name_to_host);
1.864 albertel 11779: undef(%hostname);
11780: undef(%hostdom);
11781: undef(%libserv);
11782: undef($loaded);
11783: }
1.1 albertel 11784:
1.852 albertel 11785: sub load_hosts_tab {
1.869 albertel 11786: my ($ignore_cache) = @_;
11787: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11788: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11789: my @config = <$config>;
11790: &parse_hosts_tab(\@config);
11791: close($config);
11792: $loaded=1;
1.1 albertel 11793: }
1.852 albertel 11794:
1.838 albertel 11795: sub hostname {
1.852 albertel 11796: &load_hosts_tab() if (!$loaded);
11797:
1.838 albertel 11798: my ($lonid) = @_;
11799: return $hostname{$lonid};
11800: }
1.845 albertel 11801:
1.838 albertel 11802: sub all_hostnames {
1.852 albertel 11803: &load_hosts_tab() if (!$loaded);
11804:
1.838 albertel 11805: return %hostname;
11806: }
1.845 albertel 11807:
1.888 albertel 11808: sub all_names {
11809: &load_hosts_tab() if (!$loaded);
11810:
11811: return %name_to_host;
11812: }
11813:
1.974 raeburn 11814: sub all_host_domain {
11815: &load_hosts_tab() if (!$loaded);
11816: return %hostdom;
11817: }
11818:
1.845 albertel 11819: sub is_library {
1.852 albertel 11820: &load_hosts_tab() if (!$loaded);
11821:
1.845 albertel 11822: return exists($libserv{$_[0]});
11823: }
11824:
11825: sub all_library {
1.852 albertel 11826: &load_hosts_tab() if (!$loaded);
11827:
1.845 albertel 11828: return %libserv;
11829: }
11830:
1.1062 droeschl 11831: sub unique_library {
11832: #2x reverse removes all hostnames that appear more than once
11833: my %unique = reverse &all_library();
11834: return reverse %unique;
11835: }
11836:
1.841 albertel 11837: sub get_servers {
1.852 albertel 11838: &load_hosts_tab() if (!$loaded);
11839:
1.841 albertel 11840: my ($domain,$type) = @_;
11841: my %possible_hosts = ($type eq 'library') ? %libserv
11842: : %hostname;
11843: my %result;
1.842 albertel 11844: if (ref($domain) eq 'ARRAY') {
11845: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11846: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11847: $result{$host} = $hostname;
11848: }
11849: }
11850: } else {
11851: while ( my ($host,$hostname) = each(%possible_hosts)) {
11852: if ($hostdom{$host} eq $domain) {
11853: $result{$host} = $hostname;
11854: }
1.841 albertel 11855: }
11856: }
11857: return %result;
11858: }
1.845 albertel 11859:
1.1062 droeschl 11860: sub get_unique_servers {
11861: my %unique = reverse &get_servers(@_);
11862: return reverse %unique;
11863: }
11864:
1.844 albertel 11865: sub host_domain {
1.852 albertel 11866: &load_hosts_tab() if (!$loaded);
11867:
1.844 albertel 11868: my ($lonid) = @_;
11869: return $hostdom{$lonid};
11870: }
11871:
1.841 albertel 11872: sub all_domains {
1.852 albertel 11873: &load_hosts_tab() if (!$loaded);
11874:
1.841 albertel 11875: my %seen;
11876: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11877: return @uniq;
11878: }
1.1074 raeburn 11879:
11880: sub internet_dom {
11881: &load_hosts_tab() if (!$loaded);
11882:
11883: my ($lonid) = @_;
11884: return $internetdom{$lonid};
11885: }
1.1107 raeburn 11886:
11887: sub is_LC_dns {
11888: &load_hosts_tab() if (!$loaded);
11889:
11890: my ($hostname) = @_;
11891: return exists($LC_dns_serv{$hostname});
11892: }
11893:
1.1 albertel 11894: }
11895:
1.847 albertel 11896: {
11897: my %iphost;
1.856 albertel 11898: my %name_to_ip;
11899: my %lonid_to_ip;
1.869 albertel 11900:
1.847 albertel 11901: sub get_hosts_from_ip {
11902: my ($ip) = @_;
11903: my %iphosts = &get_iphost();
11904: if (ref($iphosts{$ip})) {
11905: return @{$iphosts{$ip}};
11906: }
11907: return;
1.839 albertel 11908: }
1.864 albertel 11909:
11910: sub reset_hosts_ip_info {
11911: undef(%iphost);
11912: undef(%name_to_ip);
11913: undef(%lonid_to_ip);
11914: }
1.856 albertel 11915:
11916: sub get_host_ip {
11917: my ($lonid) = @_;
11918: if (exists($lonid_to_ip{$lonid})) {
11919: return $lonid_to_ip{$lonid};
11920: }
11921: my $name=&hostname($lonid);
11922: my $ip = gethostbyname($name);
11923: return if (!$ip || length($ip) ne 4);
11924: $ip=inet_ntoa($ip);
11925: $name_to_ip{$name} = $ip;
11926: $lonid_to_ip{$lonid} = $ip;
11927: return $ip;
11928: }
1.847 albertel 11929:
11930: sub get_iphost {
1.869 albertel 11931: my ($ignore_cache) = @_;
1.894 albertel 11932:
1.869 albertel 11933: if (!$ignore_cache) {
11934: if (%iphost) {
11935: return %iphost;
11936: }
11937: my ($ip_info,$cached)=
11938: &Apache::lonnet::is_cached_new('iphost','iphost');
11939: if ($cached) {
11940: %iphost = %{$ip_info->[0]};
11941: %name_to_ip = %{$ip_info->[1]};
11942: %lonid_to_ip = %{$ip_info->[2]};
11943: return %iphost;
11944: }
11945: }
1.894 albertel 11946:
11947: # get yesterday's info for fallback
11948: my %old_name_to_ip;
11949: my ($ip_info,$cached)=
11950: &Apache::lonnet::is_cached_new('iphost','iphost');
11951: if ($cached) {
11952: %old_name_to_ip = %{$ip_info->[1]};
11953: }
11954:
1.888 albertel 11955: my %name_to_host = &all_names();
11956: foreach my $name (keys(%name_to_host)) {
1.847 albertel 11957: my $ip;
11958: if (!exists($name_to_ip{$name})) {
11959: $ip = gethostbyname($name);
11960: if (!$ip || length($ip) ne 4) {
1.894 albertel 11961: if (defined($old_name_to_ip{$name})) {
11962: $ip = $old_name_to_ip{$name};
11963: &logthis("Can't find $name defaulting to old $ip");
11964: } else {
11965: &logthis("Name $name no IP found");
11966: next;
11967: }
11968: } else {
11969: $ip=inet_ntoa($ip);
1.847 albertel 11970: }
11971: $name_to_ip{$name} = $ip;
11972: } else {
11973: $ip = $name_to_ip{$name};
1.653 albertel 11974: }
1.888 albertel 11975: foreach my $id (@{ $name_to_host{$name} }) {
11976: $lonid_to_ip{$id} = $ip;
11977: }
11978: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 11979: }
1.1219 raeburn 11980: &do_cache_new('iphost','iphost',
11981: [\%iphost,\%name_to_ip,\%lonid_to_ip],
11982: 48*60*60);
1.869 albertel 11983:
1.847 albertel 11984: return %iphost;
1.598 albertel 11985: }
11986:
1.992 raeburn 11987: #
11988: # Given a DNS returns the loncapa host name for that DNS
11989: #
11990: sub host_from_dns {
11991: my ($dns) = @_;
11992: my @hosts;
11993: my $ip;
11994:
1.993 raeburn 11995: if (exists($name_to_ip{$dns})) {
1.992 raeburn 11996: $ip = $name_to_ip{$dns};
11997: }
11998: if (!$ip) {
11999: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12000: if (length($ip) == 4) {
12001: $ip = &IO::Socket::inet_ntoa($ip);
12002: }
12003: }
12004: if ($ip) {
12005: @hosts = get_hosts_from_ip($ip);
12006: return $hosts[0];
12007: }
12008: return undef;
1.986 foxr 12009: }
1.992 raeburn 12010:
1.1074 raeburn 12011: sub get_internet_names {
12012: my ($lonid) = @_;
12013: return if ($lonid eq '');
12014: my ($idnref,$cached)=
12015: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12016: if ($cached) {
12017: return $idnref;
12018: }
12019: my $ip = &get_host_ip($lonid);
12020: my @hosts = &get_hosts_from_ip($ip);
12021: my %iphost = &get_iphost();
12022: my (@idns,%seen);
12023: foreach my $id (@hosts) {
12024: my $dom = &host_domain($id);
12025: my $prim_id = &domain($dom,'primary');
12026: my $prim_ip = &get_host_ip($prim_id);
12027: next if ($seen{$prim_ip});
12028: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12029: foreach my $id (@{$iphost{$prim_ip}}) {
12030: my $intdom = &internet_dom($id);
12031: unless (grep(/^\Q$intdom\E$/,@idns)) {
12032: push(@idns,$intdom);
12033: }
12034: }
12035: }
12036: $seen{$prim_ip} = 1;
12037: }
1.1219 raeburn 12038: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12039: }
12040:
1.986 foxr 12041: }
12042:
1.1079 raeburn 12043: sub all_loncaparevs {
12044: 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);
12045: }
12046:
1.1227 raeburn 12047: # ---------------------------------------------------------- Read loncaparev table
12048: {
12049: sub load_loncaparevs {
12050: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12051: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12052: while (my $configline=<$config>) {
12053: chomp($configline);
12054: my ($hostid,$loncaparev)=split(/:/,$configline);
12055: $loncaparevs{$hostid}=$loncaparev;
12056: }
12057: close($config);
12058: }
12059: }
12060: }
12061: }
12062:
12063: # ---------------------------------------------------------- Read serverhostID table
12064: {
12065: sub load_serverhomeIDs {
12066: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12067: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12068: while (my $configline=<$config>) {
12069: chomp($configline);
12070: my ($name,$id)=split(/:/,$configline);
12071: $serverhomeIDs{$name}=$id;
12072: }
12073: close($config);
12074: }
12075: }
12076: }
12077: }
12078:
12079:
1.862 albertel 12080: BEGIN {
12081:
12082: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12083: unless ($readit) {
12084: {
12085: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12086: %perlvar = (%perlvar,%{$configvars});
12087: }
12088:
12089:
1.1 albertel 12090: # ------------------------------------------------------ Read spare server file
12091: {
1.448 albertel 12092: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12093:
12094: while (my $configline=<$config>) {
12095: chomp($configline);
1.284 matthew 12096: if ($configline) {
1.784 albertel 12097: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12098: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12099: push(@{ $spareid{$type} }, $host);
1.1 albertel 12100: }
12101: }
1.448 albertel 12102: close($config);
1.1 albertel 12103: }
1.11 www 12104: # ------------------------------------------------------------ Read permissions
12105: {
1.448 albertel 12106: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12107:
12108: while (my $configline=<$config>) {
1.448 albertel 12109: chomp($configline);
12110: if ($configline) {
12111: my ($role,$perm)=split(/ /,$configline);
12112: if ($perm ne '') { $pr{$role}=$perm; }
12113: }
1.11 www 12114: }
1.448 albertel 12115: close($config);
1.11 www 12116: }
12117:
12118: # -------------------------------------------- Read plain texts for permissions
12119: {
1.448 albertel 12120: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12121:
12122: while (my $configline=<$config>) {
1.448 albertel 12123: chomp($configline);
12124: if ($configline) {
1.742 raeburn 12125: my ($short,@plain)=split(/:/,$configline);
12126: %{$prp{$short}} = ();
12127: if (@plain > 0) {
12128: $prp{$short}{'std'} = $plain[0];
12129: for (my $i=1; $i<@plain; $i++) {
12130: $prp{$short}{'alt'.$i} = $plain[$i];
12131: }
12132: }
1.448 albertel 12133: }
1.135 www 12134: }
1.448 albertel 12135: close($config);
1.135 www 12136: }
12137:
12138: # ---------------------------------------------------------- Read package table
12139: {
1.448 albertel 12140: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12141:
12142: while (my $configline=<$config>) {
1.483 albertel 12143: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12144: chomp($configline);
12145: my ($short,$plain)=split(/:/,$configline);
12146: my ($pack,$name)=split(/\&/,$short);
12147: if ($plain ne '') {
12148: $packagetab{$pack.'&'.$name.'&name'}=$name;
12149: $packagetab{$short}=$plain;
12150: }
1.11 www 12151: }
1.448 albertel 12152: close($config);
1.329 matthew 12153: }
12154:
1.1073 raeburn 12155: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12156:
12157: &load_loncaparevs();
1.1073 raeburn 12158:
1.1074 raeburn 12159: # ---------------------------------------------------------- Read serverhostID table
12160:
1.1227 raeburn 12161: &load_serverhomeIDs();
12162:
12163: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12164: {
12165: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12166: if (-e $file) {
12167: my $parser = HTML::LCParser->new($file);
12168: while (my $token = $parser->get_token()) {
12169: if ($token->[0] eq 'S') {
12170: my $item = $token->[1];
12171: my $name = $token->[2]{'name'};
12172: my $value = $token->[2]{'value'};
12173: if ($item ne '' && $name ne '' && $value ne '') {
12174: my $release = $parser->get_text();
12175: $release =~ s/(^\s*|\s*$ )//gx;
12176: $needsrelease{$item.':'.$name.':'.$value} = $release;
12177: }
12178: }
12179: }
12180: }
1.1073 raeburn 12181: }
12182:
1.1138 raeburn 12183: # ---------------------------------------------------------- Read managers table
12184: {
12185: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12186: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12187: while (my $configline=<$config>) {
12188: chomp($configline);
12189: next if ($configline =~ /^\#/);
12190: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12191: $managerstab{$configline} = 1;
12192: }
12193: }
12194: close($config);
12195: }
12196: }
12197: }
12198:
1.329 matthew 12199: # ------------- set up temporary directory
12200: {
1.1117 foxr 12201: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12202:
1.11 www 12203: }
12204:
1.794 albertel 12205: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12206: 'compress_threshold'=> 20_000,
12207: });
1.185 www 12208:
1.281 www 12209: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12210: $dumpcount=0;
1.958 www 12211: $locknum=0;
1.22 www 12212:
1.163 harris41 12213: &logtouch();
1.672 albertel 12214: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12215: $readit=1;
1.564 albertel 12216: {
12217: use integer;
12218: my $test=(2**32)+1;
1.568 albertel 12219: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12220: &logthis(" Detected 64bit platform ($_64bit)");
12221: }
1.1214 raeburn 12222:
12223: {
12224: eval {
12225: ($apache) =
12226: (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12227: };
12228: if ($@) {
12229: $apache = 1.3;
1.1213 raeburn 12230: }
12231: }
1.1214 raeburn 12232:
1.195 www 12233: }
1.1 albertel 12234: }
1.179 www 12235:
1.1 albertel 12236: 1;
1.191 harris41 12237: __END__
12238:
1.243 albertel 12239: =pod
12240:
1.191 harris41 12241: =head1 NAME
12242:
1.243 albertel 12243: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12244:
12245: =head1 SYNOPSIS
12246:
1.243 albertel 12247: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12248:
12249: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12250:
1.243 albertel 12251: Common parameters:
12252:
12253: =over 4
12254:
12255: =item *
12256:
12257: $uname : an internal username (if $cname expecting a course Id specifically)
12258:
12259: =item *
12260:
12261: $udom : a domain (if $cdom expecting a course's domain specifically)
12262:
12263: =item *
12264:
12265: $symb : a resource instance identifier
12266:
12267: =item *
12268:
12269: $namespace : the name of a .db file that contains the data needed or
12270: being set.
12271:
12272: =back
12273:
1.394 bowersj2 12274: =head1 OVERVIEW
1.191 harris41 12275:
1.394 bowersj2 12276: lonnet provides subroutines which interact with the
12277: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12278: about classes, users, and resources.
1.243 albertel 12279:
12280: For many of these objects you can also use this to store data about
12281: them or modify them in various ways.
1.191 harris41 12282:
1.394 bowersj2 12283: =head2 Symbs
1.191 harris41 12284:
1.394 bowersj2 12285: To identify a specific instance of a resource, LON-CAPA uses symbols
12286: or "symbs"X<symb>. These identifiers are built from the URL of the
12287: map, the resource number of the resource in the map, and the URL of
12288: the resource itself. The latter is somewhat redundant, but might help
12289: if maps change.
12290:
12291: An example is
12292:
12293: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12294:
12295: The respective map entry is
12296:
12297: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12298: title="Problem 2">
12299: </resource>
12300:
12301: Symbs are used by the random number generator, as well as to store and
12302: restore data specific to a certain instance of for example a problem.
12303:
12304: =head2 Storing And Retrieving Data
12305:
12306: X<store()>X<cstore()>X<restore()>Three of the most important functions
12307: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12308: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12309: is is the non-critical message twin of cstore. These functions are for
12310: handlers to store a perl hash to a user's permanent data space in an
12311: easy manner, and to retrieve it again on another call. It is expected
12312: that a handler would use this once at the beginning to retrieve data,
12313: and then again once at the end to send only the new data back.
12314:
12315: The data is stored in the user's data directory on the user's
12316: homeserver under the ID of the course.
12317:
12318: The hash that is returned by restore will have all of the previous
12319: value for all of the elements of the hash.
12320:
12321: Example:
12322:
12323: #creating a hash
12324: my %hash;
12325: $hash{'foo'}='bar';
12326:
12327: #storing it
12328: &Apache::lonnet::cstore(\%hash);
12329:
12330: #changing a value
12331: $hash{'foo'}='notbar';
12332:
12333: #adding a new value
12334: $hash{'bar'}='foo';
12335: &Apache::lonnet::cstore(\%hash);
12336:
12337: #retrieving the hash
12338: my %history=&Apache::lonnet::restore();
12339:
12340: #print the hash
12341: foreach my $key (sort(keys(%history))) {
12342: print("\%history{$key} = $history{$key}");
12343: }
12344:
12345: Will print out:
1.191 harris41 12346:
1.394 bowersj2 12347: %history{1:foo} = bar
12348: %history{1:keys} = foo:timestamp
12349: %history{1:timestamp} = 990455579
12350: %history{2:bar} = foo
12351: %history{2:foo} = notbar
12352: %history{2:keys} = foo:bar:timestamp
12353: %history{2:timestamp} = 990455580
12354: %history{bar} = foo
12355: %history{foo} = notbar
12356: %history{timestamp} = 990455580
12357: %history{version} = 2
12358:
12359: Note that the special hash entries C<keys>, C<version> and
12360: C<timestamp> were added to the hash. C<version> will be equal to the
12361: total number of versions of the data that have been stored. The
12362: C<timestamp> attribute will be the UNIX time the hash was
12363: stored. C<keys> is available in every historical section to list which
12364: keys were added or changed at a specific historical revision of a
12365: hash.
12366:
12367: B<Warning>: do not store the hash that restore returns directly. This
12368: will cause a mess since it will restore the historical keys as if the
12369: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12370:
1.394 bowersj2 12371: Calling convention:
1.191 harris41 12372:
1.1225 raeburn 12373: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12374: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12375:
1.394 bowersj2 12376: For more detailed information, see lonnet specific documentation.
1.191 harris41 12377:
1.394 bowersj2 12378: =head1 RETURN MESSAGES
1.191 harris41 12379:
1.394 bowersj2 12380: =over 4
1.191 harris41 12381:
1.394 bowersj2 12382: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12383:
1.394 bowersj2 12384: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12385: when the connection is brought back up
1.191 harris41 12386:
1.394 bowersj2 12387: =item * B<con_failed>: unable to contact remote host and unable to save message
12388: for later delivery
1.191 harris41 12389:
1.967 bisitz 12390: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12391:
1.394 bowersj2 12392: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12393: that was requested
1.191 harris41 12394:
1.243 albertel 12395: =back
1.191 harris41 12396:
1.243 albertel 12397: =head1 PUBLIC SUBROUTINES
1.191 harris41 12398:
1.243 albertel 12399: =head2 Session Environment Functions
1.191 harris41 12400:
1.243 albertel 12401: =over 4
1.191 harris41 12402:
1.394 bowersj2 12403: =item *
12404: X<appenv()>
1.949 raeburn 12405: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12406: the user envirnoment file, and will be restored for each access this
1.620 albertel 12407: user makes during this session, also modifies the %env for the current
1.949 raeburn 12408: process. Optional rolesarrayref - if defined contains a reference to an array
12409: of roles which are exempt from the restriction on modifying user.role entries
12410: in the user's environment.db and in %env.
1.191 harris41 12411:
12412: =item *
1.394 bowersj2 12413: X<delenv()>
1.987 raeburn 12414: B<delenv($delthis,$regexp)>: removes all items from the session
12415: environment file that begin with $delthis. If the
12416: optional second arg - $regexp - is true, $delthis is treated as a
12417: regular expression, otherwise \Q$delthis\E is used.
12418: The values are also deleted from the current processes %env.
1.191 harris41 12419:
1.795 albertel 12420: =item * get_env_multiple($name)
12421:
12422: gets $name from the %env hash, it seemlessly handles the cases where multiple
12423: values may be defined and end up as an array ref.
12424:
12425: returns an array of values
12426:
1.243 albertel 12427: =back
12428:
12429: =head2 User Information
1.191 harris41 12430:
1.243 albertel 12431: =over 4
1.191 harris41 12432:
12433: =item *
1.394 bowersj2 12434: X<queryauthenticate()>
12435: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12436: authentication scheme
12437:
12438: =item *
1.394 bowersj2 12439: X<authenticate()>
1.1073 raeburn 12440: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12441: authenticate user from domain's lib servers (first use the current
12442: one). C<$upass> should be the users password.
1.1073 raeburn 12443: $checkdefauth is optional (value is 1 if a check should be made to
12444: authenticate user using default authentication method, and allow
12445: account creation if username does not have account in the domain).
12446: $clientcancheckhost is optional (value is 1 if checking whether the
12447: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12448:
12449: =item *
1.394 bowersj2 12450: X<homeserver()>
12451: B<homeserver($uname,$udom)>: find the server which has
12452: the user's directory and files (there must be only one), this caches
12453: the answer, and also caches if there is a borken connection.
1.191 harris41 12454:
12455: =item *
1.394 bowersj2 12456: X<idget()>
12457: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12458: (IDs are a unique resource in a domain, there must be only 1 ID per
12459: username, and only 1 username per ID in a specific domain) (returns
12460: hash: id=>name,id=>name)
1.191 harris41 12461:
12462: =item *
1.394 bowersj2 12463: X<idrget()>
12464: B<idrget($udom,@unames)>: find the IDs behind a list of
12465: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12466:
12467: =item *
1.394 bowersj2 12468: X<idput()>
12469: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12470:
12471: =item *
1.394 bowersj2 12472: X<rolesinit()>
1.1169 droeschl 12473: B<rolesinit($udom,$username)>: get user privileges.
12474: returns user role, first access and timer interval hashes
1.243 albertel 12475:
12476: =item *
1.1171 droeschl 12477: X<privileged()>
12478: B<privileged($username,$domain)>: returns a true if user has a
12479: privileged and active role (i.e. su or dc), false otherwise.
12480:
12481: =item *
1.551 albertel 12482: X<getsection()>
12483: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12484: course $cname, return section name/number or '' for "not in course"
12485: and '-1' for "no section"
12486:
12487: =item *
1.394 bowersj2 12488: X<userenvironment()>
12489: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12490: passed in @what from the requested user's environment, returns a hash
12491:
1.858 raeburn 12492: =item *
12493: X<userlog_query()>
1.859 albertel 12494: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12495: activity.log file. %filters defines filters applied when parsing the
12496: log file. These can be start or end timestamps, or the type of action
12497: - log to look for Login or Logout events, check for Checkin or
12498: Checkout, role for role selection. The response is in the form
12499: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12500: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12501:
1.243 albertel 12502: =back
12503:
12504: =head2 User Roles
12505:
12506: =over 4
12507:
12508: =item *
12509:
1.810 raeburn 12510: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12511: F: full access
12512: U,I,K: authentication modes (cxx only)
12513: '': forbidden
12514: 1: user needs to choose course
12515: 2: browse allowed
1.766 albertel 12516: A: passphrase authentication needed
1.243 albertel 12517:
12518: =item *
12519:
1.1192 raeburn 12520: constructaccess($url,$setpriv) : check for access to construction space URL
12521:
12522: See if the owner domain and name in the URL match those in the
12523: expected environment. If so, return three element list
12524: ($ownername,$ownerdomain,$ownerhome).
12525:
12526: Otherwise return the null string.
12527:
12528: If second argument 'setpriv' is true, it assigns the privileges,
12529: and returns the same three element list, unless the owner has
12530: blocked "ad hoc" Domain Coordinator access to the Author Space,
12531: in which case the null string is returned.
12532:
12533: =item *
12534:
1.243 albertel 12535: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12536: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12537: and course level
12538:
12539: =item *
12540:
1.988 raeburn 12541: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12542: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12543: $type is Course (default) or Community.
1.988 raeburn 12544: If $forcedefault evaluates to true, text returned will be default
12545: text for $type. Otherwise, if this is a course, the text returned
12546: will be a custom name for the role (if defined in the course's
12547: environment). If no custom name is defined the default is returned.
12548:
1.832 raeburn 12549: =item *
12550:
1.1219 raeburn 12551: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12552: All arguments are optional. Returns a hash of a roles, either for
12553: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12554: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12555: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12556: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12557: For each key, value is set to colon-separated start and end times for
12558: the role. If no username and domain are specified, will default to
1.934 raeburn 12559: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12560: of role statuses (active, future or previous), roles
12561: (e.g., cc,in, st etc.) and domains of the roles which can be used
12562: to restrict the list of roles reported. If no array ref is
12563: provided for types, will default to return only active roles.
1.834 albertel 12564:
1.1195 raeburn 12565: =item *
12566:
12567: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12568: user: $uname:$udom has a role in the course: $cdom_$cnum.
12569:
12570: Additional optional arguments are: $type (if role checking is to be restricted
12571: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 12572: available roles) or future (roles available in the future), and
12573: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 12574: have active Domain Coordinator role in course's domain or in additional
12575: domains (specified in 'Domains to check for privileged users' in course
12576: environment -- set via: Course Settings -> Classlists and staff listing).
12577:
12578: =item *
12579:
12580: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12581: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12582: $possdomains and $possroles are optional array refs -- to domains to check and
12583: roles to check. If $possdomains is not specified, a dump will be done of the
12584: users' roles.db to check for a dc or su role in any domain. This can be
12585: time consuming if &privileged is called repeatedly (e.g., when displaying a
12586: classlist), so in such cases, supplying a $possdomains array is preferred, as
12587: this then allows &privileged_by_domain() to be used, which caches the identity
12588: of privileged users, eliminating the need for repeated calls to &dump().
12589:
12590: =item *
12591:
12592: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12593: where the outer hash keys are domains specified in the $possdomains array ref,
12594: next inner hash keys are privileged roles specified in the $roles array ref,
12595: and the innermost hash contains key = value pairs for username:domain = end:start
12596: for active or future "privileged" users with that role in that domain. To avoid
12597: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12598: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 12599:
1.243 albertel 12600: =back
12601:
12602: =head2 User Modification
12603:
12604: =over 4
12605:
12606: =item *
12607:
1.957 raeburn 12608: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12609: user for the level given by URL. Optional start and end dates (leave empty
12610: string or zero for "no date")
1.191 harris41 12611:
12612: =item *
12613:
1.243 albertel 12614: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12615: change a users, password, possible return values are: ok,
12616: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12617: refused
1.191 harris41 12618:
12619: =item *
12620:
1.243 albertel 12621: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12622:
12623: =item *
12624:
1.1058 raeburn 12625: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12626: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12627:
12628: will update user information (firstname,middlename,lastname,generation,
12629: permanentemail), and if forceid is true, student/employee ID also.
12630: A user's institutional affiliation(s) can also be updated.
12631: User information fields will not be overwritten with empty entries
12632: unless the field is included in the $candelete array reference.
12633: This array is included when a single user is modified via "Manage Users",
12634: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12635:
12636: =item *
12637:
1.286 matthew 12638: modifystudent
12639:
1.957 raeburn 12640: modify a student's enrollment and identification information.
1.286 matthew 12641: The course id is resolved based on the current users environment.
12642: This means the envoking user must be a course coordinator or otherwise
12643: associated with a course.
12644:
1.297 matthew 12645: This call is essentially a wrapper for lonnet::modifyuser and
12646: lonnet::modify_student_enrollment
1.286 matthew 12647:
12648: Inputs:
12649:
12650: =over 4
12651:
1.957 raeburn 12652: =item B<$udom> Student's loncapa domain
1.286 matthew 12653:
1.957 raeburn 12654: =item B<$uname> Student's loncapa login name
1.286 matthew 12655:
1.964 bisitz 12656: =item B<$uid> Student/Employee ID
1.286 matthew 12657:
1.957 raeburn 12658: =item B<$umode> Student's authentication mode
1.286 matthew 12659:
1.957 raeburn 12660: =item B<$upass> Student's password
1.286 matthew 12661:
1.957 raeburn 12662: =item B<$first> Student's first name
1.286 matthew 12663:
1.957 raeburn 12664: =item B<$middle> Student's middle name
1.286 matthew 12665:
1.957 raeburn 12666: =item B<$last> Student's last name
1.286 matthew 12667:
1.957 raeburn 12668: =item B<$gene> Student's generation
1.286 matthew 12669:
1.957 raeburn 12670: =item B<$usec> Student's section in course
1.286 matthew 12671:
12672: =item B<$end> Unix time of the roles expiration
12673:
12674: =item B<$start> Unix time of the roles start date
12675:
12676: =item B<$forceid> If defined, allow $uid to be changed
12677:
12678: =item B<$desiredhome> server to use as home server for student
12679:
1.957 raeburn 12680: =item B<$email> Student's permanent e-mail address
12681:
12682: =item B<$type> Type of enrollment (auto or manual)
12683:
1.963 raeburn 12684: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12685:
12686: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12687:
1.963 raeburn 12688: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12689:
1.963 raeburn 12690: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12691:
1.1216 raeburn 12692: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12693:
12694: =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 12695:
1.286 matthew 12696: =back
1.297 matthew 12697:
12698: =item *
12699:
12700: modify_student_enrollment
12701:
12702: Change a students enrollment status in a class. The environment variable
12703: 'role.request.course' must be defined for this function to proceed.
12704:
12705: Inputs:
12706:
12707: =over 4
12708:
12709: =item $udom, students domain
12710:
12711: =item $uname, students name
12712:
12713: =item $uid, students user id
12714:
12715: =item $first, students first name
12716:
12717: =item $middle
12718:
12719: =item $last
12720:
12721: =item $gene
12722:
12723: =item $usec
12724:
12725: =item $end
12726:
12727: =item $start
12728:
1.957 raeburn 12729: =item $type
12730:
12731: =item $locktype
12732:
12733: =item $cid
12734:
12735: =item $selfenroll
12736:
12737: =item $context
12738:
1.1216 raeburn 12739: =item $credits, number of credits student will earn from this class
12740:
1.297 matthew 12741: =back
12742:
1.191 harris41 12743:
12744: =item *
12745:
1.243 albertel 12746: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12747: custom role; give a custom role to a user for the level given by URL. Specify
12748: name and domain of role author, and role name
1.191 harris41 12749:
12750: =item *
12751:
1.243 albertel 12752: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12753:
12754: =item *
12755:
1.243 albertel 12756: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12757:
12758: =back
12759:
12760: =head2 Course Infomation
12761:
12762: =over 4
1.191 harris41 12763:
12764: =item *
12765:
1.1118 foxr 12766: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12767: specified course id, including all environment settings for the
12768: course, the description of the course will be in the hash under the
12769: key 'description'
1.191 harris41 12770:
1.1118 foxr 12771: $options is an optional parameter that if supplied is a hash reference that controls
12772: what how this function works. It has the following key/values:
12773:
12774: =over 4
12775:
12776: =item freshen_cache
12777:
12778: If defined, and the environment cache for the course is valid, it is
12779: returned in the returned hash.
12780:
12781: =item one_time
12782:
12783: If defined, the last cache time is set to _now_
12784:
12785: =item user
12786:
12787: If defined, the supplied username is used instead of the current user.
12788:
12789:
12790: =back
12791:
1.191 harris41 12792: =item *
12793:
1.624 albertel 12794: resdata($name,$domain,$type,@which) : request for current parameter
12795: setting for a specific $type, where $type is either 'course' or 'user',
12796: @what should be a list of parameters to ask about. This routine caches
12797: answers for 5 minutes.
1.243 albertel 12798:
1.877 foxr 12799: =item *
12800:
12801: get_courseresdata($courseid, $domain) : dump the entire course resource
12802: data base, returning a hash that is keyed by the resource name and has
12803: values that are the resource value. I believe that the timestamps and
12804: versions are also returned.
12805:
1.243 albertel 12806: =back
12807:
12808: =head2 Course Modification
12809:
12810: =over 4
1.191 harris41 12811:
12812: =item *
12813:
1.243 albertel 12814: writecoursepref($courseid,%prefs) : write preferences (environment
12815: database) for a course
1.191 harris41 12816:
12817: =item *
12818:
1.1011 raeburn 12819: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12820:
12821: =item *
12822:
1.1038 raeburn 12823: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12824:
1.1167 droeschl 12825: =item *
12826:
12827: is_course($courseid), is_course($cdom, $cnum)
12828:
12829: Accepts either a combined $courseid (in the form of domain_courseid) or the
12830: two component version $cdom, $cnum. It checks if the specified course exists.
12831:
12832: Returns:
12833: undef if the course doesn't exist, otherwise
12834: in scalar context the combined courseid.
12835: in list context the two components of the course identifier, domain and
12836: courseid.
12837:
1.243 albertel 12838: =back
12839:
12840: =head2 Resource Subroutines
12841:
12842: =over 4
1.191 harris41 12843:
12844: =item *
12845:
1.243 albertel 12846: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12847:
12848: =item *
12849:
1.243 albertel 12850: repcopy($filename) : subscribes to the requested file, and attempts to
12851: replicate from the owning library server, Might return
1.607 raeburn 12852: 'unavailable', 'not_found', 'forbidden', 'ok', or
12853: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12854: resource. Expects the local filesystem pathname
12855: (/home/httpd/html/res/....)
12856:
12857: =back
12858:
12859: =head2 Resource Information
12860:
12861: =over 4
1.191 harris41 12862:
12863: =item *
12864:
1.1228 raeburn 12865: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
12866: and returns the value of a variety of different possible values,
12867: $varname should be a request string, and the other parameters can be
12868: used to specify who and what one is asking about. Ordinarily, $cid
12869: does not need to be specified, as it is retrived from
12870: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12871: within lonuserstate::loadmap() when initializing a course, before
12872: $env{'request.course.id'} has been set, so it needs to be provided
12873: in that one case.
1.243 albertel 12874:
12875: Possible values for $varname are environment.lastname (or other item
12876: from the envirnment hash), user.name (or someother aspect about the
12877: user), resource.0.maxtries (or some other part and parameter of a
12878: resource)
1.204 albertel 12879:
12880: =item *
12881:
1.243 albertel 12882: directcondval($number) : get current value of a condition; reads from a state
12883: string
1.204 albertel 12884:
12885: =item *
12886:
1.243 albertel 12887: condval($condidx) : value of condition index based on state
1.204 albertel 12888:
12889: =item *
12890:
1.243 albertel 12891: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12892: resource's metadata, $what should be either a specific key, or either
12893: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12894: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12895:
12896: this function automatically caches all requests
1.191 harris41 12897:
12898: =item *
12899:
1.243 albertel 12900: metadata_query($query,$custom,$customshow) : make a metadata query against the
12901: network of library servers; returns file handle of where SQL and regex results
12902: will be stored for query
1.191 harris41 12903:
12904: =item *
12905:
1.243 albertel 12906: symbread($filename) : return symbolic list entry (filename argument optional);
12907: returns the data handle
1.191 harris41 12908:
12909: =item *
12910:
1.1190 raeburn 12911: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12912: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 12913: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 12914: on failure, user must be in a course, as it assumes the existence of
12915: the course initial hash, and uses $env('request.course.id'}. The third
12916: arg is an optional reference to a scalar. If this arg is passed in the
12917: call to symbverify, it will be set to 1 if the symb has been set to be
12918: encrypted; otherwise it will be null.
1.191 harris41 12919:
12920: =item *
12921:
1.243 albertel 12922: symbclean($symb) : removes versions numbers from a symb, returns the
12923: cleaned symb
1.191 harris41 12924:
12925: =item *
12926:
1.243 albertel 12927: is_on_map($uri) : checks if the $uri is somewhere on the current
12928: course map, user must be in a course for it to work.
1.191 harris41 12929:
12930: =item *
12931:
1.243 albertel 12932: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 12933:
12934: =item *
12935:
1.243 albertel 12936: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12937: a random seed, all arguments are optional, if they aren't sent it uses the
12938: environment to derive them. Note: if symb isn't sent and it can't get one
12939: from &symbread it will use the current time as its return value
1.191 harris41 12940:
12941: =item *
12942:
1.243 albertel 12943: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12944: unfakeable, receipt
1.191 harris41 12945:
12946: =item *
12947:
1.620 albertel 12948: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 12949:
12950: =item *
12951:
1.243 albertel 12952: countacc($url) : count the number of accesses to a given URL
1.191 harris41 12953:
12954: =item *
12955:
1.243 albertel 12956: 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 12957:
12958: =item *
12959:
1.243 albertel 12960: 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 12961:
12962: =item *
12963:
1.243 albertel 12964: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 12965:
12966: =item *
12967:
1.243 albertel 12968: devalidate($symb) : devalidate temporary spreadsheet calculations,
12969: forcing spreadsheet to reevaluate the resource scores next time.
12970:
1.1195 raeburn 12971: =item *
12972:
1.1196 raeburn 12973: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
12974: when viewing in course context.
1.1195 raeburn 12975:
1.1196 raeburn 12976: input: six args -- filename (decluttered), course number, course domain,
12977: url, symb (if registered) and group (if this is a
12978: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 12979:
1.1196 raeburn 12980: output: array of five scalars --
1.1195 raeburn 12981: $cfile -- url for file editing if editable on current server
12982: $home -- homeserver of resource (i.e., for author if published,
12983: or course if uploaded.).
12984: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 12985: $forceedit -- 1 if icon/link should be to go to edit mode
12986: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 12987:
12988: =item *
12989:
12990: is_course_upload($file,$cnum,$cdom)
12991:
12992: Used in course context to determine if current file was uploaded to
12993: the course (i.e., would be found in /userfiles/docs on the course's
12994: homeserver.
12995:
12996: input: 3 args -- filename (decluttered), course number and course domain.
12997: output: boolean -- 1 if file was uploaded.
12998:
1.243 albertel 12999: =back
13000:
13001: =head2 Storing/Retreiving Data
13002:
13003: =over 4
1.191 harris41 13004:
13005: =item *
13006:
1.243 albertel 13007: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13008: for this url; hashref needs to be given and should be a \%hashname; the
13009: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13010: be derived from the env
1.191 harris41 13011:
13012: =item *
13013:
1.243 albertel 13014: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13015: uses critical subroutine
1.191 harris41 13016:
13017: =item *
13018:
1.243 albertel 13019: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13020: all args are optional
1.191 harris41 13021:
13022: =item *
13023:
1.717 albertel 13024: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13025: dumps the complete (or key matching regexp) namespace into a hash
13026: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13027: normally &store()ed into
13028:
13029: $range should be either an integer '100' (give me the first 100
13030: matching records)
13031: or be two integers sperated by a - with no spaces
13032: '30-50' (give me the 30th through the 50th matching
13033: records)
13034:
13035:
13036: =item *
13037:
13038: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13039: replaces a &store() version of data with a replacement set of data
13040: for a particular resource in a namespace passed in the $storehash hash
13041: reference
13042:
13043: =item *
13044:
1.243 albertel 13045: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13046: works very similar to store/cstore, but all data is stored in a
13047: temporary location and can be reset using tmpreset, $storehash should
13048: be a hash reference, returns nothing on success
1.191 harris41 13049:
13050: =item *
13051:
1.243 albertel 13052: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13053: similar to restore, but all data is stored in a temporary location and
13054: can be reset using tmpreset. Returns a hash of values on success,
13055: error string otherwise.
1.191 harris41 13056:
13057: =item *
13058:
1.243 albertel 13059: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13060: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13061:
13062: =item *
13063:
1.243 albertel 13064: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13065: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13066:
13067: =item *
13068:
1.243 albertel 13069: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13070: namesp ($udom and $uname are optional)
1.191 harris41 13071:
13072: =item *
13073:
1.702 albertel 13074: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13075: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13076: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13077:
1.702 albertel 13078: $range should be either an integer '100' (give me the first 100
13079: matching records)
13080: or be two integers sperated by a - with no spaces
13081: '30-50' (give me the 30th through the 50th matching
13082: records)
1.449 matthew 13083: =item *
13084:
13085: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13086: $store can be a scalar, an array reference, or if the amount to be
13087: incremented is > 1, a hash reference.
13088:
13089: ($udom and $uname are optional)
1.191 harris41 13090:
13091: =item *
13092:
1.243 albertel 13093: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13094: ($udom and $uname are optional)
1.191 harris41 13095:
13096: =item *
13097:
1.243 albertel 13098: cput($namespace,$storehash,$udom,$uname) : critical put
13099: ($udom and $uname are optional)
1.191 harris41 13100:
13101: =item *
13102:
1.748 albertel 13103: newput($namespace,$storehash,$udom,$uname) :
13104:
13105: Attempts to store the items in the $storehash, but only if they don't
13106: currently exist, if this succeeds you can be certain that you have
13107: successfully created a new key value pair in the $namespace db.
13108:
13109:
13110: Args:
13111: $namespace: name of database to store values to
13112: $storehash: hashref to store to the db
13113: $udom: (optional) domain of user containing the db
13114: $uname: (optional) name of user caontaining the db
13115:
13116: Returns:
13117: 'ok' -> succeeded in storing all keys of $storehash
13118: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13119: least <key> already existed in the db (other
13120: requested keys may also already exist)
1.967 bisitz 13121: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13122: 'con_lost' -> unable to contact request server
13123: 'refused' -> action was not allowed by remote machine
13124:
13125:
13126: =item *
13127:
1.243 albertel 13128: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13129: reference filled in from namesp (encrypts the return communication)
13130: ($udom and $uname are optional)
1.191 harris41 13131:
13132: =item *
13133:
1.243 albertel 13134: log($udom,$name,$home,$message) : write to permanent log for user; use
13135: critical subroutine
13136:
1.806 raeburn 13137: =item *
13138:
1.860 raeburn 13139: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13140: array reference filled in from namespace found in domain level on either
13141: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13142:
13143: =item *
13144:
1.860 raeburn 13145: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13146: domain level either on specified domain server ($uhome) or primary domain
13147: server ($udom and $uhome are optional)
1.806 raeburn 13148:
1.943 raeburn 13149: =item *
13150:
13151: get_domain_defaults($target_domain) : returns hash with defaults for
13152: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13153: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13154: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13155: Values are retrieved from cache (if current), or from domain's configuration.db
13156: (if available), or lastly from values in lonTabs/dns_domain,tab,
13157: or lonTabs/domain.tab.
13158:
13159: %domdefaults = &get_auth_defaults($target_domain);
13160:
1.243 albertel 13161: =back
13162:
13163: =head2 Network Status Functions
13164:
13165: =over 4
1.191 harris41 13166:
13167: =item *
13168:
1.1137 raeburn 13169: dirlist() : return directory list based on URI (first arg).
13170:
13171: Inputs: 1 required, 5 optional.
13172:
13173: =over
13174:
13175: =item
13176: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13177:
13178: =item
13179: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13180:
13181: =item
13182: $username - username of user/course to be listed. Extracted from $uri if absent.
13183:
13184: =item
13185: $getpropath - boolean: 1 if prepend path using &propath().
13186:
13187: =item
13188: $getuserdir - boolean: 1 if prepend path for "userfiles".
13189:
13190: =item
13191: $alternateRoot - path to prepend in place of path from $uri.
13192:
13193: =back
13194:
13195: Returns: Array of up to two items.
13196:
13197: =over
13198:
13199: a reference to an array of files/subdirectories
13200:
13201: =over
13202:
13203: Each element in the array of files/subdirectories is a & separated list of
13204: item name and the result of running stat on the item. If dirlist was requested
13205: for a file instead of a directory, the item name will be ''. For a directory
13206: listing, if the item is a metadata file, the element will end &N&M
13207: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13208: default copyright set (1).
13209:
13210: =back
13211:
13212: a scalar containing error condition (if encountered).
13213:
13214: =over
13215:
13216: =item
13217: no_host (no homeserver identified for $username:$domain).
13218:
13219: =item
13220: no_such_host (server contacted for listing not identified as valid host).
13221:
13222: =item
13223: con_lost (connection to remote server failed).
13224:
13225: =item
13226: refused (invalid $username:$domain received on lond side).
13227:
13228: =item
13229: no_such_dir (directory at specified path on lond side does not exist).
13230:
13231: =item
13232: empty (directory at specified path on lond side is empty).
13233:
13234: =over
13235:
13236: This is currently not encountered because the &ls3, &ls2,
13237: &ls (_handler) routines on the lond side do not filter out
13238: . and .. from a directory listing.
13239:
13240: =back
13241:
13242: =back
13243:
13244: =back
1.191 harris41 13245:
13246: =item *
13247:
1.243 albertel 13248: spareserver() : find server with least workload from spare.tab
13249:
1.986 foxr 13250:
13251: =item *
13252:
13253: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13254: if there is no corresponding loncapa host.
13255:
1.243 albertel 13256: =back
13257:
1.986 foxr 13258:
1.243 albertel 13259: =head2 Apache Request
13260:
13261: =over 4
1.191 harris41 13262:
13263: =item *
13264:
1.243 albertel 13265: ssi($url,%hash) : server side include, does a complete request cycle on url to
13266: localhost, posts hash
13267:
13268: =back
13269:
13270: =head2 Data to String to Data
13271:
13272: =over 4
1.191 harris41 13273:
13274: =item *
13275:
1.243 albertel 13276: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13277: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13278:
13279: =item *
13280:
1.243 albertel 13281: hashref2str($hashref) : convert a hashref into a string complete with
13282: escaping and '=' and '&' separators, supports elements that are
13283: arrayrefs and hashrefs
1.191 harris41 13284:
13285: =item *
13286:
1.243 albertel 13287: arrayref2str($arrayref) : convert an arrayref into a string complete
13288: with escaping and '&' separators, supports elements that are arrayrefs
13289: and hashrefs
1.191 harris41 13290:
13291: =item *
13292:
1.243 albertel 13293: str2hash($string) : convert string to hash using unescaping and
13294: splitting on '=' and '&', supports elements that are arrayrefs and
13295: hashrefs
1.191 harris41 13296:
13297: =item *
13298:
1.243 albertel 13299: str2array($string) : convert string to hash using unescaping and
13300: splitting on '&', supports elements that are arrayrefs and hashrefs
13301:
13302: =back
13303:
13304: =head2 Logging Routines
13305:
13306:
13307: These routines allow one to make log messages in the lonnet.log and
13308: lonnet.perm logfiles.
1.191 harris41 13309:
1.1119 foxr 13310: =over 4
13311:
1.191 harris41 13312: =item *
13313:
1.243 albertel 13314: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13315:
13316: =item *
13317:
1.243 albertel 13318: logthis() : append message to the normal lonnet.log file, it gets
13319: preiodically rolled over and deleted.
1.191 harris41 13320:
13321: =item *
13322:
1.243 albertel 13323: logperm() : append a permanent message to lonnet.perm.log, this log
13324: file never gets deleted by any automated portion of the system, only
13325: messages of critical importance should go in here.
13326:
1.1119 foxr 13327:
1.243 albertel 13328: =back
13329:
13330: =head2 General File Helper Routines
13331:
13332: =over 4
1.191 harris41 13333:
13334: =item *
13335:
1.481 raeburn 13336: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13337: (a) files in /uploaded
13338: (i) If a local copy of the file exists -
13339: compares modification date of local copy with last-modified date for
13340: definitive version stored on home server for course. If local copy is
13341: stale, requests a new version from the home server and stores it.
13342: If the original has been removed from the home server, then local copy
13343: is unlinked.
13344: (ii) If local copy does not exist -
13345: requests the file from the home server and stores it.
13346:
13347: If $caller is 'uploadrep':
13348: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13349: for request for files originally uploaded via DOCS.
13350: - returns 'ok' if fresh local copy now available, -1 otherwise.
13351:
13352: Otherwise:
13353: This indicates a call from the content generation phase of the request.
13354: - returns the entire contents of the file or -1.
13355:
13356: (b) files in /res
13357: - returns the entire contents of a file or -1;
13358: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13359:
1.712 albertel 13360:
13361: =item *
13362:
13363: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13364: reference
13365:
13366: returns either a stat() list of data about the file or an empty list
13367: if the file doesn't exist or couldn't find out about it (connection
13368: problems or user unknown)
13369:
1.191 harris41 13370: =item *
13371:
1.243 albertel 13372: filelocation($dir,$file) : returns file system location of a file
13373: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13374: directory that relative $file lookups are to looked in ($dir of /a/dir
13375: and a file of ../bob will become /a/bob)
1.191 harris41 13376:
13377: =item *
13378:
13379: hreflocation($dir,$file) : returns file system location or a URL; same as
13380: filelocation except for hrefs
13381:
13382: =item *
13383:
13384: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13385:
1.243 albertel 13386: =back
13387:
1.608 albertel 13388: =head2 Usererfile file routines (/uploaded*)
13389:
13390: =over 4
13391:
13392: =item *
13393:
13394: userfileupload(): main rotine for putting a file in a user or course's
13395: filespace, arguments are,
13396:
1.620 albertel 13397: formname - required - this is the name of the element in $env where the
1.608 albertel 13398: filename, and the contents of the file to create/modifed exist
1.620 albertel 13399: the filename is in $env{'form.'.$formname.'.filename'} and the
13400: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13401: context - if coursedoc, store the file in the course of the active role
13402: of the current user;
13403: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13404: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13405: subdir - required - subdirectory to put the file in under ../userfiles/
13406: if undefined, it will be placed in "unknown"
13407:
13408: (This routine calls clean_filename() to remove any dangerous
13409: characters from the filename, and then calls finuserfileupload() to
13410: complete the transaction)
13411:
13412: returns either the url of the uploaded file (/uploaded/....) if successful
13413: and /adm/notfound.html if unsuccessful
13414:
13415: =item *
13416:
13417: clean_filename(): routine for cleaing a filename up for storage in
13418: userfile space, argument is:
13419:
13420: filename - proposed filename
13421:
13422: returns: the new clean filename
13423:
13424: =item *
13425:
1.1090 raeburn 13426: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13427: userspace, probably shouldn't be called directly
13428:
13429: docuname: username or courseid of destination for the file
13430: docudom: domain of user/course of destination for the file
13431: formname: same as for userfileupload()
1.1090 raeburn 13432: fname: filename (including subdirectories) for the file
13433: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13434: allfiles: reference to hash used to store objects found by parser
13435: codebase: reference to hash used for codebases of java objects found by parser
13436: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13437: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13438: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13439: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13440: context: if 'overwrite', will move the uploaded file from its temporary location to
13441: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13442: mimetype: reference to scalar to accommodate mime type determined
13443: from File::MMagic if $parser = parse.
1.608 albertel 13444:
13445: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13446: and /adm/notfound.html if unsuccessful (or an error message if context
13447: was 'overwrite').
13448:
1.608 albertel 13449:
13450: =item *
13451:
13452: renameuserfile(): renames an existing userfile to a new name
13453:
13454: Args:
13455: docuname: username or courseid of destination for the file
13456: docudom: domain of user/course of destination for the file
13457: old: current file name (including any subdirs under userfiles)
13458: new: desired file name (including any subdirs under userfiles)
13459:
13460: =item *
13461:
13462: mkdiruserfile(): creates a directory is a userfiles dir
13463:
13464: Args:
13465: docuname: username or courseid of destination for the file
13466: docudom: domain of user/course of destination for the file
13467: dir: dir to create (including any subdirs under userfiles)
13468:
13469: =item *
13470:
13471: removeuserfile(): removes a file that exists in userfiles
13472:
13473: Args:
13474: docuname: username or courseid of destination for the file
13475: docudom: domain of user/course of destination for the file
13476: fname: filname to delete (including any subdirs under userfiles)
13477:
13478: =item *
13479:
13480: removeuploadedurl(): convience function for removeuserfile()
13481:
13482: Args:
13483: url: a full /uploaded/... url to delete
13484:
1.747 albertel 13485: =item *
13486:
13487: get_portfile_permissions():
13488: Args:
13489: domain: domain of user or course contain the portfolio files
13490: user: name of user or num of course contain the portfolio files
13491: Returns:
13492: hashref of a dump of the proper file_permissions.db
13493:
13494:
13495: =item *
13496:
13497: get_access_controls():
13498:
13499: Args:
13500: current_permissions: the hash ref returned from get_portfile_permissions()
13501: group: (optional) the group you want the files associated with
13502: file: (optional) the file you want access info on
13503:
13504: Returns:
1.749 raeburn 13505: a hash (keys are file names) of hashes containing
13506: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13507: values are XML containing access control settings (see below)
1.747 albertel 13508:
13509: Internal notes:
13510:
1.749 raeburn 13511: access controls are stored in file_permissions.db as key=value pairs.
13512: key -> path to file/file_name\0uniqueID:scope_end_start
13513: where scope -> public,guest,course,group,domains or users.
13514: end -> UNIX time for end of access (0 -> no end date)
13515: start -> UNIX time for start of access
13516:
13517: value -> XML description of access control
13518: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13519: <start></start>
13520: <end></end>
13521:
13522: <password></password> for scope type = guest
13523:
13524: <domain></domain> for scope type = course or group
13525: <number></number>
13526: <roles id="">
13527: <role></role>
13528: <access></access>
13529: <section></section>
13530: <group></group>
13531: </roles>
13532:
13533: <dom></dom> for scope type = domains
13534:
13535: <users> for scope type = users
13536: <user>
13537: <uname></uname>
13538: <udom></udom>
13539: </user>
13540: </users>
13541: </scope>
13542:
13543: Access data is also aggregated for each file in an additional key=value pair:
13544: key -> path to file/file_name\0accesscontrol
13545: value -> reference to hash
13546: hash contains key = value pairs
13547: where key = uniqueID:scope_end_start
13548: value = UNIX time record was last updated
13549:
13550: Used to improve speed of look-ups of access controls for each file.
13551:
13552: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13553:
1.1198 raeburn 13554: =item *
13555:
1.749 raeburn 13556: modify_access_controls():
13557:
13558: Modifies access controls for a portfolio file
13559: Args
13560: 1. file name
13561: 2. reference to hash of required changes,
13562: 3. domain
13563: 4. username
13564: where domain,username are the domain of the portfolio owner
13565: (either a user or a course)
13566:
13567: Returns:
13568: 1. result of additions or updates ('ok' or 'error', with error message).
13569: 2. result of deletions ('ok' or 'error', with error message).
13570: 3. reference to hash of any new or updated access controls.
13571: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13572: key = integer (inbound ID)
1.1198 raeburn 13573: value = uniqueID
13574:
13575: =item *
13576:
13577: get_timebased_id():
13578:
13579: Attempts to get a unique timestamp-based suffix for use with items added to a
13580: course via the Course Editor (e.g., folders, composite pages,
13581: group bulletin boards).
13582:
13583: Args: (first three required; six others optional)
13584:
13585: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13586: docssequence, or name of group
13587:
13588: 2. keyid (alphanumeric): name of temporary locking key in hash,
13589: e.g., num, boardids
13590:
13591: 3. namespace: name of gdbm file used to store suffixes already assigned;
13592: file will be named nohist_namespace.db
13593:
13594: 4. cdom: domain of course; default is current course domain from %env
13595:
13596: 5. cnum: course number; default is current course number from %env
13597:
13598: 6. idtype: set to concat if an additional digit is to be appended to the
13599: unix timestamp to form the suffix, if the plain timestamp is already
13600: in use. Default is to not do this, but simply increment the unix
13601: timestamp by 1 until a unique key is obtained.
13602:
13603: 7. who: holder of locking key; defaults to user:domain for user.
13604:
13605: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13606: retrying); default is 3.
13607:
13608: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13609:
13610: Returns:
13611:
13612: 1. suffix obtained (numeric)
13613:
13614: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13615:
13616: 3. error: contains (localized) error message if an error occurred.
13617:
1.747 albertel 13618:
1.608 albertel 13619: =back
13620:
1.243 albertel 13621: =head2 HTTP Helper Routines
13622:
13623: =over 4
13624:
1.191 harris41 13625: =item *
13626:
13627: escape() : unpack non-word characters into CGI-compatible hex codes
13628:
13629: =item *
13630:
13631: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13632:
1.243 albertel 13633: =back
13634:
13635: =head1 PRIVATE SUBROUTINES
13636:
13637: =head2 Underlying communication routines (Shouldn't call)
13638:
13639: =over 4
13640:
13641: =item *
13642:
13643: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13644:
13645: =item *
13646:
13647: reply() : uses subreply to send a message to remote machine, logs all failures
13648:
13649: =item *
13650:
13651: critical() : passes a critical message to another server; if cannot
13652: get through then place message in connection buffer directory and
13653: returns con_delayed, if incapable of saving message, returns
13654: con_failed
13655:
13656: =item *
13657:
13658: reconlonc() : tries to reconnect lonc client processes.
13659:
13660: =back
13661:
13662: =head2 Resource Access Logging
13663:
13664: =over 4
13665:
13666: =item *
13667:
13668: flushcourselogs() : flush (save) buffer logs and access logs
13669:
13670: =item *
13671:
13672: courselog($what) : save message for course in hash
13673:
13674: =item *
13675:
13676: courseacclog($what) : save message for course using &courselog(). Perform
13677: special processing for specific resource types (problems, exams, quizzes, etc).
13678:
1.191 harris41 13679: =item *
13680:
13681: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13682: as a PerlChildExitHandler
1.243 albertel 13683:
13684: =back
13685:
13686: =head2 Other
13687:
13688: =over 4
13689:
13690: =item *
13691:
13692: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13693:
13694: =back
13695:
13696: =cut
1.877 foxr 13697:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>