Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1241
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1241 ! raeburn 4: # $Id: lonnet.pm,v 1.1240 2013/10/06 14:20:36 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 {
1.1241 ! raeburn 359: my ($lonhost,$cachekeys) = @_;
! 360: my $items;
! 361: return unless (ref($cachekeys) eq 'ARRAY');
! 362: my $cachestr = join('&',@{$cachekeys});
! 363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 364: return $response;
365: }
366:
1.1 albertel 367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
1.838 albertel 370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
378: sleep(1);
379: }
380: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 381: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 382: #
1.550 foxr 383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
1.869 albertel 391: if ($client) {
1.550 foxr 392: last; # Connected!
1.850 albertel 393: } else {
1.853 albertel 394: &create_connection(&hostname($server),$server);
1.550 foxr 395: }
1.850 albertel 396: sleep(1); # Try again later if failed connection.
1.550 foxr 397: }
398: my $answer;
399: if ($client) {
1.704 albertel 400: print $client "sethost:$server:$cmd\n";
1.550 foxr 401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
1.1 albertel 407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
1.838 albertel 412: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 413: my $answer=subreply($cmd,$server);
1.65 www 414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 415: &logthis("<font color=\"blue\">WARNING:".
1.12 www 416: " $cmd to $server returned $answer</font>");
417: }
1.1 albertel 418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
1.891 albertel 424: my ($lonid) = @_;
425: my $hostname = &hostname($lonid);
426: if ($lonid) {
427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
1.836 www 442: &logthis("Trying to reconnect lonc");
1.1 albertel 443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 444: if (open(my $fh,"<$loncfile")) {
1.1 albertel 445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
1.836 www 451: } else {
1.12 www 452: &logthis(
1.672 albertel 453: "<font color=\"blue\">WARNING:".
1.12 www 454: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 455: }
456: } else {
1.836 www 457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
1.12 www 462:
1.1 albertel 463: sub critical {
464: my ($cmd,$server)=@_;
1.838 albertel 465: unless (&hostname($server)) {
1.672 albertel 466: &logthis("<font color=\"blue\">WARNING:".
1.89 www 467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
1.1 albertel 470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 473: my $answer=reply($cmd,$server);
1.1 albertel 474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
1.5 www 477: $middlename=substr($middlename,0,16);
1.1 albertel 478: $middlename=~s/\W//g;
479: my $dfilename=
1.305 www 480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
1.1 albertel 482: {
1.448 albertel 483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
1.1 albertel 488: }
489: sleep 2;
490: my $wcmd='';
491: {
1.448 albertel 492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
1.1 albertel 497: }
498: chomp($wcmd);
1.7 www 499: if ($wcmd eq $cmd) {
1.672 albertel 500: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 501: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
1.672 albertel 505: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 506: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
1.405 albertel 513: }
514:
1.755 albertel 515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
1.756 albertel 519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
1.783 albertel 526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
1.917 albertel 530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
1.915 albertel 532: return 0;
533: }
1.783 albertel 534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
1.786 albertel 540: if ($line !~ m/=/) {
541: return 0;
542: }
1.783 albertel 543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
1.786 albertel 554: return 1;
1.783 albertel 555: }
556:
1.374 www 557: # ------------------------------------------- Transfer profile into environment
1.780 albertel 558: my $env_loaded;
559: sub transfer_profile_to_env {
1.788 albertel 560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
1.374 www 562:
1.720 albertel 563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
1.786 albertel 570: my $convert;
571: {
1.917 albertel 572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
1.915 albertel 574: return;
575: }
1.786 albertel 576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
1.374 www 589: }
1.783 albertel 590:
1.786 albertel 591: my %remove;
1.783 albertel 592: while ( my $envname = each(%env) ) {
1.433 matthew 593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
1.783 albertel 595: $remove{$key}++;
1.433 matthew 596: }
597: }
598: }
1.783 albertel 599:
1.619 albertel 600: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 601: $env_loaded=1;
1.783 albertel 602: foreach my $expired_key (keys(%remove)) {
1.433 matthew 603: &delenv($expired_key);
1.374 www 604: }
1.1 albertel 605: }
606:
1.916 albertel 607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
1.1155 raeburn 609: my ($r,$name) = @_;
1.916 albertel 610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
1.916 albertel 615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
1.916 albertel 624: return undef if (!-e "$lonidsdir/$handle.id");
625:
1.917 albertel 626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
1.916 albertel 628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
1.1213 raeburn 640: if (($r->user() eq '') && ($apache >= 2.4)) {
1.1212 raeburn 641: if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
642: $r->user($disk_env{'user.name'});
643: } else {
644: $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
645: }
646: }
1.916 albertel 647: return $handle;
648: }
649:
1.830 albertel 650: sub timed_flock {
651: my ($file,$lock_type) = @_;
652: my $failed=0;
653: eval {
654: local $SIG{__DIE__}='DEFAULT';
655: local $SIG{ALRM}=sub {
656: $failed=1;
657: die("failed lock");
658: };
659: alarm(13);
660: flock($file,$lock_type);
661: alarm(0);
662: };
663: if ($failed) {
664: return undef;
665: } else {
666: return 1;
667: }
668: }
669:
1.5 www 670: # ---------------------------------------------------------- Append Environment
671:
672: sub appenv {
1.949 raeburn 673: my ($newenv,$roles) = @_;
674: if (ref($newenv) eq 'HASH') {
675: foreach my $key (keys(%{$newenv})) {
676: my $refused = 0;
677: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
678: $refused = 1;
679: if (ref($roles) eq 'ARRAY') {
680: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
681: if (grep(/^\Q$role\E$/,@{$roles})) {
682: $refused = 0;
683: }
684: }
685: }
686: if ($refused) {
687: &logthis("<font color=\"blue\">WARNING: ".
688: "Attempt to modify environment ".$key." to ".$newenv->{$key}
689: .'</font>');
690: delete($newenv->{$key});
691: } else {
692: $env{$key}=$newenv->{$key};
693: }
694: }
695: my $opened = open(my $env_file,'+<',$env{'user.environment'});
696: if ($opened
697: && &timed_flock($env_file,LOCK_EX)
698: &&
699: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
700: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
701: while (my ($key,$value) = each(%{$newenv})) {
702: $disk_env{$key} = $value;
703: }
704: untie(%disk_env);
1.35 www 705: }
1.191 harris41 706: }
1.56 www 707: return 'ok';
708: }
709: # ----------------------------------------------------- Delete from Environment
710:
711: sub delenv {
1.1104 raeburn 712: my ($delthis,$regexp,$roles) = @_;
713: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
714: my $refused = 1;
715: if (ref($roles) eq 'ARRAY') {
716: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
717: if (grep(/^\Q$role\E$/,@{$roles})) {
718: $refused = 0;
719: }
720: }
721: if ($refused) {
722: &logthis("<font color=\"blue\">WARNING: ".
723: "Attempt to delete from environment ".$delthis);
724: return 'error';
725: }
1.56 www 726: }
1.917 albertel 727: my $opened = open(my $env_file,'+<',$env{'user.environment'});
728: if ($opened
1.915 albertel 729: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 730: &&
731: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
732: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 733: foreach my $key (keys(%disk_env)) {
1.987 raeburn 734: if ($regexp) {
735: if ($key=~/^$delthis/) {
736: delete($env{$key});
737: delete($disk_env{$key});
738: }
739: } else {
740: if ($key=~/^\Q$delthis\E/) {
741: delete($env{$key});
742: delete($disk_env{$key});
743: }
744: }
1.448 albertel 745: }
1.783 albertel 746: untie(%disk_env);
1.5 www 747: }
748: return 'ok';
1.369 albertel 749: }
750:
1.790 albertel 751: sub get_env_multiple {
752: my ($name) = @_;
753: my @values;
754: if (defined($env{$name})) {
755: # exists is it an array
756: if (ref($env{$name})) {
757: @values=@{ $env{$name} };
758: } else {
759: $values[0]=$env{$name};
760: }
761: }
762: return(@values);
763: }
764:
1.958 www 765: # ------------------------------------------------------------------- Locking
766:
767: sub set_lock {
768: my ($text)=@_;
769: $locknum++;
770: my $id=$$.'-'.$locknum;
771: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
772: 'session.lock.'.$id => $text});
773: return $id;
774: }
775:
776: sub get_locks {
777: my $num=0;
778: my %texts=();
779: foreach my $lock (split(/\,/,$env{'session.locks'})) {
780: if ($lock=~/\w/) {
781: $num++;
782: $texts{$lock}=$env{'session.lock.'.$lock};
783: }
784: }
785: return ($num,%texts);
786: }
787:
788: sub remove_lock {
789: my ($id)=@_;
790: my $newlocks='';
791: foreach my $lock (split(/\,/,$env{'session.locks'})) {
792: if (($lock=~/\w/) && ($lock ne $id)) {
793: $newlocks.=','.$lock;
794: }
795: }
796: &appenv({'session.locks' => $newlocks});
797: &delenv('session.lock.'.$id);
798: }
799:
800: sub remove_all_locks {
801: my $activelocks=$env{'session.locks'};
802: foreach my $lock (split(/\,/,$env{'session.locks'})) {
803: if ($lock=~/\w/) {
804: &remove_lock($lock);
805: }
806: }
807: }
808:
809:
1.369 albertel 810: # ------------------------------------------ Find out current server userload
811: sub userload {
812: my $numusers=0;
813: {
814: opendir(LONIDS,$perlvar{'lonIDsDir'});
815: my $filename;
816: my $curtime=time;
817: while ($filename=readdir(LONIDS)) {
1.925 albertel 818: next if ($filename eq '.' || $filename eq '..');
819: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 820: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 821: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 822: }
823: closedir(LONIDS);
824: }
825: my $userloadpercent=0;
826: my $maxuserload=$perlvar{'lonUserLoadLim'};
827: if ($maxuserload) {
1.371 albertel 828: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 829: }
1.372 albertel 830: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 831: return $userloadpercent;
1.283 www 832: }
833:
1.1 albertel 834: # ------------------------------ Find server with least workload from spare.tab
1.11 www 835:
1.1 albertel 836: sub spareserver {
1.1083 raeburn 837: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 838: my $spare_server;
1.370 albertel 839: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 840: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
841: : $userloadpercent;
1.1083 raeburn 842: my ($uint_dom,$remotesessions);
843: if (($udom ne '') && (&domain($udom) ne '')) {
844: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
845: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
846: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
847: $remotesessions = $udomdefaults{'remotesessions'};
848: }
1.1123 raeburn 849: my $spareshash = &this_host_spares($udom);
850: if (ref($spareshash) eq 'HASH') {
851: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
852: foreach my $try_server (@{ $spareshash->{'primary'} }) {
853: if ($uint_dom) {
854: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
855: $try_server));
856: }
857: ($spare_server, $lowest_load) =
858: &compare_server_load($try_server, $spare_server, $lowest_load);
859: }
1.1083 raeburn 860: }
1.784 albertel 861:
1.1123 raeburn 862: my $found_server = ($spare_server ne '' && $lowest_load < 100);
863:
864: if (!$found_server) {
865: if (ref($spareshash->{'default'}) eq 'ARRAY') {
866: foreach my $try_server (@{ $spareshash->{'default'} }) {
867: if ($uint_dom) {
868: next unless (&spare_can_host($udom,$uint_dom,
869: $remotesessions,$try_server));
870: }
871: ($spare_server, $lowest_load) =
872: &compare_server_load($try_server, $spare_server, $lowest_load);
873: }
874: }
875: }
1.784 albertel 876: }
877:
878: if (!$want_server_name) {
1.968 raeburn 879: my $protocol = 'http';
880: if ($protocol{$spare_server} eq 'https') {
881: $protocol = $protocol{$spare_server};
882: }
1.1001 raeburn 883: if (defined($spare_server)) {
884: my $hostname = &hostname($spare_server);
1.1083 raeburn 885: if (defined($hostname)) {
1.1001 raeburn 886: $spare_server = $protocol.'://'.$hostname;
887: }
888: }
1.784 albertel 889: }
890: return $spare_server;
891: }
892:
893: sub compare_server_load {
894: my ($try_server, $spare_server, $lowest_load) = @_;
895:
896: my $loadans = &reply('load', $try_server);
897: my $userloadans = &reply('userload',$try_server);
898:
899: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 900: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 901: }
902:
903: my $load;
904: if ($loadans =~ /\d/) {
905: if ($userloadans =~ /\d/) {
906: #both are numbers, pick the bigger one
907: $load = ($loadans > $userloadans) ? $loadans
908: : $userloadans;
1.411 albertel 909: } else {
1.784 albertel 910: $load = $loadans;
1.411 albertel 911: }
1.784 albertel 912: } else {
913: $load = $userloadans;
914: }
915:
916: if (($load =~ /\d/) && ($load < $lowest_load)) {
917: $spare_server = $try_server;
918: $lowest_load = $load;
1.370 albertel 919: }
1.784 albertel 920: return ($spare_server,$lowest_load);
1.202 matthew 921: }
1.914 albertel 922:
923: # --------------------------- ask offload servers if user already has a session
924: sub find_existing_session {
925: my ($udom,$uname) = @_;
1.1123 raeburn 926: my $spareshash = &this_host_spares($udom);
927: if (ref($spareshash) eq 'HASH') {
928: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
929: foreach my $try_server (@{ $spareshash->{'primary'} }) {
930: return $try_server if (&has_user_session($try_server, $udom, $uname));
931: }
932: }
933: if (ref($spareshash->{'default'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'default'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
1.914 albertel 938: }
939: return;
940: }
941:
942: # -------------------------------- ask if server already has a session for user
943: sub has_user_session {
944: my ($lonid,$udom,$uname) = @_;
945: my $result = &reply(join(':','userhassession',
946: map {&escape($_)} ($udom,$uname)),$lonid);
947: return 1 if ($result eq 'ok');
948:
949: return 0;
950: }
951:
1.1076 raeburn 952: # --------- determine least loaded server in a user's domain which allows login
953:
954: sub choose_server {
1.1115 raeburn 955: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 956: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 957: my %servers = &get_servers($udom);
1.1076 raeburn 958: my $lowest_load = 30000;
1.1151 raeburn 959: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 960: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 961: my $loginvia;
962: if ($checkloginvia) {
963: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 964: if ($loginvia) {
965: my ($server,$path) = split(/:/,$loginvia);
966: ($login_host, $lowest_load) =
967: &compare_server_load($server, $login_host, $lowest_load);
968: if ($login_host eq $server) {
969: $portal_path = $path;
1.1151 raeburn 970: $isredirect = 1;
1.1116 raeburn 971: }
972: } else {
973: ($login_host, $lowest_load) =
974: &compare_server_load($lonhost, $login_host, $lowest_load);
975: if ($login_host eq $lonhost) {
976: $portal_path = '';
1.1151 raeburn 977: $isredirect = '';
1.1116 raeburn 978: }
979: }
980: } else {
1.1076 raeburn 981: ($login_host, $lowest_load) =
1.1116 raeburn 982: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 983: }
984: }
985: if ($login_host ne '') {
1.1116 raeburn 986: $hostname = &hostname($login_host);
1.1076 raeburn 987: }
1.1151 raeburn 988: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 989: }
990:
1.202 matthew 991: # --------------------------------------------- Try to change a user's password
992:
993: sub changepass {
1.799 raeburn 994: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 995: $currentpass = &escape($currentpass);
996: $newpass = &escape($newpass);
1.1030 raeburn 997: my $lonhost = $perlvar{'lonHostID'};
998: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 999: $server);
1000: if (! $answer) {
1001: &logthis("No reply on password change request to $server ".
1002: "by $uname in domain $udom.");
1003: } elsif ($answer =~ "^ok") {
1004: &logthis("$uname in $udom successfully changed their password ".
1005: "on $server.");
1006: } elsif ($answer =~ "^pwchange_failure") {
1007: &logthis("$uname in $udom was unable to change their password ".
1008: "on $server. The action was blocked by either lcpasswd ".
1009: "or pwchange");
1010: } elsif ($answer =~ "^non_authorized") {
1011: &logthis("$uname in $udom did not get their password correct when ".
1012: "attempting to change it on $server.");
1013: } elsif ($answer =~ "^auth_mode_error") {
1014: &logthis("$uname in $udom attempted to change their password despite ".
1015: "not being locally or internally authenticated on $server.");
1016: } elsif ($answer =~ "^unknown_user") {
1017: &logthis("$uname in $udom attempted to change their password ".
1018: "on $server but were unable to because $server is not ".
1019: "their home server.");
1020: } elsif ($answer =~ "^refused") {
1021: &logthis("$server refused to change $uname in $udom password because ".
1022: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1023: } elsif ($answer =~ "invalid_client") {
1024: &logthis("$server refused to change $uname in $udom password because ".
1025: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1026: }
1027: return $answer;
1.1 albertel 1028: }
1029:
1.169 harris41 1030: # ----------------------- Try to determine user's current authentication scheme
1031:
1032: sub queryauthenticate {
1033: my ($uname,$udom)=@_;
1.456 albertel 1034: my $uhome=&homeserver($uname,$udom);
1035: if (!$uhome) {
1036: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1037: return 'no_host';
1038: }
1039: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1040: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1041: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1042: }
1.456 albertel 1043: return $answer;
1.169 harris41 1044: }
1045:
1.1 albertel 1046: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1047:
1.1 albertel 1048: sub authenticate {
1.1073 raeburn 1049: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1050: $upass=&escape($upass);
1051: $uname= &LONCAPA::clean_username($uname);
1.836 www 1052: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1053: my $newhome;
1.836 www 1054: if ((!$uhome) || ($uhome eq 'no_host')) {
1055: # Maybe the machine was offline and only re-appeared again recently?
1056: &reconlonc();
1057: # One more
1.952 raeburn 1058: $uhome=&homeserver($uname,$udom,1);
1059: if (($uhome eq 'no_host') && $checkdefauth) {
1060: if (defined(&domain($udom,'primary'))) {
1061: $newhome=&domain($udom,'primary');
1062: }
1063: if ($newhome ne '') {
1064: $uhome = $newhome;
1065: }
1066: }
1.836 www 1067: if ((!$uhome) || ($uhome eq 'no_host')) {
1068: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1069: return 'no_host';
1070: }
1.1 albertel 1071: }
1.1073 raeburn 1072: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1073: if ($answer eq 'authorized') {
1.952 raeburn 1074: if ($newhome) {
1075: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1076: return 'no_account_on_host';
1077: } else {
1078: &logthis("User $uname at $udom authorized by $uhome");
1079: return $uhome;
1080: }
1.471 albertel 1081: }
1082: if ($answer eq 'non_authorized') {
1083: &logthis("User $uname at $udom rejected by $uhome");
1084: return 'no_host';
1.9 www 1085: }
1.471 albertel 1086: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1087: return 'no_host';
1088: }
1089:
1.1073 raeburn 1090: sub can_host_session {
1.1074 raeburn 1091: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1092: my $canhost = 1;
1.1074 raeburn 1093: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1094: if (ref($remotesessions) eq 'HASH') {
1095: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1096: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1097: $canhost = 0;
1098: } else {
1099: $canhost = 1;
1100: }
1101: }
1102: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1103: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1104: $canhost = 1;
1105: } else {
1106: $canhost = 0;
1107: }
1108: }
1109: if ($canhost) {
1110: if ($remotesessions->{'version'} ne '') {
1111: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1112: if ($reqmajor ne '' && $reqminor ne '') {
1113: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1114: my $major = $1;
1115: my $minor = $2;
1116: if (($major < $reqmajor ) ||
1117: (($major == $reqmajor) && ($minor < $reqminor))) {
1118: $canhost = 0;
1119: }
1120: } else {
1121: $canhost = 0;
1122: }
1123: }
1124: }
1125: }
1126: }
1127: if ($canhost) {
1128: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1129: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1130: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1131: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1132: if (($uint_dom ne '') &&
1133: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1134: $canhost = 0;
1135: } else {
1136: $canhost = 1;
1137: }
1138: }
1139: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1140: if (($uint_dom ne '') &&
1141: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1142: $canhost = 1;
1143: } else {
1144: $canhost = 0;
1145: }
1146: }
1147: }
1148: }
1149: return $canhost;
1150: }
1151:
1.1083 raeburn 1152: sub spare_can_host {
1153: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1154: my $canhost=1;
1155: my @intdoms;
1156: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1157: if (ref($internet_names) eq 'ARRAY') {
1158: @intdoms = @{$internet_names};
1159: }
1160: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1161: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1162: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1163: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1164: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1165: $canhost = &can_host_session($udom,$try_server,$remoterev,
1166: $remotesessions,
1167: $defdomdefaults{'hostedsessions'});
1168: }
1169: return $canhost;
1170: }
1171:
1.1123 raeburn 1172: sub this_host_spares {
1173: my ($dom) = @_;
1.1126 raeburn 1174: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1175: my @hosts = ¤t_machine_ids();
1176: foreach my $lonhost (@hosts) {
1177: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1178: $dom_in_use = $dom;
1179: $lonhost_in_use = $lonhost;
1.1123 raeburn 1180: last;
1181: }
1182: }
1.1126 raeburn 1183: if ($dom_in_use ne '') {
1184: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1185: }
1186: if (ref($result) ne 'HASH') {
1187: $lonhost_in_use = $perlvar{'lonHostID'};
1188: $dom_in_use = &host_domain($lonhost_in_use);
1189: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1190: if (ref($result) ne 'HASH') {
1191: $result = \%spareid;
1192: }
1193: }
1194: return $result;
1195: }
1196:
1197: sub spares_for_offload {
1198: my ($dom_in_use,$lonhost_in_use) = @_;
1199: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1200: if (defined($cached)) {
1201: return $result;
1202: } else {
1.1126 raeburn 1203: my $cachetime = 60*60*24;
1204: my %domconfig =
1205: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1206: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1207: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1208: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1209: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1210: }
1211: }
1212: }
1213: }
1.1126 raeburn 1214: return;
1.1123 raeburn 1215: }
1216:
1.1129 raeburn 1217: sub get_lonbalancer_config {
1218: my ($servers) = @_;
1219: my ($currbalancer,$currtargets);
1220: if (ref($servers) eq 'HASH') {
1221: foreach my $server (keys(%{$servers})) {
1222: my %what = (
1223: spareid => 1,
1224: perlvar => 1,
1225: );
1226: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1227: if ($result eq 'ok') {
1228: if (ref($returnhash) eq 'HASH') {
1229: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1230: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1231: $currbalancer = $server;
1232: $currtargets = {};
1233: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1234: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1235: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1236: }
1237: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1238: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1239: }
1240: }
1241: last;
1242: }
1243: }
1244: }
1245: }
1246: }
1247: }
1248: return ($currbalancer,$currtargets);
1249: }
1250:
1251: sub check_loadbalancing {
1252: my ($uname,$udom) = @_;
1.1191 raeburn 1253: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1254: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1255: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1256: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1257: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1258: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1259: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1260: my $serverhomedom = &host_domain($lonhost);
1261:
1262: my $cachetime = 60*60*24;
1263:
1264: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1265: $dom_in_use = $udom;
1266: $homeintdom = 1;
1267: } else {
1268: $dom_in_use = $serverhomedom;
1269: }
1270: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1271: unless (defined($cached)) {
1272: my %domconfig =
1273: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1274: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1275: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1276: }
1277: }
1278: if (ref($result) eq 'HASH') {
1.1191 raeburn 1279: ($is_balancer,$currtargets,$currrules) =
1280: &check_balancer_result($result,@hosts);
1.1129 raeburn 1281: if ($is_balancer) {
1282: if (ref($currrules) eq 'HASH') {
1283: if ($homeintdom) {
1284: if ($uname ne '') {
1285: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1286: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1287: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1288: $rule_in_effect = $currrules->{'_LC_author'};
1289: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1290: $rule_in_effect = $currrules->{'_LC_adv'}
1291: }
1292: }
1293: if ($rule_in_effect eq '') {
1294: my %userenv = &userenvironment($udom,$uname,'inststatus');
1295: if ($userenv{'inststatus'} ne '') {
1296: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1297: my ($othertitle,$usertypes,$types) =
1298: &Apache::loncommon::sorted_inst_types($udom);
1299: if (ref($types) eq 'ARRAY') {
1300: foreach my $type (@{$types}) {
1301: if (grep(/^\Q$type\E$/,@statuses)) {
1302: if (exists($currrules->{$type})) {
1303: $rule_in_effect = $currrules->{$type};
1304: }
1305: }
1306: }
1307: }
1308: } else {
1309: if (exists($currrules->{'default'})) {
1310: $rule_in_effect = $currrules->{'default'};
1311: }
1312: }
1313: }
1314: } else {
1315: if (exists($currrules->{'default'})) {
1316: $rule_in_effect = $currrules->{'default'};
1317: }
1318: }
1319: } else {
1320: if ($currrules->{'_LC_external'} ne '') {
1321: $rule_in_effect = $currrules->{'_LC_external'};
1322: }
1323: }
1324: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1325: $uname,$udom);
1326: }
1327: }
1328: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1329: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1330: unless (defined($cached)) {
1331: my %domconfig =
1332: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1333: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1334: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1335: }
1336: }
1337: if (ref($result) eq 'HASH') {
1.1191 raeburn 1338: ($is_balancer,$currtargets,$currrules) =
1339: &check_balancer_result($result,@hosts);
1340: if ($is_balancer) {
1.1129 raeburn 1341: if (ref($currrules) eq 'HASH') {
1342: if ($currrules->{'_LC_internetdom'} ne '') {
1343: $rule_in_effect = $currrules->{'_LC_internetdom'};
1344: }
1345: }
1346: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1347: $uname,$udom);
1348: }
1349: } else {
1350: if ($perlvar{'lonBalancer'} eq 'yes') {
1351: $is_balancer = 1;
1352: $offloadto = &this_host_spares($dom_in_use);
1353: }
1354: }
1355: } else {
1356: if ($perlvar{'lonBalancer'} eq 'yes') {
1357: $is_balancer = 1;
1358: $offloadto = &this_host_spares($dom_in_use);
1359: }
1360: }
1.1176 raeburn 1361: if ($is_balancer) {
1362: my $lowest_load = 30000;
1363: if (ref($offloadto) eq 'HASH') {
1364: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1365: foreach my $try_server (@{$offloadto->{'primary'}}) {
1366: ($otherserver,$lowest_load) =
1367: &compare_server_load($try_server,$otherserver,$lowest_load);
1368: }
1.1129 raeburn 1369: }
1.1176 raeburn 1370: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1371:
1.1176 raeburn 1372: if (!$found_server) {
1373: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1374: foreach my $try_server (@{$offloadto->{'default'}}) {
1375: ($otherserver,$lowest_load) =
1376: &compare_server_load($try_server,$otherserver,$lowest_load);
1377: }
1378: }
1379: }
1380: } elsif (ref($offloadto) eq 'ARRAY') {
1381: if (@{$offloadto} == 1) {
1382: $otherserver = $offloadto->[0];
1383: } elsif (@{$offloadto} > 1) {
1384: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1385: ($otherserver,$lowest_load) =
1386: &compare_server_load($try_server,$otherserver,$lowest_load);
1387: }
1388: }
1389: }
1.1176 raeburn 1390: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1391: $is_balancer = 0;
1392: if ($uname ne '' && $udom ne '') {
1393: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1394:
1395: &appenv({'user.loadbalexempt' => $lonhost,
1396: 'user.loadbalcheck.time' => time});
1397: }
1.1129 raeburn 1398: }
1399: }
1400: }
1401: return ($is_balancer,$otherserver);
1402: }
1403:
1.1191 raeburn 1404: sub check_balancer_result {
1405: my ($result,@hosts) = @_;
1406: my ($is_balancer,$currtargets,$currrules);
1407: if (ref($result) eq 'HASH') {
1408: if ($result->{'lonhost'} ne '') {
1409: my $currbalancer = $result->{'lonhost'};
1410: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1411: $is_balancer = 1;
1412: $currtargets = $result->{'targets'};
1413: $currrules = $result->{'rules'};
1414: }
1415: } else {
1416: foreach my $key (keys(%{$result})) {
1417: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1418: (ref($result->{$key}) eq 'HASH')) {
1419: $is_balancer = 1;
1420: $currrules = $result->{$key}{'rules'};
1421: $currtargets = $result->{$key}{'targets'};
1422: last;
1423: }
1424: }
1425: }
1426: }
1427: return ($is_balancer,$currtargets,$currrules);
1428: }
1429:
1.1129 raeburn 1430: sub get_loadbalancer_targets {
1431: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1432: my $offloadto;
1.1175 raeburn 1433: if ($rule_in_effect eq 'none') {
1434: return [$perlvar{'lonHostID'}];
1435: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1436: $offloadto = $currtargets;
1437: } else {
1438: if ($rule_in_effect eq 'homeserver') {
1439: my $homeserver = &homeserver($uname,$udom);
1440: if ($homeserver ne 'no_host') {
1441: $offloadto = [$homeserver];
1442: }
1443: } elsif ($rule_in_effect eq 'externalbalancer') {
1444: my %domconfig =
1445: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1446: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1447: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1448: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1449: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1450: }
1451: }
1452: } else {
1.1178 raeburn 1453: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1454: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1455: if (&hostname($remotebalancer) ne '') {
1456: $offloadto = [$remotebalancer];
1457: }
1458: }
1459: } elsif (&hostname($rule_in_effect) ne '') {
1460: $offloadto = [$rule_in_effect];
1461: }
1462: }
1463: return $offloadto;
1464: }
1465:
1.1127 raeburn 1466: sub internet_dom_servers {
1467: my ($dom) = @_;
1468: my (%uniqservers,%servers);
1469: my $primaryserver = &hostname(&domain($dom,'primary'));
1470: my @machinedoms = &machine_domains($primaryserver);
1471: foreach my $mdom (@machinedoms) {
1472: my %currservers = %servers;
1473: my %server = &get_servers($mdom);
1474: %servers = (%currservers,%server);
1475: }
1476: my %by_hostname;
1477: foreach my $id (keys(%servers)) {
1478: push(@{$by_hostname{$servers{$id}}},$id);
1479: }
1480: foreach my $hostname (sort(keys(%by_hostname))) {
1481: if (@{$by_hostname{$hostname}} > 1) {
1482: my $match = 0;
1483: foreach my $id (@{$by_hostname{$hostname}}) {
1484: if (&host_domain($id) eq $dom) {
1485: $uniqservers{$id} = $hostname;
1486: $match = 1;
1487: }
1488: }
1489: unless ($match) {
1490: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1491: }
1492: } else {
1493: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1494: }
1495: }
1496: return %uniqservers;
1497: }
1498:
1.1 albertel 1499: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1500:
1.599 albertel 1501: my %homecache;
1.1 albertel 1502: sub homeserver {
1.230 stredwic 1503: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1504: my $index="$uname:$udom";
1.426 albertel 1505:
1.599 albertel 1506: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1507:
1508: my %servers = &get_servers($udom,'library');
1509: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1510: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1511: exists($badServerCache{$tryserver}));
1.841 albertel 1512:
1513: my $answer=reply("home:$udom:$uname",$tryserver);
1514: if ($answer eq 'found') {
1515: delete($badServerCache{$tryserver});
1516: return $homecache{$index}=$tryserver;
1517: } elsif ($answer eq 'no_host') {
1518: $badServerCache{$tryserver}=1;
1519: }
1.1 albertel 1520: }
1521: return 'no_host';
1.70 www 1522: }
1523:
1524: # ------------------------------------- Find the usernames behind a list of IDs
1525:
1526: sub idget {
1527: my ($udom,@ids)=@_;
1528: my %returnhash=();
1529:
1.841 albertel 1530: my %servers = &get_servers($udom,'library');
1531: foreach my $tryserver (keys(%servers)) {
1532: my $idlist=join('&',@ids);
1533: $idlist=~tr/A-Z/a-z/;
1534: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1535: my @answer=();
1536: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1537: @answer=split(/\&/,$reply);
1538: } ;
1539: my $i;
1540: for ($i=0;$i<=$#ids;$i++) {
1541: if ($answer[$i]) {
1542: $returnhash{$ids[$i]}=$answer[$i];
1543: }
1544: }
1545: }
1.70 www 1546: return %returnhash;
1547: }
1548:
1549: # ------------------------------------- Find the IDs behind a list of usernames
1550:
1551: sub idrget {
1552: my ($udom,@unames)=@_;
1553: my %returnhash=();
1.800 albertel 1554: foreach my $uname (@unames) {
1555: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1556: }
1.70 www 1557: return %returnhash;
1558: }
1559:
1560: # ------------------------------- Store away a list of names and associated IDs
1561:
1562: sub idput {
1563: my ($udom,%ids)=@_;
1564: my %servers=();
1.800 albertel 1565: foreach my $uname (keys(%ids)) {
1566: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1567: my $uhom=&homeserver($uname,$udom);
1.70 www 1568: if ($uhom ne 'no_host') {
1.800 albertel 1569: my $id=&escape($ids{$uname});
1.70 www 1570: $id=~tr/A-Z/a-z/;
1.800 albertel 1571: my $esc_unam=&escape($uname);
1.70 www 1572: if ($servers{$uhom}) {
1.800 albertel 1573: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1574: } else {
1.800 albertel 1575: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1576: }
1577: }
1.191 harris41 1578: }
1.800 albertel 1579: foreach my $server (keys(%servers)) {
1580: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1581: }
1.344 www 1582: }
1583:
1.1231 raeburn 1584: # ---------------------------------------- Delete unwanted IDs from ids.db file
1585:
1586: sub iddel {
1587: my ($udom,$idshashref,$uhome)=@_;
1588: my %result=();
1589: unless (ref($idshashref) eq 'HASH') {
1590: return %result;
1591: }
1592: my %servers=();
1593: while (my ($id,$uname) = each(%{$idshashref})) {
1594: my $uhom;
1595: if ($uhome) {
1596: $uhom = $uhome;
1597: } else {
1598: $uhom=&homeserver($uname,$udom);
1599: }
1600: if ($uhom ne 'no_host') {
1601: if ($servers{$uhom}) {
1602: $servers{$uhom}.='&'.&escape($id);
1603: } else {
1604: $servers{$uhom}=&escape($id);
1605: }
1606: }
1607: }
1608: foreach my $server (keys(%servers)) {
1609: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1610: }
1611: return %result;
1612: }
1613:
1.1023 raeburn 1614: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1615: sub dump_dom {
1.1165 droeschl 1616: my ($namespace, $udom, $regexp) = @_;
1617:
1618: $udom ||= $env{'user.domain'};
1619:
1620: return () unless $udom;
1621:
1622: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1623: }
1624:
1.1023 raeburn 1625: # ------------------------------------------ get items from domain db files
1.806 raeburn 1626:
1627: sub get_dom {
1.860 raeburn 1628: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1629: my $items='';
1630: foreach my $item (@$storearr) {
1631: $items.=&escape($item).'&';
1632: }
1633: $items=~s/\&$//;
1.860 raeburn 1634: if (!$udom) {
1635: $udom=$env{'user.domain'};
1636: if (defined(&domain($udom,'primary'))) {
1637: $uhome=&domain($udom,'primary');
1638: } else {
1.874 albertel 1639: undef($uhome);
1.860 raeburn 1640: }
1641: } else {
1642: if (!$uhome) {
1643: if (defined(&domain($udom,'primary'))) {
1644: $uhome=&domain($udom,'primary');
1645: }
1646: }
1647: }
1648: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1649: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1650: my %returnhash;
1.875 albertel 1651: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1652: return %returnhash;
1653: }
1.806 raeburn 1654: my @pairs=split(/\&/,$rep);
1655: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1656: return @pairs;
1657: }
1658: my $i=0;
1659: foreach my $item (@$storearr) {
1660: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1661: $i++;
1662: }
1663: return %returnhash;
1664: } else {
1.880 banghart 1665: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1666: }
1667: }
1668:
1669: # -------------------------------------------- put items in domain db files
1670:
1671: sub put_dom {
1.860 raeburn 1672: my ($namespace,$storehash,$udom,$uhome)=@_;
1673: if (!$udom) {
1674: $udom=$env{'user.domain'};
1675: if (defined(&domain($udom,'primary'))) {
1676: $uhome=&domain($udom,'primary');
1677: } else {
1.874 albertel 1678: undef($uhome);
1.860 raeburn 1679: }
1680: } else {
1681: if (!$uhome) {
1682: if (defined(&domain($udom,'primary'))) {
1683: $uhome=&domain($udom,'primary');
1684: }
1685: }
1686: }
1687: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1688: my $items='';
1689: foreach my $item (keys(%$storehash)) {
1690: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1691: }
1692: $items=~s/\&$//;
1693: return &reply("putdom:$udom:$namespace:$items",$uhome);
1694: } else {
1.860 raeburn 1695: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1696: }
1697: }
1698:
1.1023 raeburn 1699: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1700: sub newput_dom {
1.1023 raeburn 1701: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1702: my $result;
1703: if (!$udom) {
1704: $udom=$env{'user.domain'};
1705: }
1.1023 raeburn 1706: if ($udom) {
1707: my $uname = &get_domainconfiguser($udom);
1708: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1709: }
1710: return $result;
1711: }
1712:
1.1023 raeburn 1713: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1714: sub del_dom {
1.1023 raeburn 1715: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1716: if (ref($storearr) eq 'ARRAY') {
1717: if (!$udom) {
1718: $udom=$env{'user.domain'};
1719: }
1.1023 raeburn 1720: if ($udom) {
1721: my $uname = &get_domainconfiguser($udom);
1722: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1723: }
1724: }
1725: }
1726:
1.1023 raeburn 1727: # ----------------------------------construct domainconfig user for a domain
1728: sub get_domainconfiguser {
1729: my ($udom) = @_;
1730: return $udom.'-domainconfig';
1731: }
1732:
1.837 raeburn 1733: sub retrieve_inst_usertypes {
1734: my ($udom) = @_;
1735: my (%returnhash,@order);
1.989 raeburn 1736: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1737: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1738: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1739: %returnhash = %{$domdefs{'inststatustypes'}};
1740: @order = @{$domdefs{'inststatusorder'}};
1741: } else {
1742: if (defined(&domain($udom,'primary'))) {
1743: my $uhome=&domain($udom,'primary');
1744: my $rep=&reply("inst_usertypes:$udom",$uhome);
1745: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1746: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1747: return (\%returnhash,\@order);
1748: }
1749: my ($hashitems,$orderitems) = split(/:/,$rep);
1750: my @pairs=split(/\&/,$hashitems);
1751: foreach my $item (@pairs) {
1752: my ($key,$value)=split(/=/,$item,2);
1753: $key = &unescape($key);
1754: next if ($key =~ /^error: 2 /);
1755: $returnhash{$key}=&thaw_unescape($value);
1756: }
1757: my @esc_order = split(/\&/,$orderitems);
1758: foreach my $item (@esc_order) {
1759: push(@order,&unescape($item));
1760: }
1761: } else {
1762: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1763: }
1764: }
1765: return (\%returnhash,\@order);
1766: }
1767:
1.868 raeburn 1768: sub is_domainimage {
1769: my ($url) = @_;
1770: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1771: if (&domain($1) ne '') {
1772: return '1';
1773: }
1774: }
1775: return;
1776: }
1777:
1.899 raeburn 1778: sub inst_directory_query {
1779: my ($srch) = @_;
1780: my $udom = $srch->{'srchdomain'};
1781: my %results;
1782: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1783: my $outcome;
1.899 raeburn 1784: if ($homeserver ne '') {
1.904 albertel 1785: my $queryid=&reply("querysend:instdirsearch:".
1786: &escape($srch->{'srchby'}).':'.
1787: &escape($srch->{'srchterm'}).':'.
1788: &escape($srch->{'srchtype'}),$homeserver);
1789: my $host=&hostname($homeserver);
1790: if ($queryid !~/^\Q$host\E\_/) {
1791: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1792: return;
1793: }
1794: my $response = &get_query_reply($queryid);
1795: my $maxtries = 5;
1796: my $tries = 1;
1797: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1798: $response = &get_query_reply($queryid);
1799: $tries ++;
1800: }
1801:
1802: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1803: if ($response eq 'unavailable') {
1804: $outcome = $response;
1805: } else {
1806: $outcome = 'ok';
1807: my @matches = split(/\n/,$response);
1808: foreach my $match (@matches) {
1809: my ($key,$value) = split(/=/,$match);
1810: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1811: }
1.899 raeburn 1812: }
1813: }
1814: }
1.909 raeburn 1815: return ($outcome,%results);
1.899 raeburn 1816: }
1817:
1818: sub usersearch {
1819: my ($srch) = @_;
1820: my $dom = $srch->{'srchdomain'};
1821: my %results;
1822: my %libserv = &all_library();
1823: my $query = 'usersearch';
1824: foreach my $tryserver (keys(%libserv)) {
1825: if (&host_domain($tryserver) eq $dom) {
1826: my $host=&hostname($tryserver);
1827: my $queryid=
1.911 raeburn 1828: &reply("querysend:".&escape($query).':'.
1829: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1830: &escape($srch->{'srchtype'}).':'.
1831: &escape($srch->{'srchterm'}),$tryserver);
1832: if ($queryid !~/^\Q$host\E\_/) {
1833: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1834: next;
1.899 raeburn 1835: }
1836: my $reply = &get_query_reply($queryid);
1837: my $maxtries = 1;
1838: my $tries = 1;
1839: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1840: $reply = &get_query_reply($queryid);
1841: $tries ++;
1842: }
1843: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1844: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1845: } else {
1.911 raeburn 1846: my @matches;
1847: if ($reply =~ /\n/) {
1848: @matches = split(/\n/,$reply);
1849: } else {
1850: @matches = split(/\&/,$reply);
1851: }
1.899 raeburn 1852: foreach my $match (@matches) {
1853: my ($uname,$udom,%userhash);
1.911 raeburn 1854: foreach my $entry (split(/:/,$match)) {
1855: my ($key,$value) =
1856: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1857: $userhash{$key} = $value;
1858: if ($key eq 'username') {
1859: $uname = $value;
1860: } elsif ($key eq 'domain') {
1861: $udom = $value;
1.911 raeburn 1862: }
1.899 raeburn 1863: }
1864: $results{$uname.':'.$udom} = \%userhash;
1865: }
1866: }
1867: }
1868: }
1869: return %results;
1870: }
1871:
1.912 raeburn 1872: sub get_instuser {
1873: my ($udom,$uname,$id) = @_;
1874: my $homeserver = &domain($udom,'primary');
1875: my ($outcome,%results);
1876: if ($homeserver ne '') {
1877: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1878: &escape($id).':'.&escape($udom),$homeserver);
1879: my $host=&hostname($homeserver);
1880: if ($queryid !~/^\Q$host\E\_/) {
1881: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1882: return;
1883: }
1884: my $response = &get_query_reply($queryid);
1885: my $maxtries = 5;
1886: my $tries = 1;
1887: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1888: $response = &get_query_reply($queryid);
1889: $tries ++;
1890: }
1891: if (!&error($response) && $response ne 'refused') {
1892: if ($response eq 'unavailable') {
1893: $outcome = $response;
1894: } else {
1895: $outcome = 'ok';
1896: my @matches = split(/\n/,$response);
1897: foreach my $match (@matches) {
1898: my ($key,$value) = split(/=/,$match);
1899: $results{&unescape($key)} = &thaw_unescape($value);
1900: }
1901: }
1902: }
1903: }
1904: my %userinfo;
1905: if (ref($results{$uname}) eq 'HASH') {
1906: %userinfo = %{$results{$uname}};
1907: }
1908: return ($outcome,%userinfo);
1909: }
1910:
1911: sub inst_rulecheck {
1.923 raeburn 1912: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1913: my %returnhash;
1914: if ($udom ne '') {
1915: if (ref($rules) eq 'ARRAY') {
1916: @{$rules} = map {&escape($_);} (@{$rules});
1917: my $rulestr = join(':',@{$rules});
1918: my $homeserver=&domain($udom,'primary');
1919: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1920: my $response;
1921: if ($item eq 'username') {
1922: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1923: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1924: $homeserver));
1.923 raeburn 1925: } elsif ($item eq 'id') {
1926: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1927: ':'.&escape($id).':'.$rulestr,
1928: $homeserver));
1.945 raeburn 1929: } elsif ($item eq 'selfcreate') {
1930: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1931: &escape($udom).':'.&escape($uname).
1932: ':'.$rulestr,$homeserver));
1.923 raeburn 1933: }
1.912 raeburn 1934: if ($response ne 'refused') {
1935: my @pairs=split(/\&/,$response);
1936: foreach my $item (@pairs) {
1937: my ($key,$value)=split(/=/,$item,2);
1938: $key = &unescape($key);
1939: next if ($key =~ /^error: 2 /);
1940: $returnhash{$key}=&thaw_unescape($value);
1941: }
1942: }
1943: }
1944: }
1945: }
1946: return %returnhash;
1947: }
1948:
1949: sub inst_userrules {
1.923 raeburn 1950: my ($udom,$check) = @_;
1.912 raeburn 1951: my (%ruleshash,@ruleorder);
1952: if ($udom ne '') {
1953: my $homeserver=&domain($udom,'primary');
1954: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1955: my $response;
1956: if ($check eq 'id') {
1957: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1958: $homeserver);
1.943 raeburn 1959: } elsif ($check eq 'email') {
1960: $response=&reply('instemailrules:'.&escape($udom),
1961: $homeserver);
1.923 raeburn 1962: } else {
1963: $response=&reply('instuserrules:'.&escape($udom),
1964: $homeserver);
1965: }
1.912 raeburn 1966: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1967: ($response ne 'unknown_cmd') &&
1.912 raeburn 1968: ($response ne 'no_such_host')) {
1969: my ($hashitems,$orderitems) = split(/:/,$response);
1970: my @pairs=split(/\&/,$hashitems);
1971: foreach my $item (@pairs) {
1972: my ($key,$value)=split(/=/,$item,2);
1973: $key = &unescape($key);
1974: next if ($key =~ /^error: 2 /);
1975: $ruleshash{$key}=&thaw_unescape($value);
1976: }
1977: my @esc_order = split(/\&/,$orderitems);
1978: foreach my $item (@esc_order) {
1979: push(@ruleorder,&unescape($item));
1980: }
1981: }
1982: }
1983: }
1984: return (\%ruleshash,\@ruleorder);
1985: }
1986:
1.976 raeburn 1987: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1988:
1989: sub get_domain_defaults {
1.1240 raeburn 1990: my ($domain,$ignore_cache) = @_;
1.943 raeburn 1991: my $cachetime = 60*60*24;
1.1240 raeburn 1992: unless ($ignore_cache) {
1993: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1994: if (defined($cached)) {
1995: if (ref($result) eq 'HASH') {
1996: return %{$result};
1997: }
1.943 raeburn 1998: }
1999: }
2000: my %domdefaults;
2001: my %domconfig =
1.989 raeburn 2002: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2003: 'requestcourses','inststatus',
1.1183 raeburn 2004: 'coursedefaults','usersessions',
2005: 'requestauthor'],$domain);
1.943 raeburn 2006: if (ref($domconfig{'defaults'}) eq 'HASH') {
2007: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2008: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2009: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2010: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2011: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2012: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2013: } else {
2014: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2015: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2016: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2017: }
1.976 raeburn 2018: if (ref($domconfig{'quotas'}) eq 'HASH') {
2019: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2020: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2021: } else {
2022: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2023: }
1.1177 raeburn 2024: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2025: foreach my $item (@usertools) {
2026: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2027: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2028: }
2029: }
1.1229 raeburn 2030: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2031: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2032: }
1.976 raeburn 2033: }
1.985 raeburn 2034: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 2035: foreach my $item ('official','unofficial','community') {
1.985 raeburn 2036: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2037: }
2038: }
1.1183 raeburn 2039: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2040: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2041: }
1.989 raeburn 2042: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2043: foreach my $item ('inststatustypes','inststatusorder') {
2044: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2045: }
2046: }
1.1047 raeburn 2047: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2048: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1216 raeburn 2049: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2050: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2051: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
2052: }
1.1230 raeburn 2053: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2054: $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
2055: $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
2056: $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
2057: }
1.1047 raeburn 2058: }
1.1073 raeburn 2059: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2060: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2061: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2062: }
2063: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2064: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2065: }
2066: }
1.1219 raeburn 2067: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2068: return %domdefaults;
2069: }
2070:
1.344 www 2071: # --------------------------------------------------- Assign a key to a student
2072:
2073: sub assign_access_key {
1.364 www 2074: #
2075: # a valid key looks like uname:udom#comments
2076: # comments are being appended
2077: #
1.498 www 2078: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2079: $kdom=
1.620 albertel 2080: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2081: $knum=
1.620 albertel 2082: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2083: $cdom=
1.620 albertel 2084: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2085: $cnum=
1.620 albertel 2086: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2087: $udom=$env{'user.name'} unless (defined($udom));
2088: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2089: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2090: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2091: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2092: # assigned to this person
2093: # - this should not happen,
1.345 www 2094: # unless something went wrong
2095: # the first time around
2096: # ready to assign
1.364 www 2097: $logentry=$1.'; '.$logentry;
1.496 www 2098: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2099: $kdom,$knum) eq 'ok') {
1.345 www 2100: # key now belongs to user
1.346 www 2101: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2102: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2103: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2104: return 'ok';
2105: } else {
2106: return
2107: 'error: Count not permanently assign key, will need to be re-entered later.';
2108: }
2109: } else {
2110: return 'error: Could not assign key, try again later.';
2111: }
1.364 www 2112: } elsif (!$existing{$ckey}) {
1.345 www 2113: # the key does not exist
2114: return 'error: The key does not exist';
2115: } else {
2116: # the key is somebody else's
2117: return 'error: The key is already in use';
2118: }
1.344 www 2119: }
2120:
1.364 www 2121: # ------------------------------------------ put an additional comment on a key
2122:
2123: sub comment_access_key {
2124: #
2125: # a valid key looks like uname:udom#comments
2126: # comments are being appended
2127: #
2128: my ($ckey,$cdom,$cnum,$logentry)=@_;
2129: $cdom=
1.620 albertel 2130: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2131: $cnum=
1.620 albertel 2132: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2133: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2134: if ($existing{$ckey}) {
2135: $existing{$ckey}.='; '.$logentry;
2136: # ready to assign
1.367 www 2137: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2138: $cdom,$cnum) eq 'ok') {
2139: return 'ok';
2140: } else {
2141: return 'error: Count not store comment.';
2142: }
2143: } else {
2144: # the key does not exist
2145: return 'error: The key does not exist';
2146: }
2147: }
2148:
1.344 www 2149: # ------------------------------------------------------ Generate a set of keys
2150:
2151: sub generate_access_keys {
1.364 www 2152: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2153: $cdom=
1.620 albertel 2154: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2155: $cnum=
1.620 albertel 2156: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2157: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2158: unless (($cdom) && ($cnum)) { return 0; }
2159: if ($number>10000) { return 0; }
2160: sleep(2); # make sure don't get same seed twice
2161: srand(time()^($$+($$<<15))); # from "Programming Perl"
2162: my $total=0;
2163: for (my $i=1;$i<=$number;$i++) {
2164: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2165: sprintf("%lx",int(100000*rand)).'-'.
2166: sprintf("%lx",int(100000*rand));
2167: $newkey=~s/1/g/g; # folks mix up 1 and l
2168: $newkey=~s/0/h/g; # and also 0 and O
2169: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2170: if ($existing{$newkey}) {
2171: $i--;
2172: } else {
1.364 www 2173: if (&put('accesskeys',
2174: { $newkey => '# generated '.localtime().
1.620 albertel 2175: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2176: '; '.$logentry },
2177: $cdom,$cnum) eq 'ok') {
1.344 www 2178: $total++;
2179: }
2180: }
2181: }
1.620 albertel 2182: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2183: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2184: return $total;
2185: }
2186:
2187: # ------------------------------------------------------- Validate an accesskey
2188:
2189: sub validate_access_key {
2190: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2191: $cdom=
1.620 albertel 2192: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2193: $cnum=
1.620 albertel 2194: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2195: $udom=$env{'user.domain'} unless (defined($udom));
2196: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2197: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2198: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2199: }
2200:
2201: # ------------------------------------- Find the section of student in a course
1.652 albertel 2202: sub devalidate_getsection_cache {
2203: my ($udom,$unam,$courseid)=@_;
2204: my $hashid="$udom:$unam:$courseid";
2205: &devalidate_cache_new('getsection',$hashid);
2206: }
1.298 matthew 2207:
1.815 albertel 2208: sub courseid_to_courseurl {
2209: my ($courseid) = @_;
2210: #already url style courseid
2211: return $courseid if ($courseid =~ m{^/});
2212:
2213: if (exists($env{'course.'.$courseid.'.num'})) {
2214: my $cnum = $env{'course.'.$courseid.'.num'};
2215: my $cdom = $env{'course.'.$courseid.'.domain'};
2216: return "/$cdom/$cnum";
2217: }
2218:
2219: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2220: if (exists($courseinfo{'num'})) {
2221: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2222: }
2223:
2224: return undef;
2225: }
2226:
1.298 matthew 2227: sub getsection {
2228: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2229: my $cachetime=1800;
1.551 albertel 2230:
2231: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2232: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2233: if (defined($cached)) { return $result; }
2234:
1.298 matthew 2235: my %Pending;
2236: my %Expired;
2237: #
2238: # Each role can either have not started yet (pending), be active,
2239: # or have expired.
2240: #
2241: # If there is an active role, we are done.
2242: #
2243: # If there is more than one role which has not started yet,
2244: # choose the one which will start sooner
2245: # If there is one role which has not started yet, return it.
2246: #
2247: # If there is more than one expired role, choose the one which ended last.
2248: # If there is a role which has expired, return it.
2249: #
1.815 albertel 2250: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2251: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2252: foreach my $key (keys(%roleshash)) {
1.479 albertel 2253: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2254: my $section=$1;
2255: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2256: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2257: my $now=time;
1.548 albertel 2258: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2259: $Expired{$end}=$section;
2260: next;
2261: }
1.548 albertel 2262: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2263: $Pending{$start}=$section;
2264: next;
2265: }
1.599 albertel 2266: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2267: }
2268: #
2269: # Presumedly there will be few matching roles from the above
2270: # loop and the sorting time will be negligible.
2271: if (scalar(keys(%Pending))) {
2272: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2273: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2274: }
2275: if (scalar(keys(%Expired))) {
2276: my @sorted = sort {$a <=> $b} keys(%Expired);
2277: my $time = pop(@sorted);
1.599 albertel 2278: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2279: }
1.599 albertel 2280: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2281: }
1.70 www 2282:
1.599 albertel 2283: sub save_cache {
2284: &purge_remembered();
1.722 albertel 2285: #&Apache::loncommon::validate_page();
1.620 albertel 2286: undef(%env);
1.780 albertel 2287: undef($env_loaded);
1.599 albertel 2288: }
1.452 albertel 2289:
1.599 albertel 2290: my $to_remember=-1;
2291: my %remembered;
2292: my %accessed;
2293: my $kicks=0;
2294: my $hits=0;
1.849 albertel 2295: sub make_key {
2296: my ($name,$id) = @_;
1.872 albertel 2297: if (length($id) > 65
2298: && length(&escape($id)) > 200) {
2299: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2300: }
1.849 albertel 2301: return &escape($name.':'.$id);
2302: }
2303:
1.599 albertel 2304: sub devalidate_cache_new {
2305: my ($name,$id,$debug) = @_;
2306: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2307: $id=&make_key($name,$id);
1.599 albertel 2308: $memcache->delete($id);
2309: delete($remembered{$id});
2310: delete($accessed{$id});
2311: }
2312:
2313: sub is_cached_new {
2314: my ($name,$id,$debug) = @_;
1.849 albertel 2315: $id=&make_key($name,$id);
1.599 albertel 2316: if (exists($remembered{$id})) {
1.1133 foxr 2317: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2318: $accessed{$id}=[&gettimeofday()];
2319: $hits++;
2320: return ($remembered{$id},1);
2321: }
2322: my $value = $memcache->get($id);
2323: if (!(defined($value))) {
2324: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2325: return (undef,undef);
1.416 albertel 2326: }
1.599 albertel 2327: if ($value eq '__undef__') {
2328: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2329: $value=undef;
2330: }
2331: &make_room($id,$value,$debug);
2332: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2333: return ($value,1);
2334: }
2335:
2336: sub do_cache_new {
2337: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2338: $id=&make_key($name,$id);
1.599 albertel 2339: my $setvalue=$value;
2340: if (!defined($setvalue)) {
2341: $setvalue='__undef__';
2342: }
1.623 albertel 2343: if (!defined($time) ) {
2344: $time=600;
2345: }
1.599 albertel 2346: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2347: my $result = $memcache->set($id,$setvalue,$time);
2348: if (! $result) {
1.872 albertel 2349: &logthis("caching of id -> $id failed");
1.910 albertel 2350: $memcache->disconnect_all();
1.872 albertel 2351: }
1.600 albertel 2352: # need to make a copy of $value
1.919 albertel 2353: &make_room($id,$value,$debug);
1.599 albertel 2354: return $value;
2355: }
2356:
2357: sub make_room {
2358: my ($id,$value,$debug)=@_;
1.919 albertel 2359:
2360: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2361: : $value;
1.599 albertel 2362: if ($to_remember<0) { return; }
2363: $accessed{$id}=[&gettimeofday()];
2364: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2365: my $to_kick;
2366: my $max_time=0;
2367: foreach my $other (keys(%accessed)) {
2368: if (&tv_interval($accessed{$other}) > $max_time) {
2369: $to_kick=$other;
2370: $max_time=&tv_interval($accessed{$other});
2371: }
2372: }
2373: delete($remembered{$to_kick});
2374: delete($accessed{$to_kick});
2375: $kicks++;
2376: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2377: return;
2378: }
2379:
1.599 albertel 2380: sub purge_remembered {
1.604 albertel 2381: #&logthis("Tossing ".scalar(keys(%remembered)));
2382: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2383: undef(%remembered);
2384: undef(%accessed);
1.428 albertel 2385: }
1.70 www 2386: # ------------------------------------- Read an entry from a user's environment
2387:
2388: sub userenvironment {
2389: my ($udom,$unam,@what)=@_;
1.976 raeburn 2390: my $items;
2391: foreach my $item (@what) {
2392: $items.=&escape($item).'&';
2393: }
2394: $items=~s/\&$//;
1.70 www 2395: my %returnhash=();
1.1009 raeburn 2396: my $uhome = &homeserver($unam,$udom);
2397: unless ($uhome eq 'no_host') {
2398: my @answer=split(/\&/,
2399: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2400: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2401: return %returnhash;
2402: }
1.1009 raeburn 2403: my $i;
2404: for ($i=0;$i<=$#what;$i++) {
2405: $returnhash{$what[$i]}=&unescape($answer[$i]);
2406: }
1.70 www 2407: }
2408: return %returnhash;
1.1 albertel 2409: }
2410:
1.617 albertel 2411: # ---------------------------------------------------------- Get a studentphoto
2412: sub studentphoto {
2413: my ($udom,$unam,$ext) = @_;
2414: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2415: if (defined($env{'request.course.id'})) {
1.708 raeburn 2416: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2417: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2418: return(&retrievestudentphoto($udom,$unam,$ext));
2419: } else {
2420: my ($result,$perm_reqd)=
1.707 albertel 2421: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2422: if ($result eq 'ok') {
2423: if (!($perm_reqd eq 'yes')) {
2424: return(&retrievestudentphoto($udom,$unam,$ext));
2425: }
2426: }
2427: }
2428: }
2429: } else {
2430: my ($result,$perm_reqd) =
1.707 albertel 2431: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2432: if ($result eq 'ok') {
2433: if (!($perm_reqd eq 'yes')) {
2434: return(&retrievestudentphoto($udom,$unam,$ext));
2435: }
2436: }
2437: }
2438: return '/adm/lonKaputt/lonlogo_broken.gif';
2439: }
2440:
2441: sub retrievestudentphoto {
2442: my ($udom,$unam,$ext,$type) = @_;
2443: my $home=&Apache::lonnet::homeserver($unam,$udom);
2444: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2445: if ($ret eq 'ok') {
2446: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2447: if ($type eq 'thumbnail') {
2448: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2449: }
2450: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2451: return $tokenurl;
2452: } else {
2453: if ($type eq 'thumbnail') {
2454: return '/adm/lonKaputt/genericstudent_tn.gif';
2455: } else {
2456: return '/adm/lonKaputt/lonlogo_broken.gif';
2457: }
1.617 albertel 2458: }
2459: }
2460:
1.263 www 2461: # -------------------------------------------------------------------- New chat
2462:
2463: sub chatsend {
1.724 raeburn 2464: my ($newentry,$anon,$group)=@_;
1.620 albertel 2465: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2466: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2467: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2468: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2469: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2470: &escape($newentry)).':'.$group,$chome);
1.292 www 2471: }
2472:
2473: # ------------------------------------------ Find current version of a resource
2474:
2475: sub getversion {
2476: my $fname=&clutter(shift);
1.1189 raeburn 2477: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2478: return ¤tversion(&filelocation('',$fname));
2479: }
2480:
2481: sub currentversion {
2482: my $fname=shift;
2483: my $author=$fname;
2484: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2485: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2486: my $home=&homeserver($uname,$udom);
1.292 www 2487: if ($home eq 'no_host') {
2488: return -1;
2489: }
1.1112 www 2490: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2491: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2492: return -1;
2493: }
1.1112 www 2494: return $answer;
1.263 www 2495: }
2496:
1.1111 www 2497: #
2498: # Return special version number of resource if set by override, empty otherwise
2499: #
2500: sub usedversion {
2501: my $fname=shift;
2502: unless ($fname) { $fname=$env{'request.uri'}; }
2503: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2504: if ($urlversion) { return $urlversion; }
2505: return '';
2506: }
2507:
1.1 albertel 2508: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2509:
1.1 albertel 2510: sub subscribe {
2511: my $fname=shift;
1.761 raeburn 2512: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2513: $fname=~s/[\n\r]//g;
1.1 albertel 2514: my $author=$fname;
2515: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2516: my ($udom,$uname)=split(/\//,$author);
2517: my $home=homeserver($uname,$udom);
1.335 albertel 2518: if ($home eq 'no_host') {
2519: return 'not_found';
1.1 albertel 2520: }
2521: my $answer=reply("sub:$fname",$home);
1.64 www 2522: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2523: $answer.=' by '.$home;
2524: }
1.1 albertel 2525: return $answer;
2526: }
2527:
1.8 www 2528: # -------------------------------------------------------------- Replicate file
2529:
2530: sub repcopy {
2531: my $filename=shift;
1.23 www 2532: $filename=~s/\/+/\//g;
1.1142 raeburn 2533: my $londocroot = $perlvar{'lonDocRoot'};
2534: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2535: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2536: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2537: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2538: return &repcopy_userfile($filename);
2539: }
1.532 albertel 2540: $filename=~s/[\n\r]//g;
1.8 www 2541: my $transname="$filename.in.transfer";
1.828 www 2542: # FIXME: this should flock
1.607 raeburn 2543: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2544: my $remoteurl=subscribe($filename);
1.64 www 2545: if ($remoteurl =~ /^con_lost by/) {
2546: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2547: return 'unavailable';
1.8 www 2548: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2549: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2550: return 'not_found';
1.64 www 2551: } elsif ($remoteurl =~ /^rejected by/) {
2552: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2553: return 'forbidden';
1.20 www 2554: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2555: return 'ok';
1.8 www 2556: } else {
1.290 www 2557: my $author=$filename;
2558: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2559: my ($udom,$uname)=split(/\//,$author);
2560: my $home=homeserver($uname,$udom);
2561: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2562: my @parts=split(/\//,$filename);
2563: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2564: if ($path ne "$londocroot/res") {
1.8 www 2565: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2566: return 'bad_request';
1.8 www 2567: }
2568: my $count;
2569: for ($count=5;$count<$#parts;$count++) {
2570: $path.="/$parts[$count]";
2571: if ((-e $path)!=1) {
2572: mkdir($path,0777);
2573: }
2574: }
2575: my $ua=new LWP::UserAgent;
2576: my $request=new HTTP::Request('GET',"$remoteurl");
2577: my $response=$ua->request($request,$transname);
2578: if ($response->is_error()) {
2579: unlink($transname);
2580: my $message=$response->status_line;
1.672 albertel 2581: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2582: ." LWP get: $message: $filename</font>");
1.607 raeburn 2583: return 'unavailable';
1.8 www 2584: } else {
1.16 www 2585: if ($remoteurl!~/\.meta$/) {
2586: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2587: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2588: if ($mresponse->is_error()) {
2589: unlink($filename.'.meta');
2590: &logthis(
1.672 albertel 2591: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2592: }
2593: }
1.8 www 2594: rename($transname,$filename);
1.607 raeburn 2595: return 'ok';
1.8 www 2596: }
1.290 www 2597: }
1.8 www 2598: }
1.330 www 2599: }
2600:
2601: # ------------------------------------------------ Get server side include body
2602: sub ssi_body {
1.381 albertel 2603: my ($filelink,%form)=@_;
1.606 matthew 2604: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2605: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2606: }
1.953 www 2607: my $output='';
2608: my $response;
1.980 raeburn 2609: if ($filelink=~/^https?\:/) {
1.954 raeburn 2610: ($output,$response)=&externalssi($filelink);
1.953 www 2611: } else {
1.1004 droeschl 2612: $filelink .= $filelink=~/\?/ ? '&' : '?';
2613: $filelink .= 'inhibitmenu=yes';
1.953 www 2614: ($output,$response)=&ssi($filelink,%form);
2615: }
1.778 albertel 2616: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2617: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2618: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2619: if (wantarray) {
2620: return ($output, $response);
2621: } else {
2622: return $output;
2623: }
1.8 www 2624: }
2625:
1.15 www 2626: # --------------------------------------------------------- Server Side Include
2627:
1.782 albertel 2628: sub absolute_url {
2629: my ($host_name) = @_;
2630: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2631: if ($host_name eq '') {
2632: $host_name = $ENV{'SERVER_NAME'};
2633: }
2634: return $protocol.$host_name;
2635: }
2636:
1.942 foxr 2637: #
2638: # Server side include.
2639: # Parameters:
2640: # fn Possibly encrypted resource name/id.
2641: # form Hash that describes how the rendering should be done
2642: # and other things.
1.944 foxr 2643: # Returns:
1.950 raeburn 2644: # Scalar context: The content of the response.
2645: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2646: #
1.15 www 2647: sub ssi {
2648:
1.944 foxr 2649: my ($fn,%form)=@_;
1.15 www 2650: my $ua=new LWP::UserAgent;
1.23 www 2651: my $request;
1.711 albertel 2652:
2653: $form{'no_update_last_known'}=1;
1.895 albertel 2654: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2655: if (%form) {
1.782 albertel 2656: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2657: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2658: } else {
1.782 albertel 2659: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2660: }
2661:
1.15 www 2662: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2663: my $response= $ua->request($request);
1.1182 foxr 2664: my $content = $response->content;
2665:
2666:
1.944 foxr 2667: if (wantarray) {
1.1173 foxr 2668: return ($content, $response);
1.944 foxr 2669: } else {
1.1173 foxr 2670: return $content;
1.942 foxr 2671: }
1.324 www 2672: }
2673:
2674: sub externalssi {
2675: my ($url)=@_;
2676: my $ua=new LWP::UserAgent;
2677: my $request=new HTTP::Request('GET',$url);
2678: my $response=$ua->request($request);
1.954 raeburn 2679: if (wantarray) {
2680: return ($response->content, $response);
2681: } else {
2682: return $response->content;
2683: }
1.15 www 2684: }
1.254 www 2685:
1.492 albertel 2686: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2687:
2688: sub allowuploaded {
2689: my ($srcurl,$url)=@_;
2690: $url=&clutter(&declutter($url));
2691: my $dir=$url;
2692: $dir=~s/\/[^\/]+$//;
2693: my %httpref=();
2694: my $httpurl=&hreflocation('',$url);
2695: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2696: &Apache::lonnet::appenv(\%httpref);
1.254 www 2697: }
1.477 raeburn 2698:
1.1193 raeburn 2699: #
2700: # Determine if the current user should be able to edit a particular resource,
2701: # when viewing in course context.
2702: # (a) When viewing resource used to determine if "Edit" item is included in
2703: # Functions.
2704: # (b) When displaying folder contents in course editor, used to determine if
2705: # "Edit" link will be displayed alongside resource.
2706: #
1.1196 raeburn 2707: # input: six args -- filename (decluttered), course number, course domain,
2708: # url, symb (if registered) and group (if this is a group
2709: # item -- e.g., bulletin board, group page etc.).
2710: # output: array of five scalars --
1.1193 raeburn 2711: # $cfile -- url for file editing if editable on current server
2712: # $home -- homeserver of resource (i.e., for author if published,
2713: # or course if uploaded.).
2714: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2715: # $forceedit -- 1 if icon/link should be to go to edit mode
2716: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2717: #
2718:
2719: sub can_edit_resource {
1.1194 raeburn 2720: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2721: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2722: #
2723: # For aboutme pages user can only edit his/her own.
2724: #
1.1199 raeburn 2725: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2726: my ($sdom,$sname) = ($1,$2);
2727: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2728: $home = $env{'user.home'};
2729: $cfile = $resurl;
2730: if ($env{'form.forceedit'}) {
2731: $forceview = 1;
2732: } else {
2733: $forceedit = 1;
2734: }
2735: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2736: } else {
2737: return;
2738: }
2739: }
2740:
2741: if ($env{'request.course.id'}) {
2742: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2743: if ($group ne '') {
2744: # if this is a group homepage or group bulletin board, check group privs
2745: my $allowed = 0;
1.1197 raeburn 2746: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2747: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2748: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2749: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2750: $allowed = 1;
2751: }
1.1197 raeburn 2752: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2753: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2754: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2755: $allowed = 1;
2756: }
2757: }
2758: if ($allowed) {
2759: $home=&homeserver($cnum,$cdom);
2760: if ($env{'form.forceedit'}) {
2761: $forceview = 1;
2762: } else {
2763: $forceedit = 1;
2764: }
2765: $cfile = $resurl;
2766: } else {
2767: return;
2768: }
2769: } else {
1.1208 raeburn 2770: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2771: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2772: return;
2773: }
2774: } elsif (!$crsedit) {
1.1194 raeburn 2775: #
2776: # No edit allowed where CC has switched to student role.
2777: #
2778: return;
2779: }
2780: }
2781: }
2782:
1.1193 raeburn 2783: if ($file ne '') {
2784: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2785: if (&is_course_upload($file,$cnum,$cdom)) {
2786: $uploaded = 1;
2787: $incourse = 1;
1.1193 raeburn 2788: if ($file =~/\.(htm|html|css|js|txt)$/) {
2789: $cfile = &hreflocation('',$file);
1.1201 raeburn 2790: if ($env{'form.forceedit'}) {
2791: $forceview = 1;
2792: } else {
2793: $forceedit = 1;
2794: }
1.1194 raeburn 2795: }
2796: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2797: $incourse = 1;
2798: if ($env{'form.forceedit'}) {
2799: $forceview = 1;
2800: } else {
2801: $forceedit = 1;
2802: }
2803: $cfile = $resurl;
2804: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2805: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2806: $incourse = 1;
2807: if ($env{'form.forceedit'}) {
2808: $forceview = 1;
2809: } else {
2810: $forceedit = 1;
2811: }
2812: $cfile = $resurl;
1.1199 raeburn 2813: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2814: $incourse = 1;
2815: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2816: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2817: $incourse = 1;
1.1199 raeburn 2818: if ($env{'form.forceedit'}) {
2819: $forceview = 1;
2820: } else {
2821: $forceedit = 1;
2822: }
2823: $cfile = $resurl;
1.1208 raeburn 2824: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2825: $incourse = 1;
2826: if ($env{'form.forceedit'}) {
2827: $forceview = 1;
2828: } else {
2829: $forceedit = 1;
2830: }
2831: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2832: }
2833: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2834: my $template = '/res/lib/templates/simpleproblem.problem';
2835: if (&is_on_map($template)) {
2836: $incourse = 1;
2837: $forceview = 1;
2838: $cfile = $template;
1.1193 raeburn 2839: }
1.1199 raeburn 2840: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2841: $incourse = 1;
2842: if ($env{'form.forceedit'}) {
2843: $forceview = 1;
2844: } else {
2845: $forceedit = 1;
2846: }
2847: $cfile = $resurl;
2848: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2849: $incourse = 1;
2850: $forceview = 1;
2851: if ($symb) {
2852: my ($map,$id,$res)=&decode_symb($symb);
2853: $env{'request.symb'} = $symb;
2854: $cfile = &clutter($res);
2855: } else {
2856: $cfile = $env{'form.suppurl'};
2857: $cfile =~ s{^http://}{};
2858: $cfile = '/adm/wrapper/ext/'.$cfile;
2859: }
1.1234 raeburn 2860: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2861: if ($env{'form.forceedit'}) {
2862: $forceview = 1;
2863: } else {
2864: $forceedit = 1;
2865: }
2866: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2867: }
2868: }
1.1194 raeburn 2869: if ($uploaded || $incourse) {
2870: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2871: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2872: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2873: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2874: # Check that the user has permission to edit this resource
2875: my $setpriv = 1;
2876: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2877: if (defined($cfudom)) {
2878: $home=&homeserver($cfuname,$cfudom);
2879: $cfile=$file;
2880: }
2881: }
1.1194 raeburn 2882: if (($cfile ne '') && (!$incourse || $uploaded) &&
2883: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2884: my @ids=¤t_machine_ids();
2885: unless (grep(/^\Q$home\E$/,@ids)) {
2886: $switchserver=1;
2887: }
2888: }
2889: }
1.1194 raeburn 2890: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2891: }
2892:
2893: sub is_course_upload {
2894: my ($file,$cnum,$cdom) = @_;
2895: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2896: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2897: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2898: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2899: return 1;
2900: }
2901: return;
2902: }
2903:
1.1194 raeburn 2904: sub in_course {
1.1195 raeburn 2905: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2906: if ($hideprivileged) {
2907: my $skipuser;
1.1219 raeburn 2908: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2909: my @possdoms = ($cdom);
2910: if ($coursehash{'checkforpriv'}) {
2911: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2912: }
2913: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 2914: $skipuser = 1;
2915: if ($coursehash{'nothideprivileged'}) {
2916: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2917: my $user;
2918: if ($item =~ /:/) {
2919: $user = $item;
2920: } else {
2921: $user = join(':',split(/[\@]/,$item));
2922: }
2923: if ($user eq $uname.':'.$udom) {
2924: undef($skipuser);
2925: last;
2926: }
2927: }
2928: }
2929: if ($skipuser) {
2930: return 0;
2931: }
2932: }
2933: }
1.1194 raeburn 2934: $type ||= 'any';
2935: if (!defined($cdom) || !defined($cnum)) {
2936: my $cid = $env{'request.course.id'};
2937: $cdom = $env{'course.'.$cid.'.domain'};
2938: $cnum = $env{'course.'.$cid.'.num'};
2939: }
2940: my $typesref;
1.1195 raeburn 2941: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 2942: $typesref = ['active','previous','future'];
2943: } elsif ($type eq 'previous' || $type eq 'future') {
2944: $typesref = [$type];
2945: }
2946: my %roles = &get_my_roles($uname,$udom,'userroles',
2947: $typesref,undef,[$cdom]);
2948: my ($tmp) = keys(%roles);
2949: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2950: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2951: if (@course_roles > 0) {
2952: return 1;
2953: }
2954: return 0;
2955: }
2956:
1.478 albertel 2957: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2958: # input: action, courseID, current domain, intended
1.637 raeburn 2959: # path to file, source of file, instruction to parse file for objects,
2960: # ref to hash for embedded objects,
2961: # ref to hash for codebase of java objects.
1.1095 raeburn 2962: # reference to scalar to accommodate mime type determined
2963: # from File::MMagic if $parser = parse.
1.637 raeburn 2964: #
1.485 raeburn 2965: # output: url to file (if action was uploaddoc),
2966: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2967: #
1.478 albertel 2968: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2969: # course.
1.477 raeburn 2970: #
1.478 albertel 2971: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2972: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2973: # course's home server.
1.477 raeburn 2974: #
1.478 albertel 2975: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2976: # be copied from $source (current location) to
2977: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2978: # and will then be copied to
2979: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2980: # course's home server.
1.485 raeburn 2981: #
1.481 raeburn 2982: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2983: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2984: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2985: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2986: # in course's home server.
1.637 raeburn 2987: #
1.477 raeburn 2988:
2989: sub process_coursefile {
1.1095 raeburn 2990: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2991: $mimetype)=@_;
1.477 raeburn 2992: my $fetchresult;
1.638 albertel 2993: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2994: if ($action eq 'propagate') {
1.638 albertel 2995: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2996: $home);
1.481 raeburn 2997: } else {
1.477 raeburn 2998: my $fpath = '';
2999: my $fname = $file;
1.478 albertel 3000: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3001: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3002: my $filepath = &build_filepath($fpath);
1.481 raeburn 3003: if ($action eq 'copy') {
3004: if ($source eq '') {
3005: $fetchresult = 'no source file';
3006: return $fetchresult;
3007: } else {
3008: my $destination = $filepath.'/'.$fname;
3009: rename($source,$destination);
3010: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3011: $home);
1.481 raeburn 3012: }
3013: } elsif ($action eq 'uploaddoc') {
3014: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3015: print $fh $env{'form.'.$source};
1.481 raeburn 3016: close($fh);
1.637 raeburn 3017: if ($parser eq 'parse') {
1.1024 raeburn 3018: my $mm = new File::MMagic;
1.1095 raeburn 3019: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3020: if ($type eq 'text/html') {
1.1024 raeburn 3021: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3022: unless ($parse_result eq 'ok') {
3023: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3024: }
1.637 raeburn 3025: }
1.1095 raeburn 3026: if (ref($mimetype)) {
3027: $$mimetype = $type;
3028: }
1.637 raeburn 3029: }
1.477 raeburn 3030: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3031: $home);
1.481 raeburn 3032: if ($fetchresult eq 'ok') {
3033: return '/uploaded/'.$fpath.'/'.$fname;
3034: } else {
3035: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3036: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3037: return '/adm/notfound.html';
3038: }
1.477 raeburn 3039: }
3040: }
1.485 raeburn 3041: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3042: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3043: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3044: }
3045: return $fetchresult;
3046: }
3047:
1.637 raeburn 3048: sub build_filepath {
3049: my ($fpath) = @_;
3050: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3051: unless ($fpath eq '') {
3052: my @parts=split('/',$fpath);
3053: foreach my $part (@parts) {
3054: $filepath.= '/'.$part;
3055: if ((-e $filepath)!=1) {
3056: mkdir($filepath,0777);
3057: }
3058: }
3059: }
3060: return $filepath;
3061: }
3062:
3063: sub store_edited_file {
1.638 albertel 3064: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3065: my $file = $primary_url;
3066: $file =~ s#^/uploaded/$docudom/$docuname/##;
3067: my $fpath = '';
3068: my $fname = $file;
3069: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3070: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3071: my $filepath = &build_filepath($fpath);
3072: open(my $fh,'>'.$filepath.'/'.$fname);
3073: print $fh $content;
3074: close($fh);
1.638 albertel 3075: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3076: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3077: $home);
1.637 raeburn 3078: if ($$fetchresult eq 'ok') {
3079: return '/uploaded/'.$fpath.'/'.$fname;
3080: } else {
1.638 albertel 3081: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3082: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3083: return '/adm/notfound.html';
3084: }
3085: }
3086:
1.531 albertel 3087: sub clean_filename {
1.831 albertel 3088: my ($fname,$args)=@_;
1.315 www 3089: # Replace Windows backslashes by forward slashes
1.257 www 3090: $fname=~s/\\/\//g;
1.831 albertel 3091: if (!$args->{'keep_path'}) {
3092: # Get rid of everything but the actual filename
3093: $fname=~s/^.*\/([^\/]+)$/$1/;
3094: }
1.315 www 3095: # Replace spaces by underscores
3096: $fname=~s/\s+/\_/g;
3097: # Replace all other weird characters by nothing
1.831 albertel 3098: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3099: # Replace all .\d. sequences with _\d. so they no longer look like version
3100: # numbers
3101: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3102: return $fname;
3103: }
1.1051 raeburn 3104: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3105: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3106: # image with the same aspect ratio as the original, but with dimensions which do
3107: # not exceed $resizewidth and $resizeheight.
3108:
1.984 neumanie 3109: sub resizeImage {
1.1051 raeburn 3110: my ($img_path,$resizewidth,$resizeheight) = @_;
3111: my $ima = Image::Magick->new;
3112: my $resized;
3113: if (-e $img_path) {
3114: $ima->Read($img_path);
3115: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3116: my $width = $ima->Get('width');
3117: my $height = $ima->Get('height');
3118: if ($width > $resizewidth) {
3119: my $factor = $width/$resizewidth;
3120: my $newheight = $height/$factor;
3121: $ima->Scale(width=>$resizewidth,height=>$newheight);
3122: $resized = 1;
3123: }
3124: }
3125: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3126: my $width = $ima->Get('width');
3127: my $height = $ima->Get('height');
3128: if ($height > $resizeheight) {
3129: my $factor = $height/$resizeheight;
3130: my $newwidth = $width/$factor;
3131: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3132: $resized = 1;
3133: }
3134: }
3135: if ($resized) {
3136: $ima->Write($img_path);
3137: }
3138: }
3139: return;
1.977 amueller 3140: }
3141:
1.608 albertel 3142: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3143: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3144: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3145: # $context - possible values: coursedoc, existingfile, overwrite,
3146: # canceloverwrite, or ''.
3147: # if 'coursedoc': upload to the current course
3148: # if 'existingfile': write file to tmp/overwrites directory
3149: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3150: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3151: # $subdir - directory in userfile to store the file into
1.858 raeburn 3152: # $parser - instruction to parse file for objects ($parser = parse)
3153: # $allfiles - reference to hash for embedded objects
3154: # $codebase - reference to hash for codebase of java objects
3155: # $desuname - username for permanent storage of uploaded file
3156: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3157: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3158: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3159: # $resizewidth - width (pixels) to which to resize uploaded image
3160: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3161: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3162: # from File::MMagic.
1.858 raeburn 3163: #
1.686 albertel 3164: # output: url of file in userspace, or error: <message>
3165: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3166:
1.531 albertel 3167: sub userfileupload {
1.1090 raeburn 3168: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3169: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3170: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3171: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3172: $fname=&clean_filename($fname);
1.1090 raeburn 3173: # See if there is anything left
1.257 www 3174: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3175: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3176: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3177: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3178: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3179: my $now = time;
1.1090 raeburn 3180: my $filepath;
1.1095 raeburn 3181: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3182: $filepath = 'tmp/helprequests/'.$now;
3183: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3184: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3185: '_'.$env{'user.domain'}.'/pending';
3186: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3187: my ($docuname,$docudom);
3188: if ($destudom) {
3189: $docudom = $destudom;
3190: } else {
3191: $docudom = $env{'user.domain'};
3192: }
3193: if ($destuname) {
3194: $docuname = $destuname;
3195: } else {
3196: $docuname = $env{'user.name'};
3197: }
3198: if (exists($env{'form.group'})) {
3199: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3200: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3201: }
3202: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3203: if ($context eq 'canceloverwrite') {
3204: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3205: if (-e $tempfile) {
3206: my @info = stat($tempfile);
3207: if ($info[9] eq $env{'form.timestamp'}) {
3208: unlink($tempfile);
3209: }
3210: }
3211: return;
1.523 raeburn 3212: }
3213: }
1.1090 raeburn 3214: # Create the directory if not present
1.741 raeburn 3215: my @parts=split(/\//,$filepath);
3216: my $fullpath = $perlvar{'lonDaemons'};
3217: for (my $i=0;$i<@parts;$i++) {
3218: $fullpath .= '/'.$parts[$i];
3219: if ((-e $fullpath)!=1) {
3220: mkdir($fullpath,0777);
3221: }
3222: }
3223: open(my $fh,'>'.$fullpath.'/'.$fname);
3224: print $fh $env{'form.'.$formname};
3225: close($fh);
1.1090 raeburn 3226: if ($context eq 'existingfile') {
3227: my @info = stat($fullpath.'/'.$fname);
3228: return ($fullpath.'/'.$fname,$info[9]);
3229: } else {
3230: return $fullpath.'/'.$fname;
3231: }
1.523 raeburn 3232: }
1.995 raeburn 3233: if ($subdir eq 'scantron') {
3234: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3235: } else {
1.995 raeburn 3236: $fname="$subdir/$fname";
3237: }
1.1090 raeburn 3238: if ($context eq 'coursedoc') {
1.638 albertel 3239: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3240: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3241: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3242: return &finishuserfileupload($docuname,$docudom,
3243: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3244: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3245: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3246: } else {
1.1218 raeburn 3247: if ($env{'form.folder'}) {
3248: $fname=$env{'form.folder'}.'/'.$fname;
3249: }
1.638 albertel 3250: return &process_coursefile('uploaddoc',$docuname,$docudom,
3251: $fname,$formname,$parser,
1.1095 raeburn 3252: $allfiles,$codebase,$mimetype);
1.481 raeburn 3253: }
1.719 banghart 3254: } elsif (defined($destuname)) {
3255: my $docuname=$destuname;
3256: my $docudom=$destudom;
1.860 raeburn 3257: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3258: $parser,$allfiles,$codebase,
1.1051 raeburn 3259: $thumbwidth,$thumbheight,
1.1095 raeburn 3260: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3261: } else {
1.638 albertel 3262: my $docuname=$env{'user.name'};
3263: my $docudom=$env{'user.domain'};
1.1220 raeburn 3264: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3265: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3266: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3267: }
1.860 raeburn 3268: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3269: $parser,$allfiles,$codebase,
1.1051 raeburn 3270: $thumbwidth,$thumbheight,
1.1095 raeburn 3271: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3272: }
1.271 www 3273: }
3274:
3275: sub finishuserfileupload {
1.860 raeburn 3276: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3277: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3278: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3279: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3280:
1.860 raeburn 3281: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3282: $file=$fname;
3283: if ($fname=~m|/|) {
3284: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3285: $path.=$fnamepath.'/';
3286: }
1.259 www 3287: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3288: my $count;
3289: for ($count=4;$count<=$#parts;$count++) {
3290: $filepath.="/$parts[$count]";
3291: if ((-e $filepath)!=1) {
3292: mkdir($filepath,0777);
3293: }
3294: }
1.984 neumanie 3295:
1.258 www 3296: # Save the file
3297: {
1.701 albertel 3298: if (!open(FH,'>'.$filepath.'/'.$file)) {
3299: &logthis('Failed to create '.$filepath.'/'.$file);
3300: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3301: return '/adm/notfound.html';
3302: }
1.1090 raeburn 3303: if ($context eq 'overwrite') {
1.1117 foxr 3304: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3305: my $target = $filepath.'/'.$file;
3306: if (-e $source) {
3307: my @info = stat($source);
3308: if ($info[9] eq $env{'form.timestamp'}) {
3309: unless (&File::Copy::move($source,$target)) {
3310: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3311: return "Moving from $source failed";
3312: }
3313: } else {
3314: return "Temporary file: $source had unexpected date/time for last modification";
3315: }
3316: } else {
3317: return "Temporary file: $source missing";
3318: }
3319: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3320: &logthis('Failed to write to '.$filepath.'/'.$file);
3321: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3322: return '/adm/notfound.html';
3323: }
1.570 albertel 3324: close(FH);
1.1051 raeburn 3325: if ($resizewidth && $resizeheight) {
3326: my $mm = new File::MMagic;
3327: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3328: if ($mime_type =~ m{^image/}) {
3329: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3330: }
1.977 amueller 3331: }
1.258 www 3332: }
1.1152 raeburn 3333: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3334: if (ref($mimetype)) {
3335: if ($$mimetype eq '') {
3336: my $mm = new File::MMagic;
3337: my $type = $mm->checktype_filename($filepath.'/'.$file);
3338: $$mimetype = $type;
3339: }
3340: }
3341: }
1.637 raeburn 3342: if ($parser eq 'parse') {
1.1152 raeburn 3343: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3344: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3345: $allfiles,$codebase);
3346: unless ($parse_result eq 'ok') {
3347: &logthis('Failed to parse '.$filepath.$file.
3348: ' for embedded media: '.$parse_result);
3349: }
1.637 raeburn 3350: }
3351: }
1.860 raeburn 3352: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3353: my $input = $filepath.'/'.$file;
3354: my $output = $filepath.'/'.'tn-'.$file;
3355: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3356: system("convert -sample $thumbsize $input $output");
3357: if (-e $filepath.'/'.'tn-'.$file) {
3358: $fetchthumb = 1;
3359: }
3360: }
1.858 raeburn 3361:
1.259 www 3362: # Notify homeserver to grep it
3363: #
1.984 neumanie 3364: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3365: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3366: if ($fetchresult eq 'ok') {
1.860 raeburn 3367: if ($fetchthumb) {
3368: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3369: if ($thumbresult ne 'ok') {
3370: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3371: $docuhome.': '.$thumbresult);
3372: }
3373: }
1.259 www 3374: #
1.258 www 3375: # Return the URL to it
1.494 albertel 3376: return '/uploaded/'.$path.$file;
1.263 www 3377: } else {
1.494 albertel 3378: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3379: ': '.$fetchresult);
1.263 www 3380: return '/adm/notfound.html';
1.858 raeburn 3381: }
1.493 albertel 3382: }
3383:
1.637 raeburn 3384: sub extract_embedded_items {
1.961 raeburn 3385: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3386: my @state = ();
1.1164 raeburn 3387: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3388: my %javafiles = (
3389: codebase => '',
3390: code => '',
3391: archive => ''
3392: );
3393: my %mediafiles = (
3394: src => '',
3395: movie => '',
3396: );
1.648 raeburn 3397: my $p;
3398: if ($content) {
3399: $p = HTML::LCParser->new($content);
3400: } else {
1.961 raeburn 3401: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3402: }
1.641 albertel 3403: while (my $t=$p->get_token()) {
1.640 albertel 3404: if ($t->[0] eq 'S') {
3405: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3406: push(@state, $tagname);
1.648 raeburn 3407: if (lc($tagname) eq 'allow') {
3408: &add_filetype($allfiles,$attr->{'src'},'src');
3409: }
1.640 albertel 3410: if (lc($tagname) eq 'img') {
3411: &add_filetype($allfiles,$attr->{'src'},'src');
3412: }
1.886 albertel 3413: if (lc($tagname) eq 'a') {
1.1222 raeburn 3414: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3415: &add_filetype($allfiles,$attr->{'href'},'href');
3416: }
1.886 albertel 3417: }
1.645 raeburn 3418: if (lc($tagname) eq 'script') {
1.1164 raeburn 3419: my $src;
1.645 raeburn 3420: if ($attr->{'archive'} =~ /\.jar$/i) {
3421: &add_filetype($allfiles,$attr->{'archive'},'archive');
3422: } else {
1.1164 raeburn 3423: if ($attr->{'src'} ne '') {
3424: $src = $attr->{'src'};
3425: &add_filetype($allfiles,$src,'src');
3426: }
3427: }
3428: my $text = $p->get_trimmed_text();
3429: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3430: my @swfargs = split(/,/,$1);
3431: foreach my $item (@swfargs) {
3432: $item =~ s/["']//g;
3433: $item =~ s/^\s+//;
3434: $item =~ s/\s+$//;
3435: }
3436: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3437: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3438: push(@{$related{$swfargs[0]}},$swfargs[2]);
3439: } else {
3440: $related{$swfargs[0]} = [$swfargs[2]];
3441: }
3442: }
1.645 raeburn 3443: }
3444: }
3445: if (lc($tagname) eq 'link') {
3446: if (lc($attr->{'rel'}) eq 'stylesheet') {
3447: &add_filetype($allfiles,$attr->{'href'},'href');
3448: }
3449: }
1.640 albertel 3450: if (lc($tagname) eq 'object' ||
3451: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3452: foreach my $item (keys(%javafiles)) {
3453: $javafiles{$item} = '';
3454: }
1.1164 raeburn 3455: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3456: $lastids{lc($tagname)} = $attr->{'id'};
3457: }
1.640 albertel 3458: }
3459: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3460: my $name = lc($attr->{'name'});
3461: foreach my $item (keys(%javafiles)) {
3462: if ($name eq $item) {
3463: $javafiles{$item} = $attr->{'value'};
3464: last;
3465: }
3466: }
1.1164 raeburn 3467: my $pathfrom;
1.640 albertel 3468: foreach my $item (keys(%mediafiles)) {
3469: if ($name eq $item) {
1.1164 raeburn 3470: $pathfrom = $attr->{'value'};
3471: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3472: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3473: last;
3474: }
3475: }
1.1164 raeburn 3476: if ($name eq 'flashvars') {
3477: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3478: }
3479: if ($pathfrom ne '') {
3480: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3481: $pathfrom);
3482: }
1.640 albertel 3483: }
3484: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3485: foreach my $item (keys(%javafiles)) {
3486: if ($attr->{$item}) {
3487: $javafiles{$item} = $attr->{$item};
3488: last;
3489: }
3490: }
3491: foreach my $item (keys(%mediafiles)) {
3492: if ($attr->{$item}) {
3493: &add_filetype($allfiles,$attr->{$item},$item);
3494: last;
3495: }
3496: }
1.1164 raeburn 3497: if (lc($tagname) eq 'embed') {
3498: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3499: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3500: $attr->{'src'});
3501: }
3502: }
1.640 albertel 3503: }
1.1164 raeburn 3504: if ($t->[4] =~ m{/>$}) {
3505: pop(@state);
3506: }
1.640 albertel 3507: } elsif ($t->[0] eq 'E') {
3508: my ($tagname) = ($t->[1]);
3509: if ($javafiles{'codebase'} ne '') {
3510: $javafiles{'codebase'} .= '/';
3511: }
3512: if (lc($tagname) eq 'applet' ||
3513: lc($tagname) eq 'object' ||
3514: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3515: ) {
3516: foreach my $item (keys(%javafiles)) {
3517: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3518: my $file=$javafiles{'codebase'}.$javafiles{$item};
3519: &add_filetype($allfiles,$file,$item);
3520: }
3521: }
3522: }
3523: pop @state;
3524: }
3525: }
1.1164 raeburn 3526: foreach my $id (sort(keys(%flashvars))) {
3527: if ($shockwave{$id} ne '') {
3528: my @pairs = split(/\&/,$flashvars{$id});
3529: foreach my $pair (@pairs) {
3530: my ($key,$value) = split(/\=/,$pair);
3531: if ($key eq 'thumb') {
3532: &add_filetype($allfiles,$value,$key);
3533: } elsif ($key eq 'content') {
3534: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3535: my ($ext) = ($value =~ /\.([^.]+)$/);
3536: if ($ext ne '') {
3537: &add_filetype($allfiles,$path.$value,$ext);
3538: }
3539: }
3540: }
3541: }
3542: }
1.637 raeburn 3543: return 'ok';
3544: }
3545:
1.639 albertel 3546: sub add_filetype {
3547: my ($allfiles,$file,$type)=@_;
3548: if (exists($allfiles->{$file})) {
3549: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3550: push(@{$allfiles->{$file}}, &escape($type));
3551: }
3552: } else {
3553: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3554: }
3555: }
3556:
1.1164 raeburn 3557: sub embedded_dependency {
3558: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3559: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3560: if (($identifier ne '') &&
3561: (ref($related->{$identifier}) eq 'ARRAY') &&
3562: ($pathfrom ne '')) {
3563: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3564: foreach my $dep (@{$related->{$identifier}}) {
3565: &add_filetype($allfiles,$path.$dep,'object');
3566: }
3567: }
3568: }
3569: return;
3570: }
3571:
1.493 albertel 3572: sub removeuploadedurl {
1.984 neumanie 3573: my ($url)=@_;
3574: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3575: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3576: }
3577:
3578: sub removeuserfile {
3579: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3580: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3581: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3582: if ($result eq 'ok') {
1.798 raeburn 3583: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3584: my $metafile = $fname.'.meta';
3585: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3586: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3587: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3588: my $sqlresult =
1.823 albertel 3589: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3590: 'portfolio_metadata',$group,
3591: 'delete');
1.798 raeburn 3592: }
3593: }
3594: return $result;
1.257 www 3595: }
1.15 www 3596:
1.530 albertel 3597: sub mkdiruserfile {
3598: my ($docuname,$docudom,$dir)=@_;
3599: my $home=&homeserver($docuname,$docudom);
3600: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3601: }
3602:
1.531 albertel 3603: sub renameuserfile {
3604: my ($docuname,$docudom,$old,$new)=@_;
3605: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3606: my $result = &reply("renameuserfile:$docudom:$docuname:".
3607: &escape("$old").':'.&escape("$new"),$home);
3608: if ($result eq 'ok') {
3609: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3610: my $oldmeta = $old.'.meta';
3611: my $newmeta = $new.'.meta';
3612: my $metaresult =
3613: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3614: my $url = "/uploaded/$docudom/$docuname/$old";
3615: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3616: my $sqlresult =
1.823 albertel 3617: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3618: 'portfolio_metadata',$group,
3619: 'delete');
1.798 raeburn 3620: }
3621: }
3622: return $result;
1.531 albertel 3623: }
3624:
1.14 www 3625: # ------------------------------------------------------------------------- Log
3626:
3627: sub log {
3628: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3629: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3630: }
3631:
3632: # ------------------------------------------------------------------ Course Log
1.352 www 3633: #
3634: # This routine flushes several buffers of non-mission-critical nature
3635: #
1.157 www 3636:
3637: sub flushcourselogs {
1.352 www 3638: &logthis('Flushing log buffers');
3639: #
3640: # course logs
3641: # This is a log of all transactions in a course, which can be used
3642: # for data mining purposes
3643: #
3644: # It also collects the courseid database, which lists last transaction
3645: # times and course titles for all courseids
3646: #
3647: my %courseidbuffer=();
1.921 raeburn 3648: foreach my $crsid (keys(%courselogs)) {
1.352 www 3649: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3650: &escape($courselogs{$crsid}),
3651: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3652: delete $courselogs{$crsid};
3653: } else {
3654: &logthis('Failed to flush log buffer for '.$crsid);
3655: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3656: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3657: " exceeded maximum size, deleting.</font>");
3658: delete $courselogs{$crsid};
3659: }
1.352 www 3660: }
1.920 raeburn 3661: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3662: 'description' => $coursedescrbuf{$crsid},
3663: 'inst_code' => $courseinstcodebuf{$crsid},
3664: 'type' => $coursetypebuf{$crsid},
3665: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3666: };
1.191 harris41 3667: }
1.352 www 3668: #
3669: # Write course id database (reverse lookup) to homeserver of courses
3670: # Is used in pickcourse
3671: #
1.840 albertel 3672: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3673: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3674: $courseidbuffer{$crs_home},
3675: $crs_home,'timeonly');
1.352 www 3676: }
3677: #
3678: # File accesses
3679: # Writes to the dynamic metadata of resources to get hit counts, etc.
3680: #
1.449 matthew 3681: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3682: if ($entry =~ /___count$/) {
3683: my ($dom,$name);
1.807 albertel 3684: ($dom,$name,undef)=
1.811 albertel 3685: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3686: if (! defined($dom) || $dom eq '' ||
3687: ! defined($name) || $name eq '') {
1.620 albertel 3688: my $cid = $env{'request.course.id'};
3689: $dom = $env{'request.'.$cid.'.domain'};
3690: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3691: }
1.450 matthew 3692: my $value = $accesshash{$entry};
3693: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3694: my %temphash=($url => $value);
1.449 matthew 3695: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3696: if ($result eq 'ok') {
3697: delete $accesshash{$entry};
3698: }
3699: } else {
1.811 albertel 3700: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3701: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3702: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3703: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3704: delete $accesshash{$entry};
3705: }
1.185 www 3706: }
1.191 harris41 3707: }
1.352 www 3708: #
3709: # Roles
3710: # Reverse lookup of user roles for course faculty/staff and co-authorship
3711: #
1.800 albertel 3712: foreach my $entry (keys(%userrolehash)) {
1.351 www 3713: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3714: split(/\:/,$entry);
3715: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3716: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3717: $rudom,$runame) eq 'ok') {
3718: delete $userrolehash{$entry};
3719: }
3720: }
1.662 raeburn 3721: #
3722: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3723: #
3724: my %domrolebuffer = ();
1.1000 raeburn 3725: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3726: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3727: if ($domrolebuffer{$rudom}) {
3728: $domrolebuffer{$rudom}.='&'.&escape($entry).
3729: '='.&escape($domainrolehash{$entry});
3730: } else {
3731: $domrolebuffer{$rudom}.=&escape($entry).
3732: '='.&escape($domainrolehash{$entry});
3733: }
3734: delete $domainrolehash{$entry};
3735: }
3736: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3737: my %servers = &get_servers($dom,'library');
3738: foreach my $tryserver (keys(%servers)) {
3739: unless (&reply('domroleput:'.$dom.':'.
3740: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3741: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3742: }
1.662 raeburn 3743: }
3744: }
1.186 www 3745: $dumpcount++;
1.157 www 3746: }
3747:
3748: sub courselog {
3749: my $what=shift;
1.158 www 3750: $what=time.':'.$what;
1.620 albertel 3751: unless ($env{'request.course.id'}) { return ''; }
3752: $coursedombuf{$env{'request.course.id'}}=
3753: $env{'course.'.$env{'request.course.id'}.'.domain'};
3754: $coursenumbuf{$env{'request.course.id'}}=
3755: $env{'course.'.$env{'request.course.id'}.'.num'};
3756: $coursehombuf{$env{'request.course.id'}}=
3757: $env{'course.'.$env{'request.course.id'}.'.home'};
3758: $coursedescrbuf{$env{'request.course.id'}}=
3759: $env{'course.'.$env{'request.course.id'}.'.description'};
3760: $courseinstcodebuf{$env{'request.course.id'}}=
3761: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3762: $courseownerbuf{$env{'request.course.id'}}=
3763: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3764: $coursetypebuf{$env{'request.course.id'}}=
3765: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3766: if (defined $courselogs{$env{'request.course.id'}}) {
3767: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3768: } else {
1.620 albertel 3769: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3770: }
1.620 albertel 3771: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3772: &flushcourselogs();
3773: }
1.158 www 3774: }
3775:
3776: sub courseacclog {
3777: my $fnsymb=shift;
1.620 albertel 3778: unless ($env{'request.course.id'}) { return ''; }
3779: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3780: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3781: $what.=':POST';
1.583 matthew 3782: # FIXME: Probably ought to escape things....
1.800 albertel 3783: foreach my $key (keys(%env)) {
3784: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3785: my $formitem = $1;
3786: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3787: $what.=':'.$formitem.'='.$env{$key};
3788: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3789: $what.=':'.$formitem.'='.$env{$key};
3790: }
1.158 www 3791: }
1.191 harris41 3792: }
1.583 matthew 3793: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3794: # FIXME: We should not be depending on a form parameter that someone
3795: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3796: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3797: $what.= ':POST';
3798: # FIXME: Probably ought to escape things....
3799: foreach my $element ('courseexp','crsfulltext','crsrelated',
3800: 'crsdiscuss') {
1.620 albertel 3801: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3802: }
3803: }
1.158 www 3804: }
3805: &courselog($what);
1.149 www 3806: }
3807:
1.185 www 3808: sub countacc {
3809: my $url=&declutter(shift);
1.458 matthew 3810: return if (! defined($url) || $url eq '');
1.620 albertel 3811: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3812: #
3813: # Mark that this url was used in this course
3814: #
1.620 albertel 3815: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3816: #
3817: # Increase the access count for this resource in this child process
3818: #
1.281 www 3819: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3820: $accesshash{$key}++;
1.185 www 3821: }
1.349 www 3822:
1.361 www 3823: sub linklog {
3824: my ($from,$to)=@_;
3825: $from=&declutter($from);
3826: $to=&declutter($to);
3827: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3828: $accesshash{$to.'___'.$from.'___goto'}=1;
3829: }
1.1160 www 3830:
3831: sub statslog {
3832: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3833: if ($users<2) { return; }
3834: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3835: 'course' => $env{'request.course.id'},
3836: 'sections' => '"all"',
3837: 'num_students' => $users,
3838: 'part' => $part,
3839: 'symb' => $symb,
3840: 'mean_tries' => $av_attempts,
3841: 'deg_of_diff' => $degdiff});
3842: foreach my $key (keys(%dynstore)) {
3843: $accesshash{$key}=$dynstore{$key};
3844: }
3845: }
1.361 www 3846:
1.349 www 3847: sub userrolelog {
3848: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3849: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3850: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3851: $userrolehash
3852: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3853: =$tend.':'.$tstart;
1.662 raeburn 3854: }
1.1169 droeschl 3855: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3856: $userrolehash
3857: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3858: =$tend.':'.$tstart;
3859: }
1.1169 droeschl 3860: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3861: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3862: $domainrolehash
3863: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3864: = $tend.':'.$tstart;
3865: }
1.351 www 3866: }
3867:
1.957 raeburn 3868: sub courserolelog {
3869: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3870: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3871: my $cdom = $1;
3872: my $cnum = $2;
3873: my $sec = $3;
3874: my $namespace = 'rolelog';
3875: my %storehash = (
3876: role => $trole,
3877: start => $tstart,
3878: end => $tend,
3879: selfenroll => $selfenroll,
3880: context => $context,
3881: );
3882: if ($trole eq 'gr') {
3883: $namespace = 'groupslog';
3884: $storehash{'group'} = $sec;
3885: } else {
3886: $storehash{'section'} = $sec;
3887: }
1.1188 raeburn 3888: &write_log('course',$namespace,\%storehash,$delflag,$username,
3889: $domain,$cnum,$cdom);
1.1184 raeburn 3890: if (($trole ne 'st') || ($sec ne '')) {
3891: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3892: }
3893: }
3894: return;
3895: }
3896:
1.1184 raeburn 3897: sub domainrolelog {
3898: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3899: if ($area =~ m{^/($match_domain)/$}) {
3900: my $cdom = $1;
3901: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3902: my $namespace = 'rolelog';
3903: my %storehash = (
3904: role => $trole,
3905: start => $tstart,
3906: end => $tend,
3907: context => $context,
3908: );
1.1188 raeburn 3909: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3910: $domain,$domconfiguser,$cdom);
1.1184 raeburn 3911: }
3912: return;
3913:
3914: }
3915:
3916: sub coauthorrolelog {
3917: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3918: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3919: my $audom = $1;
3920: my $auname = $2;
3921: my $namespace = 'rolelog';
3922: my %storehash = (
3923: role => $trole,
3924: start => $tstart,
3925: end => $tend,
3926: context => $context,
3927: );
1.1188 raeburn 3928: &write_log('author',$namespace,\%storehash,$delflag,$username,
3929: $domain,$auname,$audom);
1.1184 raeburn 3930: }
3931: return;
3932: }
3933:
1.351 www 3934: sub get_course_adv_roles {
1.948 raeburn 3935: my ($cid,$codes) = @_;
1.620 albertel 3936: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3937: my %coursehash=&coursedescription($cid);
1.988 raeburn 3938: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3939: my %nothide=();
1.800 albertel 3940: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3941: if ($user !~ /:/) {
3942: $nothide{join(':',split(/[\@]/,$user))}=1;
3943: } else {
3944: $nothide{$user}=1;
3945: }
1.470 www 3946: }
1.1219 raeburn 3947: my @possdoms = ($coursehash{'domain'});
3948: if ($coursehash{'checkforpriv'}) {
3949: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3950: }
1.351 www 3951: my %returnhash=();
3952: my %dumphash=
3953: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3954: my $now=time;
1.997 raeburn 3955: my %privileged;
1.1000 raeburn 3956: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3957: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3958: if (($tstart) && ($tstart<0)) { next; }
3959: if (($tend) && ($tend<$now)) { next; }
3960: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3961: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3962: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 3963: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 3964: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3965: if ($role eq 'cr') { next; }
1.948 raeburn 3966: if ($codes) {
3967: if ($section) { $role .= ':'.$section; }
3968: if ($returnhash{$role}) {
3969: $returnhash{$role}.=','.$username.':'.$domain;
3970: } else {
3971: $returnhash{$role}=$username.':'.$domain;
3972: }
1.351 www 3973: } else {
1.988 raeburn 3974: my $key=&plaintext($role,$crstype);
1.973 bisitz 3975: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3976: if ($returnhash{$key}) {
3977: $returnhash{$key}.=','.$username.':'.$domain;
3978: } else {
3979: $returnhash{$key}=$username.':'.$domain;
3980: }
1.351 www 3981: }
1.948 raeburn 3982: }
1.400 www 3983: return %returnhash;
3984: }
3985:
3986: sub get_my_roles {
1.937 raeburn 3987: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3988: unless (defined($uname)) { $uname=$env{'user.name'}; }
3989: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3990: my (%dumphash,%nothide);
1.1086 raeburn 3991: if ($context eq 'userroles') {
1.1166 raeburn 3992: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 3993: } else {
1.1219 raeburn 3994: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3995: if ($hidepriv) {
3996: my %coursehash=&coursedescription($udom.'_'.$uname);
3997: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3998: if ($user !~ /:/) {
3999: $nothide{join(':',split(/[\@]/,$user))} = 1;
4000: } else {
4001: $nothide{$user} = 1;
4002: }
4003: }
4004: }
1.858 raeburn 4005: }
1.400 www 4006: my %returnhash=();
4007: my $now=time;
1.999 raeburn 4008: my %privileged;
1.800 albertel 4009: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4010: my ($role,$tend,$tstart);
4011: if ($context eq 'userroles') {
1.1149 raeburn 4012: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4013: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4014: } else {
4015: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4016: }
1.400 www 4017: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4018: my $status = 'active';
1.939 raeburn 4019: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4020: $status = 'previous';
4021: }
4022: if (($tstart) && ($now<$tstart)) {
4023: $status = 'future';
4024: }
4025: if (ref($types) eq 'ARRAY') {
4026: if (!grep(/^\Q$status\E$/,@{$types})) {
4027: next;
4028: }
4029: } else {
4030: if ($status ne 'active') {
4031: next;
4032: }
4033: }
1.867 raeburn 4034: my ($rolecode,$username,$domain,$section,$area);
4035: if ($context eq 'userroles') {
1.1186 raeburn 4036: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4037: (undef,$domain,$username,$section) = split(/\//,$area);
4038: } else {
4039: ($role,$username,$domain,$section) = split(/\:/,$entry);
4040: }
1.832 raeburn 4041: if (ref($roledoms) eq 'ARRAY') {
4042: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4043: next;
4044: }
4045: }
4046: if (ref($roles) eq 'ARRAY') {
4047: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4048: if ($role =~ /^cr\//) {
4049: if (!grep(/^cr$/,@{$roles})) {
4050: next;
4051: }
1.1104 raeburn 4052: } elsif ($role =~ /^gr\//) {
4053: if (!grep(/^gr$/,@{$roles})) {
4054: next;
4055: }
1.922 raeburn 4056: } else {
4057: next;
4058: }
1.832 raeburn 4059: }
1.867 raeburn 4060: }
1.937 raeburn 4061: if ($hidepriv) {
1.1219 raeburn 4062: my @privroles = ('dc','su');
1.999 raeburn 4063: if ($context eq 'userroles') {
1.1219 raeburn 4064: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4065: } else {
1.1219 raeburn 4066: my $possdoms = [$domain];
4067: if (ref($roledoms) eq 'ARRAY') {
4068: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4069: }
1.1219 raeburn 4070: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4071: if (!$nothide{$username.':'.$domain}) {
4072: next;
4073: }
4074: }
1.937 raeburn 4075: }
4076: }
1.933 raeburn 4077: if ($withsec) {
4078: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4079: $tstart.':'.$tend;
4080: } else {
4081: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4082: }
1.832 raeburn 4083: }
1.373 www 4084: return %returnhash;
1.399 www 4085: }
4086:
4087: # ----------------------------------------------------- Frontpage Announcements
4088: #
4089: #
4090:
4091: sub postannounce {
4092: my ($server,$text)=@_;
1.844 albertel 4093: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4094: unless ($text=~/\w/) { $text=''; }
4095: return &reply('setannounce:'.&escape($text),$server);
4096: }
4097:
4098: sub getannounce {
1.448 albertel 4099:
4100: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4101: my $announcement='';
1.800 albertel 4102: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4103: close($fh);
1.399 www 4104: if ($announcement=~/\w/) {
4105: return
4106: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4107: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4108: } else {
4109: return '';
4110: }
4111: } else {
4112: return '';
4113: }
1.351 www 4114: }
1.353 www 4115:
4116: # ---------------------------------------------------------- Course ID routines
4117: # Deal with domain's nohist_courseid.db files
4118: #
4119:
4120: sub courseidput {
1.921 raeburn 4121: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4122: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4123: my $outcome;
4124: if ($caller eq 'timeonly') {
4125: my $cids = '';
4126: foreach my $item (keys(%$storehash)) {
4127: $cids.=&escape($item).'&';
4128: }
4129: $cids=~s/\&$//;
4130: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4131: $coursehome);
4132: } else {
4133: my $items = '';
4134: foreach my $item (keys(%$storehash)) {
4135: $items.= &escape($item).'='.
4136: &freeze_escape($$storehash{$item}).'&';
4137: }
4138: $items=~s/\&$//;
4139: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4140: $coursehome);
1.918 raeburn 4141: }
4142: if ($outcome eq 'unknown_cmd') {
4143: my $what;
4144: foreach my $cid (keys(%$storehash)) {
4145: $what .= &escape($cid).'=';
1.921 raeburn 4146: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4147: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4148: }
4149: $what =~ s/\:$/&/;
4150: }
4151: $what =~ s/\&$//;
4152: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4153: } else {
4154: return $outcome;
4155: }
1.353 www 4156: }
4157:
4158: sub courseiddump {
1.921 raeburn 4159: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4160: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4161: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 4162: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 4163: my $as_hash = 1;
4164: my %returnhash;
4165: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4166: my %libserv = &all_library();
4167: foreach my $tryserver (keys(%libserv)) {
4168: if ( ( $hostidflag == 1
4169: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4170: || (!defined($hostidflag)) ) {
4171:
1.918 raeburn 4172: if (($domfilter eq '') ||
4173: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4174: my $rep;
4175: if (grep { $_ eq $tryserver } current_machine_ids()) {
4176: $rep = LONCAPA::Lond::dump_course_id_handler(
4177: join(":", (&host_domain($tryserver), $sincefilter,
4178: &escape($descfilter), &escape($instcodefilter),
4179: &escape($ownerfilter), &escape($coursefilter),
4180: &escape($typefilter), &escape($regexp_ok),
4181: $as_hash, &escape($selfenrollonly),
4182: &escape($catfilter), $showhidden, $caller,
4183: &escape($cloner), &escape($cc_clone), $cloneonly,
4184: &escape($createdbefore), &escape($createdafter),
4185: &escape($creationcontext), $domcloner)));
4186: } else {
4187: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4188: $sincefilter.':'.&escape($descfilter).':'.
4189: &escape($instcodefilter).':'.&escape($ownerfilter).
4190: ':'.&escape($coursefilter).':'.&escape($typefilter).
4191: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4192: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4193: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4194: &escape($cc_clone).':'.$cloneonly.':'.
4195: &escape($createdbefore).':'.&escape($createdafter).':'.
4196: &escape($creationcontext).':'.$domcloner,
4197: $tryserver);
4198: }
4199:
1.918 raeburn 4200: my @pairs=split(/\&/,$rep);
4201: foreach my $item (@pairs) {
4202: my ($key,$value)=split(/\=/,$item,2);
4203: $key = &unescape($key);
4204: next if ($key =~ /^error: 2 /);
4205: my $result = &thaw_unescape($value);
4206: if (ref($result) eq 'HASH') {
4207: $returnhash{$key}=$result;
4208: } else {
1.921 raeburn 4209: my @responses = split(/:/,$value);
4210: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4211: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4212: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4213: }
1.1008 raeburn 4214: }
1.353 www 4215: }
4216: }
4217: }
4218: }
4219: return %returnhash;
4220: }
4221:
1.1055 raeburn 4222: sub courselastaccess {
4223: my ($cdom,$cnum,$hostidref) = @_;
4224: my %returnhash;
4225: if ($cdom && $cnum) {
4226: my $chome = &homeserver($cnum,$cdom);
4227: if ($chome ne 'no_host') {
4228: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4229: &extract_lastaccess(\%returnhash,$rep);
4230: }
4231: } else {
4232: if (!$cdom) { $cdom=''; }
4233: my %libserv = &all_library();
4234: foreach my $tryserver (keys(%libserv)) {
4235: if (ref($hostidref) eq 'ARRAY') {
4236: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4237: }
4238: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4239: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4240: &extract_lastaccess(\%returnhash,$rep);
4241: }
4242: }
4243: }
4244: return %returnhash;
4245: }
4246:
4247: sub extract_lastaccess {
4248: my ($returnhash,$rep) = @_;
4249: if (ref($returnhash) eq 'HASH') {
4250: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4251: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4252: $rep eq '') {
4253: my @pairs=split(/\&/,$rep);
4254: foreach my $item (@pairs) {
4255: my ($key,$value)=split(/\=/,$item,2);
4256: $key = &unescape($key);
4257: next if ($key =~ /^error: 2 /);
4258: $returnhash->{$key} = &thaw_unescape($value);
4259: }
4260: }
4261: }
4262: return;
4263: }
4264:
1.658 raeburn 4265: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4266:
4267: sub dcmailput {
1.685 raeburn 4268: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4269: my $status = &Apache::lonnet::critical(
1.740 www 4270: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4271: &escape($message),$server);
1.662 raeburn 4272: return $status;
4273: }
4274:
1.658 raeburn 4275: sub dcmaildump {
4276: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4277: my %returnhash=();
1.846 albertel 4278:
4279: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4280: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4281: &escape($enddate).':';
4282: my @esc_senders=map { &escape($_)} @$senders;
4283: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4284: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4285: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4286: if (($key) && ($value)) {
4287: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4288: }
4289: }
4290: }
4291: return %returnhash;
4292: }
1.662 raeburn 4293: # ---------------------------------------------------------- Domain roles
4294:
4295: sub get_domain_roles {
4296: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4297: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4298: $startdate = '.';
4299: }
1.1018 raeburn 4300: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4301: $enddate = '.';
4302: }
1.922 raeburn 4303: my $rolelist;
4304: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4305: $rolelist = join('&',@{$roles});
1.922 raeburn 4306: }
1.662 raeburn 4307: my %personnel = ();
1.841 albertel 4308:
4309: my %servers = &get_servers($dom,'library');
4310: foreach my $tryserver (keys(%servers)) {
4311: %{$personnel{$tryserver}}=();
4312: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4313: &escape($startdate).':'.
4314: &escape($enddate).':'.
4315: &escape($rolelist), $tryserver))) {
4316: my ($key,$value) = split(/\=/,$line,2);
4317: if (($key) && ($value)) {
4318: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4319: }
4320: }
1.662 raeburn 4321: }
4322: return %personnel;
4323: }
1.658 raeburn 4324:
1.1057 www 4325: # ----------------------------------------------------------- Interval timing
1.149 www 4326:
1.1153 www 4327: {
4328: # Caches needed for speedup of navmaps
4329: # We don't want to cache this for very long at all (5 seconds at most)
4330: #
4331: # The user for whom we cache
4332: my $cachedkey='';
4333: # The cached times for this user
4334: my %cachedtimes=();
4335: # When this was last done
4336: my $cachedtime=();
4337:
4338: sub load_all_first_access {
1.1154 raeburn 4339: my ($uname,$udom)=@_;
1.1156 www 4340: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4341: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4342: return;
4343: }
4344: $cachedtime=time;
4345: $cachedkey=$uname.':'.$udom;
4346: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4347: }
4348:
1.504 albertel 4349: sub get_first_access {
1.1162 raeburn 4350: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4351: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4352: if ($argsymb) { $symb=$argsymb; }
4353: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4354: if ($argmap) { $map = $argmap; }
1.926 albertel 4355: if ($type eq 'course') {
4356: $res='course';
4357: } elsif ($type eq 'map') {
1.588 albertel 4358: $res=&symbread($map);
4359: } else {
4360: $res=$symb;
4361: }
1.1153 www 4362: &load_all_first_access($uname,$udom);
4363: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4364: }
4365:
4366: sub set_first_access {
1.1162 raeburn 4367: my ($type,$interval)=@_;
1.790 albertel 4368: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4369: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4370: if ($type eq 'course') {
4371: $res='course';
4372: } elsif ($type eq 'map') {
1.588 albertel 4373: $res=&symbread($map);
4374: } else {
4375: $res=$symb;
4376: }
1.1153 www 4377: $cachedkey='';
1.1162 raeburn 4378: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4379: if (!$firstaccess) {
1.1162 raeburn 4380: my $start = time;
4381: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4382: $udom,$uname);
4383: if ($putres eq 'ok') {
4384: &put('timerinterval',{"$courseid\0$res"=>$interval},
4385: $udom,$uname);
4386: &appenv(
4387: {
4388: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4389: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4390: }
4391: );
4392: }
4393: return $putres;
1.505 albertel 4394: }
4395: return 'already_set';
1.504 albertel 4396: }
1.1153 www 4397: }
1.110 www 4398: # --------------------------------------------- Set Expire Date for Spreadsheet
4399:
4400: sub expirespread {
4401: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4402: my $cid=$env{'request.course.id'};
1.110 www 4403: if ($cid) {
4404: my $now=time;
4405: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4406: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4407: $env{'course.'.$cid.'.num'}.
1.110 www 4408: ':nohist_expirationdates:'.
4409: &escape($key).'='.$now,
1.620 albertel 4410: $env{'course.'.$cid.'.home'})
1.110 www 4411: }
4412: return 'ok';
1.14 www 4413: }
4414:
1.109 www 4415: # ----------------------------------------------------- Devalidate Spreadsheets
4416:
4417: sub devalidate {
1.325 www 4418: my ($symb,$uname,$udom)=@_;
1.620 albertel 4419: my $cid=$env{'request.course.id'};
1.109 www 4420: if ($cid) {
1.391 matthew 4421: # delete the stored spreadsheets for
4422: # - the student level sheet of this user in course's homespace
4423: # - the assessment level sheet for this resource
4424: # for this user in user's homespace
1.553 albertel 4425: # - current conditional state info
1.325 www 4426: my $key=$uname.':'.$udom.':';
1.109 www 4427: my $status=
1.299 matthew 4428: &del('nohist_calculatedsheets',
1.391 matthew 4429: [$key.'studentcalc:'],
1.620 albertel 4430: $env{'course.'.$cid.'.domain'},
4431: $env{'course.'.$cid.'.num'})
1.133 albertel 4432: .' '.
4433: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4434: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4435: unless ($status eq 'ok ok') {
4436: &logthis('Could not devalidate spreadsheet '.
1.325 www 4437: $uname.' at '.$udom.' for '.
1.109 www 4438: $symb.': '.$status);
1.133 albertel 4439: }
1.553 albertel 4440: &delenv('user.state.'.$cid);
1.109 www 4441: }
4442: }
4443:
1.265 albertel 4444: sub get_scalar {
4445: my ($string,$end) = @_;
4446: my $value;
4447: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4448: $value = $1;
4449: } elsif ($$string =~ s/^([^&]*?)&//) {
4450: $value = $1;
4451: }
4452: return &unescape($value);
4453: }
4454:
4455: sub array2str {
4456: my (@array) = @_;
4457: my $result=&arrayref2str(\@array);
4458: $result=~s/^__ARRAY_REF__//;
4459: $result=~s/__END_ARRAY_REF__$//;
4460: return $result;
4461: }
4462:
1.204 albertel 4463: sub arrayref2str {
4464: my ($arrayref) = @_;
1.265 albertel 4465: my $result='__ARRAY_REF__';
1.204 albertel 4466: foreach my $elem (@$arrayref) {
1.265 albertel 4467: if(ref($elem) eq 'ARRAY') {
4468: $result.=&arrayref2str($elem).'&';
4469: } elsif(ref($elem) eq 'HASH') {
4470: $result.=&hashref2str($elem).'&';
4471: } elsif(ref($elem)) {
4472: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4473: } else {
4474: $result.=&escape($elem).'&';
4475: }
4476: }
4477: $result=~s/\&$//;
1.265 albertel 4478: $result .= '__END_ARRAY_REF__';
1.204 albertel 4479: return $result;
4480: }
4481:
1.168 albertel 4482: sub hash2str {
1.204 albertel 4483: my (%hash) = @_;
4484: my $result=&hashref2str(\%hash);
1.265 albertel 4485: $result=~s/^__HASH_REF__//;
4486: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4487: return $result;
4488: }
4489:
4490: sub hashref2str {
4491: my ($hashref)=@_;
1.265 albertel 4492: my $result='__HASH_REF__';
1.800 albertel 4493: foreach my $key (sort(keys(%$hashref))) {
4494: if (ref($key) eq 'ARRAY') {
4495: $result.=&arrayref2str($key).'=';
4496: } elsif (ref($key) eq 'HASH') {
4497: $result.=&hashref2str($key).'=';
4498: } elsif (ref($key)) {
1.265 albertel 4499: $result.='=';
1.800 albertel 4500: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4501: } else {
1.1132 raeburn 4502: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4503: }
4504:
1.800 albertel 4505: if(ref($hashref->{$key}) eq 'ARRAY') {
4506: $result.=&arrayref2str($hashref->{$key}).'&';
4507: } elsif(ref($hashref->{$key}) eq 'HASH') {
4508: $result.=&hashref2str($hashref->{$key}).'&';
4509: } elsif(ref($hashref->{$key})) {
1.265 albertel 4510: $result.='&';
1.800 albertel 4511: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4512: } else {
1.800 albertel 4513: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4514: }
4515: }
1.168 albertel 4516: $result=~s/\&$//;
1.265 albertel 4517: $result .= '__END_HASH_REF__';
1.168 albertel 4518: return $result;
4519: }
4520:
4521: sub str2hash {
1.265 albertel 4522: my ($string)=@_;
4523: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4524: return %$hash;
4525: }
4526:
4527: sub str2hashref {
1.168 albertel 4528: my ($string) = @_;
1.265 albertel 4529:
4530: my %hash;
4531:
4532: if($string !~ /^__HASH_REF__/) {
4533: if (! ($string eq '' || !defined($string))) {
4534: $hash{'error'}='Not hash reference';
4535: }
4536: return (\%hash, $string);
4537: }
4538:
4539: $string =~ s/^__HASH_REF__//;
4540:
4541: while($string !~ /^__END_HASH_REF__/) {
4542: #key
4543: my $key='';
4544: if($string =~ /^__HASH_REF__/) {
4545: ($key, $string)=&str2hashref($string);
4546: if(defined($key->{'error'})) {
4547: $hash{'error'}='Bad data';
4548: return (\%hash, $string);
4549: }
4550: } elsif($string =~ /^__ARRAY_REF__/) {
4551: ($key, $string)=&str2arrayref($string);
4552: if($key->[0] eq 'Array reference error') {
4553: $hash{'error'}='Bad data';
4554: return (\%hash, $string);
4555: }
4556: } else {
4557: $string =~ s/^(.*?)=//;
1.267 albertel 4558: $key=&unescape($1);
1.265 albertel 4559: }
4560: $string =~ s/^=//;
4561:
4562: #value
4563: my $value='';
4564: if($string =~ /^__HASH_REF__/) {
4565: ($value, $string)=&str2hashref($string);
4566: if(defined($value->{'error'})) {
4567: $hash{'error'}='Bad data';
4568: return (\%hash, $string);
4569: }
4570: } elsif($string =~ /^__ARRAY_REF__/) {
4571: ($value, $string)=&str2arrayref($string);
4572: if($value->[0] eq 'Array reference error') {
4573: $hash{'error'}='Bad data';
4574: return (\%hash, $string);
4575: }
4576: } else {
4577: $value=&get_scalar(\$string,'__END_HASH_REF__');
4578: }
4579: $string =~ s/^&//;
4580:
4581: $hash{$key}=$value;
1.204 albertel 4582: }
1.265 albertel 4583:
4584: $string =~ s/^__END_HASH_REF__//;
4585:
4586: return (\%hash, $string);
1.204 albertel 4587: }
4588:
4589: sub str2array {
1.265 albertel 4590: my ($string)=@_;
4591: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4592: return @$array;
4593: }
4594:
4595: sub str2arrayref {
1.204 albertel 4596: my ($string) = @_;
1.265 albertel 4597: my @array;
4598:
4599: if($string !~ /^__ARRAY_REF__/) {
4600: if (! ($string eq '' || !defined($string))) {
4601: $array[0]='Array reference error';
4602: }
4603: return (\@array, $string);
4604: }
4605:
4606: $string =~ s/^__ARRAY_REF__//;
4607:
4608: while($string !~ /^__END_ARRAY_REF__/) {
4609: my $value='';
4610: if($string =~ /^__HASH_REF__/) {
4611: ($value, $string)=&str2hashref($string);
4612: if(defined($value->{'error'})) {
4613: $array[0] ='Array reference error';
4614: return (\@array, $string);
4615: }
4616: } elsif($string =~ /^__ARRAY_REF__/) {
4617: ($value, $string)=&str2arrayref($string);
4618: if($value->[0] eq 'Array reference error') {
4619: $array[0] ='Array reference error';
4620: return (\@array, $string);
4621: }
4622: } else {
4623: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4624: }
4625: $string =~ s/^&//;
4626:
4627: push(@array, $value);
1.191 harris41 4628: }
1.265 albertel 4629:
4630: $string =~ s/^__END_ARRAY_REF__//;
4631:
4632: return (\@array, $string);
1.168 albertel 4633: }
4634:
1.167 albertel 4635: # -------------------------------------------------------------------Temp Store
4636:
1.168 albertel 4637: sub tmpreset {
4638: my ($symb,$namespace,$domain,$stuname) = @_;
4639: if (!$symb) {
4640: $symb=&symbread();
1.620 albertel 4641: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4642: }
4643: $symb=escape($symb);
4644:
1.620 albertel 4645: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4646: $namespace=~s/\//\_/g;
4647: $namespace=~s/\W//g;
4648:
1.620 albertel 4649: if (!$domain) { $domain=$env{'user.domain'}; }
4650: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4651: if ($domain eq 'public' && $stuname eq 'public') {
4652: $stuname=$ENV{'REMOTE_ADDR'};
4653: }
1.1117 foxr 4654: my $path=LONCAPA::tempdir();
1.168 albertel 4655: my %hash;
4656: if (tie(%hash,'GDBM_File',
4657: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4658: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4659: foreach my $key (keys(%hash)) {
1.180 albertel 4660: if ($key=~ /:$symb/) {
1.168 albertel 4661: delete($hash{$key});
4662: }
4663: }
4664: }
4665: }
4666:
1.167 albertel 4667: sub tmpstore {
1.168 albertel 4668: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4669:
4670: if (!$symb) {
4671: $symb=&symbread();
1.620 albertel 4672: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4673: }
4674: $symb=escape($symb);
4675:
4676: if (!$namespace) {
4677: # I don't think we would ever want to store this for a course.
4678: # it seems this will only be used if we don't have a course.
1.620 albertel 4679: #$namespace=$env{'request.course.id'};
1.168 albertel 4680: #if (!$namespace) {
1.620 albertel 4681: $namespace=$env{'request.state'};
1.168 albertel 4682: #}
4683: }
4684: $namespace=~s/\//\_/g;
4685: $namespace=~s/\W//g;
1.620 albertel 4686: if (!$domain) { $domain=$env{'user.domain'}; }
4687: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4688: if ($domain eq 'public' && $stuname eq 'public') {
4689: $stuname=$ENV{'REMOTE_ADDR'};
4690: }
1.168 albertel 4691: my $now=time;
4692: my %hash;
1.1117 foxr 4693: my $path=LONCAPA::tempdir();
1.168 albertel 4694: if (tie(%hash,'GDBM_File',
4695: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4696: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4697: $hash{"version:$symb"}++;
4698: my $version=$hash{"version:$symb"};
4699: my $allkeys='';
4700: foreach my $key (keys(%$storehash)) {
4701: $allkeys.=$key.':';
1.591 albertel 4702: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4703: }
4704: $hash{"$version:$symb:timestamp"}=$now;
4705: $allkeys.='timestamp';
4706: $hash{"$version:keys:$symb"}=$allkeys;
4707: if (untie(%hash)) {
4708: return 'ok';
4709: } else {
4710: return "error:$!";
4711: }
4712: } else {
4713: return "error:$!";
4714: }
4715: }
1.167 albertel 4716:
1.168 albertel 4717: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4718:
1.168 albertel 4719: sub tmprestore {
4720: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4721:
1.168 albertel 4722: if (!$symb) {
4723: $symb=&symbread();
1.620 albertel 4724: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4725: }
4726: $symb=escape($symb);
4727:
1.620 albertel 4728: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4729:
1.620 albertel 4730: if (!$domain) { $domain=$env{'user.domain'}; }
4731: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4732: if ($domain eq 'public' && $stuname eq 'public') {
4733: $stuname=$ENV{'REMOTE_ADDR'};
4734: }
1.168 albertel 4735: my %returnhash;
4736: $namespace=~s/\//\_/g;
4737: $namespace=~s/\W//g;
4738: my %hash;
1.1117 foxr 4739: my $path=LONCAPA::tempdir();
1.168 albertel 4740: if (tie(%hash,'GDBM_File',
4741: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4742: &GDBM_READER(),0640)) {
1.168 albertel 4743: my $version=$hash{"version:$symb"};
4744: $returnhash{'version'}=$version;
4745: my $scope;
4746: for ($scope=1;$scope<=$version;$scope++) {
4747: my $vkeys=$hash{"$scope:keys:$symb"};
4748: my @keys=split(/:/,$vkeys);
4749: my $key;
4750: $returnhash{"$scope:keys"}=$vkeys;
4751: foreach $key (@keys) {
1.591 albertel 4752: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4753: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4754: }
4755: }
1.168 albertel 4756: if (!(untie(%hash))) {
4757: return "error:$!";
4758: }
4759: } else {
4760: return "error:$!";
4761: }
4762: return %returnhash;
1.167 albertel 4763: }
4764:
1.9 www 4765: # ----------------------------------------------------------------------- Store
4766:
4767: sub store {
1.124 www 4768: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4769: my $home='';
4770:
1.168 albertel 4771: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4772:
1.213 www 4773: $symb=&symbclean($symb);
1.122 albertel 4774: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4775:
1.620 albertel 4776: if (!$domain) { $domain=$env{'user.domain'}; }
4777: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4778:
4779: &devalidate($symb,$stuname,$domain);
1.109 www 4780:
4781: $symb=escape($symb);
1.187 www 4782: if (!$namespace) {
1.620 albertel 4783: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4784: return '';
4785: }
4786: }
1.620 albertel 4787: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4788:
4789: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4790: $$storehash{'host'}=$perlvar{'lonHostID'};
4791:
1.12 www 4792: my $namevalue='';
1.800 albertel 4793: foreach my $key (keys(%$storehash)) {
4794: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4795: }
1.12 www 4796: $namevalue=~s/\&$//;
1.187 www 4797: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4798: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4799: }
4800:
1.47 www 4801: # -------------------------------------------------------------- Critical Store
4802:
4803: sub cstore {
1.124 www 4804: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4805: my $home='';
4806:
1.168 albertel 4807: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4808:
1.213 www 4809: $symb=&symbclean($symb);
1.122 albertel 4810: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4811:
1.620 albertel 4812: if (!$domain) { $domain=$env{'user.domain'}; }
4813: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4814:
4815: &devalidate($symb,$stuname,$domain);
1.109 www 4816:
4817: $symb=escape($symb);
1.187 www 4818: if (!$namespace) {
1.620 albertel 4819: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4820: return '';
4821: }
4822: }
1.620 albertel 4823: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4824:
4825: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4826: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4827:
1.47 www 4828: my $namevalue='';
1.800 albertel 4829: foreach my $key (keys(%$storehash)) {
4830: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4831: }
1.47 www 4832: $namevalue=~s/\&$//;
1.187 www 4833: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4834: return critical
4835: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4836: }
4837:
1.9 www 4838: # --------------------------------------------------------------------- Restore
4839:
4840: sub restore {
1.124 www 4841: my ($symb,$namespace,$domain,$stuname) = @_;
4842: my $home='';
4843:
1.168 albertel 4844: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4845:
1.122 albertel 4846: if (!$symb) {
1.1224 raeburn 4847: return if ($namespace eq 'courserequests');
4848: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4849: } else {
1.1224 raeburn 4850: unless ($namespace eq 'courserequests') {
4851: $symb=&escape(&symbclean($symb));
4852: }
1.122 albertel 4853: }
1.188 www 4854: if (!$namespace) {
1.620 albertel 4855: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4856: return '';
4857: }
4858: }
1.620 albertel 4859: if (!$domain) { $domain=$env{'user.domain'}; }
4860: if (!$stuname) { $stuname=$env{'user.name'}; }
4861: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4862: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4863:
1.12 www 4864: my %returnhash=();
1.800 albertel 4865: foreach my $line (split(/\&/,$answer)) {
4866: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4867: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4868: }
1.75 www 4869: my $version;
4870: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4871: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4872: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4873: }
1.75 www 4874: }
1.13 www 4875: return %returnhash;
1.34 www 4876: }
4877:
4878: # ---------------------------------------------------------- Course Description
1.1118 foxr 4879: #
4880: #
1.34 www 4881:
4882: sub coursedescription {
1.731 albertel 4883: my ($courseid,$args)=@_;
1.34 www 4884: $courseid=~s/^\///;
1.49 www 4885: $courseid=~s/\_/\//g;
1.34 www 4886: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4887: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4888: my $normalid=$cdomain.'_'.$cnum;
4889: # need to always cache even if we get errors otherwise we keep
4890: # trying and trying and trying to get the course description.
4891: my %envhash=();
4892: my %returnhash=();
1.731 albertel 4893:
4894: my $expiretime=600;
4895: if ($env{'request.course.id'} eq $normalid) {
4896: $expiretime=120;
4897: }
4898:
4899: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4900: if (!$args->{'freshen_cache'}
4901: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4902: foreach my $key (keys(%env)) {
4903: next if ($key !~ /^\Q$prefix\E(.*)/);
4904: my ($setting) = $1;
4905: $returnhash{$setting} = $env{$key};
4906: }
4907: return %returnhash;
4908: }
4909:
1.1118 foxr 4910: # get the data again
4911:
1.731 albertel 4912: if (!$args->{'one_time'}) {
4913: $envhash{'course.'.$normalid.'.last_cache'}=time;
4914: }
1.811 albertel 4915:
1.34 www 4916: if ($chome ne 'no_host') {
1.302 albertel 4917: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4918: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4919: my $username = $env{'user.name'}; # Defult username
4920: if(defined $args->{'user'}) {
4921: $username = $args->{'user'};
4922: }
1.129 albertel 4923: $returnhash{'home'}= $chome;
4924: $returnhash{'domain'} = $cdomain;
4925: $returnhash{'num'} = $cnum;
1.741 raeburn 4926: if (!defined($returnhash{'type'})) {
4927: $returnhash{'type'} = 'Course';
4928: }
1.130 albertel 4929: while (my ($name,$value) = each %returnhash) {
1.53 www 4930: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4931: }
1.270 www 4932: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4933: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4934: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4935: $envhash{'course.'.$normalid.'.home'}=$chome;
4936: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4937: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4938: }
4939: }
1.731 albertel 4940: if (!$args->{'one_time'}) {
1.949 raeburn 4941: &appenv(\%envhash);
1.731 albertel 4942: }
1.302 albertel 4943: return %returnhash;
1.461 www 4944: }
4945:
1.1080 raeburn 4946: sub update_released_required {
4947: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4948: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4949: $cid = $env{'request.course.id'};
4950: $cdom = $env{'course.'.$cid.'.domain'};
4951: $cnum = $env{'course.'.$cid.'.num'};
4952: $chome = $env{'course.'.$cid.'.home'};
4953: }
4954: if ($needsrelease) {
4955: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4956: my $needsupdate;
4957: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4958: $needsupdate = 1;
4959: } else {
4960: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4961: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4962: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4963: $needsupdate = 1;
4964: }
4965: }
4966: if ($needsupdate) {
4967: my %needshash = (
4968: 'internal.releaserequired' => $needsrelease,
4969: );
4970: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4971: if ($putresult eq 'ok') {
4972: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4973: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4974: if (ref($crsinfo{$cid}) eq 'HASH') {
4975: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4976: &courseidput($cdom,\%crsinfo,$chome,'notime');
4977: }
4978: }
4979: }
4980: }
4981: return;
4982: }
4983:
1.461 www 4984: # -------------------------------------------------See if a user is privileged
4985:
4986: sub privileged {
1.1219 raeburn 4987: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 4988: my $now = time;
1.1219 raeburn 4989: my $roles;
4990: if (ref($possroles) eq 'ARRAY') {
4991: $roles = $possroles;
4992: } else {
4993: $roles = ['dc','su'];
4994: }
4995: if (ref($possdomains) eq 'ARRAY') {
4996: my %privileged = &privileged_by_domain($possdomains,$roles);
4997: foreach my $dom (@{$possdomains}) {
4998: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
4999: (ref($privileged{$dom}) eq 'HASH')) {
5000: foreach my $role (@{$roles}) {
5001: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5002: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5003: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5004: return 1 unless (($end && $end < $now) ||
5005: ($start && $start > $now));
5006: }
5007: }
5008: }
5009: }
5010: }
5011: } else {
5012: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5013: my $now = time;
1.1170 droeschl 5014:
1.1219 raeburn 5015: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5016: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5017: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5018: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5019: or ($tstart && $tstart > $now);
1.1170 droeschl 5020: }
1.1219 raeburn 5021: }
5022: }
5023: return 0;
5024: }
1.1170 droeschl 5025:
1.1219 raeburn 5026: sub privileged_by_domain {
5027: my ($domains,$roles) = @_;
5028: my %privileged = ();
5029: my $cachetime = 60*60*24;
5030: my $now = time;
5031: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5032: return %privileged;
5033: }
5034: foreach my $dom (@{$domains}) {
5035: next if (ref($privileged{$dom}) eq 'HASH');
5036: my $needroles;
5037: foreach my $role (@{$roles}) {
5038: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5039: if (defined($cached)) {
5040: if (ref($result) eq 'HASH') {
5041: $privileged{$dom}{$role} = $result;
5042: }
5043: } else {
5044: $needroles = 1;
5045: }
5046: }
5047: if ($needroles) {
5048: my %dompersonnel = &get_domain_roles($dom,$roles);
5049: $privileged{$dom} = {};
5050: foreach my $server (keys(%dompersonnel)) {
5051: if (ref($dompersonnel{$server}) eq 'HASH') {
5052: foreach my $item (keys(%{$dompersonnel{$server}})) {
5053: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5054: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5055: next if ($end && $end < $now);
5056: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5057: $dompersonnel{$server}{$item};
5058: }
5059: }
5060: }
5061: if (ref($privileged{$dom}) eq 'HASH') {
5062: foreach my $role (@{$roles}) {
5063: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5064: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5065: } else {
5066: my %hash = ();
5067: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5068: }
5069: }
5070: }
5071: }
5072: }
5073: return %privileged;
1.9 www 5074: }
1.1 albertel 5075:
1.103 harris41 5076: # -------------------------------------------------------- Get user privileges
1.11 www 5077:
5078: sub rolesinit {
1.1169 droeschl 5079: my ($domain, $username) = @_;
5080: my %userroles = ('user.login.time' => time);
5081: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5082:
5083: # firstaccess and timerinterval are related to timed maps/resources.
5084: # also, blocking can be triggered by an activating timer
5085: # it's saved in the user's %env.
5086: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5087: my %timerinterval = &dump('timerinterval', $domain, $username);
5088: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5089: %timerintchk, %timerintenv);
5090:
1.1162 raeburn 5091: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5092: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5093: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5094: }
1.1169 droeschl 5095:
1.1162 raeburn 5096: foreach my $key (keys(%timerinterval)) {
5097: my ($cid,$rest) = split(/\0/,$key);
5098: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5099: }
1.1169 droeschl 5100:
1.11 www 5101: my %allroles=();
1.1162 raeburn 5102: my %allgroups=();
1.11 www 5103:
1.1169 droeschl 5104: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5105: my $role = $rolesdump{$area};
5106: $area =~ s/\_\w\w$//;
5107:
5108: my ($trole, $tend, $tstart, $group_privs);
5109:
5110: if ($role =~ /^cr/) {
5111: # Custom role, defined by a user
5112: # e.g., user.role.cr/msu/smith/mynewrole
5113: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5114: $trole = $1;
5115: ($tend, $tstart) = split('_', $2);
5116: } else {
5117: $trole = $role;
5118: }
5119: } elsif ($role =~ m|^gr/|) {
5120: # Role of member in a group, defined within a course/community
5121: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5122: ($trole, $tend, $tstart) = split(/_/, $role);
5123: next if $tstart eq '-1';
5124: ($trole, $group_privs) = split(/\//, $trole);
5125: $group_privs = &unescape($group_privs);
5126: } else {
5127: # Just a normal role, defined in roles.tab
5128: ($trole, $tend, $tstart) = split(/_/,$role);
5129: }
5130:
5131: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5132: $username);
5133: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5134:
5135: # role expired or not available yet?
5136: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5137: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5138:
5139: next if $area eq '' or $trole eq '';
5140:
5141: my $spec = "$trole.$area";
5142: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5143:
5144: if ($trole =~ /^cr\//) {
5145: # Custom role, defined by a user
5146: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5147: } elsif ($trole eq 'gr') {
5148: # Role of a member in a group, defined within a course/community
5149: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5150: next;
5151: } else {
5152: # Normal role, defined in roles.tab
5153: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5154: }
5155:
5156: my $cid = $tdomain.'_'.$trest;
5157: unless ($firstaccchk{$cid}) {
5158: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5159: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5160: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5161: $coursetimerstarts{$cid}{$item};
5162: }
5163: }
5164: $firstaccchk{$cid} = 1;
5165: }
5166: unless ($timerintchk{$cid}) {
5167: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5168: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5169: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5170: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5171: }
1.12 www 5172: }
1.1169 droeschl 5173: $timerintchk{$cid} = 1;
1.191 harris41 5174: }
1.11 www 5175: }
1.1169 droeschl 5176:
5177: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5178: \%allroles, \%allgroups);
5179: $env{'user.adv'} = $userroles{'user.adv'};
5180:
1.1162 raeburn 5181: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5182: }
5183:
1.567 raeburn 5184: sub set_arearole {
1.1215 raeburn 5185: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5186: unless ($nolog) {
1.567 raeburn 5187: # log the associated role with the area
1.1215 raeburn 5188: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5189: }
1.743 albertel 5190: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5191: }
5192:
5193: sub custom_roleprivs {
5194: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5195: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5196: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 5197: if (&hostname($homsvr) ne '') {
1.567 raeburn 5198: my ($rdummy,$roledef)=
5199: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5200: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5201: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5202: if (defined($syspriv)) {
1.1043 raeburn 5203: if ($trest =~ /^$match_community$/) {
5204: $syspriv =~ s/bre\&S//;
5205: }
1.567 raeburn 5206: $$allroles{'cm./'}.=':'.$syspriv;
5207: $$allroles{$spec.'./'}.=':'.$syspriv;
5208: }
5209: if ($tdomain ne '') {
5210: if (defined($dompriv)) {
5211: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5212: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5213: }
5214: if (($trest ne '') && (defined($coursepriv))) {
5215: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5216: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5217: }
5218: }
5219: }
5220: }
5221: }
5222:
1.678 raeburn 5223: sub group_roleprivs {
5224: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5225: my $access = 1;
5226: my $now = time;
5227: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5228: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5229: if ($access) {
1.811 albertel 5230: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5231: $$allgroups{$course}{$group} .=':'.$group_privs;
5232: }
5233: }
1.567 raeburn 5234:
5235: sub standard_roleprivs {
5236: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5237: if (defined($pr{$trole.':s'})) {
5238: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5239: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5240: }
5241: if ($tdomain ne '') {
5242: if (defined($pr{$trole.':d'})) {
5243: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5244: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5245: }
5246: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5247: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5248: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5249: }
5250: }
5251: }
5252:
5253: sub set_userprivs {
1.1064 raeburn 5254: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5255: my $author=0;
5256: my $adv=0;
1.678 raeburn 5257: my %grouproles = ();
5258: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5259: my @groupkeys;
1.1000 raeburn 5260: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5261: push(@groupkeys,$role);
5262: }
5263: if (ref($groups_roles) eq 'HASH') {
5264: foreach my $key (keys(%{$groups_roles})) {
5265: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5266: push(@groupkeys,$key);
5267: }
5268: }
5269: }
5270: if (@groupkeys > 0) {
5271: foreach my $role (@groupkeys) {
5272: my ($trole,$area,$sec,$extendedarea);
5273: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5274: $trole = $1;
5275: $area = $2;
5276: $sec = $3;
5277: $extendedarea = $area.$sec;
5278: if (exists($$allgroups{$area})) {
5279: foreach my $group (keys(%{$$allgroups{$area}})) {
5280: my $spec = $trole.'.'.$extendedarea;
5281: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5282: $$allgroups{$area}{$group};
1.1064 raeburn 5283: }
1.678 raeburn 5284: }
5285: }
5286: }
5287: }
5288: }
1.800 albertel 5289: foreach my $group (keys(%grouproles)) {
5290: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5291: }
1.800 albertel 5292: foreach my $role (keys(%{$allroles})) {
5293: my %thesepriv;
1.941 raeburn 5294: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5295: foreach my $item (split(/:/,$$allroles{$role})) {
5296: if ($item ne '') {
5297: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5298: if ($restrictions eq '') {
5299: $thesepriv{$privilege}='F';
5300: } elsif ($thesepriv{$privilege} ne 'F') {
5301: $thesepriv{$privilege}.=$restrictions;
5302: }
5303: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5304: }
5305: }
5306: my $thesestr='';
1.1104 raeburn 5307: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5308: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5309: }
5310: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5311: }
5312: return ($author,$adv);
5313: }
5314:
1.994 raeburn 5315: sub role_status {
1.1104 raeburn 5316: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5317: my @pwhere = ();
5318: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5319: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5320: unless (!defined($$role) || $$role eq '') {
5321: $$where=join('.',@pwhere);
5322: $$trolecode=$$role.'.'.$$where;
5323: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5324: $$tstatus='is';
1.1104 raeburn 5325: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5326: $$tstatus='future';
1.1034 raeburn 5327: if ($$tstart<$now) {
5328: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5329: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5330: my (%allroles,%allgroups,$group_privs,
5331: %groups_roles,@rolecodes);
1.1002 raeburn 5332: my %userroles = (
5333: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5334: );
1.1064 raeburn 5335: @rolecodes = ('cm');
1.1002 raeburn 5336: my $spec=$$role.'.'.$$where;
5337: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5338: if ($$role =~ /^cr\//) {
5339: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5340: push(@rolecodes,'cr');
1.1002 raeburn 5341: } elsif ($$role eq 'gr') {
1.1064 raeburn 5342: push(@rolecodes,$$role);
1.1002 raeburn 5343: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5344: $env{'user.name'});
1.1064 raeburn 5345: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5346: (undef,my $group_privs) = split(/\//,$trole);
5347: $group_privs = &unescape($group_privs);
5348: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5349: 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 5350: &get_groups_roles($tdomain,$trest,
5351: \%course_roles,\@rolecodes,
5352: \%groups_roles);
1.1002 raeburn 5353: } else {
1.1064 raeburn 5354: push(@rolecodes,$$role);
1.1002 raeburn 5355: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5356: }
1.1064 raeburn 5357: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5358: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5359: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5360: }
5361: }
1.1034 raeburn 5362: $$tstatus = 'is';
1.1002 raeburn 5363: }
1.994 raeburn 5364: }
5365: if ($$tend) {
1.1104 raeburn 5366: if ($$tend<$update) {
1.994 raeburn 5367: $$tstatus='expired';
5368: } elsif ($$tend<$now) {
5369: $$tstatus='will_not';
5370: }
5371: }
5372: }
5373: }
5374: }
5375:
1.1104 raeburn 5376: sub get_groups_roles {
5377: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5378: return unless((ref($cdom_courseroles) eq 'HASH') &&
5379: (ref($rolecodes) eq 'ARRAY') &&
5380: (ref($groups_roles) eq 'HASH'));
5381: if (keys(%{$cdom_courseroles}) > 0) {
5382: my ($cnum) = ($rest =~ /^($match_courseid)/);
5383: if ($cdom ne '' && $cnum ne '') {
5384: foreach my $key (keys(%{$cdom_courseroles})) {
5385: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5386: my $crsrole = $1;
5387: my $crssec = $2;
5388: if ($crsrole =~ /^cr/) {
5389: unless (grep(/^cr$/,@{$rolecodes})) {
5390: push(@{$rolecodes},'cr');
5391: }
5392: } else {
5393: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5394: push(@{$rolecodes},$crsrole);
5395: }
5396: }
5397: my $rolekey = "$crsrole./$cdom/$cnum";
5398: if ($crssec ne '') {
5399: $rolekey .= "/$crssec";
5400: }
5401: $rolekey .= './';
5402: $groups_roles->{$rolekey} = $rolecodes;
5403: }
5404: }
5405: }
5406: }
5407: return;
5408: }
5409:
5410: sub delete_env_groupprivs {
5411: my ($where,$courseroles,$possroles) = @_;
5412: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5413: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5414: unless (ref($courseroles->{$udom}) eq 'HASH') {
5415: %{$courseroles->{$udom}} =
5416: &get_my_roles('','','userroles',['active'],
5417: $possroles,[$udom],1);
5418: }
5419: if (ref($courseroles->{$udom}) eq 'HASH') {
5420: foreach my $item (keys(%{$courseroles->{$udom}})) {
5421: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5422: my $area = '/'.$cdom.'/'.$cnum;
5423: my $privkey = "user.priv.$crsrole.$area";
5424: if ($crssec ne '') {
5425: $privkey .= '/'.$crssec;
5426: }
5427: $privkey .= ".$area/$group";
5428: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5429: }
5430: }
5431: return;
5432: }
5433:
1.994 raeburn 5434: sub check_adhoc_privs {
1.1104 raeburn 5435: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5436: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5437: my $setprivs;
1.994 raeburn 5438: if ($env{$cckey}) {
5439: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5440: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5441: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5442: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5443: $setprivs = 1;
1.994 raeburn 5444: }
5445: } else {
1.1088 raeburn 5446: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5447: $setprivs = 1;
1.994 raeburn 5448: }
1.1185 raeburn 5449: return $setprivs;
1.994 raeburn 5450: }
5451:
5452: sub set_adhoc_privileges {
5453: # role can be cc or ca
1.1088 raeburn 5454: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5455: my $area = '/'.$dcdom.'/'.$pickedcourse;
5456: my $spec = $role.'.'.$area;
5457: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5458: $env{'user.name'},1);
1.994 raeburn 5459: my %ccrole = ();
5460: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5461: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5462: &appenv(\%userroles,[$role,'cm']);
5463: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5464: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5465: &appenv( {'request.role' => $spec,
5466: 'request.role.domain' => $dcdom,
5467: 'request.course.sec' => ''
5468: }
5469: );
5470: my $tadv=0;
5471: if (&allowed('adv') eq 'F') { $tadv=1; }
5472: &appenv({'request.role.adv' => $tadv});
5473: }
1.994 raeburn 5474: }
5475:
1.12 www 5476: # --------------------------------------------------------------- get interface
5477:
5478: sub get {
1.131 albertel 5479: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5480: my $items='';
1.800 albertel 5481: foreach my $item (@$storearr) {
5482: $items.=&escape($item).'&';
1.191 harris41 5483: }
1.12 www 5484: $items=~s/\&$//;
1.620 albertel 5485: if (!$udomain) { $udomain=$env{'user.domain'}; }
5486: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5487: my $uhome=&homeserver($uname,$udomain);
5488:
1.133 albertel 5489: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5490: my @pairs=split(/\&/,$rep);
1.273 albertel 5491: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5492: return @pairs;
5493: }
1.15 www 5494: my %returnhash=();
1.42 www 5495: my $i=0;
1.800 albertel 5496: foreach my $item (@$storearr) {
5497: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5498: $i++;
1.191 harris41 5499: }
1.15 www 5500: return %returnhash;
1.27 www 5501: }
5502:
5503: # --------------------------------------------------------------- del interface
5504:
5505: sub del {
1.133 albertel 5506: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5507: my $items='';
1.800 albertel 5508: foreach my $item (@$storearr) {
5509: $items.=&escape($item).'&';
1.191 harris41 5510: }
1.984 neumanie 5511:
1.27 www 5512: $items=~s/\&$//;
1.620 albertel 5513: if (!$udomain) { $udomain=$env{'user.domain'}; }
5514: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5515: my $uhome=&homeserver($uname,$udomain);
5516: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5517: }
5518:
5519: # -------------------------------------------------------------- dump interface
5520:
1.1180 droeschl 5521: sub unserialize {
5522: my ($rep, $escapedkeys) = @_;
5523:
5524: return {} if $rep =~ /^error/;
5525:
5526: my %returnhash=();
5527: foreach my $item (split /\&/, $rep) {
5528: my ($key, $value) = split(/=/, $item, 2);
5529: $key = unescape($key) unless $escapedkeys;
5530: next if $key =~ /^error: 2 /;
5531: $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
5532: }
5533: #return %returnhash;
5534: return \%returnhash;
5535: }
5536:
5537: # see Lond::dump_with_regexp
5538: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5539: sub dump {
1.1180 droeschl 5540: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5541: if (!$udomain) { $udomain=$env{'user.domain'}; }
5542: if (!$uname) { $uname=$env{'user.name'}; }
5543: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5544:
1.1180 droeschl 5545: my $reply;
5546: if (grep { $_ eq $uhome } current_machine_ids()) {
5547: # user is hosted on this machine
5548: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5549: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5550: return %{unserialize($reply, $escapedkeys)};
5551: }
1.755 albertel 5552: if ($regexp) {
5553: $regexp=&escape($regexp);
5554: } else {
5555: $regexp='.';
5556: }
1.1166 raeburn 5557: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5558: my @pairs=split(/\&/,$rep);
5559: my %returnhash=();
1.1098 foxr 5560: if (!($rep =~ /^error/ )) {
5561: foreach my $item (@pairs) {
5562: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5563: $key = unescape($key) unless $escapedkeys;
5564: #$key = &unescape($key);
1.1098 foxr 5565: next if ($key =~ /^error: 2 /);
5566: $returnhash{$key}=&thaw_unescape($value);
5567: }
1.755 albertel 5568: }
5569: return %returnhash;
1.407 www 5570: }
5571:
1.1098 foxr 5572:
1.717 albertel 5573: # --------------------------------------------------------- dumpstore interface
5574:
5575: sub dumpstore {
5576: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5577: # same as dump but keys must be escaped. They may contain colon separated
5578: # lists of values that may themself contain colons (e.g. symbs).
5579: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5580: }
5581:
1.407 www 5582: # -------------------------------------------------------------- keys interface
5583:
5584: sub getkeys {
5585: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5586: if (!$udomain) { $udomain=$env{'user.domain'}; }
5587: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5588: my $uhome=&homeserver($uname,$udomain);
5589: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5590: my @keyarray=();
1.800 albertel 5591: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5592: next if ($key =~ /^error: 2 /);
1.800 albertel 5593: push(@keyarray,&unescape($key));
1.407 www 5594: }
5595: return @keyarray;
1.318 matthew 5596: }
5597:
1.319 matthew 5598: # --------------------------------------------------------------- currentdump
5599: sub currentdump {
1.328 matthew 5600: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5601: $courseid = $env{'request.course.id'} if (! defined($courseid));
5602: $sdom = $env{'user.domain'} if (! defined($sdom));
5603: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5604: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5605: my $rep;
5606:
5607: if (grep { $_ eq $uhome } current_machine_ids()) {
5608: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5609: $courseid)));
5610: } else {
5611: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5612: }
5613:
1.318 matthew 5614: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5615: #
1.318 matthew 5616: my %returnhash=();
1.319 matthew 5617: #
5618: if ($rep eq "unknown_cmd") {
5619: # an old lond will not know currentdump
5620: # Do a dump and make it look like a currentdump
1.822 albertel 5621: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5622: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5623: my %hash = @tmp;
5624: @tmp=();
1.424 matthew 5625: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5626: } else {
5627: my @pairs=split(/\&/,$rep);
1.800 albertel 5628: foreach my $pair (@pairs) {
5629: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5630: my ($symb,$param) = split(/:/,$key);
5631: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5632: &thaw_unescape($value);
1.319 matthew 5633: }
1.191 harris41 5634: }
1.12 www 5635: return %returnhash;
1.424 matthew 5636: }
5637:
5638: sub convert_dump_to_currentdump{
5639: my %hash = %{shift()};
5640: my %returnhash;
5641: # Code ripped from lond, essentially. The only difference
5642: # here is the unescaping done by lonnet::dump(). Conceivably
5643: # we might run in to problems with parameter names =~ /^v\./
5644: while (my ($key,$value) = each(%hash)) {
5645: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5646: $symb = &unescape($symb);
5647: $param = &unescape($param);
1.424 matthew 5648: next if ($v eq 'version' || $symb eq 'keys');
5649: next if (exists($returnhash{$symb}) &&
5650: exists($returnhash{$symb}->{$param}) &&
5651: $returnhash{$symb}->{'v.'.$param} > $v);
5652: $returnhash{$symb}->{$param}=$value;
5653: $returnhash{$symb}->{'v.'.$param}=$v;
5654: }
5655: #
5656: # Remove all of the keys in the hashes which keep track of
5657: # the version of the parameter.
5658: while (my ($symb,$param_hash) = each(%returnhash)) {
5659: # use a foreach because we are going to delete from the hash.
5660: foreach my $key (keys(%$param_hash)) {
5661: delete($param_hash->{$key}) if ($key =~ /^v\./);
5662: }
5663: }
5664: return \%returnhash;
1.12 www 5665: }
5666:
1.627 albertel 5667: # ------------------------------------------------------ critical inc interface
5668:
5669: sub cinc {
5670: return &inc(@_,'critical');
5671: }
5672:
1.449 matthew 5673: # --------------------------------------------------------------- inc interface
5674:
5675: sub inc {
1.627 albertel 5676: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5677: if (!$udomain) { $udomain=$env{'user.domain'}; }
5678: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5679: my $uhome=&homeserver($uname,$udomain);
5680: my $items='';
5681: if (! ref($store)) {
5682: # got a single value, so use that instead
5683: $items = &escape($store).'=&';
5684: } elsif (ref($store) eq 'SCALAR') {
5685: $items = &escape($$store).'=&';
5686: } elsif (ref($store) eq 'ARRAY') {
5687: $items = join('=&',map {&escape($_);} @{$store});
5688: } elsif (ref($store) eq 'HASH') {
5689: while (my($key,$value) = each(%{$store})) {
5690: $items.= &escape($key).'='.&escape($value).'&';
5691: }
5692: }
5693: $items=~s/\&$//;
1.627 albertel 5694: if ($critical) {
5695: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5696: } else {
5697: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5698: }
1.449 matthew 5699: }
5700:
1.12 www 5701: # --------------------------------------------------------------- put interface
5702:
5703: sub put {
1.134 albertel 5704: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5705: if (!$udomain) { $udomain=$env{'user.domain'}; }
5706: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5707: my $uhome=&homeserver($uname,$udomain);
1.12 www 5708: my $items='';
1.800 albertel 5709: foreach my $item (keys(%$storehash)) {
5710: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5711: }
1.12 www 5712: $items=~s/\&$//;
1.134 albertel 5713: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5714: }
5715:
1.631 albertel 5716: # ------------------------------------------------------------ newput interface
5717:
5718: sub newput {
5719: my ($namespace,$storehash,$udomain,$uname)=@_;
5720: if (!$udomain) { $udomain=$env{'user.domain'}; }
5721: if (!$uname) { $uname=$env{'user.name'}; }
5722: my $uhome=&homeserver($uname,$udomain);
5723: my $items='';
5724: foreach my $key (keys(%$storehash)) {
5725: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5726: }
5727: $items=~s/\&$//;
5728: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5729: }
5730:
5731: # --------------------------------------------------------- putstore interface
5732:
1.524 raeburn 5733: sub putstore {
1.715 albertel 5734: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5735: if (!$udomain) { $udomain=$env{'user.domain'}; }
5736: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5737: my $uhome=&homeserver($uname,$udomain);
5738: my $items='';
1.715 albertel 5739: foreach my $key (keys(%$storehash)) {
5740: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5741: }
1.715 albertel 5742: $items=~s/\&$//;
1.716 albertel 5743: my $esc_symb=&escape($symb);
5744: my $esc_v=&escape($version);
1.715 albertel 5745: my $reply =
1.716 albertel 5746: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5747: $uhome);
5748: if ($reply eq 'unknown_cmd') {
1.716 albertel 5749: # gfall back to way things use to be done
1.715 albertel 5750: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5751: $uname);
1.524 raeburn 5752: }
1.715 albertel 5753: return $reply;
5754: }
5755:
5756: sub old_putstore {
1.716 albertel 5757: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5758: if (!$udomain) { $udomain=$env{'user.domain'}; }
5759: if (!$uname) { $uname=$env{'user.name'}; }
5760: my $uhome=&homeserver($uname,$udomain);
5761: my %newstorehash;
1.800 albertel 5762: foreach my $item (keys(%$storehash)) {
5763: my $key = $version.':'.&escape($symb).':'.$item;
5764: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5765: }
5766: my $items='';
5767: my %allitems = ();
1.800 albertel 5768: foreach my $item (keys(%newstorehash)) {
5769: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5770: my $key = $1.':keys:'.$2;
5771: $allitems{$key} .= $3.':';
5772: }
1.800 albertel 5773: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5774: }
1.800 albertel 5775: foreach my $item (keys(%allitems)) {
5776: $allitems{$item} =~ s/\:$//;
5777: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5778: }
5779: $items=~s/\&$//;
5780: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5781: }
5782:
1.47 www 5783: # ------------------------------------------------------ critical put interface
5784:
5785: sub cput {
1.134 albertel 5786: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5787: if (!$udomain) { $udomain=$env{'user.domain'}; }
5788: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5789: my $uhome=&homeserver($uname,$udomain);
1.47 www 5790: my $items='';
1.800 albertel 5791: foreach my $item (keys(%$storehash)) {
5792: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5793: }
1.47 www 5794: $items=~s/\&$//;
1.134 albertel 5795: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5796: }
5797:
5798: # -------------------------------------------------------------- eget interface
5799:
5800: sub eget {
1.133 albertel 5801: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5802: my $items='';
1.800 albertel 5803: foreach my $item (@$storearr) {
5804: $items.=&escape($item).'&';
1.191 harris41 5805: }
1.12 www 5806: $items=~s/\&$//;
1.620 albertel 5807: if (!$udomain) { $udomain=$env{'user.domain'}; }
5808: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5809: my $uhome=&homeserver($uname,$udomain);
5810: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5811: my @pairs=split(/\&/,$rep);
5812: my %returnhash=();
1.42 www 5813: my $i=0;
1.800 albertel 5814: foreach my $item (@$storearr) {
5815: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5816: $i++;
1.191 harris41 5817: }
1.12 www 5818: return %returnhash;
5819: }
5820:
1.667 albertel 5821: # ------------------------------------------------------------ tmpput interface
5822: sub tmpput {
1.802 raeburn 5823: my ($storehash,$server,$context)=@_;
1.667 albertel 5824: my $items='';
1.800 albertel 5825: foreach my $item (keys(%$storehash)) {
5826: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5827: }
5828: $items=~s/\&$//;
1.802 raeburn 5829: if (defined($context)) {
5830: $items .= ':'.&escape($context);
5831: }
1.667 albertel 5832: return &reply("tmpput:$items",$server);
5833: }
5834:
5835: # ------------------------------------------------------------ tmpget interface
5836: sub tmpget {
1.688 albertel 5837: my ($token,$server)=@_;
5838: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5839: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5840: my %returnhash;
5841: foreach my $item (split(/\&/,$rep)) {
5842: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5843: next if ($key =~ /^error: 2 /);
1.667 albertel 5844: $returnhash{&unescape($key)}=&thaw_unescape($value);
5845: }
5846: return %returnhash;
5847: }
5848:
1.1113 raeburn 5849: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5850: sub tmpdel {
5851: my ($token,$server)=@_;
5852: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5853: return &reply("tmpdel:$token",$server);
5854: }
5855:
1.1198 raeburn 5856: # ------------------------------------------------------------ get_timebased_id
5857:
5858: sub get_timebased_id {
5859: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5860: $maxtries) = @_;
5861: my ($newid,$error,$dellock);
5862: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5863: return ('','ok','invalid call to get suffix');
5864: }
5865:
5866: # set defaults for any optional args for which values were not supplied
5867: if ($who eq '') {
5868: $who = $env{'user.name'}.':'.$env{'user.domain'};
5869: }
5870: if (!$locktries) {
5871: $locktries = 3;
5872: }
5873: if (!$maxtries) {
5874: $maxtries = 10;
5875: }
5876:
5877: if (($cdom eq '') || ($cnum eq '')) {
5878: if ($env{'request.course.id'}) {
5879: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5880: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5881: }
5882: if (($cdom eq '') || ($cnum eq '')) {
5883: return ('','ok','call to get suffix not in course context');
5884: }
5885: }
5886:
5887: # construct locking item
5888: my $lockhash = {
5889: $prefix."\0".'locked_'.$keyid => $who,
5890: };
5891: my $tries = 0;
5892:
5893: # attempt to get lock on nohist_$namespace file
5894: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5895: while (($gotlock ne 'ok') && $tries <$locktries) {
5896: $tries ++;
5897: sleep 1;
5898: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5899: }
5900:
5901: # attempt to get unique identifier, based on current timestamp
5902: if ($gotlock eq 'ok') {
5903: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5904: my $id = time;
5905: $newid = $id;
5906: my $idtries = 0;
5907: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5908: if ($idtype eq 'concat') {
5909: $newid = $id.$idtries;
5910: } else {
5911: $newid ++;
5912: }
5913: $idtries ++;
5914: }
5915: if (!exists($inuse{$prefix."\0".$newid})) {
5916: my %new_item = (
5917: $prefix."\0".$newid => $who,
5918: );
5919: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5920: $cdom,$cnum);
5921: if ($putresult ne 'ok') {
5922: undef($newid);
5923: $error = 'error saving new item: '.$putresult;
5924: }
5925: } else {
5926: $error = ('error: no unique suffix available for the new item ');
5927: }
5928: # remove lock
5929: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5930: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5931: } else {
5932: $error = "error: could not obtain lockfile\n";
5933: $dellock = 'ok';
5934: }
5935: return ($newid,$dellock,$error);
5936: }
5937:
1.765 albertel 5938: # -------------------------------------------------- portfolio access checking
5939:
5940: sub portfolio_access {
1.766 albertel 5941: my ($requrl) = @_;
1.765 albertel 5942: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5943: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5944: if ($result) {
5945: my %setters;
5946: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5947: my ($startblock,$endblock) =
5948: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5949: if ($startblock && $endblock) {
5950: return 'B';
5951: }
5952: } else {
5953: my ($startblock,$endblock) =
5954: &Apache::loncommon::blockcheck(\%setters,'port');
5955: if ($startblock && $endblock) {
5956: return 'B';
5957: }
5958: }
5959: }
1.765 albertel 5960: if ($result eq 'ok') {
1.766 albertel 5961: return 'F';
1.765 albertel 5962: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5963: return 'A';
1.765 albertel 5964: }
1.766 albertel 5965: return '';
1.765 albertel 5966: }
5967:
5968: sub get_portfolio_access {
1.767 albertel 5969: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5970:
5971: if (!ref($access_hash)) {
5972: my $current_perms = &get_portfile_permissions($udom,$unum);
5973: my %access_controls = &get_access_controls($current_perms,$group,
5974: $file_name);
5975: $access_hash = $access_controls{$file_name};
5976: }
5977:
1.765 albertel 5978: my ($public,$guest,@domains,@users,@courses,@groups);
5979: my $now = time;
5980: if (ref($access_hash) eq 'HASH') {
5981: foreach my $key (keys(%{$access_hash})) {
5982: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5983: if ($start > $now) {
5984: next;
5985: }
5986: if ($end && $end<$now) {
5987: next;
5988: }
5989: if ($scope eq 'public') {
5990: $public = $key;
5991: last;
5992: } elsif ($scope eq 'guest') {
5993: $guest = $key;
5994: } elsif ($scope eq 'domains') {
5995: push(@domains,$key);
5996: } elsif ($scope eq 'users') {
5997: push(@users,$key);
5998: } elsif ($scope eq 'course') {
5999: push(@courses,$key);
6000: } elsif ($scope eq 'group') {
6001: push(@groups,$key);
6002: }
6003: }
6004: if ($public) {
6005: return 'ok';
6006: }
6007: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6008: if ($guest) {
6009: return $guest;
6010: }
6011: } else {
6012: if (@domains > 0) {
6013: foreach my $domkey (@domains) {
6014: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6015: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6016: return 'ok';
6017: }
6018: }
6019: }
6020: }
6021: if (@users > 0) {
6022: foreach my $userkey (@users) {
1.865 raeburn 6023: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6024: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6025: if (ref($item) eq 'HASH') {
6026: if (($item->{'uname'} eq $env{'user.name'}) &&
6027: ($item->{'udom'} eq $env{'user.domain'})) {
6028: return 'ok';
6029: }
6030: }
6031: }
6032: }
1.765 albertel 6033: }
6034: }
6035: my %roleshash;
6036: my @courses_and_groups = @courses;
6037: push(@courses_and_groups,@groups);
6038: if (@courses_and_groups > 0) {
6039: my (%allgroups,%allroles);
6040: my ($start,$end,$role,$sec,$group);
6041: foreach my $envkey (%env) {
1.1060 raeburn 6042: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6043: my $cid = $2.'_'.$3;
6044: if ($1 eq 'gr') {
6045: $group = $4;
6046: $allgroups{$cid}{$group} = $env{$envkey};
6047: } else {
6048: if ($4 eq '') {
6049: $sec = 'none';
6050: } else {
6051: $sec = $4;
6052: }
6053: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6054: }
1.811 albertel 6055: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6056: my $cid = $2.'_'.$3;
6057: if ($4 eq '') {
6058: $sec = 'none';
6059: } else {
6060: $sec = $4;
6061: }
6062: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6063: }
6064: }
6065: if (keys(%allroles) == 0) {
6066: return;
6067: }
6068: foreach my $key (@courses_and_groups) {
6069: my %content = %{$$access_hash{$key}};
6070: my $cnum = $content{'number'};
6071: my $cdom = $content{'domain'};
6072: my $cid = $cdom.'_'.$cnum;
6073: if (!exists($allroles{$cid})) {
6074: next;
6075: }
6076: foreach my $role_id (keys(%{$content{'roles'}})) {
6077: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6078: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6079: my @status = @{$content{'roles'}{$role_id}{'access'}};
6080: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6081: foreach my $role (keys(%{$allroles{$cid}})) {
6082: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6083: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6084: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6085: if (grep/^all$/,@sections) {
6086: return 'ok';
6087: } else {
6088: if (grep/^$sec$/,@sections) {
6089: return 'ok';
6090: }
6091: }
6092: }
6093: }
6094: if (keys(%{$allgroups{$cid}}) == 0) {
6095: if (grep/^none$/,@groups) {
6096: return 'ok';
6097: }
6098: } else {
6099: if (grep/^all$/,@groups) {
6100: return 'ok';
6101: }
6102: foreach my $group (keys(%{$allgroups{$cid}})) {
6103: if (grep/^$group$/,@groups) {
6104: return 'ok';
6105: }
6106: }
6107: }
6108: }
6109: }
6110: }
6111: }
6112: }
6113: if ($guest) {
6114: return $guest;
6115: }
6116: }
6117: }
6118: return;
6119: }
6120:
6121: sub course_group_datechecker {
6122: my ($dates,$now,$status) = @_;
6123: my ($start,$end) = split(/\./,$dates);
6124: if (!$start && !$end) {
6125: return 'ok';
6126: }
6127: if (grep/^active$/,@{$status}) {
6128: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6129: return 'ok';
6130: }
6131: }
6132: if (grep/^previous$/,@{$status}) {
6133: if ($end > $now ) {
6134: return 'ok';
6135: }
6136: }
6137: if (grep/^future$/,@{$status}) {
6138: if ($start > $now) {
6139: return 'ok';
6140: }
6141: }
6142: return;
6143: }
6144:
6145: sub parse_portfolio_url {
6146: my ($url) = @_;
6147:
6148: my ($type,$udom,$unum,$group,$file_name);
6149:
1.823 albertel 6150: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6151: $type = 1;
6152: $udom = $1;
6153: $unum = $2;
6154: $file_name = $3;
1.823 albertel 6155: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6156: $type = 2;
6157: $udom = $1;
6158: $unum = $2;
6159: $group = $3;
6160: $file_name = $3.'/'.$4;
6161: }
6162: if (wantarray) {
6163: return ($type,$udom,$unum,$file_name,$group);
6164: }
6165: return $type;
6166: }
6167:
6168: sub is_portfolio_url {
6169: my ($url) = @_;
6170: return scalar(&parse_portfolio_url($url));
6171: }
6172:
1.798 raeburn 6173: sub is_portfolio_file {
6174: my ($file) = @_;
1.820 raeburn 6175: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6176: return 1;
6177: }
6178: return;
6179: }
6180:
1.976 raeburn 6181: sub usertools_access {
1.1084 raeburn 6182: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6183: my ($access,%tools);
6184: if ($context eq '') {
6185: $context = 'tools';
6186: }
6187: if ($context eq 'requestcourses') {
6188: %tools = (
6189: official => 1,
6190: unofficial => 1,
1.1006 raeburn 6191: community => 1,
1.985 raeburn 6192: );
1.1183 raeburn 6193: } elsif ($context eq 'requestauthor') {
6194: %tools = (
6195: requestauthor => 1,
6196: );
1.985 raeburn 6197: } else {
6198: %tools = (
6199: aboutme => 1,
6200: blog => 1,
1.1177 raeburn 6201: webdav => 1,
1.985 raeburn 6202: portfolio => 1,
6203: );
6204: }
1.976 raeburn 6205: return if (!defined($tools{$tool}));
6206:
6207: if ((!defined($udom)) || (!defined($uname))) {
6208: $udom = $env{'user.domain'};
6209: $uname = $env{'user.name'};
6210: }
6211:
1.978 raeburn 6212: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6213: if ($action ne 'reload') {
1.985 raeburn 6214: if ($context eq 'requestcourses') {
6215: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6216: } elsif ($context eq 'requestauthor') {
6217: return $env{'environment.canrequest.author'};
1.985 raeburn 6218: } else {
6219: return $env{'environment.availabletools.'.$tool};
6220: }
6221: }
1.976 raeburn 6222: }
6223:
1.1183 raeburn 6224: my ($toolstatus,$inststatus,$envkey);
6225: if ($context eq 'requestauthor') {
6226: $envkey = $context;
6227: } else {
6228: $envkey = $context.'.'.$tool;
6229: }
1.976 raeburn 6230:
1.985 raeburn 6231: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6232: ($action ne 'reload')) {
1.1183 raeburn 6233: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6234: $inststatus = $env{'environment.inststatus'};
6235: } else {
1.1084 raeburn 6236: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6237: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6238: $inststatus = $userenvref->{'inststatus'};
6239: } else {
1.1183 raeburn 6240: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6241: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6242: $inststatus = $userenv{'inststatus'};
6243: }
1.976 raeburn 6244: }
6245:
6246: if ($toolstatus ne '') {
6247: if ($toolstatus) {
6248: $access = 1;
6249: } else {
6250: $access = 0;
6251: }
6252: return $access;
6253: }
6254:
1.1084 raeburn 6255: my ($is_adv,%domdef);
6256: if (ref($is_advref) eq 'HASH') {
6257: $is_adv = $is_advref->{'is_adv'};
6258: } else {
6259: $is_adv = &is_advanced_user($udom,$uname);
6260: }
6261: if (ref($domdefref) eq 'HASH') {
6262: %domdef = %{$domdefref};
6263: } else {
6264: %domdef = &get_domain_defaults($udom);
6265: }
1.976 raeburn 6266: if (ref($domdef{$tool}) eq 'HASH') {
6267: if ($is_adv) {
6268: if ($domdef{$tool}{'_LC_adv'} ne '') {
6269: if ($domdef{$tool}{'_LC_adv'}) {
6270: $access = 1;
6271: } else {
6272: $access = 0;
6273: }
6274: return $access;
6275: }
6276: }
6277: if ($inststatus ne '') {
6278: my ($hasaccess,$hasnoaccess);
6279: foreach my $affiliation (split(/:/,$inststatus)) {
6280: if ($domdef{$tool}{$affiliation} ne '') {
6281: if ($domdef{$tool}{$affiliation}) {
6282: $hasaccess = 1;
6283: } else {
6284: $hasnoaccess = 1;
6285: }
6286: }
6287: }
6288: if ($hasaccess || $hasnoaccess) {
6289: if ($hasaccess) {
6290: $access = 1;
6291: } elsif ($hasnoaccess) {
6292: $access = 0;
6293: }
6294: return $access;
6295: }
6296: } else {
6297: if ($domdef{$tool}{'default'} ne '') {
6298: if ($domdef{$tool}{'default'}) {
6299: $access = 1;
6300: } elsif ($domdef{$tool}{'default'} == 0) {
6301: $access = 0;
6302: }
6303: return $access;
6304: }
6305: }
6306: } else {
1.1177 raeburn 6307: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6308: $access = 1;
6309: } else {
6310: $access = 0;
6311: }
1.976 raeburn 6312: return $access;
6313: }
6314: }
6315:
1.1050 raeburn 6316: sub is_course_owner {
6317: my ($cdom,$cnum,$udom,$uname) = @_;
6318: if (($udom eq '') || ($uname eq '')) {
6319: $udom = $env{'user.domain'};
6320: $uname = $env{'user.name'};
6321: }
6322: unless (($udom eq '') || ($uname eq '')) {
6323: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6324: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6325: return 1;
6326: } else {
6327: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6328: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6329: return 1;
6330: }
6331: }
6332: }
6333: }
6334: return;
6335: }
6336:
1.976 raeburn 6337: sub is_advanced_user {
6338: my ($udom,$uname) = @_;
1.1085 raeburn 6339: if ($udom ne '' && $uname ne '') {
6340: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6341: if (wantarray) {
6342: return ($env{'user.adv'},$env{'user.author'});
6343: } else {
6344: return $env{'user.adv'};
6345: }
1.1085 raeburn 6346: }
6347: }
1.976 raeburn 6348: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6349: my %allroles;
1.1128 raeburn 6350: my ($is_adv,$is_author);
1.976 raeburn 6351: foreach my $role (keys(%roleshash)) {
6352: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6353: my $area = '/'.$tdomain.'/'.$trest;
6354: if ($sec ne '') {
6355: $area .= '/'.$sec;
6356: }
6357: if (($area ne '') && ($trole ne '')) {
6358: my $spec=$trole.'.'.$area;
6359: if ($trole =~ /^cr\//) {
6360: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6361: } elsif ($trole ne 'gr') {
6362: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6363: }
1.1128 raeburn 6364: if ($trole eq 'au') {
6365: $is_author = 1;
6366: }
1.976 raeburn 6367: }
6368: }
6369: foreach my $role (keys(%allroles)) {
6370: last if ($is_adv);
6371: foreach my $item (split(/:/,$allroles{$role})) {
6372: if ($item ne '') {
6373: my ($privilege,$restrictions)=split(/&/,$item);
6374: if ($privilege eq 'adv') {
6375: $is_adv = 1;
6376: last;
6377: }
6378: }
6379: }
6380: }
1.1128 raeburn 6381: if (wantarray) {
6382: return ($is_adv,$is_author);
6383: }
1.976 raeburn 6384: return $is_adv;
6385: }
1.798 raeburn 6386:
1.1035 raeburn 6387: sub check_can_request {
1.1036 raeburn 6388: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6389: my $canreq = 0;
6390: my ($types,$typename) = &Apache::loncommon::course_types();
6391: my @options = ('approval','validate','autolimit');
6392: my $optregex = join('|',@options);
6393: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6394: foreach my $type (@{$types}) {
6395: if (&usertools_access($env{'user.name'},
6396: $env{'user.domain'},
6397: $type,undef,'requestcourses')) {
6398: $canreq ++;
1.1036 raeburn 6399: if (ref($request_domains) eq 'HASH') {
6400: push(@{$request_domains->{$type}},$env{'user.domain'});
6401: }
1.1035 raeburn 6402: if ($dom eq $env{'user.domain'}) {
6403: $can_request->{$type} = 1;
6404: }
6405: }
6406: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6407: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6408: if (@curr > 0) {
1.1036 raeburn 6409: foreach my $item (@curr) {
6410: if (ref($request_domains) eq 'HASH') {
6411: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6412: if ($otherdom ne '') {
6413: if (ref($request_domains->{$type}) eq 'ARRAY') {
6414: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6415: push(@{$request_domains->{$type}},$otherdom);
6416: }
6417: } else {
6418: push(@{$request_domains->{$type}},$otherdom);
6419: }
6420: }
6421: }
6422: }
6423: unless($dom eq $env{'user.domain'}) {
6424: $canreq ++;
1.1035 raeburn 6425: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6426: $can_request->{$type} = 1;
6427: }
6428: }
6429: }
6430: }
6431: }
6432: }
6433: return $canreq;
6434: }
6435:
1.341 www 6436: # ---------------------------------------------- Custom access rule evaluation
6437:
6438: sub customaccess {
6439: my ($priv,$uri)=@_;
1.807 albertel 6440: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6441: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6442: $udom = &LONCAPA::clean_domain($udom);
6443: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6444: my $access=0;
1.800 albertel 6445: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6446: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6447: if ($type eq 'user') {
6448: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6449: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6450: if ($tdom) {
6451: if ($tdom ne $env{'user.domain'}) { next; }
6452: }
1.896 albertel 6453: if ($tuname) {
6454: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6455: }
6456: $access=($effect eq 'allow');
6457: last;
6458: }
6459: } else {
6460: if ($role) {
6461: if ($role ne $urole) { next; }
6462: }
6463: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6464: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6465: if ($tdom) {
6466: if ($tdom ne $udom) { next; }
6467: }
6468: if ($tcrs) {
6469: if ($tcrs ne $ucrs) { next; }
6470: }
6471: if ($tsec) {
6472: if ($tsec ne $usec) { next; }
6473: }
6474: $access=($effect eq 'allow');
6475: last;
6476: }
6477: if ($realm eq '' && $role eq '') {
6478: $access=($effect eq 'allow');
6479: }
1.402 bowersj2 6480: }
1.341 www 6481: }
6482: return $access;
6483: }
6484:
1.103 harris41 6485: # ------------------------------------------------- Check for a user privilege
1.12 www 6486:
6487: sub allowed {
1.810 raeburn 6488: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6489: my $ver_orguri=$uri;
1.439 www 6490: $uri=&deversion($uri);
1.152 www 6491: my $orguri=$uri;
1.52 www 6492: $uri=&declutter($uri);
1.809 raeburn 6493:
1.810 raeburn 6494: if ($priv eq 'evb') {
6495: # Evade communication block restrictions for specified role in a course
6496: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6497: return $1;
6498: } else {
6499: return;
6500: }
6501: }
6502:
1.620 albertel 6503: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6504: # Free bre access to adm and meta resources
1.775 albertel 6505: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6506: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6507: && ($priv eq 'bre')) {
1.14 www 6508: return 'F';
1.159 www 6509: }
6510:
1.545 banghart 6511: # Free bre access to user's own portfolio contents
1.714 raeburn 6512: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6513: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6514: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6515: my %setters;
6516: my ($startblock,$endblock) =
6517: &Apache::loncommon::blockcheck(\%setters,'port');
6518: if ($startblock && $endblock) {
6519: return 'B';
6520: } else {
6521: return 'F';
6522: }
1.545 banghart 6523: }
6524:
1.762 raeburn 6525: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6526: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6527: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6528: if (exists($env{'request.course.id'})) {
6529: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6530: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6531: if (($domain eq $cdom) && ($name eq $cnum)) {
6532: my $courseprivid=$env{'request.course.id'};
6533: $courseprivid=~s/\_/\//;
6534: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6535: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6536: return $1;
1.762 raeburn 6537: } else {
6538: if ($env{'request.course.sec'}) {
6539: $courseprivid.='/'.$env{'request.course.sec'};
6540: }
6541: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6542: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6543: return $2;
6544: }
1.714 raeburn 6545: }
6546: }
6547: }
6548: }
6549:
1.159 www 6550: # Free bre to public access
6551:
6552: if ($priv eq 'bre') {
1.238 www 6553: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6554: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6555: return 'F';
6556: }
1.238 www 6557: if ($copyright eq 'priv') {
6558: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6559: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6560: return '';
6561: }
6562: }
6563: if ($copyright eq 'domain') {
6564: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6565: unless (($env{'user.domain'} eq $1) ||
6566: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6567: return '';
6568: }
1.262 matthew 6569: }
1.620 albertel 6570: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6571: # Library role, so allow browsing of resources in this domain.
6572: return 'F';
1.238 www 6573: }
1.341 www 6574: if ($copyright eq 'custom') {
6575: unless (&customaccess($priv,$uri)) { return ''; }
6576: }
1.14 www 6577: }
1.264 matthew 6578: # Domain coordinator is trying to create a course
1.620 albertel 6579: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6580: # uri is the requested domain in this case.
6581: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6582: # a role of dc for the domain in question.
1.620 albertel 6583: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6584: }
1.29 www 6585:
1.52 www 6586: my $thisallowed='';
6587: my $statecond=0;
6588: my $courseprivid='';
6589:
1.1039 raeburn 6590: my $ownaccess;
1.1043 raeburn 6591: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6592: if (($priv eq 'bro') && ($env{'user.author'})) {
6593: if ($uri eq '') {
6594: $ownaccess = 1;
6595: } else {
6596: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6597: my $udom = $env{'user.domain'};
6598: my $uname = $env{'user.name'};
6599: if ($uri =~ m{^\Q$udom\E/?$}) {
6600: $ownaccess = 1;
1.1040 raeburn 6601: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6602: unless ($uri =~ m{\.\./}) {
6603: $ownaccess = 1;
6604: }
6605: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6606: my $now = time;
6607: if ($uri =~ m{^([^/]+)/?$}) {
6608: my $adom = $1;
6609: foreach my $key (keys(%env)) {
1.1042 raeburn 6610: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6611: my ($start,$end) = split('.',$env{$key});
6612: if (($now >= $start) && (!$end || $end < $now)) {
6613: $ownaccess = 1;
6614: last;
6615: }
6616: }
6617: }
6618: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6619: my $adom = $1;
6620: my $aname = $2;
1.1042 raeburn 6621: foreach my $role ('ca','aa') {
6622: if ($env{"user.role.$role./$adom/$aname"}) {
6623: my ($start,$end) =
6624: split('.',$env{"user.role.$role./$adom/$aname"});
6625: if (($now >= $start) && (!$end || $end < $now)) {
6626: $ownaccess = 1;
6627: last;
6628: }
1.1039 raeburn 6629: }
6630: }
6631: }
6632: }
6633: }
6634: }
6635: }
6636:
1.52 www 6637: # Course
6638:
1.620 albertel 6639: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6640: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6641: $thisallowed.=$1;
6642: }
1.52 www 6643: }
1.29 www 6644:
1.52 www 6645: # Domain
6646:
1.620 albertel 6647: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6648: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6649: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6650: $thisallowed.=$1;
6651: }
1.12 www 6652: }
1.52 www 6653:
1.1141 raeburn 6654: # User who is not author or co-author might still be able to edit
6655: # resource of an author in the domain (e.g., if Domain Coordinator).
6656: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6657: (&allowed('mdc',$env{'request.course.id'}))) {
6658: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6659: $thisallowed.=$1;
6660: }
6661: }
6662:
1.52 www 6663: # Course: uri itself is a course
1.66 www 6664: my $courseuri=$uri;
6665: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6666: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6667:
1.620 albertel 6668: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6669: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6670: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6671: $thisallowed.=$1;
6672: }
1.12 www 6673: }
1.29 www 6674:
1.665 albertel 6675: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6676: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6677: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6678: $thisallowed='';
1.671 raeburn 6679: my ($match)=&is_on_map($uri);
6680: if ($match) {
6681: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6682: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6683: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6684: if (@blockers > 0) {
6685: $thisallowed = 'B';
6686: } else {
6687: $thisallowed.=$1;
6688: }
1.671 raeburn 6689: }
6690: } else {
1.705 albertel 6691: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6692: if ($refuri) {
6693: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6694: $thisallowed='F';
1.671 raeburn 6695: } else {
6696: $refuri=&declutter($refuri);
6697: my ($match) = &is_on_map($refuri);
6698: if ($match) {
1.1162 raeburn 6699: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6700: if (@blockers > 0) {
6701: $thisallowed = 'B';
6702: } else {
6703: $thisallowed='F';
6704: }
1.671 raeburn 6705: }
1.669 raeburn 6706: }
1.671 raeburn 6707: }
6708: }
1.314 www 6709: }
1.492 albertel 6710:
1.766 albertel 6711: if ($priv eq 'bre'
6712: && $thisallowed ne 'F'
6713: && $thisallowed ne '2'
6714: && &is_portfolio_url($uri)) {
6715: $thisallowed = &portfolio_access($uri);
6716: }
6717:
1.52 www 6718: # Full access at system, domain or course-wide level? Exit.
1.29 www 6719: if ($thisallowed=~/F/) {
6720: return 'F';
6721: }
6722:
1.52 www 6723: # If this is generating or modifying users, exit with special codes
1.29 www 6724:
1.643 www 6725: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6726: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6727: my ($audom,$auname)=split('/',$uri);
1.643 www 6728: # no author name given, so this just checks on the general right to make a co-author in this domain
6729: unless ($auname) { return $thisallowed; }
6730: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6731: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6732: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6733: ($audom ne $env{'request.role.domain'}))) { return ''; }
6734: }
1.52 www 6735: return $thisallowed;
6736: }
6737: #
1.103 harris41 6738: # Gathered so far: system, domain and course wide privileges
1.52 www 6739: #
6740: # Course: See if uri or referer is an individual resource that is part of
6741: # the course
6742:
1.620 albertel 6743: if ($env{'request.course.id'}) {
1.232 www 6744:
1.620 albertel 6745: $courseprivid=$env{'request.course.id'};
6746: if ($env{'request.course.sec'}) {
6747: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6748: }
6749: $courseprivid=~s/\_/\//;
6750: my $checkreferer=1;
1.232 www 6751: my ($match,$cond)=&is_on_map($uri);
6752: if ($match) {
6753: $statecond=$cond;
1.620 albertel 6754: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6755: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6756: my $value = $1;
6757: if ($priv eq 'bre') {
6758: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6759: if (@blockers > 0) {
6760: $thisallowed = 'B';
6761: } else {
6762: $thisallowed.=$value;
6763: }
6764: } else {
6765: $thisallowed.=$value;
6766: }
1.52 www 6767: $checkreferer=0;
6768: }
1.29 www 6769: }
1.83 www 6770:
1.148 www 6771: if ($checkreferer) {
1.620 albertel 6772: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6773: unless ($refuri) {
1.800 albertel 6774: foreach my $key (keys(%env)) {
6775: if ($key=~/^httpref\..*\*/) {
6776: my $pattern=$key;
1.156 www 6777: $pattern=~s/^httpref\.\/res\///;
1.148 www 6778: $pattern=~s/\*/\[\^\/\]\+/g;
6779: $pattern=~s/\//\\\//g;
1.152 www 6780: if ($orguri=~/$pattern/) {
1.800 albertel 6781: $refuri=$env{$key};
1.148 www 6782: }
6783: }
1.191 harris41 6784: }
1.148 www 6785: }
1.232 www 6786:
1.148 www 6787: if ($refuri) {
1.152 www 6788: $refuri=&declutter($refuri);
1.232 www 6789: my ($match,$cond)=&is_on_map($refuri);
6790: if ($match) {
6791: my $refstatecond=$cond;
1.620 albertel 6792: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6793: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6794: my $value = $1;
6795: if ($priv eq 'bre') {
6796: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6797: if (@blockers > 0) {
6798: $thisallowed = 'B';
6799: } else {
6800: $thisallowed.=$value;
6801: }
6802: } else {
6803: $thisallowed.=$value;
6804: }
1.53 www 6805: $uri=$refuri;
6806: $statecond=$refstatecond;
1.52 www 6807: }
6808: }
1.148 www 6809: }
1.29 www 6810: }
1.52 www 6811: }
1.29 www 6812:
1.52 www 6813: #
1.103 harris41 6814: # Gathered now: all privileges that could apply, and condition number
1.52 www 6815: #
6816: #
6817: # Full or no access?
6818: #
1.29 www 6819:
1.52 www 6820: if ($thisallowed=~/F/) {
6821: return 'F';
6822: }
1.29 www 6823:
1.52 www 6824: unless ($thisallowed) {
6825: return '';
6826: }
1.29 www 6827:
1.52 www 6828: # Restrictions exist, deal with them
6829: #
6830: # C:according to course preferences
6831: # R:according to resource settings
6832: # L:unless locked
6833: # X:according to user session state
6834: #
6835:
6836: # Possibly locked functionality, check all courses
1.54 www 6837: # Locks might take effect only after 10 minutes cache expiration for other
6838: # courses, and 2 minutes for current course
1.52 www 6839:
6840: my $envkey;
6841: if ($thisallowed=~/L/) {
1.1000 raeburn 6842: foreach $envkey (keys(%env)) {
1.54 www 6843: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6844: my $courseid=$2;
6845: my $roleid=$1.'.'.$2;
1.92 www 6846: $courseid=~s/^\///;
1.54 www 6847: my $expiretime=600;
1.620 albertel 6848: if ($env{'request.role'} eq $roleid) {
1.54 www 6849: $expiretime=120;
6850: }
6851: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6852: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6853: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6854: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6855: }
1.620 albertel 6856: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6857: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6858: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6859: &log($env{'user.domain'},$env{'user.name'},
6860: $env{'user.home'},
1.57 www 6861: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6862: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6863: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6864: return '';
6865: }
6866: }
1.620 albertel 6867: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6868: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6869: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6870: &log($env{'user.domain'},$env{'user.name'},
6871: $env{'user.home'},
1.57 www 6872: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6873: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6874: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6875: return '';
6876: }
6877: }
6878: }
1.29 www 6879: }
1.52 www 6880: }
6881:
6882: #
6883: # Rest of the restrictions depend on selected course
6884: #
6885:
1.620 albertel 6886: unless ($env{'request.course.id'}) {
1.766 albertel 6887: if ($thisallowed eq 'A') {
6888: return 'A';
1.814 raeburn 6889: } elsif ($thisallowed eq 'B') {
6890: return 'B';
1.766 albertel 6891: } else {
6892: return '1';
6893: }
1.52 www 6894: }
1.29 www 6895:
1.52 www 6896: #
6897: # Now user is definitely in a course
6898: #
1.53 www 6899:
6900:
6901: # Course preferences
6902:
6903: if ($thisallowed=~/C/) {
1.620 albertel 6904: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6905: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6906: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6907: =~/\Q$rolecode\E/) {
1.1103 raeburn 6908: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6909: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6910: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6911: $env{'request.course.id'});
6912: }
1.237 www 6913: return '';
6914: }
6915:
1.620 albertel 6916: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6917: =~/\Q$unamedom\E/) {
1.1103 raeburn 6918: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6919: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6920: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6921: $env{'request.course.id'});
6922: }
1.54 www 6923: return '';
6924: }
1.53 www 6925: }
6926:
6927: # Resource preferences
6928:
6929: if ($thisallowed=~/R/) {
1.620 albertel 6930: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6931: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6932: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6933: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6934: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6935: }
6936: return '';
1.54 www 6937: }
1.53 www 6938: }
1.30 www 6939:
1.246 www 6940: # Restricted by state or randomout?
1.30 www 6941:
1.52 www 6942: if ($thisallowed=~/X/) {
1.620 albertel 6943: if ($env{'acc.randomout'}) {
1.579 albertel 6944: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6945: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6946: return '';
6947: }
1.247 www 6948: }
6949: if (&condval($statecond)) {
1.52 www 6950: return '2';
6951: } else {
6952: return '';
6953: }
6954: }
1.30 www 6955:
1.766 albertel 6956: if ($thisallowed eq 'A') {
6957: return 'A';
1.814 raeburn 6958: } elsif ($thisallowed eq 'B') {
6959: return 'B';
1.766 albertel 6960: }
1.52 www 6961: return 'F';
1.232 www 6962: }
1.1162 raeburn 6963:
1.1192 raeburn 6964: # ------------------------------------------- Check construction space access
6965:
6966: sub constructaccess {
6967: my ($url,$setpriv)=@_;
6968:
6969: # We do not allow editing of previous versions of files
6970: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
6971:
6972: # Get username and domain from URL
6973: my ($ownername,$ownerdomain,$ownerhome);
6974:
6975: ($ownerdomain,$ownername) =
6976: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
6977:
6978: # The URL does not really point to any authorspace, forget it
6979: unless (($ownername) && ($ownerdomain)) { return ''; }
6980:
6981: # Now we need to see if the user has access to the authorspace of
6982: # $ownername at $ownerdomain
6983:
6984: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
6985: # Real author for this?
6986: $ownerhome = $env{'user.home'};
6987: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
6988: return ($ownername,$ownerdomain,$ownerhome);
6989: }
6990: } else {
6991: # Co-author for this?
6992: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
6993: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
6994: $ownerhome = &homeserver($ownername,$ownerdomain);
6995: return ($ownername,$ownerdomain,$ownerhome);
6996: }
6997: }
6998:
6999: # We don't have any access right now. If we are not possibly going to do anything about this,
7000: # we might as well leave
7001: unless ($setpriv) { return ''; }
7002:
7003: # Backdoor access?
7004: my $allowed=&allowed('eco',$ownerdomain);
7005: # Nope
7006: unless ($allowed) { return ''; }
7007: # Looks like we may have access, but could be locked by the owner of the construction space
7008: if ($allowed eq 'U') {
7009: my %blocked=&get('environment',['domcoord.author'],
7010: $ownerdomain,$ownername);
7011: # Is blocked by owner
7012: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7013: }
7014: if (($allowed eq 'F') || ($allowed eq 'U')) {
7015: # Grant temporary access
7016: my $then=$env{'user.login.time'};
1.1209 raeburn 7017: my $update=$env{'user.update.time'};
1.1192 raeburn 7018: if (!$update) { $update = $then; }
7019: my $refresh=$env{'user.refresh.time'};
7020: if (!$refresh) { $refresh = $update; }
7021: my $now = time;
7022: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7023: $now,'ca','constructaccess');
7024: $ownerhome = &homeserver($ownername,$ownerdomain);
7025: return($ownername,$ownerdomain,$ownerhome);
7026: }
7027: # No business here
7028: return '';
7029: }
7030:
1.1162 raeburn 7031: sub get_comm_blocks {
7032: my ($cdom,$cnum) = @_;
7033: if ($cdom eq '' || $cnum eq '') {
7034: return unless ($env{'request.course.id'});
7035: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7036: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7037: }
7038: my %commblocks;
7039: my $hashid=$cdom.'_'.$cnum;
7040: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7041: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7042: %commblocks = %{$blocksref};
7043: } else {
7044: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7045: my $cachetime = 600;
7046: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7047: }
7048: return %commblocks;
7049: }
7050:
7051: sub has_comm_blocking {
7052: my ($priv,$symb,$uri,$blocks) = @_;
7053: return unless ($env{'request.course.id'});
7054: return unless ($priv eq 'bre');
7055: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7056: my %commblocks;
7057: if (ref($blocks) eq 'HASH') {
7058: %commblocks = %{$blocks};
7059: } else {
7060: %commblocks = &get_comm_blocks();
7061: }
7062: return unless (keys(%commblocks) > 0);
7063: if (!$symb) { $symb=&symbread($uri,1); }
7064: my ($map,$resid,undef)=&decode_symb($symb);
7065: my %tocheck = (
7066: maps => $map,
7067: resources => $symb,
7068: );
7069: my @blockers;
7070: my $now = time;
1.1163 raeburn 7071: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7072: foreach my $block (keys(%commblocks)) {
7073: if ($block =~ /^(\d+)____(\d+)$/) {
7074: my ($start,$end) = ($1,$2);
7075: if ($start <= $now && $end >= $now) {
7076: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7077: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7078: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7079: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7080: unless (grep(/^\Q$block\E$/,@blockers)) {
7081: push(@blockers,$block);
7082: }
7083: }
7084: }
7085: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7086: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7087: unless (grep(/^\Q$block\E$/,@blockers)) {
7088: push(@blockers,$block);
7089: }
7090: }
7091: }
7092: }
7093: }
7094: }
7095: } elsif ($block =~ /^firstaccess____(.+)$/) {
7096: my $item = $1;
1.1163 raeburn 7097: my @to_test;
1.1162 raeburn 7098: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7099: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7100: my $check_interval;
7101: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7102: my @interval;
7103: my $type = 'map';
7104: if ($item eq 'course') {
7105: $type = 'course';
7106: @interval=&EXT("resource.0.interval");
7107: } else {
7108: if ($item =~ /___\d+___/) {
7109: $type = 'resource';
7110: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7111: if (ref($navmap)) {
7112: my $res = $navmap->getBySymb($item);
7113: push(@to_test,$res);
7114: }
1.1162 raeburn 7115: } else {
7116: my $mapsymb = &symbread($item,1);
7117: if ($mapsymb) {
7118: if (ref($navmap)) {
7119: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7120: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7121: foreach my $res (@to_test) {
1.1162 raeburn 7122: my $symb = $res->symb();
7123: next if ($symb eq $mapsymb);
7124: if ($symb ne '') {
7125: @interval=&EXT("resource.0.interval",$symb);
7126: last;
7127: }
7128: }
7129: }
7130: }
7131: }
7132: }
7133: if ($interval[0] =~ /\d+/) {
7134: my $first_access;
7135: if ($type eq 'resource') {
7136: $first_access=&get_first_access($interval[1],$item);
7137: } elsif ($type eq 'map') {
7138: $first_access=&get_first_access($interval[1],undef,$item);
7139: } else {
7140: $first_access=&get_first_access($interval[1]);
7141: }
7142: if ($first_access) {
7143: my $timesup = $first_access+$interval[0];
7144: if ($timesup > $now) {
1.1163 raeburn 7145: foreach my $res (@to_test) {
7146: if ($res->is_problem()) {
7147: if ($res->completable()) {
7148: unless (grep(/^\Q$block\E$/,@blockers)) {
7149: push(@blockers,$block);
7150: }
7151: last;
7152: }
7153: }
1.1162 raeburn 7154: }
7155: }
7156: }
7157: }
7158: }
7159: }
7160: }
7161: }
7162: }
7163: return @blockers;
7164: }
7165:
7166: sub check_docs_block {
7167: my ($docsblock,$tocheck) =@_;
7168: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7169: return;
7170: }
7171: if (ref($docsblock->{'maps'}) eq 'HASH') {
7172: if ($tocheck->{'maps'}) {
7173: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7174: return 1;
7175: }
7176: }
7177: }
7178: if (ref($docsblock->{'resources'}) eq 'HASH') {
7179: if ($tocheck->{'resources'}) {
7180: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7181: return 1;
7182: }
7183: }
7184: }
7185: return;
7186: }
7187:
1.1133 foxr 7188: #
7189: # Removes the versino from a URI and
7190: # splits it in to its filename and path to the filename.
7191: # Seems like File::Basename could have done this more clearly.
7192: # Parameters:
7193: # $uri - input URI
7194: # Returns:
7195: # Two element list consisting of
7196: # $pathname - the URI up to and excluding the trailing /
7197: # $filename - The part of the URI following the last /
7198: # NOTE:
7199: # Another realization of this is simply:
7200: # use File::Basename;
7201: # ...
7202: # $uri = shift;
7203: # $filename = basename($uri);
7204: # $path = dirname($uri);
7205: # return ($filename, $path);
7206: #
7207: # The implementation below is probably faster however.
7208: #
1.710 albertel 7209: sub split_uri_for_cond {
7210: my $uri=&deversion(&declutter(shift));
7211: my @uriparts=split(/\//,$uri);
7212: my $filename=pop(@uriparts);
7213: my $pathname=join('/',@uriparts);
7214: return ($pathname,$filename);
7215: }
1.232 www 7216: # --------------------------------------------------- Is a resource on the map?
7217:
7218: sub is_on_map {
1.710 albertel 7219: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7220: #Trying to find the conditional for the file
1.620 albertel 7221: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7222: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7223: if ($match) {
1.289 bowersj2 7224: return (1,$1);
7225: } else {
1.434 www 7226: return (0,0);
1.289 bowersj2 7227: }
1.12 www 7228: }
7229:
1.427 www 7230: # --------------------------------------------------------- Get symb from alias
7231:
7232: sub get_symb_from_alias {
7233: my $symb=shift;
7234: my ($map,$resid,$url)=&decode_symb($symb);
7235: # Already is a symb
7236: if ($url) { return $symb; }
7237: # Must be an alias
7238: my $aliassymb='';
7239: my %bighash;
1.620 albertel 7240: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7241: &GDBM_READER(),0640)) {
7242: my $rid=$bighash{'mapalias_'.$symb};
7243: if ($rid) {
7244: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7245: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7246: $resid,$bighash{'src_'.$rid});
1.427 www 7247: }
7248: untie %bighash;
7249: }
7250: return $aliassymb;
7251: }
7252:
1.12 www 7253: # ----------------------------------------------------------------- Define Role
7254:
7255: sub definerole {
7256: if (allowed('mcr','/')) {
7257: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7258: foreach my $role (split(':',$sysrole)) {
7259: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7260: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7261: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7262: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7263: return "refused:s:$crole&$cqual";
7264: }
7265: }
1.191 harris41 7266: }
1.800 albertel 7267: foreach my $role (split(':',$domrole)) {
7268: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7269: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7270: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7271: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7272: return "refused:d:$crole&$cqual";
7273: }
7274: }
1.191 harris41 7275: }
1.800 albertel 7276: foreach my $role (split(':',$courole)) {
7277: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7278: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7279: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7280: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7281: return "refused:c:$crole&$cqual";
7282: }
7283: }
1.191 harris41 7284: }
1.620 albertel 7285: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7286: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7287: "rolesdef_$rolename=".
7288: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7289: return reply($command,$env{'user.home'});
1.12 www 7290: } else {
7291: return 'refused';
7292: }
1.105 harris41 7293: }
7294:
7295: # ---------------- Make a metadata query against the network of library servers
7296:
7297: sub metadata_query {
1.1237 raeburn 7298: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7299: my %rhash;
1.845 albertel 7300: my %libserv = &all_library();
1.244 matthew 7301: my @server_list = (defined($server_array) ? @$server_array
7302: : keys(%libserv) );
7303: for my $server (@server_list) {
1.1237 raeburn 7304: my $domains = '';
7305: if (ref($domains_hash) eq 'HASH') {
7306: $domains = $domains_hash->{$server};
7307: }
1.118 harris41 7308: unless ($custom or $customshow) {
1.1237 raeburn 7309: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7310: $rhash{$server}=$reply;
7311: }
7312: else {
7313: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7314: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7315: $server);
7316: $rhash{$server}=$reply;
7317: }
1.112 harris41 7318: }
1.118 harris41 7319: return \%rhash;
1.240 www 7320: }
7321:
7322: # ----------------------------------------- Send log queries and wait for reply
7323:
7324: sub log_query {
7325: my ($uname,$udom,$query,%filters)=@_;
7326: my $uhome=&homeserver($uname,$udom);
7327: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7328: my $uhost=&hostname($uhome);
1.800 albertel 7329: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7330: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7331: $uhome);
1.479 albertel 7332: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7333: return get_query_reply($queryid);
7334: }
7335:
1.818 raeburn 7336: # -------------------------- Update MySQL table for portfolio file
7337:
7338: sub update_portfolio_table {
1.821 raeburn 7339: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7340: if ($group ne '') {
7341: $file_name =~s /^\Q$group\E//;
7342: }
1.818 raeburn 7343: my $homeserver = &homeserver($uname,$udom);
7344: my $queryid=
1.821 raeburn 7345: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7346: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7347: my $reply = &get_query_reply($queryid);
7348: return $reply;
7349: }
7350:
1.899 raeburn 7351: # -------------------------- Update MySQL allusers table
7352:
7353: sub update_allusers_table {
7354: my ($uname,$udom,$names) = @_;
7355: my $homeserver = &homeserver($uname,$udom);
7356: my $queryid=
7357: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7358: 'lastname='.&escape($names->{'lastname'}).'%%'.
7359: 'firstname='.&escape($names->{'firstname'}).'%%'.
7360: 'middlename='.&escape($names->{'middlename'}).'%%'.
7361: 'generation='.&escape($names->{'generation'}).'%%'.
7362: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7363: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7364: return;
1.899 raeburn 7365: }
7366:
1.508 raeburn 7367: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7368:
7369: sub fetch_enrollment_query {
1.511 raeburn 7370: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7371: my $homeserver;
1.547 raeburn 7372: my $maxtries = 1;
1.508 raeburn 7373: if ($context eq 'automated') {
7374: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7375: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7376: } else {
7377: $homeserver = &homeserver($cnum,$dom);
7378: }
1.838 albertel 7379: my $host=&hostname($homeserver);
1.506 raeburn 7380: my $cmd = '';
1.1000 raeburn 7381: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7382: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7383: }
7384: $cmd =~ s/%%$//;
7385: $cmd = &escape($cmd);
7386: my $query = 'fetchenrollment';
1.620 albertel 7387: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7388: unless ($queryid=~/^\Q$host\E\_/) {
7389: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7390: return 'error: '.$queryid;
7391: }
1.506 raeburn 7392: my $reply = &get_query_reply($queryid);
1.547 raeburn 7393: my $tries = 1;
7394: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7395: $reply = &get_query_reply($queryid);
7396: $tries ++;
7397: }
1.526 raeburn 7398: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7399: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7400: } else {
1.901 albertel 7401: my @responses = split(/:/,$reply);
1.515 raeburn 7402: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7403: foreach my $line (@responses) {
7404: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7405: $$replyref{$key} = $value;
7406: }
7407: } else {
1.1117 foxr 7408: my $pathname = LONCAPA::tempdir();
1.800 albertel 7409: foreach my $line (@responses) {
7410: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7411: $$replyref{$key} = $value;
7412: if ($value > 0) {
1.800 albertel 7413: foreach my $item (@{$$affiliatesref{$key}}) {
7414: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7415: my $destname = $pathname.'/'.$filename;
7416: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7417: if ($xml_classlist =~ /^error/) {
7418: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7419: } else {
1.506 raeburn 7420: if ( open(FILE,">$destname") ) {
7421: print FILE &unescape($xml_classlist);
7422: close(FILE);
1.526 raeburn 7423: } else {
7424: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7425: }
7426: }
7427: }
7428: }
7429: }
7430: }
7431: return 'ok';
7432: }
7433: return 'error';
7434: }
7435:
1.242 www 7436: sub get_query_reply {
7437: my $queryid=shift;
1.1117 foxr 7438: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7439: my $reply='';
7440: for (1..100) {
7441: sleep 2;
7442: if (-e $replyfile.'.end') {
1.448 albertel 7443: if (open(my $fh,$replyfile)) {
1.904 albertel 7444: $reply = join('',<$fh>);
7445: close($fh);
1.240 www 7446: } else { return 'error: reply_file_error'; }
1.242 www 7447: return &unescape($reply);
7448: }
1.240 www 7449: }
1.242 www 7450: return 'timeout:'.$queryid;
1.240 www 7451: }
7452:
7453: sub courselog_query {
1.241 www 7454: #
7455: # possible filters:
7456: # url: url or symb
7457: # username
7458: # domain
7459: # action: view, submit, grade
7460: # start: timestamp
7461: # end: timestamp
7462: #
1.240 www 7463: my (%filters)=@_;
1.620 albertel 7464: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7465: if ($filters{'url'}) {
7466: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7467: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7468: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7469: }
1.620 albertel 7470: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7471: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7472: return &log_query($cname,$cdom,'courselog',%filters);
7473: }
7474:
7475: sub userlog_query {
1.858 raeburn 7476: #
7477: # possible filters:
7478: # action: log check role
7479: # start: timestamp
7480: # end: timestamp
7481: #
1.240 www 7482: my ($uname,$udom,%filters)=@_;
7483: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7484: }
7485:
1.506 raeburn 7486: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7487:
7488: sub auto_run {
1.508 raeburn 7489: my ($cnum,$cdom) = @_;
1.876 raeburn 7490: my $response = 0;
7491: my $settings;
7492: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7493: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7494: $settings = $domconfig{'autoenroll'};
7495: if ($settings->{'run'} eq '1') {
7496: $response = 1;
7497: }
7498: } else {
1.934 raeburn 7499: my $homeserver;
7500: if (&is_course($cdom,$cnum)) {
7501: $homeserver = &homeserver($cnum,$cdom);
7502: } else {
7503: $homeserver = &domain($cdom,'primary');
7504: }
7505: if ($homeserver ne 'no_host') {
7506: $response = &reply('autorun:'.$cdom,$homeserver);
7507: }
1.876 raeburn 7508: }
1.506 raeburn 7509: return $response;
7510: }
1.776 albertel 7511:
1.506 raeburn 7512: sub auto_get_sections {
1.508 raeburn 7513: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7514: my $homeserver;
7515: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7516: $homeserver = &homeserver($cnum,$cdom);
7517: }
7518: if (!defined($homeserver)) {
7519: if ($cdom =~ /^$match_domain$/) {
7520: $homeserver = &domain($cdom,'primary');
7521: }
7522: }
7523: my @secs;
7524: if (defined($homeserver)) {
7525: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7526: unless ($response eq 'refused') {
7527: @secs = split(/:/,$response);
7528: }
1.506 raeburn 7529: }
7530: return @secs;
7531: }
1.776 albertel 7532:
1.506 raeburn 7533: sub auto_new_course {
1.1099 raeburn 7534: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7535: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7536: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7537: return $response;
7538: }
1.776 albertel 7539:
1.506 raeburn 7540: sub auto_validate_courseID {
1.508 raeburn 7541: my ($cnum,$cdom,$inst_course_id) = @_;
7542: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7543: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7544: return $response;
7545: }
1.776 albertel 7546:
1.1007 raeburn 7547: sub auto_validate_instcode {
1.1020 raeburn 7548: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7549: my ($homeserver,$response);
7550: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7551: $homeserver = &homeserver($cnum,$cdom);
7552: }
7553: if (!defined($homeserver)) {
7554: if ($cdom =~ /^$match_domain$/) {
7555: $homeserver = &domain($cdom,'primary');
7556: }
7557: }
1.1065 raeburn 7558: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7559: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7560: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7561: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7562: }
7563:
1.506 raeburn 7564: sub auto_create_password {
1.873 raeburn 7565: my ($cnum,$cdom,$authparam,$udom) = @_;
7566: my ($homeserver,$response);
1.506 raeburn 7567: my $create_passwd = 0;
7568: my $authchk = '';
1.873 raeburn 7569: if ($udom =~ /^$match_domain$/) {
7570: $homeserver = &domain($udom,'primary');
7571: }
7572: if ($homeserver eq '') {
7573: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7574: $homeserver = &homeserver($cnum,$cdom);
7575: }
7576: }
7577: if ($homeserver eq '') {
7578: $authchk = 'nodomain';
1.506 raeburn 7579: } else {
1.873 raeburn 7580: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7581: if ($response eq 'refused') {
7582: $authchk = 'refused';
7583: } else {
1.901 albertel 7584: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7585: }
1.506 raeburn 7586: }
7587: return ($authparam,$create_passwd,$authchk);
7588: }
7589:
1.706 raeburn 7590: sub auto_photo_permission {
7591: my ($cnum,$cdom,$students) = @_;
7592: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7593: my ($outcome,$perm_reqd,$conditions) =
7594: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7595: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7596: return (undef,undef);
7597: }
1.706 raeburn 7598: return ($outcome,$perm_reqd,$conditions);
7599: }
7600:
7601: sub auto_checkphotos {
7602: my ($uname,$udom,$pid) = @_;
7603: my $homeserver = &homeserver($uname,$udom);
7604: my ($result,$resulttype);
7605: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7606: &escape($uname).':'.&escape($pid),
7607: $homeserver));
1.709 albertel 7608: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7609: return (undef,undef);
7610: }
1.706 raeburn 7611: if ($outcome) {
7612: ($result,$resulttype) = split(/:/,$outcome);
7613: }
7614: return ($result,$resulttype);
7615: }
7616:
7617: sub auto_photochoice {
7618: my ($cnum,$cdom) = @_;
7619: my $homeserver = &homeserver($cnum,$cdom);
7620: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7621: &escape($cdom),
7622: $homeserver)));
1.709 albertel 7623: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7624: return (undef,undef);
7625: }
1.706 raeburn 7626: return ($update,$comment);
7627: }
7628:
7629: sub auto_photoupdate {
7630: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7631: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7632: my $host=&hostname($homeserver);
1.706 raeburn 7633: my $cmd = '';
7634: my $maxtries = 1;
1.800 albertel 7635: foreach my $affiliate (keys(%{$affiliatesref})) {
7636: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7637: }
7638: $cmd =~ s/%%$//;
7639: $cmd = &escape($cmd);
7640: my $query = 'institutionalphotos';
7641: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7642: unless ($queryid=~/^\Q$host\E\_/) {
7643: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7644: return 'error: '.$queryid;
7645: }
7646: my $reply = &get_query_reply($queryid);
7647: my $tries = 1;
7648: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7649: $reply = &get_query_reply($queryid);
7650: $tries ++;
7651: }
7652: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7653: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7654: } else {
7655: my @responses = split(/:/,$reply);
7656: my $outcome = shift(@responses);
7657: foreach my $item (@responses) {
7658: my ($key,$value) = split(/=/,$item);
7659: $$photo{$key} = $value;
7660: }
7661: return $outcome;
7662: }
7663: return 'error';
7664: }
7665:
1.521 raeburn 7666: sub auto_instcode_format {
1.793 albertel 7667: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7668: $cat_order) = @_;
1.521 raeburn 7669: my $courses = '';
1.772 raeburn 7670: my @homeservers;
1.521 raeburn 7671: if ($caller eq 'global') {
1.841 albertel 7672: my %servers = &get_servers($codedom,'library');
7673: foreach my $tryserver (keys(%servers)) {
7674: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7675: push(@homeservers,$tryserver);
7676: }
1.584 raeburn 7677: }
1.1022 raeburn 7678: } elsif ($caller eq 'requests') {
7679: if ($codedom =~ /^$match_domain$/) {
7680: my $chome = &domain($codedom,'primary');
7681: unless ($chome eq 'no_host') {
7682: push(@homeservers,$chome);
7683: }
7684: }
1.521 raeburn 7685: } else {
1.772 raeburn 7686: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7687: }
1.793 albertel 7688: foreach my $code (keys(%{$instcodes})) {
7689: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7690: }
7691: chop($courses);
1.772 raeburn 7692: my $ok_response = 0;
7693: my $response;
7694: while (@homeservers > 0 && $ok_response == 0) {
7695: my $server = shift(@homeservers);
7696: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7697: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7698: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7699: split(/:/,$response);
1.772 raeburn 7700: %{$codes} = (%{$codes},&str2hash($codes_str));
7701: push(@{$codetitles},&str2array($codetitles_str));
7702: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7703: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7704: $ok_response = 1;
7705: }
7706: }
7707: if ($ok_response) {
1.521 raeburn 7708: return 'ok';
1.772 raeburn 7709: } else {
7710: return $response;
1.521 raeburn 7711: }
7712: }
7713:
1.792 raeburn 7714: sub auto_instcode_defaults {
7715: my ($domain,$returnhash,$code_order) = @_;
7716: my @homeservers;
1.841 albertel 7717:
7718: my %servers = &get_servers($domain,'library');
7719: foreach my $tryserver (keys(%servers)) {
7720: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7721: push(@homeservers,$tryserver);
7722: }
1.792 raeburn 7723: }
1.841 albertel 7724:
1.792 raeburn 7725: my $response;
1.841 albertel 7726: foreach my $server (@homeservers) {
1.792 raeburn 7727: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7728: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7729:
7730: foreach my $pair (split(/\&/,$response)) {
7731: my ($name,$value)=split(/\=/,$pair);
7732: if ($name eq 'code_order') {
7733: @{$code_order} = split(/\&/,&unescape($value));
7734: } else {
7735: $returnhash->{&unescape($name)}=&unescape($value);
7736: }
7737: }
7738: return 'ok';
1.792 raeburn 7739: }
1.841 albertel 7740:
7741: return $response;
1.1003 raeburn 7742: }
7743:
7744: sub auto_possible_instcodes {
1.1007 raeburn 7745: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7746: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7747: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7748: return;
7749: }
1.1003 raeburn 7750: my (@homeservers,$uhome);
7751: if (defined(&domain($domain,'primary'))) {
7752: $uhome=&domain($domain,'primary');
7753: push(@homeservers,&domain($domain,'primary'));
7754: } else {
7755: my %servers = &get_servers($domain,'library');
7756: foreach my $tryserver (keys(%servers)) {
7757: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7758: push(@homeservers,$tryserver);
7759: }
7760: }
7761: }
7762: my $response;
7763: foreach my $server (@homeservers) {
7764: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7765: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7766: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7767: split(':',$response);
7768: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7769: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7770: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7771: my ($name,$value)=split('=',$item);
7772: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7773: }
7774: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7775: my ($name,$value)=split('=',$item);
7776: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7777: }
7778: return 'ok';
7779: }
7780: return $response;
7781: }
1.792 raeburn 7782:
1.1010 raeburn 7783: sub auto_courserequest_checks {
7784: my ($dom) = @_;
1.1020 raeburn 7785: my ($homeserver,%validations);
7786: if ($dom =~ /^$match_domain$/) {
7787: $homeserver = &domain($dom,'primary');
7788: }
7789: unless ($homeserver eq 'no_host') {
7790: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7791: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7792: my @items = split(/&/,$response);
7793: foreach my $item (@items) {
7794: my ($key,$value) = split('=',$item);
7795: $validations{&unescape($key)} = &thaw_unescape($value);
7796: }
7797: }
7798: }
1.1010 raeburn 7799: return %validations;
7800: }
7801:
1.1020 raeburn 7802: sub auto_courserequest_validation {
7803: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7804: my ($homeserver,$response);
7805: if ($dom =~ /^$match_domain$/) {
7806: $homeserver = &domain($dom,'primary');
7807: }
7808: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7809:
1.1020 raeburn 7810: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7811: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7812: ':'.&escape($instcode).':'.&escape($instseclist),
7813: $homeserver));
7814: }
7815: return $response;
7816: }
7817:
1.777 albertel 7818: sub auto_validate_class_sec {
1.918 raeburn 7819: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7820: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7821: my $ownerlist;
7822: if (ref($owners) eq 'ARRAY') {
7823: $ownerlist = join(',',@{$owners});
7824: } else {
7825: $ownerlist = $owners;
7826: }
1.773 raeburn 7827: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7828: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7829: return $response;
7830: }
7831:
1.679 raeburn 7832: # ------------------------------------------------------- Course Group routines
7833:
7834: sub get_coursegroups {
1.809 raeburn 7835: my ($cdom,$cnum,$group,$namespace) = @_;
7836: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7837: }
7838:
1.679 raeburn 7839: sub modify_coursegroup {
7840: my ($cdom,$cnum,$groupsettings) = @_;
7841: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7842: }
7843:
1.809 raeburn 7844: sub toggle_coursegroup_status {
7845: my ($cdom,$cnum,$group,$action) = @_;
7846: my ($from_namespace,$to_namespace);
7847: if ($action eq 'delete') {
7848: $from_namespace = 'coursegroups';
7849: $to_namespace = 'deleted_groups';
7850: } else {
7851: $from_namespace = 'deleted_groups';
7852: $to_namespace = 'coursegroups';
7853: }
7854: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7855: if (my $tmp = &error(%curr_group)) {
7856: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7857: return ('read error',$tmp);
7858: } else {
7859: my %savedsettings = %curr_group;
1.809 raeburn 7860: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7861: my $deloutcome;
7862: if ($result eq 'ok') {
1.809 raeburn 7863: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7864: } else {
7865: return ('write error',$result);
7866: }
7867: if ($deloutcome eq 'ok') {
7868: return 'ok';
7869: } else {
7870: return ('delete error',$deloutcome);
7871: }
7872: }
7873: }
7874:
1.679 raeburn 7875: sub modify_group_roles {
1.957 raeburn 7876: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7877: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7878: my $role = 'gr/'.&escape($userprivs);
7879: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7880: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7881: if ($result eq 'ok') {
7882: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7883: }
1.679 raeburn 7884: return $result;
7885: }
7886:
7887: sub modify_coursegroup_membership {
7888: my ($cdom,$cnum,$membership) = @_;
7889: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7890: return $result;
7891: }
7892:
1.682 raeburn 7893: sub get_active_groups {
7894: my ($udom,$uname,$cdom,$cnum) = @_;
7895: my $now = time;
7896: my %groups = ();
7897: foreach my $key (keys(%env)) {
1.811 albertel 7898: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7899: my ($start,$end) = split(/\./,$env{$key});
7900: if (($end!=0) && ($end<$now)) { next; }
7901: if (($start!=0) && ($start>$now)) { next; }
7902: if ($1 eq $cdom && $2 eq $cnum) {
7903: $groups{$3} = $env{$key} ;
7904: }
7905: }
7906: }
7907: return %groups;
7908: }
7909:
1.683 raeburn 7910: sub get_group_membership {
7911: my ($cdom,$cnum,$group) = @_;
7912: return(&dump('groupmembership',$cdom,$cnum,$group));
7913: }
7914:
7915: sub get_users_groups {
7916: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7917: my @usersgroups;
1.683 raeburn 7918: my $cachetime=1800;
7919:
7920: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7921: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7922: if (defined($cached)) {
1.734 albertel 7923: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7924: } else {
7925: $grouplist = '';
1.816 raeburn 7926: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7927: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7928: my $access_end = $env{'course.'.$courseid.
7929: '.default_enrollment_end_date'};
7930: my $now = time;
7931: foreach my $key (keys(%roleshash)) {
7932: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7933: my $group = $1;
7934: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7935: my $start = $2;
7936: my $end = $1;
7937: if ($start == -1) { next; } # deleted from group
7938: if (($start!=0) && ($start>$now)) { next; }
7939: if (($end!=0) && ($end<$now)) {
7940: if ($access_end && $access_end < $now) {
7941: if ($access_end - $end < 86400) {
7942: push(@usersgroups,$group);
1.733 raeburn 7943: }
7944: }
1.817 raeburn 7945: next;
1.733 raeburn 7946: }
1.817 raeburn 7947: push(@usersgroups,$group);
1.683 raeburn 7948: }
7949: }
7950: }
1.817 raeburn 7951: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7952: $grouplist = join(':',@usersgroups);
7953: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7954: }
1.733 raeburn 7955: return @usersgroups;
1.683 raeburn 7956: }
7957:
7958: sub devalidate_getgroups_cache {
7959: my ($udom,$uname,$cdom,$cnum)=@_;
7960: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7961:
1.683 raeburn 7962: my $hashid="$udom:$uname:$courseid";
7963: &devalidate_cache_new('getgroups',$hashid);
7964: }
7965:
1.12 www 7966: # ------------------------------------------------------------------ Plain Text
7967:
7968: sub plaintext {
1.988 raeburn 7969: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7970: if ($short =~ m{^cr/}) {
1.758 albertel 7971: return (split('/',$short))[-1];
7972: }
1.742 raeburn 7973: if (!defined($cid)) {
7974: $cid = $env{'request.course.id'};
7975: }
7976: my %rolenames = (
1.1008 raeburn 7977: Course => 'std',
7978: Community => 'alt1',
1.742 raeburn 7979: );
1.1037 raeburn 7980: if ($cid ne '') {
7981: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7982: unless ($forcedefault) {
7983: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7984: &Apache::lonlocal::mt_escape(\$roletext);
7985: return &Apache::lonlocal::mt($roletext);
7986: }
7987: }
7988: }
7989: if ((defined($type)) && (defined($rolenames{$type})) &&
7990: (defined($rolenames{$type})) &&
7991: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7992: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7993: } elsif ($cid ne '') {
7994: my $crstype = $env{'course.'.$cid.'.type'};
7995: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7996: (defined($prp{$short}{$rolenames{$crstype}}))) {
7997: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7998: }
1.742 raeburn 7999: }
1.1037 raeburn 8000: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8001: }
8002:
8003: # ----------------------------------------------------------------- Assign Role
8004:
8005: sub assignrole {
1.957 raeburn 8006: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8007: $context)=@_;
1.21 www 8008: my $mrole;
8009: if ($role =~ /^cr\//) {
1.393 www 8010: my $cwosec=$url;
1.811 albertel 8011: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8012: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8013: my $refused = 1;
8014: if ($context eq 'requestcourses') {
8015: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8016: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8017: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8018: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8019: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8020: if ($crsenv{'internal.courseowner'} eq
8021: $env{'user.name'}.':'.$env{'user.domain'}) {
8022: $refused = '';
8023: }
8024: }
8025: }
8026: }
8027: }
8028: if ($refused) {
8029: &logthis('Refused custom assignrole: '.
8030: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8031: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8032: return 'refused';
8033: }
1.104 www 8034: }
1.21 www 8035: $mrole='cr';
1.678 raeburn 8036: } elsif ($role =~ /^gr\//) {
8037: my $cwogrp=$url;
1.811 albertel 8038: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8039: unless (&allowed('mdg',$cwogrp)) {
8040: &logthis('Refused group assignrole: '.
8041: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8042: $env{'user.name'}.' at '.$env{'user.domain'});
8043: return 'refused';
8044: }
8045: $mrole='gr';
1.21 www 8046: } else {
1.82 www 8047: my $cwosec=$url;
1.811 albertel 8048: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8049: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8050: my $refused;
8051: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8052: if (!(&allowed('c'.$role,$url))) {
8053: $refused = 1;
8054: }
8055: } else {
8056: $refused = 1;
8057: }
1.947 raeburn 8058: if ($refused) {
1.1045 raeburn 8059: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8060: if (!$selfenroll && $context eq 'course') {
8061: my %crsenv;
8062: if ($role eq 'cc' || $role eq 'co') {
8063: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8064: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8065: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8066: if ($crsenv{'internal.courseowner'} eq
8067: $env{'user.name'}.':'.$env{'user.domain'}) {
8068: $refused = '';
8069: }
8070: }
8071: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8072: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8073: if ($crsenv{'internal.courseowner'} eq
8074: $env{'user.name'}.':'.$env{'user.domain'}) {
8075: $refused = '';
8076: }
8077: }
8078: }
8079: }
8080: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8081: $refused = '';
1.1017 raeburn 8082: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8083: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8084: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8085: my $wrongcc;
8086: if ($cnum =~ /^$match_community$/) {
8087: $wrongcc = 1 if ($role eq 'cc');
8088: } else {
8089: $wrongcc = 1 if ($role eq 'co');
8090: }
8091: unless ($wrongcc) {
8092: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8093: if ($crsenv{'internal.courseowner'} eq
8094: $env{'user.name'}.':'.$env{'user.domain'}) {
8095: $refused = '';
8096: }
1.1017 raeburn 8097: }
8098: }
1.1183 raeburn 8099: } elsif ($context eq 'requestauthor') {
8100: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8101: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8102: if ($env{'environment.requestauthor'} eq 'automatic') {
8103: $refused = '';
8104: } else {
8105: my %domdefaults = &get_domain_defaults($udom);
8106: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8107: my $checkbystatus;
8108: if ($env{'user.adv'}) {
8109: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8110: if ($disposition eq 'automatic') {
8111: $refused = '';
8112: } elsif ($disposition eq '') {
8113: $checkbystatus = 1;
8114: }
8115: } else {
8116: $checkbystatus = 1;
8117: }
8118: if ($checkbystatus) {
8119: if ($env{'environment.inststatus'}) {
8120: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8121: foreach my $type (@inststatuses) {
8122: if (($type ne '') &&
8123: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8124: $refused = '';
8125: }
8126: }
8127: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8128: $refused = '';
8129: }
8130: }
8131: }
8132: }
8133: }
1.1017 raeburn 8134: }
8135: if ($refused) {
1.947 raeburn 8136: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8137: ' '.$role.' '.$end.' '.$start.' by '.
8138: $env{'user.name'}.' at '.$env{'user.domain'});
8139: return 'refused';
8140: }
1.932 raeburn 8141: }
1.1131 raeburn 8142: } elsif ($role eq 'au') {
8143: if ($url ne '/'.$udom.'/') {
8144: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8145: ' to assign author role for '.$uname.':'.$udom.
8146: ' in domain: '.$url.' refused (wrong domain).');
8147: return 'refused';
8148: }
1.104 www 8149: }
1.21 www 8150: $mrole=$role;
8151: }
1.620 albertel 8152: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8153: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8154: if ($end) { $command.='_'.$end; }
1.21 www 8155: if ($start) {
8156: if ($end) {
1.81 www 8157: $command.='_'.$start;
1.21 www 8158: } else {
1.81 www 8159: $command.='_0_'.$start;
1.21 www 8160: }
8161: }
1.739 raeburn 8162: my $origstart = $start;
8163: my $origend = $end;
1.957 raeburn 8164: my $delflag;
1.357 www 8165: # actually delete
8166: if ($deleteflag) {
1.373 www 8167: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8168: # modify command to delete the role
1.620 albertel 8169: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8170: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8171: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8172: # set start and finish to negative values for userrolelog
8173: $start=-1;
8174: $end=-1;
1.957 raeburn 8175: $delflag = 1;
1.357 www 8176: }
8177: }
8178: # send command
1.349 www 8179: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8180: # log new user role if status is ok
1.349 www 8181: if ($answer eq 'ok') {
1.663 raeburn 8182: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8183: if (($role eq 'cc') || ($role eq 'in') ||
8184: ($role eq 'ep') || ($role eq 'ad') ||
8185: ($role eq 'ta') || ($role eq 'st') ||
8186: ($role=~/^cr/) || ($role eq 'gr') ||
8187: ($role eq 'co')) {
1.1200 raeburn 8188: # for course roles, perform group memberships changes triggered by role change.
8189: unless ($role =~ /^gr/) {
8190: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8191: $origstart,$selfenroll,$context);
8192: }
1.1184 raeburn 8193: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8194: $selfenroll,$context);
8195: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8196: ($role eq 'au') || ($role eq 'dc')) {
8197: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8198: $context);
8199: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8200: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8201: $context);
8202: }
1.1053 raeburn 8203: if ($role eq 'cc') {
8204: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8205: }
1.349 www 8206: }
8207: return $answer;
1.169 harris41 8208: }
8209:
1.1053 raeburn 8210: sub autoupdate_coowners {
8211: my ($url,$end,$start,$uname,$udom) = @_;
8212: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8213: if (($cdom ne '') && ($cnum ne '')) {
8214: my $now = time;
8215: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8216: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8217: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8218: my $instcode = $coursehash{'internal.coursecode'};
8219: if ($instcode ne '') {
1.1056 raeburn 8220: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8221: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8222: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8223: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8224: if ($result eq 'valid') {
8225: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8226: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8227: push(@newcoowners,$coowner);
8228: }
8229: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8230: push(@newcoowners,$uname.':'.$udom);
8231: }
8232: @newcoowners = sort(@newcoowners);
8233: } else {
8234: push(@newcoowners,$uname.':'.$udom);
8235: }
8236: } else {
8237: if ($coursehash{'internal.co-owners'}) {
8238: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8239: unless ($coowner eq $uname.':'.$udom) {
8240: push(@newcoowners,$coowner);
8241: }
8242: }
8243: unless (@newcoowners > 0) {
8244: $delcoowners = 1;
8245: $coowners = '';
8246: }
8247: }
8248: }
8249: if (@newcoowners || $delcoowners) {
8250: &store_coowners($cdom,$cnum,$coursehash{'home'},
8251: $delcoowners,@newcoowners);
8252: }
8253: }
8254: }
8255: }
8256: }
8257: }
8258: }
8259:
8260: sub store_coowners {
8261: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8262: my $cid = $cdom.'_'.$cnum;
8263: my ($coowners,$delresult,$putresult);
8264: if (@newcoowners) {
8265: $coowners = join(',',@newcoowners);
8266: my %coownershash = (
8267: 'internal.co-owners' => $coowners,
8268: );
8269: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8270: if ($putresult eq 'ok') {
8271: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8272: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8273: }
8274: }
8275: }
8276: if ($delcoowners) {
8277: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8278: if ($delresult eq 'ok') {
8279: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8280: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8281: }
8282: }
8283: }
8284: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8285: my %crsinfo =
8286: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8287: if (ref($crsinfo{$cid}) eq 'HASH') {
8288: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8289: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8290: }
8291: }
8292: }
8293:
1.169 harris41 8294: # -------------------------------------------------- Modify user authentication
1.197 www 8295: # Overrides without validation
8296:
1.169 harris41 8297: sub modifyuserauth {
8298: my ($udom,$uname,$umode,$upass)=@_;
8299: my $uhome=&homeserver($uname,$udom);
1.197 www 8300: unless (&allowed('mau',$udom)) { return 'refused'; }
8301: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8302: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8303: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8304: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8305: &escape($upass),$uhome);
1.620 albertel 8306: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8307: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8308: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8309: &log($udom,,$uname,$uhome,
1.620 albertel 8310: 'Authentication changed by '.$env{'user.domain'}.', '.
8311: $env{'user.name'}.', '.$umode.
1.197 www 8312: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8313: unless ($reply eq 'ok') {
1.197 www 8314: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8315: return 'error: '.$reply;
8316: }
1.170 harris41 8317: return 'ok';
1.80 www 8318: }
8319:
1.81 www 8320: # --------------------------------------------------------------- Modify a user
1.80 www 8321:
1.81 www 8322: sub modifyuser {
1.206 matthew 8323: my ($udom, $uname, $uid,
8324: $umode, $upass, $first,
8325: $middle, $last, $gene,
1.1058 raeburn 8326: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8327: $udom= &LONCAPA::clean_domain($udom);
8328: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8329: my $showcandelete = 'none';
8330: if (ref($candelete) eq 'ARRAY') {
8331: if (@{$candelete} > 0) {
8332: $showcandelete = join(', ',@{$candelete});
8333: }
8334: }
1.81 www 8335: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8336: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8337: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8338: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8339: ' desiredhome not specified').
1.620 albertel 8340: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8341: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8342: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8343: my $newuser;
8344: if ($uhome eq 'no_host') {
8345: $newuser = 1;
8346: }
1.80 www 8347: # ----------------------------------------------------------------- Create User
1.406 albertel 8348: if (($uhome eq 'no_host') &&
8349: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8350: my $unhome='';
1.844 albertel 8351: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8352: $unhome = $desiredhome;
1.620 albertel 8353: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8354: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8355: } else { # load balancing routine for determining $unhome
1.81 www 8356: my $loadm=10000000;
1.841 albertel 8357: my %servers = &get_servers($udom,'library');
8358: foreach my $tryserver (keys(%servers)) {
8359: my $answer=reply('load',$tryserver);
8360: if (($answer=~/\d+/) && ($answer<$loadm)) {
8361: $loadm=$answer;
8362: $unhome=$tryserver;
8363: }
1.80 www 8364: }
8365: }
8366: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8367: return 'error: unable to find a home server for '.$uname.
8368: ' in domain '.$udom;
1.80 www 8369: }
8370: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8371: &escape($upass),$unhome);
8372: unless ($reply eq 'ok') {
8373: return 'error: '.$reply;
8374: }
1.230 stredwic 8375: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8376: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8377: return 'error: unable verify users home machine.';
1.80 www 8378: }
1.209 matthew 8379: } # End of creation of new user
1.80 www 8380: # ---------------------------------------------------------------------- Add ID
8381: if ($uid) {
8382: $uid=~tr/A-Z/a-z/;
8383: my %uidhash=&idrget($udom,$uname);
1.196 www 8384: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8385: && (!$forceid)) {
1.80 www 8386: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8387: return 'error: user id "'.$uid.'" does not match '.
8388: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8389: }
8390: } else {
8391: &idput($udom,($uname => $uid));
8392: }
8393: }
8394: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8395: my @tmp=&get('environment',
1.899 raeburn 8396: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8397: 'permanentemail','inststatus'],
1.134 albertel 8398: $udom,$uname);
1.1075 raeburn 8399: my (%names,%oldnames);
1.313 matthew 8400: if ($tmp[0] =~ m/^error:.*/) {
8401: %names=();
8402: } else {
8403: %names = @tmp;
1.1075 raeburn 8404: %oldnames = %names;
1.313 matthew 8405: }
1.388 www 8406: #
1.1058 raeburn 8407: # If name, email and/or uid are blank (e.g., because an uploaded file
8408: # of users did not contain them), do not overwrite existing values
8409: # unless field is in $candelete array ref.
8410: #
8411:
8412: my @fields = ('firstname','middlename','lastname','generation',
8413: 'permanentemail','id');
8414: my %newvalues;
8415: if (ref($candelete) eq 'ARRAY') {
8416: foreach my $field (@fields) {
8417: if (grep(/^\Q$field\E$/,@{$candelete})) {
8418: if ($field eq 'firstname') {
8419: $names{$field} = $first;
8420: } elsif ($field eq 'middlename') {
8421: $names{$field} = $middle;
8422: } elsif ($field eq 'lastname') {
8423: $names{$field} = $last;
8424: } elsif ($field eq 'generation') {
8425: $names{$field} = $gene;
8426: } elsif ($field eq 'permanentemail') {
8427: $names{$field} = $email;
8428: } elsif ($field eq 'id') {
8429: $names{$field} = $uid;
8430: }
8431: }
8432: }
8433: }
1.388 www 8434: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8435: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8436: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8437: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8438: if ($email) {
8439: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8440: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8441: }
1.899 raeburn 8442: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8443: if (defined($inststatus)) {
8444: $names{'inststatus'} = '';
8445: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8446: if (ref($usertypes) eq 'HASH') {
8447: my @okstatuses;
8448: foreach my $item (split(/:/,$inststatus)) {
8449: if (defined($usertypes->{$item})) {
8450: push(@okstatuses,$item);
8451: }
8452: }
8453: if (@okstatuses) {
8454: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8455: }
8456: }
8457: }
1.1075 raeburn 8458: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8459: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8460: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8461: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8462: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8463: } else {
8464: $logmsg .= ' during self creation';
8465: }
1.1075 raeburn 8466: my $changed;
8467: if ($newuser) {
8468: $changed = 1;
8469: } else {
8470: foreach my $field (@fields) {
8471: if ($names{$field} ne $oldnames{$field}) {
8472: $changed = 1;
8473: last;
8474: }
8475: }
8476: }
8477: unless ($changed) {
8478: $logmsg = 'No changes in user information needed for: '.$logmsg;
8479: &logthis($logmsg);
8480: return 'ok';
8481: }
8482: my $reply = &put('environment', \%names, $udom,$uname);
8483: if ($reply ne 'ok') {
8484: return 'error: '.$reply;
8485: }
1.1087 raeburn 8486: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8487: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8488: }
1.1075 raeburn 8489: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8490: &devalidate_cache_new('namescache',$uname.':'.$udom);
8491: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8492: &logthis($logmsg);
1.134 albertel 8493: return 'ok';
1.80 www 8494: }
8495:
1.81 www 8496: # -------------------------------------------------------------- Modify student
1.80 www 8497:
1.81 www 8498: sub modifystudent {
8499: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8500: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8501: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8502: if (!$cid) {
1.620 albertel 8503: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8504: return 'not_in_class';
8505: }
1.80 www 8506: }
8507: # --------------------------------------------------------------- Make the user
1.81 www 8508: my $reply=&modifyuser
1.209 matthew 8509: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8510: $desiredhome,$email,$inststatus);
1.80 www 8511: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8512: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8513: # student's environment
1.297 matthew 8514: $uid = undef if (!$forceid);
1.455 albertel 8515: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8516: $gene,$usec,$end,$start,$type,$locktype,
8517: $cid,$selfenroll,$context,$credits);
1.297 matthew 8518: return $reply;
8519: }
8520:
8521: sub modify_student_enrollment {
1.1216 raeburn 8522: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8523: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8524: my ($cdom,$cnum,$chome);
8525: if (!$cid) {
1.620 albertel 8526: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8527: return 'not_in_class';
8528: }
1.620 albertel 8529: $cdom=$env{'course.'.$cid.'.domain'};
8530: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8531: } else {
8532: ($cdom,$cnum)=split(/_/,$cid);
8533: }
1.620 albertel 8534: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8535: if (!$chome) {
1.457 raeburn 8536: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8537: }
1.455 albertel 8538: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8539: # Make sure the user exists
1.81 www 8540: my $uhome=&homeserver($uname,$udom);
8541: if (($uhome eq '') || ($uhome eq 'no_host')) {
8542: return 'error: no such user';
8543: }
1.297 matthew 8544: # Get student data if we were not given enough information
8545: if (!defined($first) || $first eq '' ||
8546: !defined($last) || $last eq '' ||
8547: !defined($uid) || $uid eq '' ||
8548: !defined($middle) || $middle eq '' ||
8549: !defined($gene) || $gene eq '') {
1.294 matthew 8550: # They did not supply us with enough data to enroll the student, so
8551: # we need to pick up more information.
1.297 matthew 8552: my %tmp = &get('environment',
1.294 matthew 8553: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8554: ,$udom,$uname);
8555:
1.800 albertel 8556: #foreach my $key (keys(%tmp)) {
8557: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8558: #}
1.294 matthew 8559: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8560: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8561: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8562: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8563: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8564: }
1.556 albertel 8565: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8566: my $user = "$uname:$udom";
8567: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8568: my $reply=cput('classlist',
1.1148 raeburn 8569: {$user =>
1.1216 raeburn 8570: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8571: $cdom,$cnum);
1.1148 raeburn 8572: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8573: &devalidate_getsection_cache($udom,$uname,$cid);
8574: } else {
1.81 www 8575: return 'error: '.$reply;
8576: }
1.297 matthew 8577: # Add student role to user
1.83 www 8578: my $uurl='/'.$cid;
1.81 www 8579: $uurl=~s/\_/\//g;
8580: if ($usec) {
8581: $uurl.='/'.$usec;
8582: }
1.1148 raeburn 8583: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8584: $selfenroll,$context);
8585: if ($result ne 'ok') {
8586: if ($old_entry{$user} ne '') {
8587: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8588: } else {
8589: $reply = &del('classlist',[$user],$cdom,$cnum);
8590: }
8591: }
8592: return $result;
1.21 www 8593: }
8594:
1.556 albertel 8595: sub format_name {
8596: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8597: my $name;
8598: if ($first ne 'lastname') {
8599: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8600: } else {
8601: if ($lastname=~/\S/) {
8602: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8603: $name=~s/\s+,/,/;
8604: } else {
8605: $name.= $firstname.' '.$middlename.' '.$generation;
8606: }
8607: }
8608: $name=~s/^\s+//;
8609: $name=~s/\s+$//;
8610: $name=~s/\s+/ /g;
8611: return $name;
8612: }
8613:
1.84 www 8614: # ------------------------------------------------- Write to course preferences
8615:
8616: sub writecoursepref {
8617: my ($courseid,%prefs)=@_;
8618: $courseid=~s/^\///;
8619: $courseid=~s/\_/\//g;
8620: my ($cdomain,$cnum)=split(/\//,$courseid);
8621: my $chome=homeserver($cnum,$cdomain);
8622: if (($chome eq '') || ($chome eq 'no_host')) {
8623: return 'error: no such course';
8624: }
8625: my $cstring='';
1.800 albertel 8626: foreach my $pref (keys(%prefs)) {
8627: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8628: }
1.84 www 8629: $cstring=~s/\&$//;
8630: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8631: }
8632:
8633: # ---------------------------------------------------------- Make/modify course
8634:
8635: sub createcourse {
1.741 raeburn 8636: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8637: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8638: $url=&declutter($url);
8639: my $cid='';
1.1028 raeburn 8640: if ($context eq 'requestcourses') {
8641: my $can_create = 0;
8642: my ($ownername,$ownerdom) = split(':',$course_owner);
8643: if ($udom eq $ownerdom) {
8644: if (&usertools_access($ownername,$ownerdom,$category,undef,
8645: $context)) {
8646: $can_create = 1;
8647: }
8648: } else {
8649: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8650: $category);
8651: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8652: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8653: if (@curr > 0) {
8654: my @options = qw(approval validate autolimit);
8655: my $optregex = join('|',@options);
8656: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8657: $can_create = 1;
8658: }
8659: }
8660: }
8661: }
8662: if ($can_create) {
8663: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8664: unless (&allowed('ccc',$udom)) {
8665: return 'refused';
8666: }
1.1017 raeburn 8667: }
8668: } else {
8669: return 'refused';
8670: }
1.1028 raeburn 8671: } elsif (!&allowed('ccc',$udom)) {
8672: return 'refused';
1.84 www 8673: }
1.1011 raeburn 8674: # --------------------------------------------------------------- Get Unique ID
8675: my $uname;
8676: if ($cnum =~ /^$match_courseid$/) {
8677: my $chome=&homeserver($cnum,$udom,'true');
8678: if (($chome eq '') || ($chome eq 'no_host')) {
8679: $uname = $cnum;
8680: } else {
1.1038 raeburn 8681: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8682: }
8683: } else {
1.1038 raeburn 8684: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8685: }
8686: return $uname if ($uname =~ /^error/);
8687: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8688: if (!defined($course_server)) {
8689: if (defined(&domain($udom,'primary'))) {
8690: $course_server = &domain($udom,'primary');
8691: } else {
8692: $course_server = $env{'user.home'};
8693: }
8694: }
8695: my %host_servers =
8696: &Apache::lonnet::get_servers($udom,'library');
8697: unless ($host_servers{$course_server}) {
8698: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8699: }
1.84 www 8700: # ------------------------------------------------------------- Make the course
8701: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8702: $course_server);
1.84 www 8703: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8704: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8705: if (($uhome eq '') || ($uhome eq 'no_host')) {
8706: return 'error: no such course';
8707: }
1.271 www 8708: # ----------------------------------------------------------------- Course made
1.516 raeburn 8709: # log existence
1.1029 raeburn 8710: my $now = time;
1.918 raeburn 8711: my $newcourse = {
8712: $udom.'_'.$uname => {
1.921 raeburn 8713: description => $description,
8714: inst_code => $inst_code,
8715: owner => $course_owner,
8716: type => $crstype,
1.1029 raeburn 8717: creator => $env{'user.name'}.':'.
8718: $env{'user.domain'},
8719: created => $now,
8720: context => $context,
1.918 raeburn 8721: },
8722: };
1.921 raeburn 8723: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8724: # set toplevel url
1.271 www 8725: my $topurl=$url;
8726: unless ($nonstandard) {
8727: # ------------------------------------------ For standard courses, make top url
8728: my $mapurl=&clutter($url);
1.278 www 8729: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8730: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8731: <map>
8732: <resource id="1" type="start"></resource>
8733: <resource id="2" src="$mapurl"></resource>
8734: <resource id="3" type="finish"></resource>
8735: <link index="1" from="1" to="2"></link>
8736: <link index="2" from="2" to="3"></link>
8737: </map>
8738: ENDINITMAP
8739: $topurl=&declutter(
1.638 albertel 8740: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8741: );
8742: }
8743: # ----------------------------------------------------------- Write preferences
1.84 www 8744: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8745: ('description' => $description,
8746: 'url' => $topurl,
8747: 'internal.creator' => $env{'user.name'}.':'.
8748: $env{'user.domain'},
8749: 'internal.created' => $now,
8750: 'internal.creationcontext' => $context)
8751: );
1.84 www 8752: return '/'.$udom.'/'.$uname;
8753: }
8754:
1.1011 raeburn 8755: # ------------------------------------------------------------------- Create ID
8756: sub generate_coursenum {
1.1038 raeburn 8757: my ($udom,$crstype) = @_;
1.1011 raeburn 8758: my $domdesc = &domain($udom);
8759: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8760: my $first;
8761: if ($crstype eq 'Community') {
8762: $first = '0';
8763: } else {
8764: $first = int(1+rand(9));
8765: }
8766: my $uname=$first.
1.1011 raeburn 8767: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8768: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8769: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8770: # ----------------------------------------------- Make sure that does not exist
8771: my $uhome=&homeserver($uname,$udom,'true');
8772: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8773: if ($crstype eq 'Community') {
8774: $first = '0';
8775: } else {
8776: $first = int(1+rand(9));
8777: }
8778: $uname=$first.
1.1011 raeburn 8779: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8780: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8781: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8782: $uhome=&homeserver($uname,$udom,'true');
8783: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8784: return 'error: unable to generate unique course-ID';
8785: }
8786: }
8787: return $uname;
8788: }
8789:
1.813 albertel 8790: sub is_course {
1.1167 droeschl 8791: my ($cdom, $cnum) = scalar(@_) == 1 ?
8792: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8793:
8794: return unless $cdom and $cnum;
8795:
8796: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8797: '.');
8798:
1.1219 raeburn 8799: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8800: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8801: }
8802:
1.1015 raeburn 8803: sub store_userdata {
8804: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8805: my $result;
1.1016 raeburn 8806: if ($datakey ne '') {
1.1013 raeburn 8807: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8808: if ($udom eq '' || $uname eq '') {
8809: $udom = $env{'user.domain'};
8810: $uname = $env{'user.name'};
8811: }
8812: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8813: if (($uhome eq '') || ($uhome eq 'no_host')) {
8814: $result = 'error: no_host';
8815: } else {
8816: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8817: $storehash->{'host'} = $perlvar{'lonHostID'};
8818:
8819: my $namevalue='';
8820: foreach my $key (keys(%{$storehash})) {
8821: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8822: }
8823: $namevalue=~s/\&$//;
1.1224 raeburn 8824: unless ($namespace eq 'courserequests') {
8825: $datakey = &escape($datakey);
8826: }
1.1105 raeburn 8827: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8828: $namevalue,$uhome);
1.1013 raeburn 8829: }
8830: } else {
8831: $result = 'error: data to store was not a hash reference';
8832: }
8833: } else {
8834: $result= 'error: invalid requestkey';
8835: }
8836: return $result;
8837: }
8838:
1.21 www 8839: # ---------------------------------------------------------- Assign Custom Role
8840:
8841: sub assigncustomrole {
1.957 raeburn 8842: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8843: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8844: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8845: }
8846:
8847: # ----------------------------------------------------------------- Revoke Role
8848:
8849: sub revokerole {
1.957 raeburn 8850: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8851: my $now=time;
1.965 raeburn 8852: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8853: }
8854:
8855: # ---------------------------------------------------------- Revoke Custom Role
8856:
8857: sub revokecustomrole {
1.957 raeburn 8858: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8859: my $now=time;
1.357 www 8860: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8861: $deleteflag,$selfenroll,$context);
1.17 www 8862: }
8863:
1.533 banghart 8864: # ------------------------------------------------------------ Disk usage
1.535 albertel 8865: sub diskusage {
1.955 raeburn 8866: my ($udom,$uname,$directorypath,$getpropath)=@_;
8867: $directorypath =~ s/\/$//;
8868: my $listing=&reply('du2:'.&escape($directorypath).':'
8869: .&escape($getpropath).':'.&escape($uname).':'
8870: .&escape($udom),homeserver($uname,$udom));
8871: if ($listing eq 'unknown_cmd') {
8872: if ($getpropath) {
8873: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8874: }
8875: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8876: }
1.514 albertel 8877: return $listing;
1.512 banghart 8878: }
8879:
1.566 banghart 8880: sub is_locked {
1.1096 raeburn 8881: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8882: my @check;
8883: my $is_locked;
1.1093 raeburn 8884: push (@check,$file_name);
1.613 albertel 8885: my %locked = &get('file_permissions',\@check,
1.620 albertel 8886: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8887: my ($tmp)=keys(%locked);
8888: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8889:
1.566 banghart 8890: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8891: $is_locked = 'false';
8892: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8893: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8894: $is_locked = 'true';
1.1096 raeburn 8895: if (ref($which) eq 'ARRAY') {
8896: push(@{$which},$entry);
8897: } else {
8898: last;
8899: }
1.745 raeburn 8900: }
8901: }
1.566 banghart 8902: } else {
8903: $is_locked = 'false';
8904: }
1.1093 raeburn 8905: return $is_locked;
1.566 banghart 8906: }
8907:
1.759 albertel 8908: sub declutter_portfile {
8909: my ($file) = @_;
1.833 albertel 8910: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8911: return $file;
8912: }
8913:
1.559 banghart 8914: # ------------------------------------------------------------- Mark as Read Only
8915:
8916: sub mark_as_readonly {
8917: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8918: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8919: my ($tmp)=keys(%current_permissions);
8920: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8921: foreach my $file (@{$files}) {
1.759 albertel 8922: $file = &declutter_portfile($file);
1.561 banghart 8923: push(@{$current_permissions{$file}},$what);
1.559 banghart 8924: }
1.613 albertel 8925: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8926: return;
8927: }
8928:
1.572 banghart 8929: # ------------------------------------------------------------Save Selected Files
8930:
8931: sub save_selected_files {
8932: my ($user, $path, @files) = @_;
8933: my $filename = $user."savedfiles";
1.573 banghart 8934: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8935: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8936: foreach my $file (@files) {
1.620 albertel 8937: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8938: }
8939: foreach my $file (@other_files) {
1.574 banghart 8940: print (OUT $file."\n");
1.572 banghart 8941: }
1.574 banghart 8942: close (OUT);
1.572 banghart 8943: return 'ok';
8944: }
8945:
1.574 banghart 8946: sub clear_selected_files {
8947: my ($user) = @_;
8948: my $filename = $user."savedfiles";
1.1117 foxr 8949: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8950: print (OUT undef);
8951: close (OUT);
8952: return ("ok");
8953: }
8954:
1.572 banghart 8955: sub files_in_path {
8956: my ($user, $path) = @_;
8957: my $filename = $user."savedfiles";
8958: my %return_files;
1.1117 foxr 8959: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8960: while (my $line_in = <IN>) {
1.574 banghart 8961: chomp ($line_in);
8962: my @paths_and_file = split (m!/!, $line_in);
8963: my $file_part = pop (@paths_and_file);
8964: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8965: $path_part.='/';
8966: my $path_and_file = $path_part.$file_part;
8967: if ($path_part eq $path) {
8968: $return_files{$file_part}= 'selected';
8969: }
8970: }
1.574 banghart 8971: close (IN);
8972: return (\%return_files);
1.572 banghart 8973: }
8974:
8975: # called in portfolio select mode, to show files selected NOT in current directory
8976: sub files_not_in_path {
8977: my ($user, $path) = @_;
8978: my $filename = $user."savedfiles";
8979: my @return_files;
8980: my $path_part;
1.1117 foxr 8981: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8982: while (my $line = <IN>) {
1.572 banghart 8983: #ok, I know it's clunky, but I want it to work
1.800 albertel 8984: my @paths_and_file = split(m|/|, $line);
8985: my $file_part = pop(@paths_and_file);
8986: chomp($file_part);
8987: my $path_part = join('/', @paths_and_file);
1.572 banghart 8988: $path_part .= '/';
8989: my $path_and_file = $path_part.$file_part;
8990: if ($path_part ne $path) {
1.800 albertel 8991: push(@return_files, ($path_and_file));
1.572 banghart 8992: }
8993: }
1.800 albertel 8994: close(OUT);
1.574 banghart 8995: return (@return_files);
1.572 banghart 8996: }
8997:
1.745 raeburn 8998: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8999:
1.745 raeburn 9000: sub get_portfile_permissions {
9001: my ($domain,$user) = @_;
1.613 albertel 9002: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9003: my ($tmp)=keys(%current_permissions);
9004: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9005: return \%current_permissions;
9006: }
9007:
9008: #---------------------------------------------Get portfolio file access controls
9009:
1.749 raeburn 9010: sub get_access_controls {
1.745 raeburn 9011: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9012: my %access;
9013: my $real_file = $file;
9014: $file =~ s/\.meta$//;
1.745 raeburn 9015: if (defined($file)) {
1.749 raeburn 9016: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9017: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9018: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9019: }
9020: }
1.745 raeburn 9021: } else {
1.749 raeburn 9022: foreach my $key (keys(%{$current_permissions})) {
9023: if ($key =~ /\0accesscontrol$/) {
9024: if (defined($group)) {
9025: if ($key !~ m-^\Q$group\E/-) {
9026: next;
9027: }
9028: }
9029: my ($fullpath) = split(/\0/,$key);
9030: if (ref($$current_permissions{$key}) eq 'HASH') {
9031: foreach my $control (keys(%{$$current_permissions{$key}})) {
9032: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9033: }
9034: }
9035: }
9036: }
9037: }
9038: return %access;
9039: }
9040:
9041: sub modify_access_controls {
9042: my ($file_name,$changes,$domain,$user)=@_;
9043: my ($outcome,$deloutcome);
9044: my %store_permissions;
9045: my %new_values;
9046: my %new_control;
9047: my %translation;
9048: my @deletions = ();
9049: my $now = time;
9050: if (exists($$changes{'activate'})) {
9051: if (ref($$changes{'activate'}) eq 'HASH') {
9052: my @newitems = sort(keys(%{$$changes{'activate'}}));
9053: my $numnew = scalar(@newitems);
9054: for (my $i=0; $i<$numnew; $i++) {
9055: my $newkey = $newitems[$i];
9056: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9057: if ($newkey =~ /^\d+:/) {
9058: $newkey =~ s/^(\d+)/$newid/;
9059: $translation{$1} = $newid;
9060: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9061: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9062: $translation{$1} = $newid;
9063: }
1.749 raeburn 9064: $new_values{$file_name."\0".$newkey} =
9065: $$changes{'activate'}{$newitems[$i]};
9066: $new_control{$newkey} = $now;
9067: }
9068: }
9069: }
9070: my %todelete;
9071: my %changed_items;
9072: foreach my $action ('delete','update') {
9073: if (exists($$changes{$action})) {
9074: if (ref($$changes{$action}) eq 'HASH') {
9075: foreach my $key (keys(%{$$changes{$action}})) {
9076: my ($itemnum) = ($key =~ /^([^:]+):/);
9077: if ($action eq 'delete') {
9078: $todelete{$itemnum} = 1;
9079: } else {
9080: $changed_items{$itemnum} = $key;
9081: }
9082: }
1.745 raeburn 9083: }
9084: }
1.749 raeburn 9085: }
9086: # get lock on access controls for file.
9087: my $lockhash = {
9088: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9089: ':'.$env{'user.domain'},
9090: };
9091: my $tries = 0;
9092: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9093:
9094: while (($gotlock ne 'ok') && $tries <3) {
9095: $tries ++;
9096: sleep 1;
9097: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9098: }
9099: if ($gotlock eq 'ok') {
9100: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9101: my ($tmp)=keys(%curr_permissions);
9102: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9103: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9104: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9105: if (ref($curr_controls) eq 'HASH') {
9106: foreach my $control_item (keys(%{$curr_controls})) {
9107: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9108: if (defined($todelete{$itemnum})) {
9109: push(@deletions,$file_name."\0".$control_item);
9110: } else {
9111: if (defined($changed_items{$itemnum})) {
9112: $new_control{$changed_items{$itemnum}} = $now;
9113: push(@deletions,$file_name."\0".$control_item);
9114: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9115: } else {
9116: $new_control{$control_item} = $$curr_controls{$control_item};
9117: }
9118: }
1.745 raeburn 9119: }
9120: }
9121: }
1.970 raeburn 9122: my ($group);
9123: if (&is_course($domain,$user)) {
9124: ($group,my $file) = split(/\//,$file_name,2);
9125: }
1.749 raeburn 9126: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9127: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9128: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9129: # remove lock
9130: my @del_lock = ($file_name."\0".'locked_access_records');
9131: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9132: my $sqlresult =
1.970 raeburn 9133: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9134: $group);
1.749 raeburn 9135: } else {
9136: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9137: }
1.749 raeburn 9138: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9139: }
9140:
1.827 raeburn 9141: sub make_public_indefinitely {
9142: my ($requrl) = @_;
9143: my $now = time;
9144: my $action = 'activate';
9145: my $aclnum = 0;
9146: if (&is_portfolio_url($requrl)) {
9147: my (undef,$udom,$unum,$file_name,$group) =
9148: &parse_portfolio_url($requrl);
9149: my $current_perms = &get_portfile_permissions($udom,$unum);
9150: my %access_controls = &get_access_controls($current_perms,
9151: $group,$file_name);
9152: foreach my $key (keys(%{$access_controls{$file_name}})) {
9153: my ($num,$scope,$end,$start) =
9154: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9155: if ($scope eq 'public') {
9156: if ($start <= $now && $end == 0) {
9157: $action = 'none';
9158: } else {
9159: $action = 'update';
9160: $aclnum = $num;
9161: }
9162: last;
9163: }
9164: }
9165: if ($action eq 'none') {
9166: return 'ok';
9167: } else {
9168: my %changes;
9169: my $newend = 0;
9170: my $newstart = $now;
9171: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9172: $changes{$action}{$newkey} = {
9173: type => 'public',
9174: time => {
9175: start => $newstart,
9176: end => $newend,
9177: },
9178: };
9179: my ($outcome,$deloutcome,$new_values,$translation) =
9180: &modify_access_controls($file_name,\%changes,$udom,$unum);
9181: return $outcome;
9182: }
9183: } else {
9184: return 'invalid';
9185: }
9186: }
9187:
1.745 raeburn 9188: #------------------------------------------------------Get Marked as Read Only
9189:
9190: sub get_marked_as_readonly {
9191: my ($domain,$user,$what,$group) = @_;
9192: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9193: my @readonly_files;
1.629 banghart 9194: my $cmp1=$what;
9195: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9196: while (my ($file_name,$value) = each(%{$current_permissions})) {
9197: if (defined($group)) {
9198: if ($file_name !~ m-^\Q$group\E/-) {
9199: next;
9200: }
9201: }
1.561 banghart 9202: if (ref($value) eq "ARRAY"){
9203: foreach my $stored_what (@{$value}) {
1.629 banghart 9204: my $cmp2=$stored_what;
1.759 albertel 9205: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9206: $cmp2=join('',@{$stored_what});
1.745 raeburn 9207: }
1.629 banghart 9208: if ($cmp1 eq $cmp2) {
1.561 banghart 9209: push(@readonly_files, $file_name);
1.745 raeburn 9210: last;
1.563 banghart 9211: } elsif (!defined($what)) {
9212: push(@readonly_files, $file_name);
1.745 raeburn 9213: last;
1.561 banghart 9214: }
9215: }
1.745 raeburn 9216: }
1.561 banghart 9217: }
9218: return @readonly_files;
9219: }
1.577 banghart 9220: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9221:
1.577 banghart 9222: sub get_marked_as_readonly_hash {
1.745 raeburn 9223: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9224: my %readonly_files;
1.745 raeburn 9225: while (my ($file_name,$value) = each(%{$current_permissions})) {
9226: if (defined($group)) {
9227: if ($file_name !~ m-^\Q$group\E/-) {
9228: next;
9229: }
9230: }
1.577 banghart 9231: if (ref($value) eq "ARRAY"){
9232: foreach my $stored_what (@{$value}) {
1.745 raeburn 9233: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9234: foreach my $lock_descriptor(@{$stored_what}) {
9235: if ($lock_descriptor eq 'graded') {
9236: $readonly_files{$file_name} = 'graded';
9237: } elsif ($lock_descriptor eq 'handback') {
9238: $readonly_files{$file_name} = 'handback';
9239: } else {
9240: if (!exists($readonly_files{$file_name})) {
9241: $readonly_files{$file_name} = 'locked';
9242: }
9243: }
1.745 raeburn 9244: }
1.750 banghart 9245: }
1.577 banghart 9246: }
9247: }
9248: }
9249: return %readonly_files;
9250: }
1.559 banghart 9251: # ------------------------------------------------------------ Unmark as Read Only
9252:
9253: sub unmark_as_readonly {
1.629 banghart 9254: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9255: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9256: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9257: $file_name = &declutter_portfile($file_name);
1.634 albertel 9258: my $symb_crs = $what;
9259: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9260: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9261: my ($tmp)=keys(%current_permissions);
9262: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9263: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9264: foreach my $file (@readonly_files) {
1.759 albertel 9265: my $clean_file = &declutter_portfile($file);
9266: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9267: my $current_locks = $current_permissions{$file};
1.563 banghart 9268: my @new_locks;
9269: my @del_keys;
9270: if (ref($current_locks) eq "ARRAY"){
9271: foreach my $locker (@{$current_locks}) {
1.632 albertel 9272: my $compare=$locker;
1.749 raeburn 9273: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9274: $compare=join('',@{$locker});
1.746 raeburn 9275: if ($compare ne $symb_crs) {
9276: push(@new_locks, $locker);
9277: }
1.563 banghart 9278: }
9279: }
1.650 albertel 9280: if (scalar(@new_locks) > 0) {
1.563 banghart 9281: $current_permissions{$file} = \@new_locks;
9282: } else {
9283: push(@del_keys, $file);
1.613 albertel 9284: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9285: delete($current_permissions{$file});
1.563 banghart 9286: }
9287: }
1.561 banghart 9288: }
1.613 albertel 9289: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9290: return;
9291: }
1.512 banghart 9292:
1.17 www 9293: # ------------------------------------------------------------ Directory lister
9294:
9295: sub dirlist {
1.955 raeburn 9296: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9297: $uri=~s/^\///;
9298: $uri=~s/\/$//;
1.253 stredwic 9299: my ($udom, $uname);
1.955 raeburn 9300: if ($getuserdir) {
1.253 stredwic 9301: $udom = $userdomain;
9302: $uname = $username;
1.955 raeburn 9303: } else {
9304: (undef,$udom,$uname)=split(/\//,$uri);
9305: if(defined($userdomain)) {
9306: $udom = $userdomain;
9307: }
9308: if(defined($username)) {
9309: $uname = $username;
9310: }
1.253 stredwic 9311: }
1.955 raeburn 9312: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9313:
1.955 raeburn 9314: $dirRoot = $perlvar{'lonDocRoot'};
9315: if (defined($getpropath)) {
9316: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9317: $dirRoot =~ s/\/$//;
1.955 raeburn 9318: } elsif (defined($getuserdir)) {
9319: my $subdir=$uname.'__';
9320: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9321: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9322: ."/$udom/$subdir/$uname";
9323: } elsif (defined($alternateRoot)) {
9324: $dirRoot = $alternateRoot;
1.751 banghart 9325: }
1.253 stredwic 9326:
9327: if($udom) {
9328: if($uname) {
1.1135 raeburn 9329: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9330: if ($uhome eq 'no_host') {
9331: return ([],'no_host');
9332: }
1.955 raeburn 9333: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9334: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9335: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9336: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9337: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9338: } else {
9339: @listing_results = map { &unescape($_); } split(/:/,$listing);
9340: }
1.605 matthew 9341: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9342: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9343: @listing_results = split(/:/,$listing);
9344: } else {
9345: @listing_results = map { &unescape($_); } split(/:/,$listing);
9346: }
1.1135 raeburn 9347: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9348: ($listing eq 'rejected') || ($listing eq 'refused') ||
9349: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9350: return ([],$listing);
9351: } else {
9352: return (\@listing_results);
1.1135 raeburn 9353: }
1.955 raeburn 9354: } elsif(!$alternateRoot) {
1.1136 raeburn 9355: my (%allusers,%listerror);
1.841 albertel 9356: my %servers = &get_servers($udom,'library');
1.955 raeburn 9357: foreach my $tryserver (keys(%servers)) {
9358: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9359: &escape($udom),$tryserver);
9360: if ($listing eq 'unknown_cmd') {
9361: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9362: $udom, $tryserver);
9363: } else {
9364: @listing_results = map { &unescape($_); } split(/:/,$listing);
9365: }
1.841 albertel 9366: if ($listing eq 'unknown_cmd') {
9367: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9368: $udom, $tryserver);
9369: @listing_results = split(/:/,$listing);
9370: } else {
9371: @listing_results =
9372: map { &unescape($_); } split(/:/,$listing);
9373: }
1.1136 raeburn 9374: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9375: ($listing eq 'rejected') || ($listing eq 'refused') ||
9376: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9377: $listerror{$tryserver} = $listing;
9378: } else {
1.841 albertel 9379: foreach my $line (@listing_results) {
9380: my ($entry) = split(/&/,$line,2);
9381: $allusers{$entry} = 1;
9382: }
9383: }
1.253 stredwic 9384: }
1.1136 raeburn 9385: my @alluserslist=();
1.800 albertel 9386: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9387: push(@alluserslist,$user.'&user');
1.253 stredwic 9388: }
1.1136 raeburn 9389: return (\@alluserslist);
1.253 stredwic 9390: } else {
1.1136 raeburn 9391: return ([],'missing username');
1.253 stredwic 9392: }
1.955 raeburn 9393: } elsif(!defined($getpropath)) {
1.1136 raeburn 9394: my $path = $perlvar{'lonDocRoot'}.'/res/';
9395: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9396: return (\@all_domains);
1.955 raeburn 9397: } else {
1.1136 raeburn 9398: return ([],'missing domain');
1.275 stredwic 9399: }
9400: }
9401:
9402: # --------------------------------------------- GetFileTimestamp
9403: # This function utilizes dirlist and returns the date stamp for
9404: # when it was last modified. It will also return an error of -1
9405: # if an error occurs
9406:
9407: sub GetFileTimestamp {
1.955 raeburn 9408: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9409: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9410: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9411: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9412: undef,$getuserdir);
9413: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9414: return -1;
9415: }
9416: if (ref($fileref) eq 'ARRAY') {
9417: my @stats = split('&',$fileref->[0]);
1.375 matthew 9418: # @stats contains first the filename, then the stat output
9419: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9420: } else {
9421: return -1;
1.253 stredwic 9422: }
1.26 www 9423: }
9424:
1.712 albertel 9425: sub stat_file {
9426: my ($uri) = @_;
1.787 albertel 9427: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9428:
1.955 raeburn 9429: my ($udom,$uname,$file);
1.712 albertel 9430: if ($uri =~ m-^/(uploaded|editupload)/-) {
9431: ($udom,$uname,$file) =
1.811 albertel 9432: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9433: $file = 'userfiles/'.$file;
9434: }
9435: if ($uri =~ m-^/res/-) {
9436: ($udom,$uname) =
1.807 albertel 9437: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9438: $file = $uri;
9439: }
9440:
9441: if (!$udom || !$uname || !$file) {
9442: # unable to handle the uri
9443: return ();
9444: }
1.956 raeburn 9445: my $getpropath;
9446: if ($file =~ /^userfiles\//) {
9447: $getpropath = 1;
9448: }
1.1136 raeburn 9449: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9450: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9451: return ();
9452: } else {
9453: if (ref($listref) eq 'ARRAY') {
9454: my @stats = split('&',$listref->[0]);
9455: shift(@stats); #filename is first
9456: return @stats;
9457: }
1.712 albertel 9458: }
9459: return ();
9460: }
9461:
1.26 www 9462: # -------------------------------------------------------- Value of a Condition
9463:
1.713 albertel 9464: # gets the value of a specific preevaluated condition
9465: # stored in the string $env{user.state.<cid>}
9466: # or looks up a condition reference in the bighash and if if hasn't
9467: # already been evaluated recurses into docondval to get the value of
9468: # the condition, then memoizing it to
9469: # $env{user.state.<cid>.<condition>}
1.40 www 9470: sub directcondval {
9471: my $number=shift;
1.620 albertel 9472: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9473: &Apache::lonuserstate::evalstate();
9474: }
1.713 albertel 9475: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9476: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9477: } elsif ($number =~ /^_/) {
9478: my $sub_condition;
9479: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9480: &GDBM_READER(),0640)) {
9481: $sub_condition=$bighash{'conditions'.$number};
9482: untie(%bighash);
9483: }
9484: my $value = &docondval($sub_condition);
1.949 raeburn 9485: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9486: return $value;
9487: }
1.620 albertel 9488: if ($env{'user.state.'.$env{'request.course.id'}}) {
9489: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9490: } else {
9491: return 2;
9492: }
9493: }
9494:
1.713 albertel 9495: # get the collection of conditions for this resource
1.26 www 9496: sub condval {
9497: my $condidx=shift;
1.54 www 9498: my $allpathcond='';
1.713 albertel 9499: foreach my $cond (split(/\|/,$condidx)) {
9500: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9501: $allpathcond.=
9502: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9503: }
1.191 harris41 9504: }
1.54 www 9505: $allpathcond=~s/\|$//;
1.713 albertel 9506: return &docondval($allpathcond);
9507: }
9508:
9509: #evaluates an expression of conditions
9510: sub docondval {
9511: my ($allpathcond) = @_;
9512: my $result=0;
9513: if ($env{'request.course.id'}
9514: && defined($allpathcond)) {
9515: my $operand='|';
9516: my @stack;
9517: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9518: if ($chunk eq '(') {
9519: push @stack,($operand,$result);
9520: } elsif ($chunk eq ')') {
9521: my $before=pop @stack;
9522: if (pop @stack eq '&') {
9523: $result=$result>$before?$before:$result;
9524: } else {
9525: $result=$result>$before?$result:$before;
9526: }
9527: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9528: $operand=$chunk;
9529: } else {
9530: my $new=directcondval($chunk);
9531: if ($operand eq '&') {
9532: $result=$result>$new?$new:$result;
9533: } else {
9534: $result=$result>$new?$result:$new;
9535: }
9536: }
9537: }
1.26 www 9538: }
9539: return $result;
1.421 albertel 9540: }
9541:
9542: # ---------------------------------------------------- Devalidate courseresdata
9543:
9544: sub devalidatecourseresdata {
9545: my ($coursenum,$coursedomain)=@_;
9546: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9547: &devalidate_cache_new('courseres',$hashid);
1.28 www 9548: }
9549:
1.763 www 9550:
1.200 www 9551: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9552: #
9553: # Parameters:
9554: # $coursenum - Number of the course.
9555: # $coursedomain - Domain at which the course was created.
9556: # Returns:
9557: # A hash of the course parameters along (I think) with timestamps
9558: # and version info.
1.877 foxr 9559:
1.624 albertel 9560: sub get_courseresdata {
9561: my ($coursenum,$coursedomain)=@_;
1.200 www 9562: my $coursehom=&homeserver($coursenum,$coursedomain);
9563: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9564: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9565: my %dumpreply;
1.417 albertel 9566: unless (defined($cached)) {
1.624 albertel 9567: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9568: $result=\%dumpreply;
1.251 albertel 9569: my ($tmp) = keys(%dumpreply);
9570: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9571: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9572: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9573: return $tmp;
1.416 albertel 9574: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9575: $result=undef;
1.599 albertel 9576: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9577: }
9578: }
1.624 albertel 9579: return $result;
9580: }
9581:
1.633 albertel 9582: sub devalidateuserresdata {
9583: my ($uname,$udom)=@_;
9584: my $hashid="$udom:$uname";
9585: &devalidate_cache_new('userres',$hashid);
9586: }
9587:
1.624 albertel 9588: sub get_userresdata {
9589: my ($uname,$udom)=@_;
9590: #most student don\'t have any data set, check if there is some data
9591: if (&EXT_cache_status($udom,$uname)) { return undef; }
9592:
9593: my $hashid="$udom:$uname";
9594: my ($result,$cached)=&is_cached_new('userres',$hashid);
9595: if (!defined($cached)) {
9596: my %resourcedata=&dump('resourcedata',$udom,$uname);
9597: $result=\%resourcedata;
9598: &do_cache_new('userres',$hashid,$result,600);
9599: }
9600: my ($tmp)=keys(%$result);
9601: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9602: return $result;
9603: }
9604: #error 2 occurs when the .db doesn't exist
9605: if ($tmp!~/error: 2 /) {
1.672 albertel 9606: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9607: " Trying to get resource data for ".
9608: $uname." at ".$udom.": ".
9609: $tmp."</font>");
9610: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9611: #&EXT_cache_set($udom,$uname);
9612: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9613: undef($tmp); # not really an error so don't send it back
1.624 albertel 9614: }
9615: return $tmp;
9616: }
1.879 foxr 9617: #----------------------------------------------- resdata - return resource data
9618: # Purpose:
9619: # Return resource data for either users or for a course.
9620: # Parameters:
9621: # $name - Course/user name.
9622: # $domain - Name of the domain the user/course is registered on.
9623: # $type - Type of thing $name is (must be 'course' or 'user'
9624: # @which - Array of names of resources desired.
9625: # Returns:
9626: # The value of the first reasource in @which that is found in the
9627: # resource hash.
9628: # Exceptional Conditions:
9629: # If the $type passed in is not valid (not the string 'course' or
9630: # 'user', an undefined reference is returned.
9631: # If none of the resources are found, an undef is returned
1.624 albertel 9632: sub resdata {
9633: my ($name,$domain,$type,@which)=@_;
9634: my $result;
9635: if ($type eq 'course') {
9636: $result=&get_courseresdata($name,$domain);
9637: } elsif ($type eq 'user') {
9638: $result=&get_userresdata($name,$domain);
9639: }
9640: if (!ref($result)) { return $result; }
1.251 albertel 9641: foreach my $item (@which) {
1.927 albertel 9642: if (defined($result->{$item->[0]})) {
9643: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9644: }
1.250 albertel 9645: }
1.291 albertel 9646: return undef;
1.200 www 9647: }
9648:
1.1236 raeburn 9649: sub get_numsuppfiles {
9650: my ($cnum,$cdom,$ignorecache)=@_;
9651: my $hashid=$cnum.':'.$cdom;
9652: my ($suppcount,$cached);
9653: unless ($ignorecache) {
9654: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9655: }
9656: unless (defined($cached)) {
9657: my $chome=&homeserver($cnum,$cdom);
9658: unless ($chome eq 'no_host') {
9659: ($suppcount,my $errors) = (0,0);
9660: my $suppmap = 'supplemental.sequence';
9661: ($suppcount,$errors) =
9662: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9663: }
9664: &do_cache_new('suppcount',$hashid,$suppcount,600);
9665: }
9666: return $suppcount;
9667: }
9668:
1.379 matthew 9669: #
9670: # EXT resource caching routines
9671: #
9672:
9673: sub clear_EXT_cache_status {
1.383 albertel 9674: &delenv('cache.EXT.');
1.379 matthew 9675: }
9676:
9677: sub EXT_cache_status {
9678: my ($target_domain,$target_user) = @_;
1.383 albertel 9679: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9680: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9681: # We know already the user has no data
9682: return 1;
9683: } else {
9684: return 0;
9685: }
9686: }
9687:
9688: sub EXT_cache_set {
9689: my ($target_domain,$target_user) = @_;
1.383 albertel 9690: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9691: #&appenv({$cachename => time});
1.379 matthew 9692: }
9693:
1.28 www 9694: # --------------------------------------------------------- Value of a Variable
1.58 www 9695: sub EXT {
1.715 albertel 9696:
1.1228 raeburn 9697: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9698: unless ($varname) { return ''; }
1.218 albertel 9699: #get real user name/domain, courseid and symb
9700: my $courseid;
1.359 albertel 9701: my $publicuser;
1.427 www 9702: if ($symbparm) {
9703: $symbparm=&get_symb_from_alias($symbparm);
9704: }
1.218 albertel 9705: if (!($uname && $udom)) {
1.790 albertel 9706: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9707: if (!$symbparm) { $symbparm=$cursymb; }
9708: } else {
1.620 albertel 9709: $courseid=$env{'request.course.id'};
1.218 albertel 9710: }
1.48 www 9711: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9712: my $rest;
1.320 albertel 9713: if (defined($therest[0])) {
1.48 www 9714: $rest=join('.',@therest);
9715: } else {
9716: $rest='';
9717: }
1.320 albertel 9718:
1.57 www 9719: my $qualifierrest=$qualifier;
9720: if ($rest) { $qualifierrest.='.'.$rest; }
9721: my $spacequalifierrest=$space;
9722: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9723: if ($realm eq 'user') {
1.48 www 9724: # --------------------------------------------------------------- user.resource
9725: if ($space eq 'resource') {
1.651 albertel 9726: if ( (defined($Apache::lonhomework::parsing_a_problem)
9727: || defined($Apache::lonhomework::parsing_a_task))
9728: &&
1.744 albertel 9729: ($symbparm eq &symbread()) ) {
9730: # if we are in the middle of processing the resource the
9731: # get the value we are planning on committing
9732: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9733: return $Apache::lonhomework::results{$qualifierrest};
9734: } else {
9735: return $Apache::lonhomework::history{$qualifierrest};
9736: }
1.335 albertel 9737: } else {
1.359 albertel 9738: my %restored;
1.620 albertel 9739: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9740: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9741: } else {
9742: %restored=&restore($symbparm,$courseid,$udom,$uname);
9743: }
1.335 albertel 9744: return $restored{$qualifierrest};
9745: }
1.48 www 9746: # ----------------------------------------------------------------- user.access
9747: } elsif ($space eq 'access') {
1.218 albertel 9748: # FIXME - not supporting calls for a specific user
1.48 www 9749: return &allowed($qualifier,$rest);
9750: # ------------------------------------------ user.preferences, user.environment
9751: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9752: if (($uname eq $env{'user.name'}) &&
9753: ($udom eq $env{'user.domain'})) {
9754: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9755: } else {
1.359 albertel 9756: my %returnhash;
9757: if (!$publicuser) {
9758: %returnhash=&userenvironment($udom,$uname,
9759: $qualifierrest);
9760: }
1.218 albertel 9761: return $returnhash{$qualifierrest};
9762: }
1.48 www 9763: # ----------------------------------------------------------------- user.course
9764: } elsif ($space eq 'course') {
1.218 albertel 9765: # FIXME - not supporting calls for a specific user
1.620 albertel 9766: return $env{join('.',('request.course',$qualifier))};
1.48 www 9767: # ------------------------------------------------------------------- user.role
9768: } elsif ($space eq 'role') {
1.218 albertel 9769: # FIXME - not supporting calls for a specific user
1.620 albertel 9770: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9771: if ($qualifier eq 'value') {
9772: return $role;
9773: } elsif ($qualifier eq 'extent') {
9774: return $where;
9775: }
9776: # ----------------------------------------------------------------- user.domain
9777: } elsif ($space eq 'domain') {
1.218 albertel 9778: return $udom;
1.48 www 9779: # ------------------------------------------------------------------- user.name
9780: } elsif ($space eq 'name') {
1.218 albertel 9781: return $uname;
1.48 www 9782: # ---------------------------------------------------- Any other user namespace
1.29 www 9783: } else {
1.359 albertel 9784: my %reply;
9785: if (!$publicuser) {
9786: %reply=&get($space,[$qualifierrest],$udom,$uname);
9787: }
9788: return $reply{$qualifierrest};
1.48 www 9789: }
1.236 www 9790: } elsif ($realm eq 'query') {
9791: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9792: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9793: [$spacequalifierrest]);
1.620 albertel 9794: return $env{'form.'.$spacequalifierrest};
1.236 www 9795: } elsif ($realm eq 'request') {
1.48 www 9796: # ------------------------------------------------------------- request.browser
9797: if ($space eq 'browser') {
1.1145 bisitz 9798: return $env{'browser.'.$qualifier};
1.57 www 9799: # ------------------------------------------------------------ request.filename
9800: } else {
1.620 albertel 9801: return $env{'request.'.$spacequalifierrest};
1.29 www 9802: }
1.28 www 9803: } elsif ($realm eq 'course') {
1.48 www 9804: # ---------------------------------------------------------- course.description
1.620 albertel 9805: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9806: } elsif ($realm eq 'resource') {
1.165 www 9807:
1.620 albertel 9808: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9809: if (!$symbparm) { $symbparm=&symbread(); }
9810: }
1.693 albertel 9811:
1.1232 raeburn 9812: if ($qualifier eq '') {
9813: if ($space eq 'title') {
9814: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9815: return &gettitle($symbparm);
9816: }
1.693 albertel 9817:
1.1232 raeburn 9818: if ($space eq 'map') {
9819: my ($map) = &decode_symb($symbparm);
9820: return &symbread($map);
9821: }
9822: if ($space eq 'maptitle') {
9823: my ($map) = &decode_symb($symbparm);
9824: return &gettitle($map);
9825: }
9826: if ($space eq 'filename') {
9827: if ($symbparm) {
9828: return &clutter((&decode_symb($symbparm))[2]);
9829: }
9830: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9831: }
1.1232 raeburn 9832:
1.1233 raeburn 9833: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9834: if ($space eq 'visibleparts') {
9835: my $navmap = Apache::lonnavmaps::navmap->new();
9836: my $item;
9837: if (ref($navmap)) {
9838: my $res = $navmap->getBySymb($symbparm);
9839: my $parts = $res->parts();
9840: if (ref($parts) eq 'ARRAY') {
9841: $item = join(',',@{$parts});
9842: }
9843: undef($navmap);
1.1232 raeburn 9844: }
1.1233 raeburn 9845: return $item;
1.1232 raeburn 9846: }
9847: }
9848: }
1.693 albertel 9849:
9850: my ($section, $group, @groups);
1.593 albertel 9851: my ($courselevelm,$courselevel);
1.1228 raeburn 9852: if (($courseid eq '') && ($cid)) {
9853: $courseid = $cid;
9854: }
9855: if (($symbparm && $courseid) &&
9856: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9857:
1.218 albertel 9858: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9859:
1.60 www 9860: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9861: my $symbp=$symbparm;
1.735 albertel 9862: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9863:
9864: my $symbparm=$symbp.'.'.$spacequalifierrest;
9865: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9866:
1.620 albertel 9867: if (($env{'user.name'} eq $uname) &&
9868: ($env{'user.domain'} eq $udom)) {
9869: $section=$env{'request.course.sec'};
1.733 raeburn 9870: @groups = split(/:/,$env{'request.course.groups'});
9871: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9872: } else {
1.539 albertel 9873: if (! defined($usection)) {
1.551 albertel 9874: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9875: } else {
9876: $section = $usection;
9877: }
1.733 raeburn 9878: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9879: }
9880:
9881: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9882: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9883: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9884:
1.593 albertel 9885: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9886: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9887: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9888:
1.60 www 9889: # ----------------------------------------------------------- first, check user
1.624 albertel 9890:
9891: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9892: ([$courselevelr,'resource'],
9893: [$courselevelm,'map' ],
9894: [$courselevel, 'course' ]));
1.931 albertel 9895: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9896:
1.594 albertel 9897: # ------------------------------------------------ second, check some of course
1.684 raeburn 9898: my $coursereply;
1.691 raeburn 9899: if (@groups > 0) {
9900: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9901: $mapparm,$spacequalifierrest);
1.927 albertel 9902: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9903: }
1.96 www 9904:
1.684 raeburn 9905: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9906: $env{'course.'.$courseid.'.domain'},
9907: 'course',
9908: ([$seclevelr, 'resource'],
9909: [$seclevelm, 'map' ],
9910: [$seclevel, 'course' ],
9911: [$courselevelr,'resource']));
9912: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9913:
1.60 www 9914: # ------------------------------------------------------ third, check map parms
1.218 albertel 9915: my %parmhash=();
9916: my $thisparm='';
9917: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9918: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9919: &GDBM_READER(),0640)) {
1.218 albertel 9920: $thisparm=$parmhash{$symbparm};
9921: untie(%parmhash);
9922: }
1.927 albertel 9923: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9924: }
1.594 albertel 9925: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9926:
1.218 albertel 9927: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9928: my $filename;
9929: if (!$symbparm) { $symbparm=&symbread(); }
9930: if ($symbparm) {
1.409 www 9931: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9932: } else {
1.620 albertel 9933: $filename=$env{'request.filename'};
1.282 albertel 9934: }
9935: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9936: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9937: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9938: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9939:
1.927 albertel 9940: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9941: if ($symbparm && defined($courseid) &&
1.620 albertel 9942: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9943: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9944: $env{'course.'.$courseid.'.domain'},
9945: 'course',
1.927 albertel 9946: ([$courselevelm,'map' ],
9947: [$courselevel, 'course']));
9948: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9949: }
1.145 www 9950: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9951: unless ($space eq '0') {
1.336 albertel 9952: my @parts=split(/_/,$space);
9953: my $id=pop(@parts);
9954: my $part=join('_',@parts);
9955: if ($part eq '') { $part='0'; }
1.927 albertel 9956: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9957: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9958: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9959: }
1.395 albertel 9960: if ($recurse) { return undef; }
9961: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9962: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9963: # ---------------------------------------------------- Any other user namespace
9964: } elsif ($realm eq 'environment') {
9965: # ----------------------------------------------------------------- environment
1.620 albertel 9966: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9967: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9968: } else {
1.770 albertel 9969: if ($uname eq 'anonymous' && $udom eq '') {
9970: return '';
9971: }
1.219 albertel 9972: my %returnhash=&userenvironment($udom,$uname,
9973: $spacequalifierrest);
9974: return $returnhash{$spacequalifierrest};
9975: }
1.28 www 9976: } elsif ($realm eq 'system') {
1.48 www 9977: # ----------------------------------------------------------------- system.time
9978: if ($space eq 'time') {
9979: return time;
9980: }
1.696 albertel 9981: } elsif ($realm eq 'server') {
9982: # ----------------------------------------------------------------- system.time
9983: if ($space eq 'name') {
9984: return $ENV{'SERVER_NAME'};
9985: }
1.28 www 9986: }
1.48 www 9987: return '';
1.61 www 9988: }
9989:
1.927 albertel 9990: sub get_reply {
9991: my ($reply_value) = @_;
1.940 raeburn 9992: if (ref($reply_value) eq 'ARRAY') {
9993: if (wantarray) {
9994: return @$reply_value;
9995: }
9996: return $reply_value->[0];
9997: } else {
9998: return $reply_value;
1.927 albertel 9999: }
10000: }
10001:
1.691 raeburn 10002: sub check_group_parms {
10003: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10004: my @groupitems = ();
10005: my $resultitem;
1.927 albertel 10006: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10007: foreach my $group (@{$groups}) {
10008: foreach my $level (@levels) {
1.927 albertel 10009: my $item = $courseid.'.['.$group.'].'.$level->[0];
10010: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10011: }
10012: }
10013: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10014: $env{'course.'.$courseid.'.domain'},
10015: 'course',@groupitems);
10016: return $coursereply;
10017: }
10018:
10019: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10020: my ($courseid,@groups) = @_;
10021: @groups = sort(@groups);
1.691 raeburn 10022: return @groups;
10023: }
10024:
1.395 albertel 10025: sub packages_tab_default {
10026: my ($uri,$varname)=@_;
10027: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10028:
10029: my (@extension,@specifics,$do_default);
10030: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10031: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10032: if ($pack_type eq 'default') {
10033: $do_default=1;
10034: } elsif ($pack_type eq 'extension') {
10035: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10036: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10037: # only look at packages defaults for packages that this id is
1.738 albertel 10038: push(@specifics,[$package,$pack_type,$pack_part]);
10039: }
10040: }
10041: # first look for a package that matches the requested part id
10042: foreach my $package (@specifics) {
10043: my (undef,$pack_type,$pack_part)=@{$package};
10044: next if ($pack_part ne $part);
10045: if (defined($packagetab{"$pack_type&$name&default"})) {
10046: return $packagetab{"$pack_type&$name&default"};
10047: }
10048: }
10049: # look for any possible matching non extension_ package
10050: foreach my $package (@specifics) {
10051: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10052: if (defined($packagetab{"$pack_type&$name&default"})) {
10053: return $packagetab{"$pack_type&$name&default"};
10054: }
1.585 albertel 10055: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10056: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10057: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10058: }
10059: }
1.738 albertel 10060: # look for any posible extension_ match
10061: foreach my $package (@extension) {
10062: my ($package,$pack_type)=@{$package};
10063: if (defined($packagetab{"$pack_type&$name&default"})) {
10064: return $packagetab{"$pack_type&$name&default"};
10065: }
10066: if (defined($packagetab{$package."&$name&default"})) {
10067: return $packagetab{$package."&$name&default"};
10068: }
10069: }
10070: # look for a global default setting
10071: if ($do_default && defined($packagetab{"default&$name&default"})) {
10072: return $packagetab{"default&$name&default"};
10073: }
1.395 albertel 10074: return undef;
10075: }
10076:
1.334 albertel 10077: sub add_prefix_and_part {
10078: my ($prefix,$part)=@_;
10079: my $keyroot;
10080: if (defined($prefix) && $prefix !~ /^__/) {
10081: # prefix that has a part already
10082: $keyroot=$prefix;
10083: } elsif (defined($prefix)) {
10084: # prefix that is missing a part
10085: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10086: } else {
10087: # no prefix at all
10088: if (defined($part)) { $keyroot='_'.$part; }
10089: }
10090: return $keyroot;
10091: }
10092:
1.71 www 10093: # ---------------------------------------------------------------- Get metadata
10094:
1.599 albertel 10095: my %metaentry;
1.1070 www 10096: my %importedpartids;
1.71 www 10097: sub metadata {
1.176 www 10098: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10099: $uri=&declutter($uri);
1.288 albertel 10100: # if it is a non metadata possible uri return quickly
1.529 albertel 10101: if (($uri eq '') ||
10102: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10103: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10104: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10105: return undef;
10106: }
1.1140 www 10107: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10108: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10109: return undef;
1.288 albertel 10110: }
1.73 www 10111: my $filename=$uri;
10112: $uri=~s/\.meta$//;
1.172 www 10113: #
10114: # Is the metadata already cached?
1.177 www 10115: # Look at timestamp of caching
1.172 www 10116: # Everything is cached by the main uri, libraries are never directly cached
10117: #
1.428 albertel 10118: if (!defined($liburi)) {
1.599 albertel 10119: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10120: if (defined($cached)) { return $result->{':'.$what}; }
10121: }
10122: {
1.1069 www 10123: # Imported parts would go here
1.1070 www 10124: my %importedids=();
10125: my @origfileimportpartids=();
1.1069 www 10126: my $importedparts=0;
1.172 www 10127: #
10128: # Is this a recursive call for a library?
10129: #
1.599 albertel 10130: # if (! exists($metacache{$uri})) {
10131: # $metacache{$uri}={};
10132: # }
1.924 albertel 10133: my $cachetime = 60*60;
1.171 www 10134: if ($liburi) {
10135: $liburi=&declutter($liburi);
10136: $filename=$liburi;
1.401 bowersj2 10137: } else {
1.599 albertel 10138: &devalidate_cache_new('meta',$uri);
10139: undef(%metaentry);
1.401 bowersj2 10140: }
1.140 www 10141: my %metathesekeys=();
1.73 www 10142: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10143: my $metastring;
1.1140 www 10144: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10145: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10146: $metastring =
1.929 albertel 10147: &Apache::lonnet::ssi_body($which,
1.924 albertel 10148: ('grade_target' => 'meta'));
10149: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10150: } elsif (($uri !~ m -^(editupload)/-) &&
10151: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10152: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10153: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10154: $metastring=&getfile($file);
1.489 albertel 10155: }
1.208 albertel 10156: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10157: my $token;
1.140 www 10158: undef %metathesekeys;
1.71 www 10159: while ($token=$parser->get_token) {
1.339 albertel 10160: if ($token->[0] eq 'S') {
10161: if (defined($token->[2]->{'package'})) {
1.172 www 10162: #
10163: # This is a package - get package info
10164: #
1.339 albertel 10165: my $package=$token->[2]->{'package'};
10166: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10167: if (defined($token->[2]->{'id'})) {
10168: $keyroot.='_'.$token->[2]->{'id'};
10169: }
1.599 albertel 10170: if ($metaentry{':packages'}) {
10171: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10172: } else {
1.599 albertel 10173: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10174: }
1.736 albertel 10175: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10176: my $part=$keyroot;
10177: $part=~s/^\_//;
1.736 albertel 10178: if ($pack_entry=~/^\Q$package\E\&/ ||
10179: $pack_entry=~/^\Q$package\E_0\&/) {
10180: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10181: # ignore package.tab specified default values
10182: # here &package_tab_default() will fetch those
10183: if ($subp eq 'default') { next; }
1.736 albertel 10184: my $value=$packagetab{$pack_entry};
1.432 albertel 10185: my $unikey;
10186: if ($pack =~ /_0$/) {
10187: $unikey='parameter_0_'.$name;
10188: $part=0;
10189: } else {
10190: $unikey='parameter'.$keyroot.'_'.$name;
10191: }
1.339 albertel 10192: if ($subp eq 'display') {
10193: $value.=' [Part: '.$part.']';
10194: }
1.599 albertel 10195: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10196: $metathesekeys{$unikey}=1;
1.599 albertel 10197: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10198: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10199: }
1.599 albertel 10200: if (defined($metaentry{':'.$unikey.'.default'})) {
10201: $metaentry{':'.$unikey}=
10202: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10203: }
1.339 albertel 10204: }
10205: }
10206: } else {
1.172 www 10207: #
10208: # This is not a package - some other kind of start tag
1.339 albertel 10209: #
10210: my $entry=$token->[1];
1.1068 www 10211: my $unikey='';
1.175 www 10212:
1.339 albertel 10213: if ($entry eq 'import') {
1.175 www 10214: #
10215: # Importing a library here
1.339 albertel 10216: #
1.1067 www 10217: my $location=$parser->get_text('/import');
10218: my $dir=$filename;
10219: $dir=~s|[^/]*$||;
10220: $location=&filelocation($dir,$location);
1.1069 www 10221:
1.1068 www 10222: my $importmode=$token->[2]->{'importmode'};
10223: if ($importmode eq 'problem') {
1.1069 www 10224: # Import as problem/response
1.1068 www 10225: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10226: } elsif ($importmode eq 'part') {
10227: # Import as part(s)
1.1069 www 10228: $importedparts=1;
10229: # We need to get the original file and the imported file to get the part order correct
10230: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10231: # Load and inspect original file
1.1070 www 10232: if ($#origfileimportpartids<0) {
10233: undef(%importedpartids);
10234: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10235: my $origfile=&getfile($origfilelocation);
10236: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10237: }
10238:
1.1069 www 10239: # Load and inspect imported file
10240: my $impfile=&getfile($location);
10241: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10242: if ($#impfilepartids>=0) {
10243: # This problem had parts
1.1070 www 10244: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10245: } else {
10246: # Importing by turning a single problem into a problem part
10247: # It gets the import-tags ID as part-ID
10248: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10249: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10250: }
1.1068 www 10251: } else {
10252: # Normal import
10253: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10254: if (defined($token->[2]->{'id'})) {
10255: $unikey.='_'.$token->[2]->{'id'};
10256: }
1.1067 www 10257: }
10258:
1.339 albertel 10259: if ($depthcount<20) {
1.736 albertel 10260: my $metadata =
10261: &metadata($uri,'keys', $location,$unikey,
10262: $depthcount+1);
10263: foreach my $meta (split(',',$metadata)) {
10264: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10265: $metathesekeys{$meta}=1;
1.339 albertel 10266: }
1.1068 www 10267:
10268: }
1.1067 www 10269: } else {
10270: #
10271: # Not importing, some other kind of non-package, non-library start tag
10272: #
10273: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10274: if (defined($token->[2]->{'id'})) {
10275: $unikey.='_'.$token->[2]->{'id'};
10276: }
1.339 albertel 10277: if (defined($token->[2]->{'name'})) {
10278: $unikey.='_'.$token->[2]->{'name'};
10279: }
10280: $metathesekeys{$unikey}=1;
1.736 albertel 10281: foreach my $param (@{$token->[3]}) {
10282: $metaentry{':'.$unikey.'.'.$param} =
10283: $token->[2]->{$param};
1.339 albertel 10284: }
10285: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10286: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10287: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10288: # only ws inside the tag, and not in default, so use default
10289: # as value
1.599 albertel 10290: $metaentry{':'.$unikey}=$default;
1.908 albertel 10291: } elsif ( $internaltext =~ /\S/ ) {
10292: # something interesting inside the tag
10293: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10294: } else {
1.908 albertel 10295: # no interesting values, don't set a default
1.339 albertel 10296: }
1.172 www 10297: # end of not-a-package not-a-library import
1.339 albertel 10298: }
1.172 www 10299: # end of not-a-package start tag
1.339 albertel 10300: }
1.172 www 10301: # the next is the end of "start tag"
1.339 albertel 10302: }
10303: }
1.483 albertel 10304: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10305: $extension = lc($extension);
10306: if ($extension eq 'htm') { $extension='html'; }
10307:
1.737 albertel 10308: foreach my $key (keys(%packagetab)) {
1.483 albertel 10309: #no specific packages #how's our extension
10310: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10311: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10312: \%metathesekeys);
10313: }
1.883 albertel 10314:
10315: if (!exists($metaentry{':packages'})
10316: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10317: foreach my $key (keys(%packagetab)) {
1.483 albertel 10318: #no specific packages well let's get default then
10319: if ($key!~/^default&/) { next; }
1.488 albertel 10320: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10321: \%metathesekeys);
10322: }
10323: }
1.338 www 10324: # are there custom rights to evaluate
1.599 albertel 10325: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10326:
1.338 www 10327: #
10328: # Importing a rights file here
1.339 albertel 10329: #
10330: unless ($depthcount) {
1.599 albertel 10331: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10332: my $dir=$filename;
10333: $dir=~s|[^/]*$||;
10334: $location=&filelocation($dir,$location);
1.736 albertel 10335: my $rights_metadata =
10336: &metadata($uri,'keys',$location,'_rights',
10337: $depthcount+1);
10338: foreach my $rights (split(',',$rights_metadata)) {
10339: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10340: $metathesekeys{$rights}=1;
1.339 albertel 10341: }
10342: }
10343: }
1.737 albertel 10344: # uniqifiy package listing
10345: my %seen;
10346: my @uniq_packages =
10347: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10348: $metaentry{':packages'} = join(',',@uniq_packages);
10349:
1.1070 www 10350: if ($importedparts) {
10351: # We had imported parts and need to rebuild partorder
10352: $metaentry{':partorder'}='';
10353: $metathesekeys{'partorder'}=1;
10354: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10355: if ($origfileimportpartids[$index] eq 'part') {
10356: # original part, part of the problem
10357: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10358: } else {
10359: # we have imported parts at this position
10360: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10361: }
10362: }
10363: $metaentry{':partorder'}=~s/^\,//;
10364: }
10365:
1.737 albertel 10366: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10367: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10368: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10369: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10370: # this is the end of "was not already recently cached
1.71 www 10371: }
1.599 albertel 10372: return $metaentry{':'.$what};
1.261 albertel 10373: }
10374:
1.488 albertel 10375: sub metadata_create_package_def {
1.483 albertel 10376: my ($uri,$key,$package,$metathesekeys)=@_;
10377: my ($pack,$name,$subp)=split(/\&/,$key);
10378: if ($subp eq 'default') { next; }
10379:
1.599 albertel 10380: if (defined($metaentry{':packages'})) {
10381: $metaentry{':packages'}.=','.$package;
1.483 albertel 10382: } else {
1.599 albertel 10383: $metaentry{':packages'}=$package;
1.483 albertel 10384: }
10385: my $value=$packagetab{$key};
10386: my $unikey;
10387: $unikey='parameter_0_'.$name;
1.599 albertel 10388: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10389: $$metathesekeys{$unikey}=1;
1.599 albertel 10390: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10391: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10392: }
1.599 albertel 10393: if (defined($metaentry{':'.$unikey.'.default'})) {
10394: $metaentry{':'.$unikey}=
10395: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10396: }
10397: }
10398:
1.261 albertel 10399: sub metadata_generate_part0 {
10400: my ($metadata,$metacache,$uri) = @_;
10401: my %allnames;
1.737 albertel 10402: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10403: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10404: my $part=$$metacache{':'.$metakey.'.part'};
10405: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10406: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10407: $allnames{$name}=$part;
10408: }
10409: }
10410: }
10411: foreach my $name (keys(%allnames)) {
10412: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10413: my $key=":parameter_0_$name";
1.261 albertel 10414: $$metacache{"$key.part"}='0';
10415: $$metacache{"$key.name"}=$name;
1.428 albertel 10416: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10417: $allnames{$name}.'_'.$name.
10418: '.type'};
1.428 albertel 10419: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10420: '.display'};
1.644 www 10421: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10422: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10423: $$metacache{"$key.display"}=$olddis;
10424: }
1.71 www 10425: }
10426:
1.764 albertel 10427: # ------------------------------------------------------ Devalidate title cache
10428:
10429: sub devalidate_title_cache {
10430: my ($url)=@_;
10431: if (!$env{'request.course.id'}) { return; }
10432: my $symb=&symbread($url);
10433: if (!$symb) { return; }
10434: my $key=$env{'request.course.id'}."\0".$symb;
10435: &devalidate_cache_new('title',$key);
10436: }
10437:
1.1014 droeschl 10438: # ------------------------------------------------- Get the title of a course
10439:
10440: sub current_course_title {
10441: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10442: }
1.301 www 10443: # ------------------------------------------------- Get the title of a resource
10444:
10445: sub gettitle {
10446: my $urlsymb=shift;
10447: my $symb=&symbread($urlsymb);
1.534 albertel 10448: if ($symb) {
1.620 albertel 10449: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10450: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10451: if (defined($cached)) {
10452: return $result;
10453: }
1.534 albertel 10454: my ($map,$resid,$url)=&decode_symb($symb);
10455: my $title='';
1.907 albertel 10456: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10457: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10458: } else {
10459: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10460: &GDBM_READER(),0640)) {
10461: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10462: $title=$bighash{'title_'.$mapid.'.'.$resid};
10463: untie(%bighash);
10464: }
1.534 albertel 10465: }
10466: $title=~s/\&colon\;/\:/gs;
10467: if ($title) {
1.1159 www 10468: # Remember both $symb and $title for dynamic metadata
10469: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10470: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10471: # Cache this title and then return it
1.599 albertel 10472: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10473: }
10474: $urlsymb=$url;
10475: }
10476: my $title=&metadata($urlsymb,'title');
10477: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10478: return $title;
1.301 www 10479: }
1.613 albertel 10480:
1.614 albertel 10481: sub get_slot {
10482: my ($which,$cnum,$cdom)=@_;
10483: if (!$cnum || !$cdom) {
1.790 albertel 10484: (undef,my $courseid)=&whichuser();
1.620 albertel 10485: $cdom=$env{'course.'.$courseid.'.domain'};
10486: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10487: }
1.703 albertel 10488: my $key=join("\0",'slots',$cdom,$cnum,$which);
10489: my %slotinfo;
10490: if (exists($remembered{$key})) {
10491: $slotinfo{$which} = $remembered{$key};
10492: } else {
10493: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10494: &Apache::lonhomework::showhash(%slotinfo);
10495: my ($tmp)=keys(%slotinfo);
10496: if ($tmp=~/^error:/) { return (); }
10497: $remembered{$key} = $slotinfo{$which};
10498: }
1.616 albertel 10499: if (ref($slotinfo{$which}) eq 'HASH') {
10500: return %{$slotinfo{$which}};
10501: }
10502: return $slotinfo{$which};
1.614 albertel 10503: }
1.1150 raeburn 10504:
10505: sub get_reservable_slots {
10506: my ($cnum,$cdom,$uname,$udom) = @_;
10507: my $now = time;
10508: my $reservable_info;
10509: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10510: if (exists($remembered{$key})) {
10511: $reservable_info = $remembered{$key};
10512: } else {
10513: my %resv;
10514: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10515: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10516: $reservable_info = \%resv;
10517: $remembered{$key} = $reservable_info;
10518: }
10519: return $reservable_info;
10520: }
10521:
10522: sub get_course_slots {
10523: my ($cnum,$cdom) = @_;
10524: my $hashid=$cnum.':'.$cdom;
10525: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10526: if (defined($cached)) {
10527: if (ref($result) eq 'HASH') {
10528: return %{$result};
10529: }
10530: } else {
10531: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10532: my ($tmp) = keys(%slots);
10533: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10534: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10535: return %slots;
10536: }
10537: }
10538: return;
10539: }
10540:
10541: sub devalidate_slots_cache {
10542: my ($cnum,$cdom)=@_;
10543: my $hashid=$cnum.':'.$cdom;
10544: &devalidate_cache_new('allslots',$hashid);
10545: }
10546:
1.1181 raeburn 10547: sub get_coursechange {
10548: my ($cdom,$cnum) = @_;
10549: if ($cdom eq '' || $cnum eq '') {
10550: return unless ($env{'request.course.id'});
10551: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10552: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10553: }
10554: my $hashid=$cdom.'_'.$cnum;
10555: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10556: if ((defined($cached)) && ($change ne '')) {
10557: return $change;
10558: } else {
10559: my %crshash;
10560: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10561: if ($crshash{'internal.contentchange'} eq '') {
10562: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10563: if ($change eq '') {
10564: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10565: $change = $crshash{'internal.created'};
10566: }
10567: } else {
10568: $change = $crshash{'internal.contentchange'};
10569: }
10570: my $cachetime = 600;
10571: &do_cache_new('crschange',$hashid,$change,$cachetime);
10572: }
10573: return $change;
10574: }
10575:
10576: sub devalidate_coursechange_cache {
10577: my ($cnum,$cdom)=@_;
10578: my $hashid=$cnum.':'.$cdom;
10579: &devalidate_cache_new('crschange',$hashid);
10580: }
10581:
1.31 www 10582: # ------------------------------------------------- Update symbolic store links
10583:
10584: sub symblist {
10585: my ($mapname,%newhash)=@_;
1.438 www 10586: $mapname=&deversion(&declutter($mapname));
1.31 www 10587: my %hash;
1.620 albertel 10588: if (($env{'request.course.fn'}) && (%newhash)) {
10589: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10590: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10591: foreach my $url (keys(%newhash)) {
1.711 albertel 10592: next if ($url eq 'last_known'
10593: && $env{'form.no_update_last_known'});
10594: $hash{declutter($url)}=&encode_symb($mapname,
10595: $newhash{$url}->[1],
10596: $newhash{$url}->[0]);
1.191 harris41 10597: }
1.31 www 10598: if (untie(%hash)) {
10599: return 'ok';
10600: }
10601: }
10602: }
10603: return 'error';
1.212 www 10604: }
10605:
10606: # --------------------------------------------------------------- Verify a symb
10607:
10608: sub symbverify {
1.1190 raeburn 10609: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10610: my $thisfn=$thisurl;
1.439 www 10611: $thisfn=&declutter($thisfn);
1.215 www 10612: # direct jump to resource in page or to a sequence - will construct own symbs
10613: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10614: # check URL part
1.409 www 10615: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10616:
1.431 www 10617: unless ($url eq $thisfn) { return 0; }
1.213 www 10618:
1.216 www 10619: $symb=&symbclean($symb);
1.510 www 10620: $thisurl=&deversion($thisurl);
1.439 www 10621: $thisfn=&deversion($thisfn);
1.213 www 10622:
10623: my %bighash;
10624: my $okay=0;
1.431 www 10625:
1.620 albertel 10626: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10627: &GDBM_READER(),0640)) {
1.1204 raeburn 10628: my $noclutter;
1.1032 raeburn 10629: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10630: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10631: if ($map =~ m{^uploaded/.+\.page$}) {
10632: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10633: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10634: $noclutter = 1;
10635: }
10636: }
10637: my $ids;
10638: if ($noclutter) {
10639: $ids=$bighash{'ids_'.$thisurl};
10640: } else {
10641: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10642: }
1.1102 raeburn 10643: unless ($ids) {
10644: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10645: $ids=$bighash{$idkey};
1.216 www 10646: }
10647: if ($ids) {
10648: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10649: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10650: $symb =~ s/\?.+$//;
1.1202 raeburn 10651: }
1.800 albertel 10652: foreach my $id (split(/\,/,$ids)) {
10653: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10654: if (
10655: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 10656: eq $symb) {
10657: if (ref($encstate)) {
10658: $$encstate = $bighash{'encrypted_'.$id};
10659: }
1.620 albertel 10660: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10661: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10662: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 10663: $okay=1;
1.1202 raeburn 10664: last;
1.582 albertel 10665: }
10666: }
1.216 www 10667: }
10668: }
1.213 www 10669: untie(%bighash);
10670: }
10671: return $okay;
1.31 www 10672: }
10673:
1.210 www 10674: # --------------------------------------------------------------- Clean-up symb
10675:
10676: sub symbclean {
10677: my $symb=shift;
1.568 albertel 10678: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10679: # remove version from map
10680: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10681:
1.210 www 10682: # remove version from URL
10683: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10684:
1.507 www 10685: # remove wrapper
10686:
1.510 www 10687: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10688: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10689: return $symb;
1.409 www 10690: }
10691:
10692: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10693:
10694: sub encode_symb {
10695: my ($map,$resid,$url)=@_;
10696: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10697: }
1.409 www 10698:
10699: sub decode_symb {
1.568 albertel 10700: my $symb=shift;
10701: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10702: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10703: return (&fixversion($map),$resid,&fixversion($url));
10704: }
10705:
10706: sub fixversion {
10707: my $fn=shift;
1.609 banghart 10708: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10709: my %bighash;
10710: my $uri=&clutter($fn);
1.620 albertel 10711: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10712: # is this cached?
1.599 albertel 10713: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10714: if (defined($cached)) { return $result; }
10715: # unfortunately not cached, or expired
1.620 albertel 10716: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10717: &GDBM_READER(),0640)) {
10718: if ($bighash{'version_'.$uri}) {
10719: my $version=$bighash{'version_'.$uri};
1.444 www 10720: unless (($version eq 'mostrecent') ||
10721: ($version==&getversion($uri))) {
1.440 www 10722: $uri=~s/\.(\w+)$/\.$version\.$1/;
10723: }
10724: }
10725: untie %bighash;
1.413 www 10726: }
1.599 albertel 10727: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10728: }
10729:
10730: sub deversion {
10731: my $url=shift;
10732: $url=~s/\.\d+\.(\w+)$/\.$1/;
10733: return $url;
1.210 www 10734: }
10735:
1.31 www 10736: # ------------------------------------------------------ Return symb list entry
10737:
10738: sub symbread {
1.249 www 10739: my ($thisfn,$donotrecurse)=@_;
1.1206 raeburn 10740: my $cache_str;
10741: if ($thisfn ne '') {
10742: $cache_str='request.symbread.cached.'.$thisfn;
10743: if ($env{$cache_str} ne '') {
1.1179 raeburn 10744: return $env{$cache_str};
10745: }
1.1206 raeburn 10746: } else {
1.242 www 10747: # no filename provided? try from environment
1.620 albertel 10748: if ($env{'request.symb'}) {
10749: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10750: }
1.620 albertel 10751: $thisfn=$env{'request.filename'};
1.44 www 10752: }
1.569 albertel 10753: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10754: # is that filename actually a symb? Verify, clean, and return
10755: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10756: if (&symbverify($thisfn,$1)) {
1.620 albertel 10757: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10758: }
1.242 www 10759: }
1.44 www 10760: $thisfn=declutter($thisfn);
1.31 www 10761: my %hash;
1.37 www 10762: my %bighash;
10763: my $syval='';
1.620 albertel 10764: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10765: my $targetfn = $thisfn;
1.609 banghart 10766: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10767: $targetfn = 'adm/wrapper/'.$thisfn;
10768: }
1.687 albertel 10769: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10770: $targetfn=$1;
10771: }
1.620 albertel 10772: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10773: &GDBM_READER(),0640)) {
1.481 raeburn 10774: $syval=$hash{$targetfn};
1.37 www 10775: untie(%hash);
10776: }
10777: # ---------------------------------------------------------- There was an entry
10778: if ($syval) {
1.601 albertel 10779: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10780: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10781: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10782: #return $env{$cache_str}='';
1.601 albertel 10783: #}
10784: #$syval.=$1;
10785: #}
1.37 www 10786: } else {
10787: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10788: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10789: &GDBM_READER(),0640)) {
1.37 www 10790: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10791: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10792: unless ($ids) {
10793: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10794: }
10795: unless ($ids) {
10796: # alias?
10797: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10798: }
1.37 www 10799: if ($ids) {
10800: # ------------------------------------------------------------------- Has ID(s)
10801: my @possibilities=split(/\,/,$ids);
1.39 www 10802: if ($#possibilities==0) {
10803: # ----------------------------------------------- There is only one possibility
1.37 www 10804: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10805: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10806: $resid,$thisfn);
1.249 www 10807: } elsif (!$donotrecurse) {
1.39 www 10808: # ------------------------------------------ There is more than one possibility
10809: my $realpossible=0;
1.800 albertel 10810: foreach my $id (@possibilities) {
10811: my $file=$bighash{'src_'.$id};
1.39 www 10812: if (&allowed('bre',$file)) {
1.800 albertel 10813: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10814: if ($bighash{'map_type_'.$mapid} ne 'page') {
10815: $realpossible++;
1.626 albertel 10816: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10817: $resid,$thisfn);
1.39 www 10818: }
10819: }
1.191 harris41 10820: }
1.39 www 10821: if ($realpossible!=1) { $syval=''; }
1.249 www 10822: } else {
10823: $syval='';
1.37 www 10824: }
10825: }
10826: untie(%bighash)
1.481 raeburn 10827: }
1.31 www 10828: }
1.62 www 10829: if ($syval) {
1.620 albertel 10830: return $env{$cache_str}=$syval;
1.62 www 10831: }
1.31 www 10832: }
1.949 raeburn 10833: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10834: return $env{$cache_str}='';
1.31 www 10835: }
10836:
10837: # ---------------------------------------------------------- Return random seed
10838:
1.32 www 10839: sub numval {
10840: my $txt=shift;
10841: $txt=~tr/A-J/0-9/;
10842: $txt=~tr/a-j/0-9/;
10843: $txt=~tr/K-T/0-9/;
10844: $txt=~tr/k-t/0-9/;
10845: $txt=~tr/U-Z/0-5/;
10846: $txt=~tr/u-z/0-5/;
10847: $txt=~s/\D//g;
1.564 albertel 10848: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10849: return int($txt);
1.368 albertel 10850: }
10851:
1.484 albertel 10852: sub numval2 {
10853: my $txt=shift;
10854: $txt=~tr/A-J/0-9/;
10855: $txt=~tr/a-j/0-9/;
10856: $txt=~tr/K-T/0-9/;
10857: $txt=~tr/k-t/0-9/;
10858: $txt=~tr/U-Z/0-5/;
10859: $txt=~tr/u-z/0-5/;
10860: $txt=~s/\D//g;
10861: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10862: my $total;
10863: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10864: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10865: return int($total);
10866: }
10867:
1.575 albertel 10868: sub numval3 {
10869: use integer;
10870: my $txt=shift;
10871: $txt=~tr/A-J/0-9/;
10872: $txt=~tr/a-j/0-9/;
10873: $txt=~tr/K-T/0-9/;
10874: $txt=~tr/k-t/0-9/;
10875: $txt=~tr/U-Z/0-5/;
10876: $txt=~tr/u-z/0-5/;
10877: $txt=~s/\D//g;
10878: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10879: my $total;
10880: foreach my $val (@txts) { $total+=$val; }
10881: if ($_64bit) { $total=(($total<<32)>>32); }
10882: return $total;
10883: }
10884:
1.675 albertel 10885: sub digest {
10886: my ($data)=@_;
10887: my $digest=&Digest::MD5::md5($data);
10888: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10889: my ($e,$f);
10890: {
10891: use integer;
10892: $e=($a+$b);
10893: $f=($c+$d);
10894: if ($_64bit) {
10895: $e=(($e<<32)>>32);
10896: $f=(($f<<32)>>32);
10897: }
10898: }
10899: if (wantarray) {
10900: return ($e,$f);
10901: } else {
10902: my $g;
10903: {
10904: use integer;
10905: $g=($e+$f);
10906: if ($_64bit) {
10907: $g=(($g<<32)>>32);
10908: }
10909: }
10910: return $g;
10911: }
10912: }
10913:
1.368 albertel 10914: sub latest_rnd_algorithm_id {
1.675 albertel 10915: return '64bit5';
1.366 albertel 10916: }
1.32 www 10917:
1.503 albertel 10918: sub get_rand_alg {
10919: my ($courseid)=@_;
1.790 albertel 10920: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10921: if ($courseid) {
1.620 albertel 10922: return $env{"course.$courseid.rndseed"};
1.503 albertel 10923: }
10924: return &latest_rnd_algorithm_id();
10925: }
10926:
1.562 albertel 10927: sub validCODE {
10928: my ($CODE)=@_;
10929: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10930: return 0;
10931: }
10932:
1.491 albertel 10933: sub getCODE {
1.620 albertel 10934: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10935: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10936: defined($Apache::lonhomework::parsing_a_task) ) &&
10937: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10938: return $Apache::lonhomework::history{'resource.CODE'};
10939: }
10940: return undef;
10941: }
1.1133 foxr 10942: #
10943: # Determines the random seed for a specific context:
10944: #
10945: # parameters:
10946: # symb - in course context the symb for the seed.
10947: # course_id - The course id of the form domain_coursenum.
10948: # domain - Domain for the user.
10949: # course - Course for the user.
10950: # cenv - environment of the course.
10951: #
10952: # NOTE:
10953: # All parameters are picked out of the environment if missing
10954: # or not defined.
10955: # If a symb cannot be determined the current time is used instead.
10956: #
10957: # For a given well defined symb, courside, domain, username,
10958: # and course environment, the seed is reproducible.
10959: #
1.31 www 10960: sub rndseed {
1.1133 foxr 10961: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10962: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10963: if (!defined($symb)) {
1.366 albertel 10964: unless ($symb=$wsymb) { return time; }
10965: }
1.1146 foxr 10966: if (!defined $courseid) {
10967: $courseid=$wcourseid;
10968: }
10969: if (!defined $domain) { $domain=$wdomain; }
10970: if (!defined $username) { $username=$wusername }
1.1133 foxr 10971:
10972: my $which;
10973: if (defined($cenv->{'rndseed'})) {
10974: $which = $cenv->{'rndseed'};
10975: } else {
10976: $which =&get_rand_alg($courseid);
10977: }
1.491 albertel 10978: if (defined(&getCODE())) {
1.1133 foxr 10979:
1.675 albertel 10980: if ($which eq '64bit5') {
10981: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10982: } elsif ($which eq '64bit4') {
1.575 albertel 10983: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10984: } else {
10985: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10986: }
1.675 albertel 10987: } elsif ($which eq '64bit5') {
10988: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10989: } elsif ($which eq '64bit4') {
10990: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10991: } elsif ($which eq '64bit3') {
10992: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10993: } elsif ($which eq '64bit2') {
10994: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10995: } elsif ($which eq '64bit') {
10996: return &rndseed_64bit($symb,$courseid,$domain,$username);
10997: }
10998: return &rndseed_32bit($symb,$courseid,$domain,$username);
10999: }
11000:
11001: sub rndseed_32bit {
11002: my ($symb,$courseid,$domain,$username)=@_;
11003: {
11004: use integer;
11005: my $symbchck=unpack("%32C*",$symb) << 27;
11006: my $symbseed=numval($symb) << 22;
11007: my $namechck=unpack("%32C*",$username) << 17;
11008: my $nameseed=numval($username) << 12;
11009: my $domainseed=unpack("%32C*",$domain) << 7;
11010: my $courseseed=unpack("%32C*",$courseid);
11011: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11012: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11013: #&logthis("rndseed :$num:$symb");
1.564 albertel 11014: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11015: return $num;
11016: }
11017: }
11018:
11019: sub rndseed_64bit {
11020: my ($symb,$courseid,$domain,$username)=@_;
11021: {
11022: use integer;
11023: my $symbchck=unpack("%32S*",$symb) << 21;
11024: my $symbseed=numval($symb) << 10;
11025: my $namechck=unpack("%32S*",$username);
11026:
11027: my $nameseed=numval($username) << 21;
11028: my $domainseed=unpack("%32S*",$domain) << 10;
11029: my $courseseed=unpack("%32S*",$courseid);
11030:
11031: my $num1=$symbchck+$symbseed+$namechck;
11032: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11033: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11034: #&logthis("rndseed :$num:$symb");
1.564 albertel 11035: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11036: return "$num1,$num2";
1.155 albertel 11037: }
1.366 albertel 11038: }
11039:
1.443 albertel 11040: sub rndseed_64bit2 {
11041: my ($symb,$courseid,$domain,$username)=@_;
11042: {
11043: use integer;
11044: # strings need to be an even # of cahracters long, it it is odd the
11045: # last characters gets thrown away
11046: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11047: my $symbseed=numval($symb) << 10;
11048: my $namechck=unpack("%32S*",$username.' ');
11049:
11050: my $nameseed=numval($username) << 21;
1.501 albertel 11051: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11052: my $courseseed=unpack("%32S*",$courseid.' ');
11053:
11054: my $num1=$symbchck+$symbseed+$namechck;
11055: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11056: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11057: #&logthis("rndseed :$num:$symb");
1.803 albertel 11058: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11059: return "$num1,$num2";
11060: }
11061: }
11062:
11063: sub rndseed_64bit3 {
11064: my ($symb,$courseid,$domain,$username)=@_;
11065: {
11066: use integer;
11067: # strings need to be an even # of cahracters long, it it is odd the
11068: # last characters gets thrown away
11069: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11070: my $symbseed=numval2($symb) << 10;
11071: my $namechck=unpack("%32S*",$username.' ');
11072:
11073: my $nameseed=numval2($username) << 21;
1.443 albertel 11074: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11075: my $courseseed=unpack("%32S*",$courseid.' ');
11076:
11077: my $num1=$symbchck+$symbseed+$namechck;
11078: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11079: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11080: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11081: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11082:
1.503 albertel 11083: return "$num1:$num2";
1.443 albertel 11084: }
11085: }
11086:
1.575 albertel 11087: sub rndseed_64bit4 {
11088: my ($symb,$courseid,$domain,$username)=@_;
11089: {
11090: use integer;
11091: # strings need to be an even # of cahracters long, it it is odd the
11092: # last characters gets thrown away
11093: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11094: my $symbseed=numval3($symb) << 10;
11095: my $namechck=unpack("%32S*",$username.' ');
11096:
11097: my $nameseed=numval3($username) << 21;
11098: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11099: my $courseseed=unpack("%32S*",$courseid.' ');
11100:
11101: my $num1=$symbchck+$symbseed+$namechck;
11102: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11103: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11104: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11105: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11106:
1.575 albertel 11107: return "$num1:$num2";
11108: }
11109: }
11110:
1.675 albertel 11111: sub rndseed_64bit5 {
11112: my ($symb,$courseid,$domain,$username)=@_;
11113: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11114: return "$num1:$num2";
11115: }
11116:
1.366 albertel 11117: sub rndseed_CODE_64bit {
11118: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11119: {
1.366 albertel 11120: use integer;
1.443 albertel 11121: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11122: my $symbseed=numval2($symb);
1.491 albertel 11123: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11124: my $CODEseed=numval(&getCODE());
1.443 albertel 11125: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11126: my $num1=$symbseed+$CODEchck;
11127: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11128: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11129: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11130: if ($_64bit) { $num1=(($num1<<32)>>32); }
11131: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11132: return "$num1:$num2";
1.366 albertel 11133: }
11134: }
11135:
1.575 albertel 11136: sub rndseed_CODE_64bit4 {
11137: my ($symb,$courseid,$domain,$username)=@_;
11138: {
11139: use integer;
11140: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11141: my $symbseed=numval3($symb);
11142: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11143: my $CODEseed=numval3(&getCODE());
11144: my $courseseed=unpack("%32S*",$courseid.' ');
11145: my $num1=$symbseed+$CODEchck;
11146: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11147: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11148: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11149: if ($_64bit) { $num1=(($num1<<32)>>32); }
11150: if ($_64bit) { $num2=(($num2<<32)>>32); }
11151: return "$num1:$num2";
11152: }
11153: }
11154:
1.675 albertel 11155: sub rndseed_CODE_64bit5 {
11156: my ($symb,$courseid,$domain,$username)=@_;
11157: my $code = &getCODE();
11158: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11159: return "$num1:$num2";
11160: }
11161:
1.366 albertel 11162: sub setup_random_from_rndseed {
11163: my ($rndseed)=@_;
1.503 albertel 11164: if ($rndseed =~/([,:])/) {
11165: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11166: &Math::Random::random_set_seed(abs($num1),abs($num2));
11167: } else {
11168: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11169: }
1.36 albertel 11170: }
11171:
1.474 albertel 11172: sub latest_receipt_algorithm_id {
1.835 albertel 11173: return 'receipt3';
1.474 albertel 11174: }
11175:
1.480 www 11176: sub recunique {
11177: my $fucourseid=shift;
11178: my $unique;
1.835 albertel 11179: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11180: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11181: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11182: } else {
11183: $unique=$perlvar{'lonReceipt'};
11184: }
11185: return unpack("%32C*",$unique);
11186: }
11187:
11188: sub recprefix {
11189: my $fucourseid=shift;
11190: my $prefix;
1.835 albertel 11191: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11192: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11193: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11194: } else {
11195: $prefix=$perlvar{'lonHostID'};
11196: }
11197: return unpack("%32C*",$prefix);
11198: }
11199:
1.76 www 11200: sub ireceipt {
1.474 albertel 11201: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11202:
11203: my $return =&recprefix($fucourseid).'-';
11204:
11205: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11206: $env{'request.state'} eq 'construct') {
11207: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11208: return $return;
11209: }
11210:
1.76 www 11211: my $cuname=unpack("%32C*",$funame);
11212: my $cudom=unpack("%32C*",$fudom);
11213: my $cucourseid=unpack("%32C*",$fucourseid);
11214: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11215: my $cunique=&recunique($fucourseid);
1.474 albertel 11216: my $cpart=unpack("%32S*",$part);
1.835 albertel 11217: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11218:
1.790 albertel 11219: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11220:
11221: $return.= ($cunique%$cuname+
11222: $cunique%$cudom+
11223: $cusymb%$cuname+
11224: $cusymb%$cudom+
11225: $cucourseid%$cuname+
11226: $cucourseid%$cudom+
11227: $cpart%$cuname+
11228: $cpart%$cudom);
11229: } else {
11230: $return.= ($cunique%$cuname+
11231: $cunique%$cudom+
11232: $cusymb%$cuname+
11233: $cusymb%$cudom+
11234: $cucourseid%$cuname+
11235: $cucourseid%$cudom);
11236: }
11237: return $return;
1.76 www 11238: }
11239:
11240: sub receipt {
1.474 albertel 11241: my ($part)=@_;
1.790 albertel 11242: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11243: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11244: }
1.260 ng 11245:
1.790 albertel 11246: sub whichuser {
11247: my ($passedsymb)=@_;
11248: my ($symb,$courseid,$domain,$name,$publicuser);
11249: if (defined($env{'form.grade_symb'})) {
11250: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11251: my $allowed=&allowed('vgr',$tmp_courseid);
11252: if (!$allowed &&
11253: exists($env{'request.course.sec'}) &&
11254: $env{'request.course.sec'} !~ /^\s*$/) {
11255: $allowed=&allowed('vgr',$tmp_courseid.
11256: '/'.$env{'request.course.sec'});
11257: }
11258: if ($allowed) {
11259: ($symb)=&get_env_multiple('form.grade_symb');
11260: $courseid=$tmp_courseid;
11261: ($domain)=&get_env_multiple('form.grade_domain');
11262: ($name)=&get_env_multiple('form.grade_username');
11263: return ($symb,$courseid,$domain,$name,$publicuser);
11264: }
11265: }
11266: if (!$passedsymb) {
11267: $symb=&symbread();
11268: } else {
11269: $symb=$passedsymb;
11270: }
11271: $courseid=$env{'request.course.id'};
11272: $domain=$env{'user.domain'};
11273: $name=$env{'user.name'};
11274: if ($name eq 'public' && $domain eq 'public') {
11275: if (!defined($env{'form.username'})) {
11276: $env{'form.username'}.=time.rand(10000000);
11277: }
11278: $name.=$env{'form.username'};
11279: }
11280: return ($symb,$courseid,$domain,$name,$publicuser);
11281:
11282: }
11283:
1.36 albertel 11284: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11285: # returns either the contents of the file or
11286: # -1 if the file doesn't exist
1.481 raeburn 11287: #
11288: # if the target is a file that was uploaded via DOCS,
11289: # a check will be made to see if a current copy exists on the local server,
11290: # if it does this will be served, otherwise a copy will be retrieved from
11291: # the home server for the course and stored in /home/httpd/html/userfiles on
11292: # the local server.
1.472 albertel 11293:
1.36 albertel 11294: sub getfile {
1.538 albertel 11295: my ($file) = @_;
1.609 banghart 11296: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11297: &repcopy($file);
11298: return &readfile($file);
11299: }
11300:
11301: sub repcopy_userfile {
11302: my ($file)=@_;
1.1142 raeburn 11303: my $londocroot = $perlvar{'lonDocRoot'};
11304: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11305: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11306: my ($cdom,$cnum,$filename) =
1.811 albertel 11307: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11308: my $uri="/uploaded/$cdom/$cnum/$filename";
11309: if (-e "$file") {
1.828 www 11310: # we already have a local copy, check it out
1.538 albertel 11311: my @fileinfo = stat($file);
1.828 www 11312: my $rtncode;
11313: my $info;
1.538 albertel 11314: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11315: if ($lwpresp ne 'ok') {
1.828 www 11316: # there is no such file anymore, even though we had a local copy
1.482 albertel 11317: if ($rtncode eq '404') {
1.538 albertel 11318: unlink($file);
1.482 albertel 11319: }
11320: return -1;
11321: }
11322: if ($info < $fileinfo[9]) {
1.828 www 11323: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11324: return 'ok';
1.828 www 11325: } else {
11326: # the file is outdated, get rid of it
11327: unlink($file);
1.482 albertel 11328: }
1.828 www 11329: }
11330: # one way or the other, at this point, we don't have the file
11331: # construct the correct path for the file
11332: my @parts = ($cdom,$cnum);
11333: if ($filename =~ m|^(.+)/[^/]+$|) {
11334: push @parts, split(/\//,$1);
11335: }
11336: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11337: foreach my $part (@parts) {
11338: $path .= '/'.$part;
11339: if (!-e $path) {
11340: mkdir($path,0770);
1.482 albertel 11341: }
11342: }
1.828 www 11343: # now the path exists for sure
11344: # get a user agent
11345: my $ua=new LWP::UserAgent;
11346: my $transferfile=$file.'.in.transfer';
11347: # FIXME: this should flock
11348: if (-e $transferfile) { return 'ok'; }
11349: my $request;
11350: $uri=~s/^\///;
1.980 raeburn 11351: my $homeserver = &homeserver($cnum,$cdom);
11352: my $protocol = $protocol{$homeserver};
11353: $protocol = 'http' if ($protocol ne 'https');
11354: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11355: my $response=$ua->request($request,$transferfile);
11356: # did it work?
11357: if ($response->is_error()) {
11358: unlink($transferfile);
11359: &logthis("Userfile repcopy failed for $uri");
11360: return -1;
11361: }
11362: # worked, rename the transfer file
11363: rename($transferfile,$file);
1.607 raeburn 11364: return 'ok';
1.481 raeburn 11365: }
11366:
1.517 albertel 11367: sub tokenwrapper {
11368: my $uri=shift;
1.980 raeburn 11369: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11370: $uri=~s|^/||;
1.620 albertel 11371: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11372: my $token=$1;
1.552 albertel 11373: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11374: if ($udom && $uname && $file) {
11375: $file=~s|(\?\.*)*$||;
1.949 raeburn 11376: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11377: my $homeserver = &homeserver($uname,$udom);
11378: my $protocol = $protocol{$homeserver};
11379: $protocol = 'http' if ($protocol ne 'https');
11380: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11381: (($uri=~/\?/)?'&':'?').'token='.$token.
11382: '&tokenissued='.$perlvar{'lonHostID'};
11383: } else {
11384: return '/adm/notfound.html';
11385: }
11386: }
11387:
1.828 www 11388: # call with reqtype HEAD: get last modification time
11389: # call with reqtype GET: get the file contents
11390: # Do not call this with reqtype GET for large files! It loads everything into memory
11391: #
1.481 raeburn 11392: sub getuploaded {
11393: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11394: $uri=~s/^\///;
1.980 raeburn 11395: my $homeserver = &homeserver($cnum,$cdom);
11396: my $protocol = $protocol{$homeserver};
11397: $protocol = 'http' if ($protocol ne 'https');
11398: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11399: my $ua=new LWP::UserAgent;
11400: my $request=new HTTP::Request($reqtype,$uri);
11401: my $response=$ua->request($request);
11402: $$rtncode = $response->code;
1.482 albertel 11403: if (! $response->is_success()) {
11404: return 'failed';
11405: }
11406: if ($reqtype eq 'HEAD') {
1.486 www 11407: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11408: } elsif ($reqtype eq 'GET') {
11409: $$info = $response->content;
1.472 albertel 11410: }
1.482 albertel 11411: return 'ok';
1.36 albertel 11412: }
11413:
1.481 raeburn 11414: sub readfile {
11415: my $file = shift;
11416: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11417: my $fh;
11418: open($fh,"<$file");
11419: my $a='';
1.800 albertel 11420: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11421: return $a;
11422: }
11423:
1.36 albertel 11424: sub filelocation {
1.590 banghart 11425: my ($dir,$file) = @_;
11426: my $location;
11427: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11428:
11429: if ($file =~ m-^/adm/-) {
11430: $file=~s-^/adm/wrapper/-/-;
11431: $file=~s-^/adm/coursedocs/showdoc/-/-;
11432: }
1.882 albertel 11433:
1.1139 www 11434: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11435: $location = $file;
1.609 banghart 11436: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11437: my ($udom,$uname,$filename)=
1.811 albertel 11438: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11439: my $home=&homeserver($uname,$udom);
11440: my $is_me=0;
11441: my @ids=¤t_machine_ids();
11442: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11443: if ($is_me) {
1.1117 foxr 11444: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11445: } else {
11446: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11447: $udom.'/'.$uname.'/'.$filename;
11448: }
1.882 albertel 11449: } elsif ($file =~ m-^/adm/-) {
11450: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11451: } else {
11452: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11453: $file=~s:^/(res|priv)/:/:;
11454: my $space=$1;
1.590 banghart 11455: if ( !( $file =~ m:^/:) ) {
11456: $location = $dir. '/'.$file;
11457: } else {
1.1142 raeburn 11458: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11459: }
1.59 albertel 11460: }
1.590 banghart 11461: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11462: while ($location=~m{/\.\./}) {
11463: if ($location =~ m{/[^/]+/\.\./}) {
11464: $location=~ s{/[^/]+/\.\./}{/}g;
11465: } else {
11466: $location=~ s{/\.\./}{/}g;
11467: }
11468: } #remove dir/..
1.590 banghart 11469: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11470: return $location;
1.46 www 11471: }
1.36 albertel 11472:
1.46 www 11473: sub hreflocation {
11474: my ($dir,$file)=@_;
1.980 raeburn 11475: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11476: $file=filelocation($dir,$file);
1.700 albertel 11477: } elsif ($file=~m-^/adm/-) {
11478: $file=~s-^/adm/wrapper/-/-;
11479: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11480: }
11481: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11482: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11483: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11484: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11485: {/uploaded/$1/$2/}x;
1.46 www 11486: }
1.913 albertel 11487: if ($file=~ m{^/userfiles/}) {
11488: $file =~ s{^/userfiles/}{/uploaded/};
11489: }
1.462 albertel 11490: return $file;
1.465 albertel 11491: }
11492:
1.1139 www 11493:
11494:
11495:
11496:
1.465 albertel 11497: sub current_machine_domains {
1.853 albertel 11498: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11499: }
11500:
11501: sub machine_domains {
11502: my ($hostname) = @_;
1.465 albertel 11503: my @domains;
1.838 albertel 11504: my %hostname = &all_hostnames();
1.465 albertel 11505: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11506: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11507: if ($hostname eq $name) {
1.844 albertel 11508: push(@domains,&host_domain($id));
1.465 albertel 11509: }
11510: }
11511: return @domains;
11512: }
11513:
11514: sub current_machine_ids {
1.853 albertel 11515: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11516: }
11517:
11518: sub machine_ids {
11519: my ($hostname) = @_;
11520: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11521: my @ids;
1.888 albertel 11522: my %name_to_host = &all_names();
1.889 albertel 11523: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11524: return @{ $name_to_host{$hostname} };
11525: }
11526: return;
1.31 www 11527: }
11528:
1.824 raeburn 11529: sub additional_machine_domains {
11530: my @domains;
11531: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11532: while( my $line = <$fh>) {
11533: $line =~ s/\s//g;
11534: push(@domains,$line);
11535: }
11536: return @domains;
11537: }
11538:
11539: sub default_login_domain {
11540: my $domain = $perlvar{'lonDefDomain'};
11541: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11542: foreach my $posdom (¤t_machine_domains(),
11543: &additional_machine_domains()) {
11544: if (lc($posdom) eq lc($testdomain)) {
11545: $domain=$posdom;
11546: last;
11547: }
11548: }
11549: return $domain;
11550: }
11551:
1.31 www 11552: # ------------------------------------------------------------- Declutters URLs
11553:
11554: sub declutter {
11555: my $thisfn=shift;
1.569 albertel 11556: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11557: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11558: $thisfn=~s/^\///;
1.697 albertel 11559: $thisfn=~s|^adm/wrapper/||;
11560: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11561: $thisfn=~s/^res\///;
1.1172 bisitz 11562: $thisfn=~s/^priv\///;
1.1032 raeburn 11563: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11564: $thisfn=~s/\?.+$//;
11565: }
1.268 www 11566: return $thisfn;
11567: }
11568:
11569: # ------------------------------------------------------------- Clutter up URLs
11570:
11571: sub clutter {
11572: my $thisfn='/'.&declutter(shift);
1.887 albertel 11573: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11574: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11575: $thisfn='/res'.$thisfn;
11576: }
1.1031 raeburn 11577: if ($thisfn !~m|^/adm|) {
11578: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11579: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11580: } else {
11581: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11582: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11583: if ($embstyle eq 'ssi'
11584: || ($embstyle eq 'hdn')
11585: || ($embstyle eq 'rat')
11586: || ($embstyle eq 'prv')
11587: || ($embstyle eq 'ign')) {
11588: #do nothing with these
11589: } elsif (($embstyle eq 'img')
1.695 albertel 11590: || ($embstyle eq 'emb')
11591: || ($embstyle eq 'wrp')) {
11592: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11593: } elsif ($embstyle eq 'unk'
11594: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11595: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11596: } else {
1.718 www 11597: # &logthis("Got a blank emb style");
1.695 albertel 11598: }
1.694 albertel 11599: }
11600: }
1.31 www 11601: return $thisfn;
1.12 www 11602: }
11603:
1.787 albertel 11604: sub clutter_with_no_wrapper {
11605: my $uri = &clutter(shift);
11606: if ($uri =~ m-^/adm/-) {
11607: $uri =~ s-^/adm/wrapper/-/-;
11608: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11609: }
11610: return $uri;
11611: }
11612:
1.557 albertel 11613: sub freeze_escape {
11614: my ($value)=@_;
11615: if (ref($value)) {
11616: $value=&nfreeze($value);
11617: return '__FROZEN__'.&escape($value);
11618: }
11619: return &escape($value);
11620: }
11621:
1.11 www 11622:
1.557 albertel 11623: sub thaw_unescape {
11624: my ($value)=@_;
11625: if ($value =~ /^__FROZEN__/) {
11626: substr($value,0,10,undef);
11627: $value=&unescape($value);
11628: return &thaw($value);
11629: }
11630: return &unescape($value);
11631: }
11632:
1.436 albertel 11633: sub correct_line_ends {
11634: my ($result)=@_;
11635: $$result =~s/\r\n/\n/mg;
11636: $$result =~s/\r/\n/mg;
1.415 albertel 11637: }
1.1 albertel 11638: # ================================================================ Main Program
11639:
1.184 www 11640: sub goodbye {
1.204 albertel 11641: &logthis("Starting Shut down");
1.443 albertel 11642: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11643: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11644: #converted
1.599 albertel 11645: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11646: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11647: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11648: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11649: #1.1 only
1.870 albertel 11650: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11651: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11652: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11653: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11654: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11655: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11656: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11657: &flushcourselogs();
11658: &logthis("Shutting down");
11659: }
11660:
1.852 albertel 11661: sub get_dns {
1.1210 raeburn 11662: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11663: if (!$ignore_cache) {
11664: my ($content,$cached)=
11665: &Apache::lonnet::is_cached_new('dns',$url);
11666: if ($cached) {
1.1210 raeburn 11667: &$func($content,$hashref);
1.869 albertel 11668: return;
11669: }
11670: }
11671:
11672: my %alldns;
1.852 albertel 11673: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11674: foreach my $dns (<$config>) {
11675: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11676: my $line = $1;
11677: my ($host,$protocol) = split(/:/,$line);
11678: if ($protocol ne 'https') {
11679: $protocol = 'http';
11680: }
11681: $alldns{$host} = $protocol;
1.869 albertel 11682: }
11683: while (%alldns) {
11684: my ($dns) = keys(%alldns);
1.852 albertel 11685: my $ua=new LWP::UserAgent;
1.1134 raeburn 11686: $ua->timeout(30);
1.979 raeburn 11687: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11688: my $response=$ua->request($request);
1.979 raeburn 11689: delete($alldns{$dns});
1.852 albertel 11690: next if ($response->is_error());
11691: my @content = split("\n",$response->content);
1.1210 raeburn 11692: unless ($nocache) {
1.1219 raeburn 11693: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 11694: }
11695: &$func(\@content,$hashref);
1.869 albertel 11696: return;
1.852 albertel 11697: }
11698: close($config);
1.871 albertel 11699: my $which = (split('/',$url))[3];
11700: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11701: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11702: my @content = <$config>;
1.1210 raeburn 11703: &$func(\@content,$hashref);
11704: return;
11705: }
11706:
11707: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 11708: sub parse_dns_checksums_tab {
1.1210 raeburn 11709: my ($lines,$hashref) = @_;
11710: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11711: my $loncaparev = &get_server_loncaparev($machine_dom);
11712: my ($release,$timestamp) = split(/\-/,$loncaparev);
11713: my (%chksum,%revnum);
11714: if (ref($lines) eq 'ARRAY') {
11715: chomp(@{$lines});
1.1238 raeburn 11716: my $version = shift(@{$lines});
11717: if ($version eq $release) {
1.1210 raeburn 11718: foreach my $line (@{$lines}) {
1.1238 raeburn 11719: my ($file,$version,$shasum) = split(/,/,$line);
11720: $chksum{$file} = $shasum;
11721: $revnum{$file} = $version;
1.1210 raeburn 11722: }
11723: if (ref($hashref) eq 'HASH') {
11724: %{$hashref} = (
11725: sums => \%chksum,
11726: versions => \%revnum,
11727: );
11728: }
11729: }
11730: }
1.869 albertel 11731: return;
1.852 albertel 11732: }
1.1210 raeburn 11733:
11734: sub fetch_dns_checksums {
1.1238 raeburn 11735: my %checksums;
11736: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11737: my $loncaparev = &get_server_loncaparev($machine_dom);
11738: my ($release,$timestamp) = split(/\-/,$loncaparev);
11739: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 11740: \%checksums);
1.1210 raeburn 11741: return \%checksums;
11742: }
11743:
1.327 albertel 11744: # ------------------------------------------------------------ Read domain file
11745: {
1.852 albertel 11746: my $loaded;
1.846 albertel 11747: my %domain;
11748:
1.852 albertel 11749: sub parse_domain_tab {
11750: my ($lines) = @_;
11751: foreach my $line (@$lines) {
11752: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11753:
1.846 albertel 11754: chomp($line);
1.852 albertel 11755: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11756: my %this_domain;
11757: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11758: 'lang_def', 'city', 'longi', 'lati',
11759: 'primary') {
11760: $this_domain{$field} = shift(@elements);
11761: }
11762: $domain{$name} = \%this_domain;
1.852 albertel 11763: }
11764: }
1.864 albertel 11765:
11766: sub reset_domain_info {
11767: undef($loaded);
11768: undef(%domain);
11769: }
11770:
1.852 albertel 11771: sub load_domain_tab {
1.869 albertel 11772: my ($ignore_cache) = @_;
11773: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11774: my $fh;
11775: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11776: my @lines = <$fh>;
11777: &parse_domain_tab(\@lines);
1.448 albertel 11778: }
1.852 albertel 11779: close($fh);
11780: $loaded = 1;
1.327 albertel 11781: }
1.846 albertel 11782:
11783: sub domain {
1.852 albertel 11784: &load_domain_tab() if (!$loaded);
11785:
1.846 albertel 11786: my ($name,$what) = @_;
11787: return if ( !exists($domain{$name}) );
11788:
11789: if (!$what) {
11790: return $domain{$name}{'description'};
11791: }
11792: return $domain{$name}{$what};
11793: }
1.974 raeburn 11794:
11795: sub domain_info {
11796: &load_domain_tab() if (!$loaded);
11797: return %domain;
11798: }
11799:
1.327 albertel 11800: }
11801:
11802:
1.1 albertel 11803: # ------------------------------------------------------------- Read hosts file
11804: {
1.838 albertel 11805: my %hostname;
1.844 albertel 11806: my %hostdom;
1.845 albertel 11807: my %libserv;
1.852 albertel 11808: my $loaded;
1.888 albertel 11809: my %name_to_host;
1.1074 raeburn 11810: my %internetdom;
1.1107 raeburn 11811: my %LC_dns_serv;
1.852 albertel 11812:
11813: sub parse_hosts_tab {
11814: my ($file) = @_;
11815: foreach my $configline (@$file) {
11816: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11817: chomp($configline);
11818: if ($configline =~ /^\^/) {
11819: if ($configline =~ /^\^([\w.\-]+)/) {
11820: $LC_dns_serv{$1} = 1;
11821: }
11822: next;
11823: }
1.1074 raeburn 11824: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11825: $name=~s/\s//g;
11826: if ($id && $domain && $role && $name) {
11827: $hostname{$id}=$name;
1.888 albertel 11828: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11829: $hostdom{$id}=$domain;
11830: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11831: if (defined($protocol)) {
11832: if ($protocol eq 'https') {
11833: $protocol{$id} = $protocol;
11834: } else {
11835: $protocol{$id} = 'http';
11836: }
1.968 raeburn 11837: } else {
1.969 raeburn 11838: $protocol{$id} = 'http';
1.968 raeburn 11839: }
1.1074 raeburn 11840: if (defined($intdom)) {
11841: $internetdom{$id} = $intdom;
11842: }
1.852 albertel 11843: }
11844: }
11845: }
1.864 albertel 11846:
11847: sub reset_hosts_info {
1.897 albertel 11848: &purge_remembered();
1.864 albertel 11849: &reset_domain_info();
11850: &reset_hosts_ip_info();
1.892 albertel 11851: undef(%name_to_host);
1.864 albertel 11852: undef(%hostname);
11853: undef(%hostdom);
11854: undef(%libserv);
11855: undef($loaded);
11856: }
1.1 albertel 11857:
1.852 albertel 11858: sub load_hosts_tab {
1.869 albertel 11859: my ($ignore_cache) = @_;
11860: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11861: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11862: my @config = <$config>;
11863: &parse_hosts_tab(\@config);
11864: close($config);
11865: $loaded=1;
1.1 albertel 11866: }
1.852 albertel 11867:
1.838 albertel 11868: sub hostname {
1.852 albertel 11869: &load_hosts_tab() if (!$loaded);
11870:
1.838 albertel 11871: my ($lonid) = @_;
11872: return $hostname{$lonid};
11873: }
1.845 albertel 11874:
1.838 albertel 11875: sub all_hostnames {
1.852 albertel 11876: &load_hosts_tab() if (!$loaded);
11877:
1.838 albertel 11878: return %hostname;
11879: }
1.845 albertel 11880:
1.888 albertel 11881: sub all_names {
11882: &load_hosts_tab() if (!$loaded);
11883:
11884: return %name_to_host;
11885: }
11886:
1.974 raeburn 11887: sub all_host_domain {
11888: &load_hosts_tab() if (!$loaded);
11889: return %hostdom;
11890: }
11891:
1.845 albertel 11892: sub is_library {
1.852 albertel 11893: &load_hosts_tab() if (!$loaded);
11894:
1.845 albertel 11895: return exists($libserv{$_[0]});
11896: }
11897:
11898: sub all_library {
1.852 albertel 11899: &load_hosts_tab() if (!$loaded);
11900:
1.845 albertel 11901: return %libserv;
11902: }
11903:
1.1062 droeschl 11904: sub unique_library {
11905: #2x reverse removes all hostnames that appear more than once
11906: my %unique = reverse &all_library();
11907: return reverse %unique;
11908: }
11909:
1.841 albertel 11910: sub get_servers {
1.852 albertel 11911: &load_hosts_tab() if (!$loaded);
11912:
1.841 albertel 11913: my ($domain,$type) = @_;
11914: my %possible_hosts = ($type eq 'library') ? %libserv
11915: : %hostname;
11916: my %result;
1.842 albertel 11917: if (ref($domain) eq 'ARRAY') {
11918: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11919: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11920: $result{$host} = $hostname;
11921: }
11922: }
11923: } else {
11924: while ( my ($host,$hostname) = each(%possible_hosts)) {
11925: if ($hostdom{$host} eq $domain) {
11926: $result{$host} = $hostname;
11927: }
1.841 albertel 11928: }
11929: }
11930: return %result;
11931: }
1.845 albertel 11932:
1.1062 droeschl 11933: sub get_unique_servers {
11934: my %unique = reverse &get_servers(@_);
11935: return reverse %unique;
11936: }
11937:
1.844 albertel 11938: sub host_domain {
1.852 albertel 11939: &load_hosts_tab() if (!$loaded);
11940:
1.844 albertel 11941: my ($lonid) = @_;
11942: return $hostdom{$lonid};
11943: }
11944:
1.841 albertel 11945: sub all_domains {
1.852 albertel 11946: &load_hosts_tab() if (!$loaded);
11947:
1.841 albertel 11948: my %seen;
11949: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11950: return @uniq;
11951: }
1.1074 raeburn 11952:
11953: sub internet_dom {
11954: &load_hosts_tab() if (!$loaded);
11955:
11956: my ($lonid) = @_;
11957: return $internetdom{$lonid};
11958: }
1.1107 raeburn 11959:
11960: sub is_LC_dns {
11961: &load_hosts_tab() if (!$loaded);
11962:
11963: my ($hostname) = @_;
11964: return exists($LC_dns_serv{$hostname});
11965: }
11966:
1.1 albertel 11967: }
11968:
1.847 albertel 11969: {
11970: my %iphost;
1.856 albertel 11971: my %name_to_ip;
11972: my %lonid_to_ip;
1.869 albertel 11973:
1.847 albertel 11974: sub get_hosts_from_ip {
11975: my ($ip) = @_;
11976: my %iphosts = &get_iphost();
11977: if (ref($iphosts{$ip})) {
11978: return @{$iphosts{$ip}};
11979: }
11980: return;
1.839 albertel 11981: }
1.864 albertel 11982:
11983: sub reset_hosts_ip_info {
11984: undef(%iphost);
11985: undef(%name_to_ip);
11986: undef(%lonid_to_ip);
11987: }
1.856 albertel 11988:
11989: sub get_host_ip {
11990: my ($lonid) = @_;
11991: if (exists($lonid_to_ip{$lonid})) {
11992: return $lonid_to_ip{$lonid};
11993: }
11994: my $name=&hostname($lonid);
11995: my $ip = gethostbyname($name);
11996: return if (!$ip || length($ip) ne 4);
11997: $ip=inet_ntoa($ip);
11998: $name_to_ip{$name} = $ip;
11999: $lonid_to_ip{$lonid} = $ip;
12000: return $ip;
12001: }
1.847 albertel 12002:
12003: sub get_iphost {
1.869 albertel 12004: my ($ignore_cache) = @_;
1.894 albertel 12005:
1.869 albertel 12006: if (!$ignore_cache) {
12007: if (%iphost) {
12008: return %iphost;
12009: }
12010: my ($ip_info,$cached)=
12011: &Apache::lonnet::is_cached_new('iphost','iphost');
12012: if ($cached) {
12013: %iphost = %{$ip_info->[0]};
12014: %name_to_ip = %{$ip_info->[1]};
12015: %lonid_to_ip = %{$ip_info->[2]};
12016: return %iphost;
12017: }
12018: }
1.894 albertel 12019:
12020: # get yesterday's info for fallback
12021: my %old_name_to_ip;
12022: my ($ip_info,$cached)=
12023: &Apache::lonnet::is_cached_new('iphost','iphost');
12024: if ($cached) {
12025: %old_name_to_ip = %{$ip_info->[1]};
12026: }
12027:
1.888 albertel 12028: my %name_to_host = &all_names();
12029: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12030: my $ip;
12031: if (!exists($name_to_ip{$name})) {
12032: $ip = gethostbyname($name);
12033: if (!$ip || length($ip) ne 4) {
1.894 albertel 12034: if (defined($old_name_to_ip{$name})) {
12035: $ip = $old_name_to_ip{$name};
12036: &logthis("Can't find $name defaulting to old $ip");
12037: } else {
12038: &logthis("Name $name no IP found");
12039: next;
12040: }
12041: } else {
12042: $ip=inet_ntoa($ip);
1.847 albertel 12043: }
12044: $name_to_ip{$name} = $ip;
12045: } else {
12046: $ip = $name_to_ip{$name};
1.653 albertel 12047: }
1.888 albertel 12048: foreach my $id (@{ $name_to_host{$name} }) {
12049: $lonid_to_ip{$id} = $ip;
12050: }
12051: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12052: }
1.1219 raeburn 12053: &do_cache_new('iphost','iphost',
12054: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12055: 48*60*60);
1.869 albertel 12056:
1.847 albertel 12057: return %iphost;
1.598 albertel 12058: }
12059:
1.992 raeburn 12060: #
12061: # Given a DNS returns the loncapa host name for that DNS
12062: #
12063: sub host_from_dns {
12064: my ($dns) = @_;
12065: my @hosts;
12066: my $ip;
12067:
1.993 raeburn 12068: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12069: $ip = $name_to_ip{$dns};
12070: }
12071: if (!$ip) {
12072: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12073: if (length($ip) == 4) {
12074: $ip = &IO::Socket::inet_ntoa($ip);
12075: }
12076: }
12077: if ($ip) {
12078: @hosts = get_hosts_from_ip($ip);
12079: return $hosts[0];
12080: }
12081: return undef;
1.986 foxr 12082: }
1.992 raeburn 12083:
1.1074 raeburn 12084: sub get_internet_names {
12085: my ($lonid) = @_;
12086: return if ($lonid eq '');
12087: my ($idnref,$cached)=
12088: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12089: if ($cached) {
12090: return $idnref;
12091: }
12092: my $ip = &get_host_ip($lonid);
12093: my @hosts = &get_hosts_from_ip($ip);
12094: my %iphost = &get_iphost();
12095: my (@idns,%seen);
12096: foreach my $id (@hosts) {
12097: my $dom = &host_domain($id);
12098: my $prim_id = &domain($dom,'primary');
12099: my $prim_ip = &get_host_ip($prim_id);
12100: next if ($seen{$prim_ip});
12101: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12102: foreach my $id (@{$iphost{$prim_ip}}) {
12103: my $intdom = &internet_dom($id);
12104: unless (grep(/^\Q$intdom\E$/,@idns)) {
12105: push(@idns,$intdom);
12106: }
12107: }
12108: }
12109: $seen{$prim_ip} = 1;
12110: }
1.1219 raeburn 12111: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12112: }
12113:
1.986 foxr 12114: }
12115:
1.1079 raeburn 12116: sub all_loncaparevs {
12117: 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);
12118: }
12119:
1.1227 raeburn 12120: # ---------------------------------------------------------- Read loncaparev table
12121: {
12122: sub load_loncaparevs {
12123: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12124: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12125: while (my $configline=<$config>) {
12126: chomp($configline);
12127: my ($hostid,$loncaparev)=split(/:/,$configline);
12128: $loncaparevs{$hostid}=$loncaparev;
12129: }
12130: close($config);
12131: }
12132: }
12133: }
12134: }
12135:
12136: # ---------------------------------------------------------- Read serverhostID table
12137: {
12138: sub load_serverhomeIDs {
12139: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12140: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12141: while (my $configline=<$config>) {
12142: chomp($configline);
12143: my ($name,$id)=split(/:/,$configline);
12144: $serverhomeIDs{$name}=$id;
12145: }
12146: close($config);
12147: }
12148: }
12149: }
12150: }
12151:
12152:
1.862 albertel 12153: BEGIN {
12154:
12155: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12156: unless ($readit) {
12157: {
12158: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12159: %perlvar = (%perlvar,%{$configvars});
12160: }
12161:
12162:
1.1 albertel 12163: # ------------------------------------------------------ Read spare server file
12164: {
1.448 albertel 12165: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12166:
12167: while (my $configline=<$config>) {
12168: chomp($configline);
1.284 matthew 12169: if ($configline) {
1.784 albertel 12170: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12171: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12172: push(@{ $spareid{$type} }, $host);
1.1 albertel 12173: }
12174: }
1.448 albertel 12175: close($config);
1.1 albertel 12176: }
1.11 www 12177: # ------------------------------------------------------------ Read permissions
12178: {
1.448 albertel 12179: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12180:
12181: while (my $configline=<$config>) {
1.448 albertel 12182: chomp($configline);
12183: if ($configline) {
12184: my ($role,$perm)=split(/ /,$configline);
12185: if ($perm ne '') { $pr{$role}=$perm; }
12186: }
1.11 www 12187: }
1.448 albertel 12188: close($config);
1.11 www 12189: }
12190:
12191: # -------------------------------------------- Read plain texts for permissions
12192: {
1.448 albertel 12193: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12194:
12195: while (my $configline=<$config>) {
1.448 albertel 12196: chomp($configline);
12197: if ($configline) {
1.742 raeburn 12198: my ($short,@plain)=split(/:/,$configline);
12199: %{$prp{$short}} = ();
12200: if (@plain > 0) {
12201: $prp{$short}{'std'} = $plain[0];
12202: for (my $i=1; $i<@plain; $i++) {
12203: $prp{$short}{'alt'.$i} = $plain[$i];
12204: }
12205: }
1.448 albertel 12206: }
1.135 www 12207: }
1.448 albertel 12208: close($config);
1.135 www 12209: }
12210:
12211: # ---------------------------------------------------------- Read package table
12212: {
1.448 albertel 12213: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12214:
12215: while (my $configline=<$config>) {
1.483 albertel 12216: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12217: chomp($configline);
12218: my ($short,$plain)=split(/:/,$configline);
12219: my ($pack,$name)=split(/\&/,$short);
12220: if ($plain ne '') {
12221: $packagetab{$pack.'&'.$name.'&name'}=$name;
12222: $packagetab{$short}=$plain;
12223: }
1.11 www 12224: }
1.448 albertel 12225: close($config);
1.329 matthew 12226: }
12227:
1.1073 raeburn 12228: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12229:
12230: &load_loncaparevs();
1.1073 raeburn 12231:
1.1074 raeburn 12232: # ---------------------------------------------------------- Read serverhostID table
12233:
1.1227 raeburn 12234: &load_serverhomeIDs();
12235:
12236: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12237: {
12238: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12239: if (-e $file) {
12240: my $parser = HTML::LCParser->new($file);
12241: while (my $token = $parser->get_token()) {
12242: if ($token->[0] eq 'S') {
12243: my $item = $token->[1];
12244: my $name = $token->[2]{'name'};
12245: my $value = $token->[2]{'value'};
12246: if ($item ne '' && $name ne '' && $value ne '') {
12247: my $release = $parser->get_text();
12248: $release =~ s/(^\s*|\s*$ )//gx;
12249: $needsrelease{$item.':'.$name.':'.$value} = $release;
12250: }
12251: }
12252: }
12253: }
1.1073 raeburn 12254: }
12255:
1.1138 raeburn 12256: # ---------------------------------------------------------- Read managers table
12257: {
12258: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12259: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12260: while (my $configline=<$config>) {
12261: chomp($configline);
12262: next if ($configline =~ /^\#/);
12263: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12264: $managerstab{$configline} = 1;
12265: }
12266: }
12267: close($config);
12268: }
12269: }
12270: }
12271:
1.329 matthew 12272: # ------------- set up temporary directory
12273: {
1.1117 foxr 12274: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12275:
1.11 www 12276: }
12277:
1.794 albertel 12278: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12279: 'compress_threshold'=> 20_000,
12280: });
1.185 www 12281:
1.281 www 12282: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12283: $dumpcount=0;
1.958 www 12284: $locknum=0;
1.22 www 12285:
1.163 harris41 12286: &logtouch();
1.672 albertel 12287: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12288: $readit=1;
1.564 albertel 12289: {
12290: use integer;
12291: my $test=(2**32)+1;
1.568 albertel 12292: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12293: &logthis(" Detected 64bit platform ($_64bit)");
12294: }
1.1214 raeburn 12295:
12296: {
12297: eval {
12298: ($apache) =
12299: (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12300: };
12301: if ($@) {
12302: $apache = 1.3;
1.1213 raeburn 12303: }
12304: }
1.1214 raeburn 12305:
1.195 www 12306: }
1.1 albertel 12307: }
1.179 www 12308:
1.1 albertel 12309: 1;
1.191 harris41 12310: __END__
12311:
1.243 albertel 12312: =pod
12313:
1.191 harris41 12314: =head1 NAME
12315:
1.243 albertel 12316: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12317:
12318: =head1 SYNOPSIS
12319:
1.243 albertel 12320: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12321:
12322: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12323:
1.243 albertel 12324: Common parameters:
12325:
12326: =over 4
12327:
12328: =item *
12329:
12330: $uname : an internal username (if $cname expecting a course Id specifically)
12331:
12332: =item *
12333:
12334: $udom : a domain (if $cdom expecting a course's domain specifically)
12335:
12336: =item *
12337:
12338: $symb : a resource instance identifier
12339:
12340: =item *
12341:
12342: $namespace : the name of a .db file that contains the data needed or
12343: being set.
12344:
12345: =back
12346:
1.394 bowersj2 12347: =head1 OVERVIEW
1.191 harris41 12348:
1.394 bowersj2 12349: lonnet provides subroutines which interact with the
12350: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12351: about classes, users, and resources.
1.243 albertel 12352:
12353: For many of these objects you can also use this to store data about
12354: them or modify them in various ways.
1.191 harris41 12355:
1.394 bowersj2 12356: =head2 Symbs
1.191 harris41 12357:
1.394 bowersj2 12358: To identify a specific instance of a resource, LON-CAPA uses symbols
12359: or "symbs"X<symb>. These identifiers are built from the URL of the
12360: map, the resource number of the resource in the map, and the URL of
12361: the resource itself. The latter is somewhat redundant, but might help
12362: if maps change.
12363:
12364: An example is
12365:
12366: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12367:
12368: The respective map entry is
12369:
12370: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12371: title="Problem 2">
12372: </resource>
12373:
12374: Symbs are used by the random number generator, as well as to store and
12375: restore data specific to a certain instance of for example a problem.
12376:
12377: =head2 Storing And Retrieving Data
12378:
12379: X<store()>X<cstore()>X<restore()>Three of the most important functions
12380: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12381: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12382: is is the non-critical message twin of cstore. These functions are for
12383: handlers to store a perl hash to a user's permanent data space in an
12384: easy manner, and to retrieve it again on another call. It is expected
12385: that a handler would use this once at the beginning to retrieve data,
12386: and then again once at the end to send only the new data back.
12387:
12388: The data is stored in the user's data directory on the user's
12389: homeserver under the ID of the course.
12390:
12391: The hash that is returned by restore will have all of the previous
12392: value for all of the elements of the hash.
12393:
12394: Example:
12395:
12396: #creating a hash
12397: my %hash;
12398: $hash{'foo'}='bar';
12399:
12400: #storing it
12401: &Apache::lonnet::cstore(\%hash);
12402:
12403: #changing a value
12404: $hash{'foo'}='notbar';
12405:
12406: #adding a new value
12407: $hash{'bar'}='foo';
12408: &Apache::lonnet::cstore(\%hash);
12409:
12410: #retrieving the hash
12411: my %history=&Apache::lonnet::restore();
12412:
12413: #print the hash
12414: foreach my $key (sort(keys(%history))) {
12415: print("\%history{$key} = $history{$key}");
12416: }
12417:
12418: Will print out:
1.191 harris41 12419:
1.394 bowersj2 12420: %history{1:foo} = bar
12421: %history{1:keys} = foo:timestamp
12422: %history{1:timestamp} = 990455579
12423: %history{2:bar} = foo
12424: %history{2:foo} = notbar
12425: %history{2:keys} = foo:bar:timestamp
12426: %history{2:timestamp} = 990455580
12427: %history{bar} = foo
12428: %history{foo} = notbar
12429: %history{timestamp} = 990455580
12430: %history{version} = 2
12431:
12432: Note that the special hash entries C<keys>, C<version> and
12433: C<timestamp> were added to the hash. C<version> will be equal to the
12434: total number of versions of the data that have been stored. The
12435: C<timestamp> attribute will be the UNIX time the hash was
12436: stored. C<keys> is available in every historical section to list which
12437: keys were added or changed at a specific historical revision of a
12438: hash.
12439:
12440: B<Warning>: do not store the hash that restore returns directly. This
12441: will cause a mess since it will restore the historical keys as if the
12442: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12443:
1.394 bowersj2 12444: Calling convention:
1.191 harris41 12445:
1.1225 raeburn 12446: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12447: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12448:
1.394 bowersj2 12449: For more detailed information, see lonnet specific documentation.
1.191 harris41 12450:
1.394 bowersj2 12451: =head1 RETURN MESSAGES
1.191 harris41 12452:
1.394 bowersj2 12453: =over 4
1.191 harris41 12454:
1.394 bowersj2 12455: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12456:
1.394 bowersj2 12457: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12458: when the connection is brought back up
1.191 harris41 12459:
1.394 bowersj2 12460: =item * B<con_failed>: unable to contact remote host and unable to save message
12461: for later delivery
1.191 harris41 12462:
1.967 bisitz 12463: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12464:
1.394 bowersj2 12465: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12466: that was requested
1.191 harris41 12467:
1.243 albertel 12468: =back
1.191 harris41 12469:
1.243 albertel 12470: =head1 PUBLIC SUBROUTINES
1.191 harris41 12471:
1.243 albertel 12472: =head2 Session Environment Functions
1.191 harris41 12473:
1.243 albertel 12474: =over 4
1.191 harris41 12475:
1.394 bowersj2 12476: =item *
12477: X<appenv()>
1.949 raeburn 12478: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12479: the user envirnoment file, and will be restored for each access this
1.620 albertel 12480: user makes during this session, also modifies the %env for the current
1.949 raeburn 12481: process. Optional rolesarrayref - if defined contains a reference to an array
12482: of roles which are exempt from the restriction on modifying user.role entries
12483: in the user's environment.db and in %env.
1.191 harris41 12484:
12485: =item *
1.394 bowersj2 12486: X<delenv()>
1.987 raeburn 12487: B<delenv($delthis,$regexp)>: removes all items from the session
12488: environment file that begin with $delthis. If the
12489: optional second arg - $regexp - is true, $delthis is treated as a
12490: regular expression, otherwise \Q$delthis\E is used.
12491: The values are also deleted from the current processes %env.
1.191 harris41 12492:
1.795 albertel 12493: =item * get_env_multiple($name)
12494:
12495: gets $name from the %env hash, it seemlessly handles the cases where multiple
12496: values may be defined and end up as an array ref.
12497:
12498: returns an array of values
12499:
1.243 albertel 12500: =back
12501:
12502: =head2 User Information
1.191 harris41 12503:
1.243 albertel 12504: =over 4
1.191 harris41 12505:
12506: =item *
1.394 bowersj2 12507: X<queryauthenticate()>
12508: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12509: authentication scheme
12510:
12511: =item *
1.394 bowersj2 12512: X<authenticate()>
1.1073 raeburn 12513: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12514: authenticate user from domain's lib servers (first use the current
12515: one). C<$upass> should be the users password.
1.1073 raeburn 12516: $checkdefauth is optional (value is 1 if a check should be made to
12517: authenticate user using default authentication method, and allow
12518: account creation if username does not have account in the domain).
12519: $clientcancheckhost is optional (value is 1 if checking whether the
12520: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12521:
12522: =item *
1.394 bowersj2 12523: X<homeserver()>
12524: B<homeserver($uname,$udom)>: find the server which has
12525: the user's directory and files (there must be only one), this caches
12526: the answer, and also caches if there is a borken connection.
1.191 harris41 12527:
12528: =item *
1.394 bowersj2 12529: X<idget()>
12530: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12531: (IDs are a unique resource in a domain, there must be only 1 ID per
12532: username, and only 1 username per ID in a specific domain) (returns
12533: hash: id=>name,id=>name)
1.191 harris41 12534:
12535: =item *
1.394 bowersj2 12536: X<idrget()>
12537: B<idrget($udom,@unames)>: find the IDs behind a list of
12538: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12539:
12540: =item *
1.394 bowersj2 12541: X<idput()>
12542: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12543:
12544: =item *
1.394 bowersj2 12545: X<rolesinit()>
1.1169 droeschl 12546: B<rolesinit($udom,$username)>: get user privileges.
12547: returns user role, first access and timer interval hashes
1.243 albertel 12548:
12549: =item *
1.1171 droeschl 12550: X<privileged()>
12551: B<privileged($username,$domain)>: returns a true if user has a
12552: privileged and active role (i.e. su or dc), false otherwise.
12553:
12554: =item *
1.551 albertel 12555: X<getsection()>
12556: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12557: course $cname, return section name/number or '' for "not in course"
12558: and '-1' for "no section"
12559:
12560: =item *
1.394 bowersj2 12561: X<userenvironment()>
12562: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12563: passed in @what from the requested user's environment, returns a hash
12564:
1.858 raeburn 12565: =item *
12566: X<userlog_query()>
1.859 albertel 12567: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12568: activity.log file. %filters defines filters applied when parsing the
12569: log file. These can be start or end timestamps, or the type of action
12570: - log to look for Login or Logout events, check for Checkin or
12571: Checkout, role for role selection. The response is in the form
12572: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12573: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12574:
1.243 albertel 12575: =back
12576:
12577: =head2 User Roles
12578:
12579: =over 4
12580:
12581: =item *
12582:
1.810 raeburn 12583: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12584: F: full access
12585: U,I,K: authentication modes (cxx only)
12586: '': forbidden
12587: 1: user needs to choose course
12588: 2: browse allowed
1.766 albertel 12589: A: passphrase authentication needed
1.243 albertel 12590:
12591: =item *
12592:
1.1192 raeburn 12593: constructaccess($url,$setpriv) : check for access to construction space URL
12594:
12595: See if the owner domain and name in the URL match those in the
12596: expected environment. If so, return three element list
12597: ($ownername,$ownerdomain,$ownerhome).
12598:
12599: Otherwise return the null string.
12600:
12601: If second argument 'setpriv' is true, it assigns the privileges,
12602: and returns the same three element list, unless the owner has
12603: blocked "ad hoc" Domain Coordinator access to the Author Space,
12604: in which case the null string is returned.
12605:
12606: =item *
12607:
1.243 albertel 12608: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12609: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12610: and course level
12611:
12612: =item *
12613:
1.988 raeburn 12614: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12615: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12616: $type is Course (default) or Community.
1.988 raeburn 12617: If $forcedefault evaluates to true, text returned will be default
12618: text for $type. Otherwise, if this is a course, the text returned
12619: will be a custom name for the role (if defined in the course's
12620: environment). If no custom name is defined the default is returned.
12621:
1.832 raeburn 12622: =item *
12623:
1.1219 raeburn 12624: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12625: All arguments are optional. Returns a hash of a roles, either for
12626: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12627: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12628: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12629: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12630: For each key, value is set to colon-separated start and end times for
12631: the role. If no username and domain are specified, will default to
1.934 raeburn 12632: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12633: of role statuses (active, future or previous), roles
12634: (e.g., cc,in, st etc.) and domains of the roles which can be used
12635: to restrict the list of roles reported. If no array ref is
12636: provided for types, will default to return only active roles.
1.834 albertel 12637:
1.1195 raeburn 12638: =item *
12639:
12640: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12641: user: $uname:$udom has a role in the course: $cdom_$cnum.
12642:
12643: Additional optional arguments are: $type (if role checking is to be restricted
12644: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 12645: available roles) or future (roles available in the future), and
12646: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 12647: have active Domain Coordinator role in course's domain or in additional
12648: domains (specified in 'Domains to check for privileged users' in course
12649: environment -- set via: Course Settings -> Classlists and staff listing).
12650:
12651: =item *
12652:
12653: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12654: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12655: $possdomains and $possroles are optional array refs -- to domains to check and
12656: roles to check. If $possdomains is not specified, a dump will be done of the
12657: users' roles.db to check for a dc or su role in any domain. This can be
12658: time consuming if &privileged is called repeatedly (e.g., when displaying a
12659: classlist), so in such cases, supplying a $possdomains array is preferred, as
12660: this then allows &privileged_by_domain() to be used, which caches the identity
12661: of privileged users, eliminating the need for repeated calls to &dump().
12662:
12663: =item *
12664:
12665: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12666: where the outer hash keys are domains specified in the $possdomains array ref,
12667: next inner hash keys are privileged roles specified in the $roles array ref,
12668: and the innermost hash contains key = value pairs for username:domain = end:start
12669: for active or future "privileged" users with that role in that domain. To avoid
12670: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12671: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 12672:
1.243 albertel 12673: =back
12674:
12675: =head2 User Modification
12676:
12677: =over 4
12678:
12679: =item *
12680:
1.957 raeburn 12681: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12682: user for the level given by URL. Optional start and end dates (leave empty
12683: string or zero for "no date")
1.191 harris41 12684:
12685: =item *
12686:
1.243 albertel 12687: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12688: change a users, password, possible return values are: ok,
12689: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12690: refused
1.191 harris41 12691:
12692: =item *
12693:
1.243 albertel 12694: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12695:
12696: =item *
12697:
1.1058 raeburn 12698: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12699: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12700:
12701: will update user information (firstname,middlename,lastname,generation,
12702: permanentemail), and if forceid is true, student/employee ID also.
12703: A user's institutional affiliation(s) can also be updated.
12704: User information fields will not be overwritten with empty entries
12705: unless the field is included in the $candelete array reference.
12706: This array is included when a single user is modified via "Manage Users",
12707: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12708:
12709: =item *
12710:
1.286 matthew 12711: modifystudent
12712:
1.957 raeburn 12713: modify a student's enrollment and identification information.
1.1235 raeburn 12714: The course id is resolved based on the current user's environment.
12715: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12716: associated with a course.
12717:
1.297 matthew 12718: This call is essentially a wrapper for lonnet::modifyuser and
12719: lonnet::modify_student_enrollment
1.286 matthew 12720:
12721: Inputs:
12722:
12723: =over 4
12724:
1.957 raeburn 12725: =item B<$udom> Student's loncapa domain
1.286 matthew 12726:
1.957 raeburn 12727: =item B<$uname> Student's loncapa login name
1.286 matthew 12728:
1.964 bisitz 12729: =item B<$uid> Student/Employee ID
1.286 matthew 12730:
1.957 raeburn 12731: =item B<$umode> Student's authentication mode
1.286 matthew 12732:
1.957 raeburn 12733: =item B<$upass> Student's password
1.286 matthew 12734:
1.957 raeburn 12735: =item B<$first> Student's first name
1.286 matthew 12736:
1.957 raeburn 12737: =item B<$middle> Student's middle name
1.286 matthew 12738:
1.957 raeburn 12739: =item B<$last> Student's last name
1.286 matthew 12740:
1.957 raeburn 12741: =item B<$gene> Student's generation
1.286 matthew 12742:
1.957 raeburn 12743: =item B<$usec> Student's section in course
1.286 matthew 12744:
12745: =item B<$end> Unix time of the roles expiration
12746:
12747: =item B<$start> Unix time of the roles start date
12748:
12749: =item B<$forceid> If defined, allow $uid to be changed
12750:
12751: =item B<$desiredhome> server to use as home server for student
12752:
1.957 raeburn 12753: =item B<$email> Student's permanent e-mail address
12754:
12755: =item B<$type> Type of enrollment (auto or manual)
12756:
1.963 raeburn 12757: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12758:
12759: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12760:
1.963 raeburn 12761: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12762:
1.963 raeburn 12763: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12764:
1.1216 raeburn 12765: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12766:
12767: =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 12768:
1.286 matthew 12769: =back
1.297 matthew 12770:
12771: =item *
12772:
12773: modify_student_enrollment
12774:
1.1235 raeburn 12775: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12776: 'role.request.course' must be defined for this function to proceed.
12777:
12778: Inputs:
12779:
12780: =over 4
12781:
1.1235 raeburn 12782: =item $udom, student's domain
1.297 matthew 12783:
1.1235 raeburn 12784: =item $uname, student's name
1.297 matthew 12785:
1.1235 raeburn 12786: =item $uid, student's user id
1.297 matthew 12787:
1.1235 raeburn 12788: =item $first, student's first name
1.297 matthew 12789:
12790: =item $middle
12791:
12792: =item $last
12793:
12794: =item $gene
12795:
12796: =item $usec
12797:
12798: =item $end
12799:
12800: =item $start
12801:
1.957 raeburn 12802: =item $type
12803:
12804: =item $locktype
12805:
12806: =item $cid
12807:
12808: =item $selfenroll
12809:
12810: =item $context
12811:
1.1216 raeburn 12812: =item $credits, number of credits student will earn from this class
12813:
1.297 matthew 12814: =back
12815:
1.191 harris41 12816:
12817: =item *
12818:
1.243 albertel 12819: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12820: custom role; give a custom role to a user for the level given by URL. Specify
12821: name and domain of role author, and role name
1.191 harris41 12822:
12823: =item *
12824:
1.243 albertel 12825: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12826:
12827: =item *
12828:
1.243 albertel 12829: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12830:
12831: =back
12832:
12833: =head2 Course Infomation
12834:
12835: =over 4
1.191 harris41 12836:
12837: =item *
12838:
1.1118 foxr 12839: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12840: specified course id, including all environment settings for the
12841: course, the description of the course will be in the hash under the
12842: key 'description'
1.191 harris41 12843:
1.1118 foxr 12844: $options is an optional parameter that if supplied is a hash reference that controls
12845: what how this function works. It has the following key/values:
12846:
12847: =over 4
12848:
12849: =item freshen_cache
12850:
12851: If defined, and the environment cache for the course is valid, it is
12852: returned in the returned hash.
12853:
12854: =item one_time
12855:
12856: If defined, the last cache time is set to _now_
12857:
12858: =item user
12859:
12860: If defined, the supplied username is used instead of the current user.
12861:
12862:
12863: =back
12864:
1.191 harris41 12865: =item *
12866:
1.624 albertel 12867: resdata($name,$domain,$type,@which) : request for current parameter
12868: setting for a specific $type, where $type is either 'course' or 'user',
12869: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 12870: answers for 10 minutes.
1.243 albertel 12871:
1.877 foxr 12872: =item *
12873:
12874: get_courseresdata($courseid, $domain) : dump the entire course resource
12875: data base, returning a hash that is keyed by the resource name and has
12876: values that are the resource value. I believe that the timestamps and
12877: versions are also returned.
12878:
1.1236 raeburn 12879: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12880: supplemental content area. This routine caches the number of files for
12881: 10 minutes.
12882:
1.243 albertel 12883: =back
12884:
12885: =head2 Course Modification
12886:
12887: =over 4
1.191 harris41 12888:
12889: =item *
12890:
1.243 albertel 12891: writecoursepref($courseid,%prefs) : write preferences (environment
12892: database) for a course
1.191 harris41 12893:
12894: =item *
12895:
1.1011 raeburn 12896: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12897:
12898: =item *
12899:
1.1038 raeburn 12900: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12901:
1.1167 droeschl 12902: =item *
12903:
12904: is_course($courseid), is_course($cdom, $cnum)
12905:
12906: Accepts either a combined $courseid (in the form of domain_courseid) or the
12907: two component version $cdom, $cnum. It checks if the specified course exists.
12908:
12909: Returns:
12910: undef if the course doesn't exist, otherwise
12911: in scalar context the combined courseid.
12912: in list context the two components of the course identifier, domain and
12913: courseid.
12914:
1.243 albertel 12915: =back
12916:
12917: =head2 Resource Subroutines
12918:
12919: =over 4
1.191 harris41 12920:
12921: =item *
12922:
1.243 albertel 12923: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12924:
12925: =item *
12926:
1.243 albertel 12927: repcopy($filename) : subscribes to the requested file, and attempts to
12928: replicate from the owning library server, Might return
1.607 raeburn 12929: 'unavailable', 'not_found', 'forbidden', 'ok', or
12930: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12931: resource. Expects the local filesystem pathname
12932: (/home/httpd/html/res/....)
12933:
12934: =back
12935:
12936: =head2 Resource Information
12937:
12938: =over 4
1.191 harris41 12939:
12940: =item *
12941:
1.1228 raeburn 12942: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
12943: and returns the value of a variety of different possible values,
12944: $varname should be a request string, and the other parameters can be
12945: used to specify who and what one is asking about. Ordinarily, $cid
12946: does not need to be specified, as it is retrived from
12947: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12948: within lonuserstate::loadmap() when initializing a course, before
12949: $env{'request.course.id'} has been set, so it needs to be provided
12950: in that one case.
1.243 albertel 12951:
12952: Possible values for $varname are environment.lastname (or other item
12953: from the envirnment hash), user.name (or someother aspect about the
12954: user), resource.0.maxtries (or some other part and parameter of a
12955: resource)
1.204 albertel 12956:
12957: =item *
12958:
1.243 albertel 12959: directcondval($number) : get current value of a condition; reads from a state
12960: string
1.204 albertel 12961:
12962: =item *
12963:
1.243 albertel 12964: condval($condidx) : value of condition index based on state
1.204 albertel 12965:
12966: =item *
12967:
1.243 albertel 12968: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12969: resource's metadata, $what should be either a specific key, or either
12970: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12971: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12972:
12973: this function automatically caches all requests
1.191 harris41 12974:
12975: =item *
12976:
1.243 albertel 12977: metadata_query($query,$custom,$customshow) : make a metadata query against the
12978: network of library servers; returns file handle of where SQL and regex results
12979: will be stored for query
1.191 harris41 12980:
12981: =item *
12982:
1.243 albertel 12983: symbread($filename) : return symbolic list entry (filename argument optional);
12984: returns the data handle
1.191 harris41 12985:
12986: =item *
12987:
1.1190 raeburn 12988: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12989: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 12990: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 12991: on failure, user must be in a course, as it assumes the existence of
12992: the course initial hash, and uses $env('request.course.id'}. The third
12993: arg is an optional reference to a scalar. If this arg is passed in the
12994: call to symbverify, it will be set to 1 if the symb has been set to be
12995: encrypted; otherwise it will be null.
1.191 harris41 12996:
12997: =item *
12998:
1.243 albertel 12999: symbclean($symb) : removes versions numbers from a symb, returns the
13000: cleaned symb
1.191 harris41 13001:
13002: =item *
13003:
1.243 albertel 13004: is_on_map($uri) : checks if the $uri is somewhere on the current
13005: course map, user must be in a course for it to work.
1.191 harris41 13006:
13007: =item *
13008:
1.243 albertel 13009: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13010:
13011: =item *
13012:
1.243 albertel 13013: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13014: a random seed, all arguments are optional, if they aren't sent it uses the
13015: environment to derive them. Note: if symb isn't sent and it can't get one
13016: from &symbread it will use the current time as its return value
1.191 harris41 13017:
13018: =item *
13019:
1.243 albertel 13020: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13021: unfakeable, receipt
1.191 harris41 13022:
13023: =item *
13024:
1.620 albertel 13025: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13026:
13027: =item *
13028:
1.243 albertel 13029: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13030:
13031: =item *
13032:
1.243 albertel 13033: 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 13034:
13035: =item *
13036:
1.243 albertel 13037: 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 13038:
13039: =item *
13040:
1.243 albertel 13041: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13042:
13043: =item *
13044:
1.243 albertel 13045: devalidate($symb) : devalidate temporary spreadsheet calculations,
13046: forcing spreadsheet to reevaluate the resource scores next time.
13047:
1.1195 raeburn 13048: =item *
13049:
1.1196 raeburn 13050: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13051: when viewing in course context.
1.1195 raeburn 13052:
1.1196 raeburn 13053: input: six args -- filename (decluttered), course number, course domain,
13054: url, symb (if registered) and group (if this is a
13055: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13056:
1.1196 raeburn 13057: output: array of five scalars --
1.1195 raeburn 13058: $cfile -- url for file editing if editable on current server
13059: $home -- homeserver of resource (i.e., for author if published,
13060: or course if uploaded.).
13061: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13062: $forceedit -- 1 if icon/link should be to go to edit mode
13063: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13064:
13065: =item *
13066:
13067: is_course_upload($file,$cnum,$cdom)
13068:
13069: Used in course context to determine if current file was uploaded to
13070: the course (i.e., would be found in /userfiles/docs on the course's
13071: homeserver.
13072:
13073: input: 3 args -- filename (decluttered), course number and course domain.
13074: output: boolean -- 1 if file was uploaded.
13075:
1.243 albertel 13076: =back
13077:
13078: =head2 Storing/Retreiving Data
13079:
13080: =over 4
1.191 harris41 13081:
13082: =item *
13083:
1.243 albertel 13084: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13085: for this url; hashref needs to be given and should be a \%hashname; the
13086: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13087: be derived from the env
1.191 harris41 13088:
13089: =item *
13090:
1.243 albertel 13091: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13092: uses critical subroutine
1.191 harris41 13093:
13094: =item *
13095:
1.243 albertel 13096: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13097: all args are optional
1.191 harris41 13098:
13099: =item *
13100:
1.717 albertel 13101: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13102: dumps the complete (or key matching regexp) namespace into a hash
13103: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13104: normally &store()ed into
13105:
13106: $range should be either an integer '100' (give me the first 100
13107: matching records)
13108: or be two integers sperated by a - with no spaces
13109: '30-50' (give me the 30th through the 50th matching
13110: records)
13111:
13112:
13113: =item *
13114:
13115: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13116: replaces a &store() version of data with a replacement set of data
13117: for a particular resource in a namespace passed in the $storehash hash
13118: reference
13119:
13120: =item *
13121:
1.243 albertel 13122: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13123: works very similar to store/cstore, but all data is stored in a
13124: temporary location and can be reset using tmpreset, $storehash should
13125: be a hash reference, returns nothing on success
1.191 harris41 13126:
13127: =item *
13128:
1.243 albertel 13129: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13130: similar to restore, but all data is stored in a temporary location and
13131: can be reset using tmpreset. Returns a hash of values on success,
13132: error string otherwise.
1.191 harris41 13133:
13134: =item *
13135:
1.243 albertel 13136: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13137: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13138:
13139: =item *
13140:
1.243 albertel 13141: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13142: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13143:
13144: =item *
13145:
1.243 albertel 13146: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13147: namesp ($udom and $uname are optional)
1.191 harris41 13148:
13149: =item *
13150:
1.702 albertel 13151: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13152: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13153: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13154:
1.702 albertel 13155: $range should be either an integer '100' (give me the first 100
13156: matching records)
13157: or be two integers sperated by a - with no spaces
13158: '30-50' (give me the 30th through the 50th matching
13159: records)
1.449 matthew 13160: =item *
13161:
13162: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13163: $store can be a scalar, an array reference, or if the amount to be
13164: incremented is > 1, a hash reference.
13165:
13166: ($udom and $uname are optional)
1.191 harris41 13167:
13168: =item *
13169:
1.243 albertel 13170: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13171: ($udom and $uname are optional)
1.191 harris41 13172:
13173: =item *
13174:
1.243 albertel 13175: cput($namespace,$storehash,$udom,$uname) : critical put
13176: ($udom and $uname are optional)
1.191 harris41 13177:
13178: =item *
13179:
1.748 albertel 13180: newput($namespace,$storehash,$udom,$uname) :
13181:
13182: Attempts to store the items in the $storehash, but only if they don't
13183: currently exist, if this succeeds you can be certain that you have
13184: successfully created a new key value pair in the $namespace db.
13185:
13186:
13187: Args:
13188: $namespace: name of database to store values to
13189: $storehash: hashref to store to the db
13190: $udom: (optional) domain of user containing the db
13191: $uname: (optional) name of user caontaining the db
13192:
13193: Returns:
13194: 'ok' -> succeeded in storing all keys of $storehash
13195: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13196: least <key> already existed in the db (other
13197: requested keys may also already exist)
1.967 bisitz 13198: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13199: 'con_lost' -> unable to contact request server
13200: 'refused' -> action was not allowed by remote machine
13201:
13202:
13203: =item *
13204:
1.243 albertel 13205: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13206: reference filled in from namesp (encrypts the return communication)
13207: ($udom and $uname are optional)
1.191 harris41 13208:
13209: =item *
13210:
1.243 albertel 13211: log($udom,$name,$home,$message) : write to permanent log for user; use
13212: critical subroutine
13213:
1.806 raeburn 13214: =item *
13215:
1.860 raeburn 13216: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13217: array reference filled in from namespace found in domain level on either
13218: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13219:
13220: =item *
13221:
1.860 raeburn 13222: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13223: domain level either on specified domain server ($uhome) or primary domain
13224: server ($udom and $uhome are optional)
1.806 raeburn 13225:
1.943 raeburn 13226: =item *
13227:
1.1240 raeburn 13228: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13229: for: authentication, language, quotas, timezone, date locale, and portal URL in
13230: the target domain.
13231:
13232: May also include additional key => value pairs for the following groups:
13233:
13234: =over
13235:
13236: =item
13237: disk quotas (MB allocated by default to portfolios and authoring spaces).
13238:
13239: =over
13240:
13241: =item defaultquota, authorquota
13242:
13243: =back
13244:
13245: =item
13246: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13247: portfolio for users).
13248:
13249: =over
13250:
13251: =item
13252: aboutme, blog, webdav, portfolio
13253:
13254: =back
13255:
13256: =item
13257: requestcourses: ability to request courses, and how requests are processed.
13258:
13259: =over
13260:
13261: =item
13262: official, unofficial, community
13263:
13264: =back
13265:
13266: =item
13267: inststatus: types of institutional affiliation, and order in which they are displayed.
13268:
13269: =over
13270:
13271: =item
13272: inststatustypes, inststatusorder
13273:
13274: =back
13275:
13276: =item
13277: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13278: for course's uploaded content.
13279:
13280: =over
13281:
13282: =item
13283: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
13284:
13285: =back
13286:
13287: =item
13288: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13289: on your servers.
13290:
13291: =over
13292:
13293: =item
13294: remotesessions, hostedsessions
13295:
13296: =back
13297:
13298: =back
13299:
13300: In cases where a domain coordinator has never used the "Set Domain Configuration"
13301: utility to create a configuration.db file on a domain's primary library server
13302: only the following domain defaults: auth_def, auth_arg_def, lang_def
13303: -- corresponding values are authentication type (internal, krb4, krb5,
13304: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13305: will be available. Values are retrieved from cache (if current), unless the
13306: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13307: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13308:
13309: Typical usage:
1.943 raeburn 13310:
1.1240 raeburn 13311: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13312:
1.243 albertel 13313: =back
13314:
13315: =head2 Network Status Functions
13316:
13317: =over 4
1.191 harris41 13318:
13319: =item *
13320:
1.1137 raeburn 13321: dirlist() : return directory list based on URI (first arg).
13322:
13323: Inputs: 1 required, 5 optional.
13324:
13325: =over
13326:
13327: =item
13328: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13329:
13330: =item
13331: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13332:
13333: =item
13334: $username - username of user/course to be listed. Extracted from $uri if absent.
13335:
13336: =item
13337: $getpropath - boolean: 1 if prepend path using &propath().
13338:
13339: =item
13340: $getuserdir - boolean: 1 if prepend path for "userfiles".
13341:
13342: =item
13343: $alternateRoot - path to prepend in place of path from $uri.
13344:
13345: =back
13346:
13347: Returns: Array of up to two items.
13348:
13349: =over
13350:
13351: a reference to an array of files/subdirectories
13352:
13353: =over
13354:
13355: Each element in the array of files/subdirectories is a & separated list of
13356: item name and the result of running stat on the item. If dirlist was requested
13357: for a file instead of a directory, the item name will be ''. For a directory
13358: listing, if the item is a metadata file, the element will end &N&M
13359: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13360: default copyright set (1).
13361:
13362: =back
13363:
13364: a scalar containing error condition (if encountered).
13365:
13366: =over
13367:
13368: =item
13369: no_host (no homeserver identified for $username:$domain).
13370:
13371: =item
13372: no_such_host (server contacted for listing not identified as valid host).
13373:
13374: =item
13375: con_lost (connection to remote server failed).
13376:
13377: =item
13378: refused (invalid $username:$domain received on lond side).
13379:
13380: =item
13381: no_such_dir (directory at specified path on lond side does not exist).
13382:
13383: =item
13384: empty (directory at specified path on lond side is empty).
13385:
13386: =over
13387:
13388: This is currently not encountered because the &ls3, &ls2,
13389: &ls (_handler) routines on the lond side do not filter out
13390: . and .. from a directory listing.
13391:
13392: =back
13393:
13394: =back
13395:
13396: =back
1.191 harris41 13397:
13398: =item *
13399:
1.243 albertel 13400: spareserver() : find server with least workload from spare.tab
13401:
1.986 foxr 13402:
13403: =item *
13404:
13405: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13406: if there is no corresponding loncapa host.
13407:
1.243 albertel 13408: =back
13409:
1.986 foxr 13410:
1.243 albertel 13411: =head2 Apache Request
13412:
13413: =over 4
1.191 harris41 13414:
13415: =item *
13416:
1.243 albertel 13417: ssi($url,%hash) : server side include, does a complete request cycle on url to
13418: localhost, posts hash
13419:
13420: =back
13421:
13422: =head2 Data to String to Data
13423:
13424: =over 4
1.191 harris41 13425:
13426: =item *
13427:
1.243 albertel 13428: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13429: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13430:
13431: =item *
13432:
1.243 albertel 13433: hashref2str($hashref) : convert a hashref into a string complete with
13434: escaping and '=' and '&' separators, supports elements that are
13435: arrayrefs and hashrefs
1.191 harris41 13436:
13437: =item *
13438:
1.243 albertel 13439: arrayref2str($arrayref) : convert an arrayref into a string complete
13440: with escaping and '&' separators, supports elements that are arrayrefs
13441: and hashrefs
1.191 harris41 13442:
13443: =item *
13444:
1.243 albertel 13445: str2hash($string) : convert string to hash using unescaping and
13446: splitting on '=' and '&', supports elements that are arrayrefs and
13447: hashrefs
1.191 harris41 13448:
13449: =item *
13450:
1.243 albertel 13451: str2array($string) : convert string to hash using unescaping and
13452: splitting on '&', supports elements that are arrayrefs and hashrefs
13453:
13454: =back
13455:
13456: =head2 Logging Routines
13457:
13458:
13459: These routines allow one to make log messages in the lonnet.log and
13460: lonnet.perm logfiles.
1.191 harris41 13461:
1.1119 foxr 13462: =over 4
13463:
1.191 harris41 13464: =item *
13465:
1.243 albertel 13466: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13467:
13468: =item *
13469:
1.243 albertel 13470: logthis() : append message to the normal lonnet.log file, it gets
13471: preiodically rolled over and deleted.
1.191 harris41 13472:
13473: =item *
13474:
1.243 albertel 13475: logperm() : append a permanent message to lonnet.perm.log, this log
13476: file never gets deleted by any automated portion of the system, only
13477: messages of critical importance should go in here.
13478:
1.1119 foxr 13479:
1.243 albertel 13480: =back
13481:
13482: =head2 General File Helper Routines
13483:
13484: =over 4
1.191 harris41 13485:
13486: =item *
13487:
1.481 raeburn 13488: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13489: (a) files in /uploaded
13490: (i) If a local copy of the file exists -
13491: compares modification date of local copy with last-modified date for
13492: definitive version stored on home server for course. If local copy is
13493: stale, requests a new version from the home server and stores it.
13494: If the original has been removed from the home server, then local copy
13495: is unlinked.
13496: (ii) If local copy does not exist -
13497: requests the file from the home server and stores it.
13498:
13499: If $caller is 'uploadrep':
13500: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13501: for request for files originally uploaded via DOCS.
13502: - returns 'ok' if fresh local copy now available, -1 otherwise.
13503:
13504: Otherwise:
13505: This indicates a call from the content generation phase of the request.
13506: - returns the entire contents of the file or -1.
13507:
13508: (b) files in /res
13509: - returns the entire contents of a file or -1;
13510: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13511:
1.712 albertel 13512:
13513: =item *
13514:
13515: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13516: reference
13517:
13518: returns either a stat() list of data about the file or an empty list
13519: if the file doesn't exist or couldn't find out about it (connection
13520: problems or user unknown)
13521:
1.191 harris41 13522: =item *
13523:
1.243 albertel 13524: filelocation($dir,$file) : returns file system location of a file
13525: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13526: directory that relative $file lookups are to looked in ($dir of /a/dir
13527: and a file of ../bob will become /a/bob)
1.191 harris41 13528:
13529: =item *
13530:
13531: hreflocation($dir,$file) : returns file system location or a URL; same as
13532: filelocation except for hrefs
13533:
13534: =item *
13535:
13536: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13537:
1.243 albertel 13538: =back
13539:
1.608 albertel 13540: =head2 Usererfile file routines (/uploaded*)
13541:
13542: =over 4
13543:
13544: =item *
13545:
13546: userfileupload(): main rotine for putting a file in a user or course's
13547: filespace, arguments are,
13548:
1.620 albertel 13549: formname - required - this is the name of the element in $env where the
1.608 albertel 13550: filename, and the contents of the file to create/modifed exist
1.620 albertel 13551: the filename is in $env{'form.'.$formname.'.filename'} and the
13552: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13553: context - if coursedoc, store the file in the course of the active role
13554: of the current user;
13555: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13556: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13557: subdir - required - subdirectory to put the file in under ../userfiles/
13558: if undefined, it will be placed in "unknown"
13559:
13560: (This routine calls clean_filename() to remove any dangerous
13561: characters from the filename, and then calls finuserfileupload() to
13562: complete the transaction)
13563:
13564: returns either the url of the uploaded file (/uploaded/....) if successful
13565: and /adm/notfound.html if unsuccessful
13566:
13567: =item *
13568:
13569: clean_filename(): routine for cleaing a filename up for storage in
13570: userfile space, argument is:
13571:
13572: filename - proposed filename
13573:
13574: returns: the new clean filename
13575:
13576: =item *
13577:
1.1090 raeburn 13578: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13579: userspace, probably shouldn't be called directly
13580:
13581: docuname: username or courseid of destination for the file
13582: docudom: domain of user/course of destination for the file
13583: formname: same as for userfileupload()
1.1090 raeburn 13584: fname: filename (including subdirectories) for the file
13585: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13586: allfiles: reference to hash used to store objects found by parser
13587: codebase: reference to hash used for codebases of java objects found by parser
13588: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13589: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13590: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13591: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13592: context: if 'overwrite', will move the uploaded file from its temporary location to
13593: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13594: mimetype: reference to scalar to accommodate mime type determined
13595: from File::MMagic if $parser = parse.
1.608 albertel 13596:
13597: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13598: and /adm/notfound.html if unsuccessful (or an error message if context
13599: was 'overwrite').
13600:
1.608 albertel 13601:
13602: =item *
13603:
13604: renameuserfile(): renames an existing userfile to a new name
13605:
13606: Args:
13607: docuname: username or courseid of destination for the file
13608: docudom: domain of user/course of destination for the file
13609: old: current file name (including any subdirs under userfiles)
13610: new: desired file name (including any subdirs under userfiles)
13611:
13612: =item *
13613:
13614: mkdiruserfile(): creates a directory is a userfiles dir
13615:
13616: Args:
13617: docuname: username or courseid of destination for the file
13618: docudom: domain of user/course of destination for the file
13619: dir: dir to create (including any subdirs under userfiles)
13620:
13621: =item *
13622:
13623: removeuserfile(): removes a file that exists in userfiles
13624:
13625: Args:
13626: docuname: username or courseid of destination for the file
13627: docudom: domain of user/course of destination for the file
13628: fname: filname to delete (including any subdirs under userfiles)
13629:
13630: =item *
13631:
13632: removeuploadedurl(): convience function for removeuserfile()
13633:
13634: Args:
13635: url: a full /uploaded/... url to delete
13636:
1.747 albertel 13637: =item *
13638:
13639: get_portfile_permissions():
13640: Args:
13641: domain: domain of user or course contain the portfolio files
13642: user: name of user or num of course contain the portfolio files
13643: Returns:
13644: hashref of a dump of the proper file_permissions.db
13645:
13646:
13647: =item *
13648:
13649: get_access_controls():
13650:
13651: Args:
13652: current_permissions: the hash ref returned from get_portfile_permissions()
13653: group: (optional) the group you want the files associated with
13654: file: (optional) the file you want access info on
13655:
13656: Returns:
1.749 raeburn 13657: a hash (keys are file names) of hashes containing
13658: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13659: values are XML containing access control settings (see below)
1.747 albertel 13660:
13661: Internal notes:
13662:
1.749 raeburn 13663: access controls are stored in file_permissions.db as key=value pairs.
13664: key -> path to file/file_name\0uniqueID:scope_end_start
13665: where scope -> public,guest,course,group,domains or users.
13666: end -> UNIX time for end of access (0 -> no end date)
13667: start -> UNIX time for start of access
13668:
13669: value -> XML description of access control
13670: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13671: <start></start>
13672: <end></end>
13673:
13674: <password></password> for scope type = guest
13675:
13676: <domain></domain> for scope type = course or group
13677: <number></number>
13678: <roles id="">
13679: <role></role>
13680: <access></access>
13681: <section></section>
13682: <group></group>
13683: </roles>
13684:
13685: <dom></dom> for scope type = domains
13686:
13687: <users> for scope type = users
13688: <user>
13689: <uname></uname>
13690: <udom></udom>
13691: </user>
13692: </users>
13693: </scope>
13694:
13695: Access data is also aggregated for each file in an additional key=value pair:
13696: key -> path to file/file_name\0accesscontrol
13697: value -> reference to hash
13698: hash contains key = value pairs
13699: where key = uniqueID:scope_end_start
13700: value = UNIX time record was last updated
13701:
13702: Used to improve speed of look-ups of access controls for each file.
13703:
13704: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13705:
1.1198 raeburn 13706: =item *
13707:
1.749 raeburn 13708: modify_access_controls():
13709:
13710: Modifies access controls for a portfolio file
13711: Args
13712: 1. file name
13713: 2. reference to hash of required changes,
13714: 3. domain
13715: 4. username
13716: where domain,username are the domain of the portfolio owner
13717: (either a user or a course)
13718:
13719: Returns:
13720: 1. result of additions or updates ('ok' or 'error', with error message).
13721: 2. result of deletions ('ok' or 'error', with error message).
13722: 3. reference to hash of any new or updated access controls.
13723: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13724: key = integer (inbound ID)
1.1198 raeburn 13725: value = uniqueID
13726:
13727: =item *
13728:
13729: get_timebased_id():
13730:
13731: Attempts to get a unique timestamp-based suffix for use with items added to a
13732: course via the Course Editor (e.g., folders, composite pages,
13733: group bulletin boards).
13734:
13735: Args: (first three required; six others optional)
13736:
13737: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13738: docssequence, or name of group
13739:
13740: 2. keyid (alphanumeric): name of temporary locking key in hash,
13741: e.g., num, boardids
13742:
13743: 3. namespace: name of gdbm file used to store suffixes already assigned;
13744: file will be named nohist_namespace.db
13745:
13746: 4. cdom: domain of course; default is current course domain from %env
13747:
13748: 5. cnum: course number; default is current course number from %env
13749:
13750: 6. idtype: set to concat if an additional digit is to be appended to the
13751: unix timestamp to form the suffix, if the plain timestamp is already
13752: in use. Default is to not do this, but simply increment the unix
13753: timestamp by 1 until a unique key is obtained.
13754:
13755: 7. who: holder of locking key; defaults to user:domain for user.
13756:
13757: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13758: retrying); default is 3.
13759:
13760: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13761:
13762: Returns:
13763:
13764: 1. suffix obtained (numeric)
13765:
13766: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13767:
13768: 3. error: contains (localized) error message if an error occurred.
13769:
1.747 albertel 13770:
1.608 albertel 13771: =back
13772:
1.243 albertel 13773: =head2 HTTP Helper Routines
13774:
13775: =over 4
13776:
1.191 harris41 13777: =item *
13778:
13779: escape() : unpack non-word characters into CGI-compatible hex codes
13780:
13781: =item *
13782:
13783: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13784:
1.243 albertel 13785: =back
13786:
13787: =head1 PRIVATE SUBROUTINES
13788:
13789: =head2 Underlying communication routines (Shouldn't call)
13790:
13791: =over 4
13792:
13793: =item *
13794:
13795: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13796:
13797: =item *
13798:
13799: reply() : uses subreply to send a message to remote machine, logs all failures
13800:
13801: =item *
13802:
13803: critical() : passes a critical message to another server; if cannot
13804: get through then place message in connection buffer directory and
13805: returns con_delayed, if incapable of saving message, returns
13806: con_failed
13807:
13808: =item *
13809:
13810: reconlonc() : tries to reconnect lonc client processes.
13811:
13812: =back
13813:
13814: =head2 Resource Access Logging
13815:
13816: =over 4
13817:
13818: =item *
13819:
13820: flushcourselogs() : flush (save) buffer logs and access logs
13821:
13822: =item *
13823:
13824: courselog($what) : save message for course in hash
13825:
13826: =item *
13827:
13828: courseacclog($what) : save message for course using &courselog(). Perform
13829: special processing for specific resource types (problems, exams, quizzes, etc).
13830:
1.191 harris41 13831: =item *
13832:
13833: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13834: as a PerlChildExitHandler
1.243 albertel 13835:
13836: =back
13837:
13838: =head2 Other
13839:
13840: =over 4
13841:
13842: =item *
13843:
13844: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13845:
13846: =back
13847:
13848: =cut
1.877 foxr 13849:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>