Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1278
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1278 ! raeburn 4: # $Id: lonnet.pm,v 1.1277 2015/03/07 23:17:21 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1245 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
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.1245 raeburn 609: my ($r,$name,$userhashref) = @_;
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.1245 raeburn 640:
641: if (ref($userhashref) eq 'HASH') {
642: $userhashref->{'name'} = $disk_env{'user.name'};
643: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 644: }
1.1245 raeburn 645:
1.916 albertel 646: return $handle;
647: }
648:
1.830 albertel 649: sub timed_flock {
650: my ($file,$lock_type) = @_;
651: my $failed=0;
652: eval {
653: local $SIG{__DIE__}='DEFAULT';
654: local $SIG{ALRM}=sub {
655: $failed=1;
656: die("failed lock");
657: };
658: alarm(13);
659: flock($file,$lock_type);
660: alarm(0);
661: };
662: if ($failed) {
663: return undef;
664: } else {
665: return 1;
666: }
667: }
668:
1.5 www 669: # ---------------------------------------------------------- Append Environment
670:
671: sub appenv {
1.949 raeburn 672: my ($newenv,$roles) = @_;
673: if (ref($newenv) eq 'HASH') {
674: foreach my $key (keys(%{$newenv})) {
675: my $refused = 0;
676: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
677: $refused = 1;
678: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 679: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 680: if (grep(/^\Q$role\E$/,@{$roles})) {
681: $refused = 0;
682: }
683: }
684: }
685: if ($refused) {
686: &logthis("<font color=\"blue\">WARNING: ".
687: "Attempt to modify environment ".$key." to ".$newenv->{$key}
688: .'</font>');
689: delete($newenv->{$key});
690: } else {
691: $env{$key}=$newenv->{$key};
692: }
693: }
694: my $opened = open(my $env_file,'+<',$env{'user.environment'});
695: if ($opened
696: && &timed_flock($env_file,LOCK_EX)
697: &&
698: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
699: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
700: while (my ($key,$value) = each(%{$newenv})) {
701: $disk_env{$key} = $value;
702: }
703: untie(%disk_env);
1.35 www 704: }
1.191 harris41 705: }
1.56 www 706: return 'ok';
707: }
708: # ----------------------------------------------------- Delete from Environment
709:
710: sub delenv {
1.1104 raeburn 711: my ($delthis,$regexp,$roles) = @_;
712: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
713: my $refused = 1;
714: if (ref($roles) eq 'ARRAY') {
715: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
716: if (grep(/^\Q$role\E$/,@{$roles})) {
717: $refused = 0;
718: }
719: }
720: if ($refused) {
721: &logthis("<font color=\"blue\">WARNING: ".
722: "Attempt to delete from environment ".$delthis);
723: return 'error';
724: }
1.56 www 725: }
1.917 albertel 726: my $opened = open(my $env_file,'+<',$env{'user.environment'});
727: if ($opened
1.915 albertel 728: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 729: &&
730: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
731: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 732: foreach my $key (keys(%disk_env)) {
1.987 raeburn 733: if ($regexp) {
734: if ($key=~/^$delthis/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: } else {
739: if ($key=~/^\Q$delthis\E/) {
740: delete($env{$key});
741: delete($disk_env{$key});
742: }
743: }
1.448 albertel 744: }
1.783 albertel 745: untie(%disk_env);
1.5 www 746: }
747: return 'ok';
1.369 albertel 748: }
749:
1.790 albertel 750: sub get_env_multiple {
751: my ($name) = @_;
752: my @values;
753: if (defined($env{$name})) {
754: # exists is it an array
755: if (ref($env{$name})) {
756: @values=@{ $env{$name} };
757: } else {
758: $values[0]=$env{$name};
759: }
760: }
761: return(@values);
762: }
763:
1.958 www 764: # ------------------------------------------------------------------- Locking
765:
766: sub set_lock {
767: my ($text)=@_;
768: $locknum++;
769: my $id=$$.'-'.$locknum;
770: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
771: 'session.lock.'.$id => $text});
772: return $id;
773: }
774:
775: sub get_locks {
776: my $num=0;
777: my %texts=();
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if ($lock=~/\w/) {
780: $num++;
781: $texts{$lock}=$env{'session.lock.'.$lock};
782: }
783: }
784: return ($num,%texts);
785: }
786:
787: sub remove_lock {
788: my ($id)=@_;
789: my $newlocks='';
790: foreach my $lock (split(/\,/,$env{'session.locks'})) {
791: if (($lock=~/\w/) && ($lock ne $id)) {
792: $newlocks.=','.$lock;
793: }
794: }
795: &appenv({'session.locks' => $newlocks});
796: &delenv('session.lock.'.$id);
797: }
798:
799: sub remove_all_locks {
800: my $activelocks=$env{'session.locks'};
801: foreach my $lock (split(/\,/,$env{'session.locks'})) {
802: if ($lock=~/\w/) {
803: &remove_lock($lock);
804: }
805: }
806: }
807:
808:
1.369 albertel 809: # ------------------------------------------ Find out current server userload
810: sub userload {
811: my $numusers=0;
812: {
813: opendir(LONIDS,$perlvar{'lonIDsDir'});
814: my $filename;
815: my $curtime=time;
816: while ($filename=readdir(LONIDS)) {
1.925 albertel 817: next if ($filename eq '.' || $filename eq '..');
818: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 819: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 820: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 821: }
822: closedir(LONIDS);
823: }
824: my $userloadpercent=0;
825: my $maxuserload=$perlvar{'lonUserLoadLim'};
826: if ($maxuserload) {
1.371 albertel 827: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 828: }
1.372 albertel 829: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 830: return $userloadpercent;
1.283 www 831: }
832:
1.1 albertel 833: # ------------------------------ Find server with least workload from spare.tab
1.11 www 834:
1.1 albertel 835: sub spareserver {
1.1083 raeburn 836: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 837: my $spare_server;
1.370 albertel 838: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 839: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
840: : $userloadpercent;
1.1083 raeburn 841: my ($uint_dom,$remotesessions);
842: if (($udom ne '') && (&domain($udom) ne '')) {
843: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
844: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
845: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
846: $remotesessions = $udomdefaults{'remotesessions'};
847: }
1.1123 raeburn 848: my $spareshash = &this_host_spares($udom);
849: if (ref($spareshash) eq 'HASH') {
850: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'primary'} }) {
852: if ($uint_dom) {
853: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
854: $try_server));
855: }
856: ($spare_server, $lowest_load) =
857: &compare_server_load($try_server, $spare_server, $lowest_load);
858: }
1.1083 raeburn 859: }
1.784 albertel 860:
1.1123 raeburn 861: my $found_server = ($spare_server ne '' && $lowest_load < 100);
862:
863: if (!$found_server) {
864: if (ref($spareshash->{'default'}) eq 'ARRAY') {
865: foreach my $try_server (@{ $spareshash->{'default'} }) {
866: if ($uint_dom) {
867: next unless (&spare_can_host($udom,$uint_dom,
868: $remotesessions,$try_server));
869: }
870: ($spare_server, $lowest_load) =
871: &compare_server_load($try_server, $spare_server, $lowest_load);
872: }
873: }
874: }
1.784 albertel 875: }
876:
877: if (!$want_server_name) {
1.968 raeburn 878: my $protocol = 'http';
879: if ($protocol{$spare_server} eq 'https') {
880: $protocol = $protocol{$spare_server};
881: }
1.1001 raeburn 882: if (defined($spare_server)) {
883: my $hostname = &hostname($spare_server);
1.1083 raeburn 884: if (defined($hostname)) {
1.1001 raeburn 885: $spare_server = $protocol.'://'.$hostname;
886: }
887: }
1.784 albertel 888: }
889: return $spare_server;
890: }
891:
892: sub compare_server_load {
1.1253 raeburn 893: my ($try_server, $spare_server, $lowest_load, $required) = @_;
894:
895: if ($required) {
896: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
897: my $remoterev = &get_server_loncaparev(undef,$try_server);
898: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
899: if (($major eq '' && $minor eq '') ||
900: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
901: return ($spare_server,$lowest_load);
902: }
903: }
1.784 albertel 904:
905: my $loadans = &reply('load', $try_server);
906: my $userloadans = &reply('userload',$try_server);
907:
908: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 909: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 910: }
911:
912: my $load;
913: if ($loadans =~ /\d/) {
914: if ($userloadans =~ /\d/) {
915: #both are numbers, pick the bigger one
916: $load = ($loadans > $userloadans) ? $loadans
917: : $userloadans;
1.411 albertel 918: } else {
1.784 albertel 919: $load = $loadans;
1.411 albertel 920: }
1.784 albertel 921: } else {
922: $load = $userloadans;
923: }
924:
925: if (($load =~ /\d/) && ($load < $lowest_load)) {
926: $spare_server = $try_server;
927: $lowest_load = $load;
1.370 albertel 928: }
1.784 albertel 929: return ($spare_server,$lowest_load);
1.202 matthew 930: }
1.914 albertel 931:
932: # --------------------------- ask offload servers if user already has a session
933: sub find_existing_session {
934: my ($udom,$uname) = @_;
1.1123 raeburn 935: my $spareshash = &this_host_spares($udom);
936: if (ref($spareshash) eq 'HASH') {
937: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'primary'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
942: if (ref($spareshash->{'default'}) eq 'ARRAY') {
943: foreach my $try_server (@{ $spareshash->{'default'} }) {
944: return $try_server if (&has_user_session($try_server, $udom, $uname));
945: }
946: }
1.914 albertel 947: }
948: return;
949: }
950:
951: # -------------------------------- ask if server already has a session for user
952: sub has_user_session {
953: my ($lonid,$udom,$uname) = @_;
954: my $result = &reply(join(':','userhassession',
955: map {&escape($_)} ($udom,$uname)),$lonid);
956: return 1 if ($result eq 'ok');
957:
958: return 0;
959: }
960:
1.1076 raeburn 961: # --------- determine least loaded server in a user's domain which allows login
962:
963: sub choose_server {
1.1259 raeburn 964: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 965: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 966: my %servers = &get_servers($udom);
1.1076 raeburn 967: my $lowest_load = 30000;
1.1259 raeburn 968: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
969: if ($skiploadbal) {
970: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
971: unless (defined($cached)) {
972: my $cachetime = 60*60*24;
973: my %domconfig =
974: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
975: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
976: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
977: $cachetime);
978: }
979: }
980: }
1.1076 raeburn 981: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 982: if ($skiploadbal) {
983: if (ref($balancers) eq 'HASH') {
984: next if (exists($balancers->{$lonhost}));
985: }
986: }
1.1115 raeburn 987: my $loginvia;
988: if ($checkloginvia) {
989: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 990: if ($loginvia) {
991: my ($server,$path) = split(/:/,$loginvia);
992: ($login_host, $lowest_load) =
1.1253 raeburn 993: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 994: if ($login_host eq $server) {
995: $portal_path = $path;
1.1151 raeburn 996: $isredirect = 1;
1.1116 raeburn 997: }
998: } else {
999: ($login_host, $lowest_load) =
1.1253 raeburn 1000: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1001: if ($login_host eq $lonhost) {
1002: $portal_path = '';
1.1151 raeburn 1003: $isredirect = '';
1.1116 raeburn 1004: }
1005: }
1006: } else {
1.1076 raeburn 1007: ($login_host, $lowest_load) =
1.1253 raeburn 1008: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1009: }
1010: }
1011: if ($login_host ne '') {
1.1116 raeburn 1012: $hostname = &hostname($login_host);
1.1076 raeburn 1013: }
1.1151 raeburn 1014: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1015: }
1016:
1.202 matthew 1017: # --------------------------------------------- Try to change a user's password
1018:
1019: sub changepass {
1.799 raeburn 1020: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1021: $currentpass = &escape($currentpass);
1022: $newpass = &escape($newpass);
1.1030 raeburn 1023: my $lonhost = $perlvar{'lonHostID'};
1024: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1025: $server);
1026: if (! $answer) {
1027: &logthis("No reply on password change request to $server ".
1028: "by $uname in domain $udom.");
1029: } elsif ($answer =~ "^ok") {
1030: &logthis("$uname in $udom successfully changed their password ".
1031: "on $server.");
1032: } elsif ($answer =~ "^pwchange_failure") {
1033: &logthis("$uname in $udom was unable to change their password ".
1034: "on $server. The action was blocked by either lcpasswd ".
1035: "or pwchange");
1036: } elsif ($answer =~ "^non_authorized") {
1037: &logthis("$uname in $udom did not get their password correct when ".
1038: "attempting to change it on $server.");
1039: } elsif ($answer =~ "^auth_mode_error") {
1040: &logthis("$uname in $udom attempted to change their password despite ".
1041: "not being locally or internally authenticated on $server.");
1042: } elsif ($answer =~ "^unknown_user") {
1043: &logthis("$uname in $udom attempted to change their password ".
1044: "on $server but were unable to because $server is not ".
1045: "their home server.");
1046: } elsif ($answer =~ "^refused") {
1047: &logthis("$server refused to change $uname in $udom password because ".
1048: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1049: } elsif ($answer =~ "invalid_client") {
1050: &logthis("$server refused to change $uname in $udom password because ".
1051: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1052: }
1053: return $answer;
1.1 albertel 1054: }
1055:
1.169 harris41 1056: # ----------------------- Try to determine user's current authentication scheme
1057:
1058: sub queryauthenticate {
1059: my ($uname,$udom)=@_;
1.456 albertel 1060: my $uhome=&homeserver($uname,$udom);
1061: if (!$uhome) {
1062: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1063: return 'no_host';
1064: }
1065: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1066: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1067: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1068: }
1.456 albertel 1069: return $answer;
1.169 harris41 1070: }
1071:
1.1 albertel 1072: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1073:
1.1 albertel 1074: sub authenticate {
1.1073 raeburn 1075: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1076: $upass=&escape($upass);
1077: $uname= &LONCAPA::clean_username($uname);
1.836 www 1078: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1079: my $newhome;
1.836 www 1080: if ((!$uhome) || ($uhome eq 'no_host')) {
1081: # Maybe the machine was offline and only re-appeared again recently?
1082: &reconlonc();
1083: # One more
1.952 raeburn 1084: $uhome=&homeserver($uname,$udom,1);
1085: if (($uhome eq 'no_host') && $checkdefauth) {
1086: if (defined(&domain($udom,'primary'))) {
1087: $newhome=&domain($udom,'primary');
1088: }
1089: if ($newhome ne '') {
1090: $uhome = $newhome;
1091: }
1092: }
1.836 www 1093: if ((!$uhome) || ($uhome eq 'no_host')) {
1094: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1095: return 'no_host';
1096: }
1.1 albertel 1097: }
1.1073 raeburn 1098: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1099: if ($answer eq 'authorized') {
1.952 raeburn 1100: if ($newhome) {
1101: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1102: return 'no_account_on_host';
1103: } else {
1104: &logthis("User $uname at $udom authorized by $uhome");
1105: return $uhome;
1106: }
1.471 albertel 1107: }
1108: if ($answer eq 'non_authorized') {
1109: &logthis("User $uname at $udom rejected by $uhome");
1110: return 'no_host';
1.9 www 1111: }
1.471 albertel 1112: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1113: return 'no_host';
1114: }
1115:
1.1073 raeburn 1116: sub can_host_session {
1.1074 raeburn 1117: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1118: my $canhost = 1;
1.1074 raeburn 1119: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1120: if (ref($remotesessions) eq 'HASH') {
1121: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1122: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1123: $canhost = 0;
1124: } else {
1125: $canhost = 1;
1126: }
1127: }
1128: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1129: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1130: $canhost = 1;
1131: } else {
1132: $canhost = 0;
1133: }
1134: }
1135: if ($canhost) {
1136: if ($remotesessions->{'version'} ne '') {
1137: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1138: if ($reqmajor ne '' && $reqminor ne '') {
1139: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1140: my $major = $1;
1141: my $minor = $2;
1142: if (($major < $reqmajor ) ||
1143: (($major == $reqmajor) && ($minor < $reqminor))) {
1144: $canhost = 0;
1145: }
1146: } else {
1147: $canhost = 0;
1148: }
1149: }
1150: }
1151: }
1152: }
1153: if ($canhost) {
1154: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1155: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1156: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1157: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1158: if (($uint_dom ne '') &&
1159: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1160: $canhost = 0;
1161: } else {
1162: $canhost = 1;
1163: }
1164: }
1165: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1166: if (($uint_dom ne '') &&
1167: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1168: $canhost = 1;
1169: } else {
1170: $canhost = 0;
1171: }
1172: }
1173: }
1174: }
1175: return $canhost;
1176: }
1177:
1.1083 raeburn 1178: sub spare_can_host {
1179: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1180: my $canhost=1;
1181: my @intdoms;
1.1278 ! raeburn 1182: my $internet_names = &get_internet_names($try_server);
1.1083 raeburn 1183: if (ref($internet_names) eq 'ARRAY') {
1184: @intdoms = @{$internet_names};
1185: }
1186: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.1278 ! raeburn 1187: my $try_server_hostname = &hostname($try_server);
! 1188: my $serverhomeID = &get_server_homeID($try_server_hostname);
! 1189: my $serverhomedom = &host_domain($serverhomeID);
! 1190: my %defdomdefaults = &get_domain_defaults($serverhomedom);
! 1191: my $remoterev = &get_server_loncaparev(undef,$try_server);
1.1083 raeburn 1192: $canhost = &can_host_session($udom,$try_server,$remoterev,
1193: $remotesessions,
1194: $defdomdefaults{'hostedsessions'});
1195: }
1196: return $canhost;
1197: }
1198:
1.1123 raeburn 1199: sub this_host_spares {
1200: my ($dom) = @_;
1.1126 raeburn 1201: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1202: my @hosts = ¤t_machine_ids();
1203: foreach my $lonhost (@hosts) {
1204: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1205: $dom_in_use = $dom;
1206: $lonhost_in_use = $lonhost;
1.1123 raeburn 1207: last;
1208: }
1209: }
1.1126 raeburn 1210: if ($dom_in_use ne '') {
1211: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1212: }
1213: if (ref($result) ne 'HASH') {
1214: $lonhost_in_use = $perlvar{'lonHostID'};
1215: $dom_in_use = &host_domain($lonhost_in_use);
1216: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1217: if (ref($result) ne 'HASH') {
1218: $result = \%spareid;
1219: }
1220: }
1221: return $result;
1222: }
1223:
1224: sub spares_for_offload {
1225: my ($dom_in_use,$lonhost_in_use) = @_;
1226: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1227: if (defined($cached)) {
1228: return $result;
1229: } else {
1.1126 raeburn 1230: my $cachetime = 60*60*24;
1231: my %domconfig =
1232: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1233: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1234: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1235: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1236: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1237: }
1238: }
1239: }
1240: }
1.1126 raeburn 1241: return;
1.1123 raeburn 1242: }
1243:
1.1129 raeburn 1244: sub get_lonbalancer_config {
1245: my ($servers) = @_;
1246: my ($currbalancer,$currtargets);
1247: if (ref($servers) eq 'HASH') {
1248: foreach my $server (keys(%{$servers})) {
1249: my %what = (
1250: spareid => 1,
1251: perlvar => 1,
1252: );
1253: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1254: if ($result eq 'ok') {
1255: if (ref($returnhash) eq 'HASH') {
1256: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1257: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1258: $currbalancer = $server;
1259: $currtargets = {};
1260: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1261: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1262: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1263: }
1264: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1265: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1266: }
1267: }
1268: last;
1269: }
1270: }
1271: }
1272: }
1273: }
1274: }
1275: return ($currbalancer,$currtargets);
1276: }
1277:
1278: sub check_loadbalancing {
1279: my ($uname,$udom) = @_;
1.1191 raeburn 1280: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1281: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1282: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1283: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1284: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1285: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1286: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1287: my $serverhomedom = &host_domain($lonhost);
1288:
1289: my $cachetime = 60*60*24;
1290:
1291: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1292: $dom_in_use = $udom;
1293: $homeintdom = 1;
1294: } else {
1295: $dom_in_use = $serverhomedom;
1296: }
1297: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1298: unless (defined($cached)) {
1299: my %domconfig =
1300: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1301: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1302: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1303: }
1304: }
1305: if (ref($result) eq 'HASH') {
1.1191 raeburn 1306: ($is_balancer,$currtargets,$currrules) =
1307: &check_balancer_result($result,@hosts);
1.1129 raeburn 1308: if ($is_balancer) {
1309: if (ref($currrules) eq 'HASH') {
1310: if ($homeintdom) {
1311: if ($uname ne '') {
1312: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1313: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1314: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1315: $rule_in_effect = $currrules->{'_LC_author'};
1316: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1317: $rule_in_effect = $currrules->{'_LC_adv'}
1318: }
1319: }
1320: if ($rule_in_effect eq '') {
1321: my %userenv = &userenvironment($udom,$uname,'inststatus');
1322: if ($userenv{'inststatus'} ne '') {
1323: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1324: my ($othertitle,$usertypes,$types) =
1325: &Apache::loncommon::sorted_inst_types($udom);
1326: if (ref($types) eq 'ARRAY') {
1327: foreach my $type (@{$types}) {
1328: if (grep(/^\Q$type\E$/,@statuses)) {
1329: if (exists($currrules->{$type})) {
1330: $rule_in_effect = $currrules->{$type};
1331: }
1332: }
1333: }
1334: }
1335: } else {
1336: if (exists($currrules->{'default'})) {
1337: $rule_in_effect = $currrules->{'default'};
1338: }
1339: }
1340: }
1341: } else {
1342: if (exists($currrules->{'default'})) {
1343: $rule_in_effect = $currrules->{'default'};
1344: }
1345: }
1346: } else {
1347: if ($currrules->{'_LC_external'} ne '') {
1348: $rule_in_effect = $currrules->{'_LC_external'};
1349: }
1350: }
1351: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1352: $uname,$udom);
1353: }
1354: }
1355: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1356: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1357: unless (defined($cached)) {
1358: my %domconfig =
1359: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1360: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1361: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1362: }
1363: }
1364: if (ref($result) eq 'HASH') {
1.1191 raeburn 1365: ($is_balancer,$currtargets,$currrules) =
1366: &check_balancer_result($result,@hosts);
1367: if ($is_balancer) {
1.1129 raeburn 1368: if (ref($currrules) eq 'HASH') {
1369: if ($currrules->{'_LC_internetdom'} ne '') {
1370: $rule_in_effect = $currrules->{'_LC_internetdom'};
1371: }
1372: }
1373: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1374: $uname,$udom);
1375: }
1376: } else {
1377: if ($perlvar{'lonBalancer'} eq 'yes') {
1378: $is_balancer = 1;
1379: $offloadto = &this_host_spares($dom_in_use);
1380: }
1381: }
1382: } else {
1383: if ($perlvar{'lonBalancer'} eq 'yes') {
1384: $is_balancer = 1;
1385: $offloadto = &this_host_spares($dom_in_use);
1386: }
1387: }
1.1176 raeburn 1388: if ($is_balancer) {
1389: my $lowest_load = 30000;
1390: if (ref($offloadto) eq 'HASH') {
1391: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1392: foreach my $try_server (@{$offloadto->{'primary'}}) {
1393: ($otherserver,$lowest_load) =
1394: &compare_server_load($try_server,$otherserver,$lowest_load);
1395: }
1.1129 raeburn 1396: }
1.1176 raeburn 1397: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1398:
1.1176 raeburn 1399: if (!$found_server) {
1400: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1401: foreach my $try_server (@{$offloadto->{'default'}}) {
1402: ($otherserver,$lowest_load) =
1403: &compare_server_load($try_server,$otherserver,$lowest_load);
1404: }
1405: }
1406: }
1407: } elsif (ref($offloadto) eq 'ARRAY') {
1408: if (@{$offloadto} == 1) {
1409: $otherserver = $offloadto->[0];
1410: } elsif (@{$offloadto} > 1) {
1411: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1412: ($otherserver,$lowest_load) =
1413: &compare_server_load($try_server,$otherserver,$lowest_load);
1414: }
1415: }
1416: }
1.1176 raeburn 1417: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1418: $is_balancer = 0;
1419: if ($uname ne '' && $udom ne '') {
1420: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1421:
1422: &appenv({'user.loadbalexempt' => $lonhost,
1423: 'user.loadbalcheck.time' => time});
1424: }
1.1129 raeburn 1425: }
1426: }
1427: }
1428: return ($is_balancer,$otherserver);
1429: }
1430:
1.1191 raeburn 1431: sub check_balancer_result {
1432: my ($result,@hosts) = @_;
1433: my ($is_balancer,$currtargets,$currrules);
1434: if (ref($result) eq 'HASH') {
1435: if ($result->{'lonhost'} ne '') {
1436: my $currbalancer = $result->{'lonhost'};
1437: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1438: $is_balancer = 1;
1439: $currtargets = $result->{'targets'};
1440: $currrules = $result->{'rules'};
1441: }
1442: } else {
1443: foreach my $key (keys(%{$result})) {
1444: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1445: (ref($result->{$key}) eq 'HASH')) {
1446: $is_balancer = 1;
1447: $currrules = $result->{$key}{'rules'};
1448: $currtargets = $result->{$key}{'targets'};
1449: last;
1450: }
1451: }
1452: }
1453: }
1454: return ($is_balancer,$currtargets,$currrules);
1455: }
1456:
1.1129 raeburn 1457: sub get_loadbalancer_targets {
1458: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1459: my $offloadto;
1.1175 raeburn 1460: if ($rule_in_effect eq 'none') {
1461: return [$perlvar{'lonHostID'}];
1462: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1463: $offloadto = $currtargets;
1464: } else {
1465: if ($rule_in_effect eq 'homeserver') {
1466: my $homeserver = &homeserver($uname,$udom);
1467: if ($homeserver ne 'no_host') {
1468: $offloadto = [$homeserver];
1469: }
1470: } elsif ($rule_in_effect eq 'externalbalancer') {
1471: my %domconfig =
1472: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1473: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1474: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1475: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1476: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1477: }
1478: }
1479: } else {
1.1178 raeburn 1480: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1481: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1482: if (&hostname($remotebalancer) ne '') {
1483: $offloadto = [$remotebalancer];
1484: }
1485: }
1486: } elsif (&hostname($rule_in_effect) ne '') {
1487: $offloadto = [$rule_in_effect];
1488: }
1489: }
1490: return $offloadto;
1491: }
1492:
1.1127 raeburn 1493: sub internet_dom_servers {
1494: my ($dom) = @_;
1495: my (%uniqservers,%servers);
1496: my $primaryserver = &hostname(&domain($dom,'primary'));
1497: my @machinedoms = &machine_domains($primaryserver);
1498: foreach my $mdom (@machinedoms) {
1499: my %currservers = %servers;
1500: my %server = &get_servers($mdom);
1501: %servers = (%currservers,%server);
1502: }
1503: my %by_hostname;
1504: foreach my $id (keys(%servers)) {
1505: push(@{$by_hostname{$servers{$id}}},$id);
1506: }
1507: foreach my $hostname (sort(keys(%by_hostname))) {
1508: if (@{$by_hostname{$hostname}} > 1) {
1509: my $match = 0;
1510: foreach my $id (@{$by_hostname{$hostname}}) {
1511: if (&host_domain($id) eq $dom) {
1512: $uniqservers{$id} = $hostname;
1513: $match = 1;
1514: }
1515: }
1516: unless ($match) {
1517: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1518: }
1519: } else {
1520: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1521: }
1522: }
1523: return %uniqservers;
1524: }
1525:
1.1 albertel 1526: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1527:
1.599 albertel 1528: my %homecache;
1.1 albertel 1529: sub homeserver {
1.230 stredwic 1530: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1531: my $index="$uname:$udom";
1.426 albertel 1532:
1.599 albertel 1533: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1534:
1535: my %servers = &get_servers($udom,'library');
1536: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1537: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1538: exists($badServerCache{$tryserver}));
1.841 albertel 1539:
1540: my $answer=reply("home:$udom:$uname",$tryserver);
1541: if ($answer eq 'found') {
1542: delete($badServerCache{$tryserver});
1543: return $homecache{$index}=$tryserver;
1544: } elsif ($answer eq 'no_host') {
1545: $badServerCache{$tryserver}=1;
1546: }
1.1 albertel 1547: }
1548: return 'no_host';
1.70 www 1549: }
1550:
1551: # ------------------------------------- Find the usernames behind a list of IDs
1552:
1553: sub idget {
1554: my ($udom,@ids)=@_;
1555: my %returnhash=();
1556:
1.841 albertel 1557: my %servers = &get_servers($udom,'library');
1558: foreach my $tryserver (keys(%servers)) {
1559: my $idlist=join('&',@ids);
1560: $idlist=~tr/A-Z/a-z/;
1561: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1562: my @answer=();
1563: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1564: @answer=split(/\&/,$reply);
1565: } ;
1566: my $i;
1567: for ($i=0;$i<=$#ids;$i++) {
1568: if ($answer[$i]) {
1569: $returnhash{$ids[$i]}=$answer[$i];
1570: }
1571: }
1572: }
1.70 www 1573: return %returnhash;
1574: }
1575:
1576: # ------------------------------------- Find the IDs behind a list of usernames
1577:
1578: sub idrget {
1579: my ($udom,@unames)=@_;
1580: my %returnhash=();
1.800 albertel 1581: foreach my $uname (@unames) {
1582: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1583: }
1.70 www 1584: return %returnhash;
1585: }
1586:
1587: # ------------------------------- Store away a list of names and associated IDs
1588:
1589: sub idput {
1590: my ($udom,%ids)=@_;
1591: my %servers=();
1.800 albertel 1592: foreach my $uname (keys(%ids)) {
1593: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1594: my $uhom=&homeserver($uname,$udom);
1.70 www 1595: if ($uhom ne 'no_host') {
1.800 albertel 1596: my $id=&escape($ids{$uname});
1.70 www 1597: $id=~tr/A-Z/a-z/;
1.800 albertel 1598: my $esc_unam=&escape($uname);
1.70 www 1599: if ($servers{$uhom}) {
1.800 albertel 1600: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1601: } else {
1.800 albertel 1602: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1603: }
1604: }
1.191 harris41 1605: }
1.800 albertel 1606: foreach my $server (keys(%servers)) {
1607: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1608: }
1.344 www 1609: }
1610:
1.1231 raeburn 1611: # ---------------------------------------- Delete unwanted IDs from ids.db file
1612:
1613: sub iddel {
1614: my ($udom,$idshashref,$uhome)=@_;
1615: my %result=();
1616: unless (ref($idshashref) eq 'HASH') {
1617: return %result;
1618: }
1619: my %servers=();
1620: while (my ($id,$uname) = each(%{$idshashref})) {
1621: my $uhom;
1622: if ($uhome) {
1623: $uhom = $uhome;
1624: } else {
1625: $uhom=&homeserver($uname,$udom);
1626: }
1627: if ($uhom ne 'no_host') {
1628: if ($servers{$uhom}) {
1629: $servers{$uhom}.='&'.&escape($id);
1630: } else {
1631: $servers{$uhom}=&escape($id);
1632: }
1633: }
1634: }
1635: foreach my $server (keys(%servers)) {
1636: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1637: }
1638: return %result;
1639: }
1640:
1.1023 raeburn 1641: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1642: sub dump_dom {
1.1165 droeschl 1643: my ($namespace, $udom, $regexp) = @_;
1644:
1645: $udom ||= $env{'user.domain'};
1646:
1647: return () unless $udom;
1648:
1649: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1650: }
1651:
1.1023 raeburn 1652: # ------------------------------------------ get items from domain db files
1.806 raeburn 1653:
1654: sub get_dom {
1.860 raeburn 1655: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1656: return if ($udom eq 'public');
1.806 raeburn 1657: my $items='';
1658: foreach my $item (@$storearr) {
1659: $items.=&escape($item).'&';
1660: }
1661: $items=~s/\&$//;
1.860 raeburn 1662: if (!$udom) {
1663: $udom=$env{'user.domain'};
1.1267 raeburn 1664: return if ($udom eq 'public');
1.860 raeburn 1665: if (defined(&domain($udom,'primary'))) {
1666: $uhome=&domain($udom,'primary');
1667: } else {
1.874 albertel 1668: undef($uhome);
1.860 raeburn 1669: }
1670: } else {
1671: if (!$uhome) {
1672: if (defined(&domain($udom,'primary'))) {
1673: $uhome=&domain($udom,'primary');
1674: }
1675: }
1676: }
1677: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1678: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1679: my %returnhash;
1.875 albertel 1680: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1681: return %returnhash;
1682: }
1.806 raeburn 1683: my @pairs=split(/\&/,$rep);
1684: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1685: return @pairs;
1686: }
1687: my $i=0;
1688: foreach my $item (@$storearr) {
1689: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1690: $i++;
1691: }
1692: return %returnhash;
1693: } else {
1.880 banghart 1694: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1695: }
1696: }
1697:
1698: # -------------------------------------------- put items in domain db files
1699:
1700: sub put_dom {
1.860 raeburn 1701: my ($namespace,$storehash,$udom,$uhome)=@_;
1702: if (!$udom) {
1703: $udom=$env{'user.domain'};
1704: if (defined(&domain($udom,'primary'))) {
1705: $uhome=&domain($udom,'primary');
1706: } else {
1.874 albertel 1707: undef($uhome);
1.860 raeburn 1708: }
1709: } else {
1710: if (!$uhome) {
1711: if (defined(&domain($udom,'primary'))) {
1712: $uhome=&domain($udom,'primary');
1713: }
1714: }
1715: }
1716: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1717: my $items='';
1718: foreach my $item (keys(%$storehash)) {
1719: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1720: }
1721: $items=~s/\&$//;
1722: return &reply("putdom:$udom:$namespace:$items",$uhome);
1723: } else {
1.860 raeburn 1724: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1725: }
1726: }
1727:
1.1023 raeburn 1728: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1729: sub newput_dom {
1.1023 raeburn 1730: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1731: my $result;
1732: if (!$udom) {
1733: $udom=$env{'user.domain'};
1734: }
1.1023 raeburn 1735: if ($udom) {
1736: my $uname = &get_domainconfiguser($udom);
1737: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1738: }
1739: return $result;
1740: }
1741:
1.1023 raeburn 1742: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1743: sub del_dom {
1.1023 raeburn 1744: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1745: if (ref($storearr) eq 'ARRAY') {
1746: if (!$udom) {
1747: $udom=$env{'user.domain'};
1748: }
1.1023 raeburn 1749: if ($udom) {
1750: my $uname = &get_domainconfiguser($udom);
1751: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1752: }
1753: }
1754: }
1755:
1.1023 raeburn 1756: # ----------------------------------construct domainconfig user for a domain
1757: sub get_domainconfiguser {
1758: my ($udom) = @_;
1759: return $udom.'-domainconfig';
1760: }
1761:
1.837 raeburn 1762: sub retrieve_inst_usertypes {
1763: my ($udom) = @_;
1764: my (%returnhash,@order);
1.989 raeburn 1765: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1766: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1767: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1768: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1769: } else {
1770: if (defined(&domain($udom,'primary'))) {
1771: my $uhome=&domain($udom,'primary');
1772: my $rep=&reply("inst_usertypes:$udom",$uhome);
1773: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1774: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1775: return (\%returnhash,\@order);
1776: }
1777: my ($hashitems,$orderitems) = split(/:/,$rep);
1778: my @pairs=split(/\&/,$hashitems);
1779: foreach my $item (@pairs) {
1780: my ($key,$value)=split(/=/,$item,2);
1781: $key = &unescape($key);
1782: next if ($key =~ /^error: 2 /);
1783: $returnhash{$key}=&thaw_unescape($value);
1784: }
1785: my @esc_order = split(/\&/,$orderitems);
1786: foreach my $item (@esc_order) {
1787: push(@order,&unescape($item));
1788: }
1789: } else {
1.1256 raeburn 1790: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1791: }
1.1256 raeburn 1792: return (\%returnhash,\@order);
1.837 raeburn 1793: }
1794: }
1795:
1.868 raeburn 1796: sub is_domainimage {
1797: my ($url) = @_;
1798: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1799: if (&domain($1) ne '') {
1800: return '1';
1801: }
1802: }
1803: return;
1804: }
1805:
1.899 raeburn 1806: sub inst_directory_query {
1807: my ($srch) = @_;
1808: my $udom = $srch->{'srchdomain'};
1809: my %results;
1810: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1811: my $outcome;
1.899 raeburn 1812: if ($homeserver ne '') {
1.904 albertel 1813: my $queryid=&reply("querysend:instdirsearch:".
1814: &escape($srch->{'srchby'}).':'.
1815: &escape($srch->{'srchterm'}).':'.
1816: &escape($srch->{'srchtype'}),$homeserver);
1817: my $host=&hostname($homeserver);
1818: if ($queryid !~/^\Q$host\E\_/) {
1819: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1820: return;
1821: }
1822: my $response = &get_query_reply($queryid);
1823: my $maxtries = 5;
1824: my $tries = 1;
1825: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1826: $response = &get_query_reply($queryid);
1827: $tries ++;
1828: }
1829:
1830: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1831: if ($response eq 'unavailable') {
1832: $outcome = $response;
1833: } else {
1834: $outcome = 'ok';
1835: my @matches = split(/\n/,$response);
1836: foreach my $match (@matches) {
1837: my ($key,$value) = split(/=/,$match);
1838: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1839: }
1.899 raeburn 1840: }
1841: }
1842: }
1.909 raeburn 1843: return ($outcome,%results);
1.899 raeburn 1844: }
1845:
1846: sub usersearch {
1847: my ($srch) = @_;
1848: my $dom = $srch->{'srchdomain'};
1849: my %results;
1850: my %libserv = &all_library();
1851: my $query = 'usersearch';
1852: foreach my $tryserver (keys(%libserv)) {
1853: if (&host_domain($tryserver) eq $dom) {
1854: my $host=&hostname($tryserver);
1855: my $queryid=
1.911 raeburn 1856: &reply("querysend:".&escape($query).':'.
1857: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1858: &escape($srch->{'srchtype'}).':'.
1859: &escape($srch->{'srchterm'}),$tryserver);
1860: if ($queryid !~/^\Q$host\E\_/) {
1861: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1862: next;
1.899 raeburn 1863: }
1864: my $reply = &get_query_reply($queryid);
1865: my $maxtries = 1;
1866: my $tries = 1;
1867: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1868: $reply = &get_query_reply($queryid);
1869: $tries ++;
1870: }
1871: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1872: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1873: } else {
1.911 raeburn 1874: my @matches;
1875: if ($reply =~ /\n/) {
1876: @matches = split(/\n/,$reply);
1877: } else {
1878: @matches = split(/\&/,$reply);
1879: }
1.899 raeburn 1880: foreach my $match (@matches) {
1881: my ($uname,$udom,%userhash);
1.911 raeburn 1882: foreach my $entry (split(/:/,$match)) {
1883: my ($key,$value) =
1884: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1885: $userhash{$key} = $value;
1886: if ($key eq 'username') {
1887: $uname = $value;
1888: } elsif ($key eq 'domain') {
1889: $udom = $value;
1.911 raeburn 1890: }
1.899 raeburn 1891: }
1892: $results{$uname.':'.$udom} = \%userhash;
1893: }
1894: }
1895: }
1896: }
1897: return %results;
1898: }
1899:
1.912 raeburn 1900: sub get_instuser {
1901: my ($udom,$uname,$id) = @_;
1902: my $homeserver = &domain($udom,'primary');
1903: my ($outcome,%results);
1904: if ($homeserver ne '') {
1905: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1906: &escape($id).':'.&escape($udom),$homeserver);
1907: my $host=&hostname($homeserver);
1908: if ($queryid !~/^\Q$host\E\_/) {
1909: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1910: return;
1911: }
1912: my $response = &get_query_reply($queryid);
1913: my $maxtries = 5;
1914: my $tries = 1;
1915: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1916: $response = &get_query_reply($queryid);
1917: $tries ++;
1918: }
1919: if (!&error($response) && $response ne 'refused') {
1920: if ($response eq 'unavailable') {
1921: $outcome = $response;
1922: } else {
1923: $outcome = 'ok';
1924: my @matches = split(/\n/,$response);
1925: foreach my $match (@matches) {
1926: my ($key,$value) = split(/=/,$match);
1927: $results{&unescape($key)} = &thaw_unescape($value);
1928: }
1929: }
1930: }
1931: }
1932: my %userinfo;
1933: if (ref($results{$uname}) eq 'HASH') {
1934: %userinfo = %{$results{$uname}};
1935: }
1936: return ($outcome,%userinfo);
1937: }
1938:
1939: sub inst_rulecheck {
1.923 raeburn 1940: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1941: my %returnhash;
1942: if ($udom ne '') {
1943: if (ref($rules) eq 'ARRAY') {
1944: @{$rules} = map {&escape($_);} (@{$rules});
1945: my $rulestr = join(':',@{$rules});
1946: my $homeserver=&domain($udom,'primary');
1947: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1948: my $response;
1949: if ($item eq 'username') {
1950: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1951: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1952: $homeserver));
1.923 raeburn 1953: } elsif ($item eq 'id') {
1954: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1955: ':'.&escape($id).':'.$rulestr,
1956: $homeserver));
1.945 raeburn 1957: } elsif ($item eq 'selfcreate') {
1958: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1959: &escape($udom).':'.&escape($uname).
1960: ':'.$rulestr,$homeserver));
1.923 raeburn 1961: }
1.912 raeburn 1962: if ($response ne 'refused') {
1963: my @pairs=split(/\&/,$response);
1964: foreach my $item (@pairs) {
1965: my ($key,$value)=split(/=/,$item,2);
1966: $key = &unescape($key);
1967: next if ($key =~ /^error: 2 /);
1968: $returnhash{$key}=&thaw_unescape($value);
1969: }
1970: }
1971: }
1972: }
1973: }
1974: return %returnhash;
1975: }
1976:
1977: sub inst_userrules {
1.923 raeburn 1978: my ($udom,$check) = @_;
1.912 raeburn 1979: my (%ruleshash,@ruleorder);
1980: if ($udom ne '') {
1981: my $homeserver=&domain($udom,'primary');
1982: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1983: my $response;
1984: if ($check eq 'id') {
1985: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1986: $homeserver);
1.943 raeburn 1987: } elsif ($check eq 'email') {
1988: $response=&reply('instemailrules:'.&escape($udom),
1989: $homeserver);
1.923 raeburn 1990: } else {
1991: $response=&reply('instuserrules:'.&escape($udom),
1992: $homeserver);
1993: }
1.912 raeburn 1994: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1995: ($response ne 'unknown_cmd') &&
1.912 raeburn 1996: ($response ne 'no_such_host')) {
1997: my ($hashitems,$orderitems) = split(/:/,$response);
1998: my @pairs=split(/\&/,$hashitems);
1999: foreach my $item (@pairs) {
2000: my ($key,$value)=split(/=/,$item,2);
2001: $key = &unescape($key);
2002: next if ($key =~ /^error: 2 /);
2003: $ruleshash{$key}=&thaw_unescape($value);
2004: }
2005: my @esc_order = split(/\&/,$orderitems);
2006: foreach my $item (@esc_order) {
2007: push(@ruleorder,&unescape($item));
2008: }
2009: }
2010: }
2011: }
2012: return (\%ruleshash,\@ruleorder);
2013: }
2014:
1.976 raeburn 2015: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2016:
2017: sub get_domain_defaults {
1.1240 raeburn 2018: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2019: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2020: my $cachetime = 60*60*24;
1.1240 raeburn 2021: unless ($ignore_cache) {
2022: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2023: if (defined($cached)) {
2024: if (ref($result) eq 'HASH') {
2025: return %{$result};
2026: }
1.943 raeburn 2027: }
2028: }
2029: my %domdefaults;
2030: my %domconfig =
1.989 raeburn 2031: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2032: 'requestcourses','inststatus',
1.1183 raeburn 2033: 'coursedefaults','usersessions',
1.1258 raeburn 2034: 'requestauthor','selfenrollment',
2035: 'coursecategories'],$domain);
1.1254 raeburn 2036: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2037: if (ref($domconfig{'defaults'}) eq 'HASH') {
2038: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2039: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2040: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2041: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2042: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2043: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2044: } else {
2045: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2046: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2047: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2048: }
1.976 raeburn 2049: if (ref($domconfig{'quotas'}) eq 'HASH') {
2050: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2051: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2052: } else {
2053: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2054: }
1.1177 raeburn 2055: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2056: foreach my $item (@usertools) {
2057: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2058: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2059: }
2060: }
1.1229 raeburn 2061: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2062: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2063: }
1.976 raeburn 2064: }
1.985 raeburn 2065: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246 raeburn 2066: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2067: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2068: }
2069: }
1.1183 raeburn 2070: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2071: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2072: }
1.989 raeburn 2073: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2074: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2075: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2076: }
2077: }
1.1047 raeburn 2078: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2079: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2080: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2081: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2082: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2083: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2084: }
1.1254 raeburn 2085: foreach my $type (@coursetypes) {
2086: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2087: unless ($type eq 'community') {
2088: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2089: }
2090: }
2091: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2092: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2093: }
1.1277 raeburn 2094: if ($domdefaults{'postsubmit'} eq 'on') {
2095: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2096: $domdefaults{$type.'postsubtimeout'} =
2097: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2098: }
2099: }
1.1230 raeburn 2100: }
1.1047 raeburn 2101: }
1.1073 raeburn 2102: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2103: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2104: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2105: }
2106: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2107: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2108: }
2109: }
1.1254 raeburn 2110: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2111: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2112: my @settings = ('types','registered','enroll_dates','access_dates','section',
2113: 'approval','limit');
2114: foreach my $type (@coursetypes) {
2115: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2116: my @mgrdc = ();
2117: foreach my $item (@settings) {
2118: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2119: push(@mgrdc,$item);
2120: }
2121: }
2122: if (@mgrdc) {
2123: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2124: }
2125: }
2126: }
2127: }
2128: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2129: foreach my $type (@coursetypes) {
2130: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2131: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2132: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2133: }
2134: }
2135: }
2136: }
2137: }
1.1258 raeburn 2138: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2139: $domdefaults{'catauth'} = 'std';
2140: $domdefaults{'catunauth'} = 'std';
2141: if ($domconfig{'coursecategories'}{'auth'}) {
2142: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2143: }
2144: if ($domconfig{'coursecategories'}{'unauth'}) {
2145: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2146: }
2147: }
1.1219 raeburn 2148: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2149: return %domdefaults;
2150: }
2151:
1.344 www 2152: # --------------------------------------------------- Assign a key to a student
2153:
2154: sub assign_access_key {
1.364 www 2155: #
2156: # a valid key looks like uname:udom#comments
2157: # comments are being appended
2158: #
1.498 www 2159: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2160: $kdom=
1.620 albertel 2161: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2162: $knum=
1.620 albertel 2163: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2164: $cdom=
1.620 albertel 2165: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2166: $cnum=
1.620 albertel 2167: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2168: $udom=$env{'user.name'} unless (defined($udom));
2169: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2170: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2171: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2172: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2173: # assigned to this person
2174: # - this should not happen,
1.345 www 2175: # unless something went wrong
2176: # the first time around
2177: # ready to assign
1.364 www 2178: $logentry=$1.'; '.$logentry;
1.496 www 2179: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2180: $kdom,$knum) eq 'ok') {
1.345 www 2181: # key now belongs to user
1.346 www 2182: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2183: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2184: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2185: return 'ok';
2186: } else {
2187: return
2188: 'error: Count not permanently assign key, will need to be re-entered later.';
2189: }
2190: } else {
2191: return 'error: Could not assign key, try again later.';
2192: }
1.364 www 2193: } elsif (!$existing{$ckey}) {
1.345 www 2194: # the key does not exist
2195: return 'error: The key does not exist';
2196: } else {
2197: # the key is somebody else's
2198: return 'error: The key is already in use';
2199: }
1.344 www 2200: }
2201:
1.364 www 2202: # ------------------------------------------ put an additional comment on a key
2203:
2204: sub comment_access_key {
2205: #
2206: # a valid key looks like uname:udom#comments
2207: # comments are being appended
2208: #
2209: my ($ckey,$cdom,$cnum,$logentry)=@_;
2210: $cdom=
1.620 albertel 2211: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2212: $cnum=
1.620 albertel 2213: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2214: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2215: if ($existing{$ckey}) {
2216: $existing{$ckey}.='; '.$logentry;
2217: # ready to assign
1.367 www 2218: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2219: $cdom,$cnum) eq 'ok') {
2220: return 'ok';
2221: } else {
2222: return 'error: Count not store comment.';
2223: }
2224: } else {
2225: # the key does not exist
2226: return 'error: The key does not exist';
2227: }
2228: }
2229:
1.344 www 2230: # ------------------------------------------------------ Generate a set of keys
2231:
2232: sub generate_access_keys {
1.364 www 2233: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2234: $cdom=
1.620 albertel 2235: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2236: $cnum=
1.620 albertel 2237: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2238: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2239: unless (($cdom) && ($cnum)) { return 0; }
2240: if ($number>10000) { return 0; }
2241: sleep(2); # make sure don't get same seed twice
2242: srand(time()^($$+($$<<15))); # from "Programming Perl"
2243: my $total=0;
2244: for (my $i=1;$i<=$number;$i++) {
2245: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2246: sprintf("%lx",int(100000*rand)).'-'.
2247: sprintf("%lx",int(100000*rand));
2248: $newkey=~s/1/g/g; # folks mix up 1 and l
2249: $newkey=~s/0/h/g; # and also 0 and O
2250: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2251: if ($existing{$newkey}) {
2252: $i--;
2253: } else {
1.364 www 2254: if (&put('accesskeys',
2255: { $newkey => '# generated '.localtime().
1.620 albertel 2256: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2257: '; '.$logentry },
2258: $cdom,$cnum) eq 'ok') {
1.344 www 2259: $total++;
2260: }
2261: }
2262: }
1.620 albertel 2263: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2264: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2265: return $total;
2266: }
2267:
2268: # ------------------------------------------------------- Validate an accesskey
2269:
2270: sub validate_access_key {
2271: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2272: $cdom=
1.620 albertel 2273: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2274: $cnum=
1.620 albertel 2275: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2276: $udom=$env{'user.domain'} unless (defined($udom));
2277: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2278: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2279: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2280: }
2281:
2282: # ------------------------------------- Find the section of student in a course
1.652 albertel 2283: sub devalidate_getsection_cache {
2284: my ($udom,$unam,$courseid)=@_;
2285: my $hashid="$udom:$unam:$courseid";
2286: &devalidate_cache_new('getsection',$hashid);
2287: }
1.298 matthew 2288:
1.815 albertel 2289: sub courseid_to_courseurl {
2290: my ($courseid) = @_;
2291: #already url style courseid
2292: return $courseid if ($courseid =~ m{^/});
2293:
2294: if (exists($env{'course.'.$courseid.'.num'})) {
2295: my $cnum = $env{'course.'.$courseid.'.num'};
2296: my $cdom = $env{'course.'.$courseid.'.domain'};
2297: return "/$cdom/$cnum";
2298: }
2299:
2300: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2301: if (exists($courseinfo{'num'})) {
2302: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2303: }
2304:
2305: return undef;
2306: }
2307:
1.298 matthew 2308: sub getsection {
2309: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2310: my $cachetime=1800;
1.551 albertel 2311:
2312: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2313: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2314: if (defined($cached)) { return $result; }
2315:
1.298 matthew 2316: my %Pending;
2317: my %Expired;
2318: #
2319: # Each role can either have not started yet (pending), be active,
2320: # or have expired.
2321: #
2322: # If there is an active role, we are done.
2323: #
2324: # If there is more than one role which has not started yet,
2325: # choose the one which will start sooner
2326: # If there is one role which has not started yet, return it.
2327: #
2328: # If there is more than one expired role, choose the one which ended last.
2329: # If there is a role which has expired, return it.
2330: #
1.815 albertel 2331: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2332: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2333: foreach my $key (keys(%roleshash)) {
1.479 albertel 2334: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2335: my $section=$1;
2336: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2337: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2338: my $now=time;
1.548 albertel 2339: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2340: $Expired{$end}=$section;
2341: next;
2342: }
1.548 albertel 2343: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2344: $Pending{$start}=$section;
2345: next;
2346: }
1.599 albertel 2347: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2348: }
2349: #
2350: # Presumedly there will be few matching roles from the above
2351: # loop and the sorting time will be negligible.
2352: if (scalar(keys(%Pending))) {
2353: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2354: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2355: }
2356: if (scalar(keys(%Expired))) {
2357: my @sorted = sort {$a <=> $b} keys(%Expired);
2358: my $time = pop(@sorted);
1.599 albertel 2359: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2360: }
1.599 albertel 2361: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2362: }
1.70 www 2363:
1.599 albertel 2364: sub save_cache {
2365: &purge_remembered();
1.722 albertel 2366: #&Apache::loncommon::validate_page();
1.620 albertel 2367: undef(%env);
1.780 albertel 2368: undef($env_loaded);
1.599 albertel 2369: }
1.452 albertel 2370:
1.599 albertel 2371: my $to_remember=-1;
2372: my %remembered;
2373: my %accessed;
2374: my $kicks=0;
2375: my $hits=0;
1.849 albertel 2376: sub make_key {
2377: my ($name,$id) = @_;
1.872 albertel 2378: if (length($id) > 65
2379: && length(&escape($id)) > 200) {
2380: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2381: }
1.849 albertel 2382: return &escape($name.':'.$id);
2383: }
2384:
1.599 albertel 2385: sub devalidate_cache_new {
2386: my ($name,$id,$debug) = @_;
2387: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2388: $id=&make_key($name,$id);
1.599 albertel 2389: $memcache->delete($id);
2390: delete($remembered{$id});
2391: delete($accessed{$id});
2392: }
2393:
2394: sub is_cached_new {
2395: my ($name,$id,$debug) = @_;
1.849 albertel 2396: $id=&make_key($name,$id);
1.599 albertel 2397: if (exists($remembered{$id})) {
1.1133 foxr 2398: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2399: $accessed{$id}=[&gettimeofday()];
2400: $hits++;
2401: return ($remembered{$id},1);
2402: }
2403: my $value = $memcache->get($id);
2404: if (!(defined($value))) {
2405: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2406: return (undef,undef);
1.416 albertel 2407: }
1.599 albertel 2408: if ($value eq '__undef__') {
2409: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2410: $value=undef;
2411: }
2412: &make_room($id,$value,$debug);
2413: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2414: return ($value,1);
2415: }
2416:
2417: sub do_cache_new {
2418: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2419: $id=&make_key($name,$id);
1.599 albertel 2420: my $setvalue=$value;
2421: if (!defined($setvalue)) {
2422: $setvalue='__undef__';
2423: }
1.623 albertel 2424: if (!defined($time) ) {
2425: $time=600;
2426: }
1.599 albertel 2427: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2428: my $result = $memcache->set($id,$setvalue,$time);
2429: if (! $result) {
1.872 albertel 2430: &logthis("caching of id -> $id failed");
1.910 albertel 2431: $memcache->disconnect_all();
1.872 albertel 2432: }
1.600 albertel 2433: # need to make a copy of $value
1.919 albertel 2434: &make_room($id,$value,$debug);
1.599 albertel 2435: return $value;
2436: }
2437:
2438: sub make_room {
2439: my ($id,$value,$debug)=@_;
1.919 albertel 2440:
2441: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2442: : $value;
1.599 albertel 2443: if ($to_remember<0) { return; }
2444: $accessed{$id}=[&gettimeofday()];
2445: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2446: my $to_kick;
2447: my $max_time=0;
2448: foreach my $other (keys(%accessed)) {
2449: if (&tv_interval($accessed{$other}) > $max_time) {
2450: $to_kick=$other;
2451: $max_time=&tv_interval($accessed{$other});
2452: }
2453: }
2454: delete($remembered{$to_kick});
2455: delete($accessed{$to_kick});
2456: $kicks++;
2457: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2458: return;
2459: }
2460:
1.599 albertel 2461: sub purge_remembered {
1.604 albertel 2462: #&logthis("Tossing ".scalar(keys(%remembered)));
2463: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2464: undef(%remembered);
2465: undef(%accessed);
1.428 albertel 2466: }
1.70 www 2467: # ------------------------------------- Read an entry from a user's environment
2468:
2469: sub userenvironment {
2470: my ($udom,$unam,@what)=@_;
1.976 raeburn 2471: my $items;
2472: foreach my $item (@what) {
2473: $items.=&escape($item).'&';
2474: }
2475: $items=~s/\&$//;
1.70 www 2476: my %returnhash=();
1.1009 raeburn 2477: my $uhome = &homeserver($unam,$udom);
2478: unless ($uhome eq 'no_host') {
2479: my @answer=split(/\&/,
2480: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2481: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2482: return %returnhash;
2483: }
1.1009 raeburn 2484: my $i;
2485: for ($i=0;$i<=$#what;$i++) {
2486: $returnhash{$what[$i]}=&unescape($answer[$i]);
2487: }
1.70 www 2488: }
2489: return %returnhash;
1.1 albertel 2490: }
2491:
1.617 albertel 2492: # ---------------------------------------------------------- Get a studentphoto
2493: sub studentphoto {
2494: my ($udom,$unam,$ext) = @_;
2495: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2496: if (defined($env{'request.course.id'})) {
1.708 raeburn 2497: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2498: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2499: return(&retrievestudentphoto($udom,$unam,$ext));
2500: } else {
2501: my ($result,$perm_reqd)=
1.707 albertel 2502: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2503: if ($result eq 'ok') {
2504: if (!($perm_reqd eq 'yes')) {
2505: return(&retrievestudentphoto($udom,$unam,$ext));
2506: }
2507: }
2508: }
2509: }
2510: } else {
2511: my ($result,$perm_reqd) =
1.707 albertel 2512: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2513: if ($result eq 'ok') {
2514: if (!($perm_reqd eq 'yes')) {
2515: return(&retrievestudentphoto($udom,$unam,$ext));
2516: }
2517: }
2518: }
2519: return '/adm/lonKaputt/lonlogo_broken.gif';
2520: }
2521:
2522: sub retrievestudentphoto {
2523: my ($udom,$unam,$ext,$type) = @_;
2524: my $home=&Apache::lonnet::homeserver($unam,$udom);
2525: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2526: if ($ret eq 'ok') {
2527: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2528: if ($type eq 'thumbnail') {
2529: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2530: }
2531: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2532: return $tokenurl;
2533: } else {
2534: if ($type eq 'thumbnail') {
2535: return '/adm/lonKaputt/genericstudent_tn.gif';
2536: } else {
2537: return '/adm/lonKaputt/lonlogo_broken.gif';
2538: }
1.617 albertel 2539: }
2540: }
2541:
1.263 www 2542: # -------------------------------------------------------------------- New chat
2543:
2544: sub chatsend {
1.724 raeburn 2545: my ($newentry,$anon,$group)=@_;
1.620 albertel 2546: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2547: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2548: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2549: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2550: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2551: &escape($newentry)).':'.$group,$chome);
1.292 www 2552: }
2553:
2554: # ------------------------------------------ Find current version of a resource
2555:
2556: sub getversion {
2557: my $fname=&clutter(shift);
1.1189 raeburn 2558: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2559: return ¤tversion(&filelocation('',$fname));
2560: }
2561:
2562: sub currentversion {
2563: my $fname=shift;
2564: my $author=$fname;
2565: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2566: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2567: my $home=&homeserver($uname,$udom);
1.292 www 2568: if ($home eq 'no_host') {
2569: return -1;
2570: }
1.1112 www 2571: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2572: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2573: return -1;
2574: }
1.1112 www 2575: return $answer;
1.263 www 2576: }
2577:
1.1111 www 2578: #
2579: # Return special version number of resource if set by override, empty otherwise
2580: #
2581: sub usedversion {
2582: my $fname=shift;
2583: unless ($fname) { $fname=$env{'request.uri'}; }
2584: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2585: if ($urlversion) { return $urlversion; }
2586: return '';
2587: }
2588:
1.1 albertel 2589: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2590:
1.1 albertel 2591: sub subscribe {
2592: my $fname=shift;
1.761 raeburn 2593: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2594: $fname=~s/[\n\r]//g;
1.1 albertel 2595: my $author=$fname;
2596: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2597: my ($udom,$uname)=split(/\//,$author);
2598: my $home=homeserver($uname,$udom);
1.335 albertel 2599: if ($home eq 'no_host') {
2600: return 'not_found';
1.1 albertel 2601: }
2602: my $answer=reply("sub:$fname",$home);
1.64 www 2603: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2604: $answer.=' by '.$home;
2605: }
1.1 albertel 2606: return $answer;
2607: }
2608:
1.8 www 2609: # -------------------------------------------------------------- Replicate file
2610:
2611: sub repcopy {
2612: my $filename=shift;
1.23 www 2613: $filename=~s/\/+/\//g;
1.1142 raeburn 2614: my $londocroot = $perlvar{'lonDocRoot'};
2615: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2616: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2617: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2618: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2619: return &repcopy_userfile($filename);
2620: }
1.532 albertel 2621: $filename=~s/[\n\r]//g;
1.8 www 2622: my $transname="$filename.in.transfer";
1.828 www 2623: # FIXME: this should flock
1.607 raeburn 2624: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2625: my $remoteurl=subscribe($filename);
1.64 www 2626: if ($remoteurl =~ /^con_lost by/) {
2627: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2628: return 'unavailable';
1.8 www 2629: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2630: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2631: return 'not_found';
1.64 www 2632: } elsif ($remoteurl =~ /^rejected by/) {
2633: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2634: return 'forbidden';
1.20 www 2635: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2636: return 'ok';
1.8 www 2637: } else {
1.290 www 2638: my $author=$filename;
2639: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2640: my ($udom,$uname)=split(/\//,$author);
2641: my $home=homeserver($uname,$udom);
2642: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2643: my @parts=split(/\//,$filename);
2644: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2645: if ($path ne "$londocroot/res") {
1.8 www 2646: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2647: return 'bad_request';
1.8 www 2648: }
2649: my $count;
2650: for ($count=5;$count<$#parts;$count++) {
2651: $path.="/$parts[$count]";
2652: if ((-e $path)!=1) {
2653: mkdir($path,0777);
2654: }
2655: }
2656: my $ua=new LWP::UserAgent;
2657: my $request=new HTTP::Request('GET',"$remoteurl");
2658: my $response=$ua->request($request,$transname);
2659: if ($response->is_error()) {
2660: unlink($transname);
2661: my $message=$response->status_line;
1.672 albertel 2662: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2663: ." LWP get: $message: $filename</font>");
1.607 raeburn 2664: return 'unavailable';
1.8 www 2665: } else {
1.16 www 2666: if ($remoteurl!~/\.meta$/) {
2667: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2668: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2669: if ($mresponse->is_error()) {
2670: unlink($filename.'.meta');
2671: &logthis(
1.672 albertel 2672: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2673: }
2674: }
1.8 www 2675: rename($transname,$filename);
1.607 raeburn 2676: return 'ok';
1.8 www 2677: }
1.290 www 2678: }
1.8 www 2679: }
1.330 www 2680: }
2681:
2682: # ------------------------------------------------ Get server side include body
2683: sub ssi_body {
1.381 albertel 2684: my ($filelink,%form)=@_;
1.606 matthew 2685: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2686: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2687: }
1.953 www 2688: my $output='';
2689: my $response;
1.980 raeburn 2690: if ($filelink=~/^https?\:/) {
1.954 raeburn 2691: ($output,$response)=&externalssi($filelink);
1.953 www 2692: } else {
1.1004 droeschl 2693: $filelink .= $filelink=~/\?/ ? '&' : '?';
2694: $filelink .= 'inhibitmenu=yes';
1.953 www 2695: ($output,$response)=&ssi($filelink,%form);
2696: }
1.778 albertel 2697: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2698: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2699: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2700: if (wantarray) {
2701: return ($output, $response);
2702: } else {
2703: return $output;
2704: }
1.8 www 2705: }
2706:
1.15 www 2707: # --------------------------------------------------------- Server Side Include
2708:
1.782 albertel 2709: sub absolute_url {
2710: my ($host_name) = @_;
2711: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2712: if ($host_name eq '') {
2713: $host_name = $ENV{'SERVER_NAME'};
2714: }
2715: return $protocol.$host_name;
2716: }
2717:
1.942 foxr 2718: #
2719: # Server side include.
2720: # Parameters:
2721: # fn Possibly encrypted resource name/id.
2722: # form Hash that describes how the rendering should be done
2723: # and other things.
1.944 foxr 2724: # Returns:
1.950 raeburn 2725: # Scalar context: The content of the response.
2726: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2727: #
1.15 www 2728: sub ssi {
2729:
1.944 foxr 2730: my ($fn,%form)=@_;
1.15 www 2731: my $ua=new LWP::UserAgent;
1.23 www 2732: my $request;
1.711 albertel 2733:
2734: $form{'no_update_last_known'}=1;
1.895 albertel 2735: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2736: if (%form) {
1.782 albertel 2737: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 2738: $request->content(join('&',map {
2739: my $name = escape($_);
2740: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2741: ? join("&$name=", map {escape($_) } @{$form{$_}})
2742: : &escape($form{$_}) );
2743: } keys(%form)));
1.23 www 2744: } else {
1.782 albertel 2745: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2746: }
2747:
1.15 www 2748: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2749: my $response= $ua->request($request);
1.1182 foxr 2750: my $content = $response->content;
2751:
2752:
1.944 foxr 2753: if (wantarray) {
1.1173 foxr 2754: return ($content, $response);
1.944 foxr 2755: } else {
1.1173 foxr 2756: return $content;
1.942 foxr 2757: }
1.324 www 2758: }
2759:
2760: sub externalssi {
2761: my ($url)=@_;
2762: my $ua=new LWP::UserAgent;
2763: my $request=new HTTP::Request('GET',$url);
2764: my $response=$ua->request($request);
1.954 raeburn 2765: if (wantarray) {
2766: return ($response->content, $response);
2767: } else {
2768: return $response->content;
2769: }
1.15 www 2770: }
1.254 www 2771:
1.492 albertel 2772: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2773:
2774: sub allowuploaded {
2775: my ($srcurl,$url)=@_;
2776: $url=&clutter(&declutter($url));
2777: my $dir=$url;
2778: $dir=~s/\/[^\/]+$//;
2779: my %httpref=();
2780: my $httpurl=&hreflocation('',$url);
2781: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2782: &Apache::lonnet::appenv(\%httpref);
1.254 www 2783: }
1.477 raeburn 2784:
1.1193 raeburn 2785: #
2786: # Determine if the current user should be able to edit a particular resource,
2787: # when viewing in course context.
2788: # (a) When viewing resource used to determine if "Edit" item is included in
2789: # Functions.
2790: # (b) When displaying folder contents in course editor, used to determine if
2791: # "Edit" link will be displayed alongside resource.
2792: #
1.1196 raeburn 2793: # input: six args -- filename (decluttered), course number, course domain,
2794: # url, symb (if registered) and group (if this is a group
2795: # item -- e.g., bulletin board, group page etc.).
2796: # output: array of five scalars --
1.1193 raeburn 2797: # $cfile -- url for file editing if editable on current server
2798: # $home -- homeserver of resource (i.e., for author if published,
2799: # or course if uploaded.).
2800: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2801: # $forceedit -- 1 if icon/link should be to go to edit mode
2802: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2803: #
2804:
2805: sub can_edit_resource {
1.1194 raeburn 2806: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2807: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2808: #
2809: # For aboutme pages user can only edit his/her own.
2810: #
1.1199 raeburn 2811: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2812: my ($sdom,$sname) = ($1,$2);
2813: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2814: $home = $env{'user.home'};
2815: $cfile = $resurl;
2816: if ($env{'form.forceedit'}) {
2817: $forceview = 1;
2818: } else {
2819: $forceedit = 1;
2820: }
2821: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2822: } else {
2823: return;
2824: }
2825: }
2826:
2827: if ($env{'request.course.id'}) {
2828: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2829: if ($group ne '') {
2830: # if this is a group homepage or group bulletin board, check group privs
2831: my $allowed = 0;
1.1197 raeburn 2832: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2833: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2834: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2835: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2836: $allowed = 1;
2837: }
1.1197 raeburn 2838: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2839: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2840: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2841: $allowed = 1;
2842: }
2843: }
2844: if ($allowed) {
2845: $home=&homeserver($cnum,$cdom);
2846: if ($env{'form.forceedit'}) {
2847: $forceview = 1;
2848: } else {
2849: $forceedit = 1;
2850: }
2851: $cfile = $resurl;
2852: } else {
2853: return;
2854: }
2855: } else {
1.1208 raeburn 2856: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2857: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2858: return;
2859: }
2860: } elsif (!$crsedit) {
1.1194 raeburn 2861: #
2862: # No edit allowed where CC has switched to student role.
2863: #
2864: return;
2865: }
2866: }
2867: }
2868:
1.1193 raeburn 2869: if ($file ne '') {
2870: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2871: if (&is_course_upload($file,$cnum,$cdom)) {
2872: $uploaded = 1;
2873: $incourse = 1;
1.1193 raeburn 2874: if ($file =~/\.(htm|html|css|js|txt)$/) {
2875: $cfile = &hreflocation('',$file);
1.1201 raeburn 2876: if ($env{'form.forceedit'}) {
2877: $forceview = 1;
2878: } else {
2879: $forceedit = 1;
2880: }
1.1194 raeburn 2881: }
2882: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2883: $incourse = 1;
2884: if ($env{'form.forceedit'}) {
2885: $forceview = 1;
2886: } else {
2887: $forceedit = 1;
2888: }
2889: $cfile = $resurl;
2890: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2891: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2892: $incourse = 1;
2893: if ($env{'form.forceedit'}) {
2894: $forceview = 1;
2895: } else {
2896: $forceedit = 1;
2897: }
2898: $cfile = $resurl;
1.1199 raeburn 2899: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2900: $incourse = 1;
2901: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2902: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2903: $incourse = 1;
1.1199 raeburn 2904: if ($env{'form.forceedit'}) {
2905: $forceview = 1;
2906: } else {
2907: $forceedit = 1;
2908: }
2909: $cfile = $resurl;
1.1208 raeburn 2910: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2911: $incourse = 1;
2912: if ($env{'form.forceedit'}) {
2913: $forceview = 1;
2914: } else {
2915: $forceedit = 1;
2916: }
2917: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2918: }
2919: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2920: my $template = '/res/lib/templates/simpleproblem.problem';
2921: if (&is_on_map($template)) {
2922: $incourse = 1;
2923: $forceview = 1;
2924: $cfile = $template;
1.1193 raeburn 2925: }
1.1199 raeburn 2926: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2927: $incourse = 1;
2928: if ($env{'form.forceedit'}) {
2929: $forceview = 1;
2930: } else {
2931: $forceedit = 1;
2932: }
2933: $cfile = $resurl;
2934: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2935: $incourse = 1;
2936: $forceview = 1;
2937: if ($symb) {
2938: my ($map,$id,$res)=&decode_symb($symb);
2939: $env{'request.symb'} = $symb;
2940: $cfile = &clutter($res);
2941: } else {
2942: $cfile = $env{'form.suppurl'};
2943: $cfile =~ s{^http://}{};
2944: $cfile = '/adm/wrapper/ext/'.$cfile;
2945: }
1.1234 raeburn 2946: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2947: if ($env{'form.forceedit'}) {
2948: $forceview = 1;
2949: } else {
2950: $forceedit = 1;
2951: }
2952: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2953: }
2954: }
1.1194 raeburn 2955: if ($uploaded || $incourse) {
2956: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2957: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2958: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2959: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2960: # Check that the user has permission to edit this resource
2961: my $setpriv = 1;
2962: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2963: if (defined($cfudom)) {
2964: $home=&homeserver($cfuname,$cfudom);
2965: $cfile=$file;
2966: }
2967: }
1.1194 raeburn 2968: if (($cfile ne '') && (!$incourse || $uploaded) &&
2969: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2970: my @ids=¤t_machine_ids();
2971: unless (grep(/^\Q$home\E$/,@ids)) {
2972: $switchserver=1;
2973: }
2974: }
2975: }
1.1194 raeburn 2976: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2977: }
2978:
2979: sub is_course_upload {
2980: my ($file,$cnum,$cdom) = @_;
2981: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2982: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2983: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2984: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2985: return 1;
2986: }
2987: return;
2988: }
2989:
1.1194 raeburn 2990: sub in_course {
1.1195 raeburn 2991: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2992: if ($hideprivileged) {
2993: my $skipuser;
1.1219 raeburn 2994: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2995: my @possdoms = ($cdom);
2996: if ($coursehash{'checkforpriv'}) {
2997: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2998: }
2999: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3000: $skipuser = 1;
3001: if ($coursehash{'nothideprivileged'}) {
3002: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3003: my $user;
3004: if ($item =~ /:/) {
3005: $user = $item;
3006: } else {
3007: $user = join(':',split(/[\@]/,$item));
3008: }
3009: if ($user eq $uname.':'.$udom) {
3010: undef($skipuser);
3011: last;
3012: }
3013: }
3014: }
3015: if ($skipuser) {
3016: return 0;
3017: }
3018: }
3019: }
1.1194 raeburn 3020: $type ||= 'any';
3021: if (!defined($cdom) || !defined($cnum)) {
3022: my $cid = $env{'request.course.id'};
3023: $cdom = $env{'course.'.$cid.'.domain'};
3024: $cnum = $env{'course.'.$cid.'.num'};
3025: }
3026: my $typesref;
1.1195 raeburn 3027: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3028: $typesref = ['active','previous','future'];
3029: } elsif ($type eq 'previous' || $type eq 'future') {
3030: $typesref = [$type];
3031: }
3032: my %roles = &get_my_roles($uname,$udom,'userroles',
3033: $typesref,undef,[$cdom]);
3034: my ($tmp) = keys(%roles);
3035: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3036: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3037: if (@course_roles > 0) {
3038: return 1;
3039: }
3040: return 0;
3041: }
3042:
1.478 albertel 3043: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3044: # input: action, courseID, current domain, intended
1.637 raeburn 3045: # path to file, source of file, instruction to parse file for objects,
3046: # ref to hash for embedded objects,
3047: # ref to hash for codebase of java objects.
1.1095 raeburn 3048: # reference to scalar to accommodate mime type determined
3049: # from File::MMagic if $parser = parse.
1.637 raeburn 3050: #
1.485 raeburn 3051: # output: url to file (if action was uploaddoc),
3052: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3053: #
1.478 albertel 3054: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3055: # course.
1.477 raeburn 3056: #
1.478 albertel 3057: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3058: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3059: # course's home server.
1.477 raeburn 3060: #
1.478 albertel 3061: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3062: # be copied from $source (current location) to
3063: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3064: # and will then be copied to
3065: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3066: # course's home server.
1.485 raeburn 3067: #
1.481 raeburn 3068: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3069: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3070: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3071: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3072: # in course's home server.
1.637 raeburn 3073: #
1.477 raeburn 3074:
3075: sub process_coursefile {
1.1095 raeburn 3076: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3077: $mimetype)=@_;
1.477 raeburn 3078: my $fetchresult;
1.638 albertel 3079: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3080: if ($action eq 'propagate') {
1.638 albertel 3081: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3082: $home);
1.481 raeburn 3083: } else {
1.477 raeburn 3084: my $fpath = '';
3085: my $fname = $file;
1.478 albertel 3086: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3087: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3088: my $filepath = &build_filepath($fpath);
1.481 raeburn 3089: if ($action eq 'copy') {
3090: if ($source eq '') {
3091: $fetchresult = 'no source file';
3092: return $fetchresult;
3093: } else {
3094: my $destination = $filepath.'/'.$fname;
3095: rename($source,$destination);
3096: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3097: $home);
1.481 raeburn 3098: }
3099: } elsif ($action eq 'uploaddoc') {
3100: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3101: print $fh $env{'form.'.$source};
1.481 raeburn 3102: close($fh);
1.637 raeburn 3103: if ($parser eq 'parse') {
1.1024 raeburn 3104: my $mm = new File::MMagic;
1.1095 raeburn 3105: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3106: if ($type eq 'text/html') {
1.1024 raeburn 3107: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3108: unless ($parse_result eq 'ok') {
3109: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3110: }
1.637 raeburn 3111: }
1.1095 raeburn 3112: if (ref($mimetype)) {
3113: $$mimetype = $type;
3114: }
1.637 raeburn 3115: }
1.477 raeburn 3116: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3117: $home);
1.481 raeburn 3118: if ($fetchresult eq 'ok') {
3119: return '/uploaded/'.$fpath.'/'.$fname;
3120: } else {
3121: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3122: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3123: return '/adm/notfound.html';
3124: }
1.477 raeburn 3125: }
3126: }
1.485 raeburn 3127: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3128: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3129: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3130: }
3131: return $fetchresult;
3132: }
3133:
1.637 raeburn 3134: sub build_filepath {
3135: my ($fpath) = @_;
3136: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3137: unless ($fpath eq '') {
3138: my @parts=split('/',$fpath);
3139: foreach my $part (@parts) {
3140: $filepath.= '/'.$part;
3141: if ((-e $filepath)!=1) {
3142: mkdir($filepath,0777);
3143: }
3144: }
3145: }
3146: return $filepath;
3147: }
3148:
3149: sub store_edited_file {
1.638 albertel 3150: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3151: my $file = $primary_url;
3152: $file =~ s#^/uploaded/$docudom/$docuname/##;
3153: my $fpath = '';
3154: my $fname = $file;
3155: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3156: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3157: my $filepath = &build_filepath($fpath);
3158: open(my $fh,'>'.$filepath.'/'.$fname);
3159: print $fh $content;
3160: close($fh);
1.638 albertel 3161: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3162: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3163: $home);
1.637 raeburn 3164: if ($$fetchresult eq 'ok') {
3165: return '/uploaded/'.$fpath.'/'.$fname;
3166: } else {
1.638 albertel 3167: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3168: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3169: return '/adm/notfound.html';
3170: }
3171: }
3172:
1.531 albertel 3173: sub clean_filename {
1.831 albertel 3174: my ($fname,$args)=@_;
1.315 www 3175: # Replace Windows backslashes by forward slashes
1.257 www 3176: $fname=~s/\\/\//g;
1.831 albertel 3177: if (!$args->{'keep_path'}) {
3178: # Get rid of everything but the actual filename
3179: $fname=~s/^.*\/([^\/]+)$/$1/;
3180: }
1.315 www 3181: # Replace spaces by underscores
3182: $fname=~s/\s+/\_/g;
3183: # Replace all other weird characters by nothing
1.831 albertel 3184: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3185: # Replace all .\d. sequences with _\d. so they no longer look like version
3186: # numbers
3187: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3188: return $fname;
3189: }
1.1051 raeburn 3190: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3191: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3192: # image with the same aspect ratio as the original, but with dimensions which do
3193: # not exceed $resizewidth and $resizeheight.
3194:
1.984 neumanie 3195: sub resizeImage {
1.1051 raeburn 3196: my ($img_path,$resizewidth,$resizeheight) = @_;
3197: my $ima = Image::Magick->new;
3198: my $resized;
3199: if (-e $img_path) {
3200: $ima->Read($img_path);
3201: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3202: my $width = $ima->Get('width');
3203: my $height = $ima->Get('height');
3204: if ($width > $resizewidth) {
3205: my $factor = $width/$resizewidth;
3206: my $newheight = $height/$factor;
3207: $ima->Scale(width=>$resizewidth,height=>$newheight);
3208: $resized = 1;
3209: }
3210: }
3211: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3212: my $width = $ima->Get('width');
3213: my $height = $ima->Get('height');
3214: if ($height > $resizeheight) {
3215: my $factor = $height/$resizeheight;
3216: my $newwidth = $width/$factor;
3217: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3218: $resized = 1;
3219: }
3220: }
3221: if ($resized) {
3222: $ima->Write($img_path);
3223: }
3224: }
3225: return;
1.977 amueller 3226: }
3227:
1.608 albertel 3228: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3229: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3230: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3231: # $context - possible values: coursedoc, existingfile, overwrite,
3232: # canceloverwrite, or ''.
3233: # if 'coursedoc': upload to the current course
3234: # if 'existingfile': write file to tmp/overwrites directory
3235: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3236: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3237: # $subdir - directory in userfile to store the file into
1.858 raeburn 3238: # $parser - instruction to parse file for objects ($parser = parse)
3239: # $allfiles - reference to hash for embedded objects
3240: # $codebase - reference to hash for codebase of java objects
3241: # $desuname - username for permanent storage of uploaded file
3242: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3243: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3244: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3245: # $resizewidth - width (pixels) to which to resize uploaded image
3246: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3247: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3248: # from File::MMagic.
1.858 raeburn 3249: #
1.686 albertel 3250: # output: url of file in userspace, or error: <message>
3251: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3252:
1.531 albertel 3253: sub userfileupload {
1.1090 raeburn 3254: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3255: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3256: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3257: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3258: $fname=&clean_filename($fname);
1.1090 raeburn 3259: # See if there is anything left
1.257 www 3260: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3261: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3262: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3263: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3264: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3265: my $now = time;
1.1090 raeburn 3266: my $filepath;
1.1095 raeburn 3267: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3268: $filepath = 'tmp/helprequests/'.$now;
3269: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3270: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3271: '_'.$env{'user.domain'}.'/pending';
3272: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3273: my ($docuname,$docudom);
3274: if ($destudom) {
3275: $docudom = $destudom;
3276: } else {
3277: $docudom = $env{'user.domain'};
3278: }
3279: if ($destuname) {
3280: $docuname = $destuname;
3281: } else {
3282: $docuname = $env{'user.name'};
3283: }
3284: if (exists($env{'form.group'})) {
3285: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3286: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3287: }
3288: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3289: if ($context eq 'canceloverwrite') {
3290: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3291: if (-e $tempfile) {
3292: my @info = stat($tempfile);
3293: if ($info[9] eq $env{'form.timestamp'}) {
3294: unlink($tempfile);
3295: }
3296: }
3297: return;
1.523 raeburn 3298: }
3299: }
1.1090 raeburn 3300: # Create the directory if not present
1.741 raeburn 3301: my @parts=split(/\//,$filepath);
3302: my $fullpath = $perlvar{'lonDaemons'};
3303: for (my $i=0;$i<@parts;$i++) {
3304: $fullpath .= '/'.$parts[$i];
3305: if ((-e $fullpath)!=1) {
3306: mkdir($fullpath,0777);
3307: }
3308: }
3309: open(my $fh,'>'.$fullpath.'/'.$fname);
3310: print $fh $env{'form.'.$formname};
3311: close($fh);
1.1090 raeburn 3312: if ($context eq 'existingfile') {
3313: my @info = stat($fullpath.'/'.$fname);
3314: return ($fullpath.'/'.$fname,$info[9]);
3315: } else {
3316: return $fullpath.'/'.$fname;
3317: }
1.523 raeburn 3318: }
1.995 raeburn 3319: if ($subdir eq 'scantron') {
3320: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3321: } else {
1.995 raeburn 3322: $fname="$subdir/$fname";
3323: }
1.1090 raeburn 3324: if ($context eq 'coursedoc') {
1.638 albertel 3325: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3326: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3327: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3328: return &finishuserfileupload($docuname,$docudom,
3329: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3330: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3331: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3332: } else {
1.1218 raeburn 3333: if ($env{'form.folder'}) {
3334: $fname=$env{'form.folder'}.'/'.$fname;
3335: }
1.638 albertel 3336: return &process_coursefile('uploaddoc',$docuname,$docudom,
3337: $fname,$formname,$parser,
1.1095 raeburn 3338: $allfiles,$codebase,$mimetype);
1.481 raeburn 3339: }
1.719 banghart 3340: } elsif (defined($destuname)) {
3341: my $docuname=$destuname;
3342: my $docudom=$destudom;
1.860 raeburn 3343: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3344: $parser,$allfiles,$codebase,
1.1051 raeburn 3345: $thumbwidth,$thumbheight,
1.1095 raeburn 3346: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3347: } else {
1.638 albertel 3348: my $docuname=$env{'user.name'};
3349: my $docudom=$env{'user.domain'};
1.1220 raeburn 3350: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3351: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3352: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3353: }
1.860 raeburn 3354: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3355: $parser,$allfiles,$codebase,
1.1051 raeburn 3356: $thumbwidth,$thumbheight,
1.1095 raeburn 3357: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3358: }
1.271 www 3359: }
3360:
3361: sub finishuserfileupload {
1.860 raeburn 3362: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3363: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3364: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3365: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3366:
1.860 raeburn 3367: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3368: $file=$fname;
3369: if ($fname=~m|/|) {
3370: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3371: $path.=$fnamepath.'/';
3372: }
1.259 www 3373: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3374: my $count;
3375: for ($count=4;$count<=$#parts;$count++) {
3376: $filepath.="/$parts[$count]";
3377: if ((-e $filepath)!=1) {
3378: mkdir($filepath,0777);
3379: }
3380: }
1.984 neumanie 3381:
1.258 www 3382: # Save the file
3383: {
1.701 albertel 3384: if (!open(FH,'>'.$filepath.'/'.$file)) {
3385: &logthis('Failed to create '.$filepath.'/'.$file);
3386: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3387: return '/adm/notfound.html';
3388: }
1.1090 raeburn 3389: if ($context eq 'overwrite') {
1.1117 foxr 3390: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3391: my $target = $filepath.'/'.$file;
3392: if (-e $source) {
3393: my @info = stat($source);
3394: if ($info[9] eq $env{'form.timestamp'}) {
3395: unless (&File::Copy::move($source,$target)) {
3396: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3397: return "Moving from $source failed";
3398: }
3399: } else {
3400: return "Temporary file: $source had unexpected date/time for last modification";
3401: }
3402: } else {
3403: return "Temporary file: $source missing";
3404: }
3405: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3406: &logthis('Failed to write to '.$filepath.'/'.$file);
3407: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3408: return '/adm/notfound.html';
3409: }
1.570 albertel 3410: close(FH);
1.1051 raeburn 3411: if ($resizewidth && $resizeheight) {
3412: my $mm = new File::MMagic;
3413: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3414: if ($mime_type =~ m{^image/}) {
3415: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3416: }
1.977 amueller 3417: }
1.258 www 3418: }
1.1152 raeburn 3419: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3420: if (ref($mimetype)) {
3421: if ($$mimetype eq '') {
3422: my $mm = new File::MMagic;
3423: my $type = $mm->checktype_filename($filepath.'/'.$file);
3424: $$mimetype = $type;
3425: }
3426: }
3427: }
1.637 raeburn 3428: if ($parser eq 'parse') {
1.1152 raeburn 3429: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3430: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3431: $allfiles,$codebase);
3432: unless ($parse_result eq 'ok') {
3433: &logthis('Failed to parse '.$filepath.$file.
3434: ' for embedded media: '.$parse_result);
3435: }
1.637 raeburn 3436: }
3437: }
1.860 raeburn 3438: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3439: my $input = $filepath.'/'.$file;
3440: my $output = $filepath.'/'.'tn-'.$file;
3441: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3442: system("convert -sample $thumbsize $input $output");
3443: if (-e $filepath.'/'.'tn-'.$file) {
3444: $fetchthumb = 1;
3445: }
3446: }
1.858 raeburn 3447:
1.259 www 3448: # Notify homeserver to grep it
3449: #
1.984 neumanie 3450: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3451: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3452: if ($fetchresult eq 'ok') {
1.860 raeburn 3453: if ($fetchthumb) {
3454: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3455: if ($thumbresult ne 'ok') {
3456: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3457: $docuhome.': '.$thumbresult);
3458: }
3459: }
1.259 www 3460: #
1.258 www 3461: # Return the URL to it
1.494 albertel 3462: return '/uploaded/'.$path.$file;
1.263 www 3463: } else {
1.494 albertel 3464: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3465: ': '.$fetchresult);
1.263 www 3466: return '/adm/notfound.html';
1.858 raeburn 3467: }
1.493 albertel 3468: }
3469:
1.637 raeburn 3470: sub extract_embedded_items {
1.961 raeburn 3471: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3472: my @state = ();
1.1164 raeburn 3473: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3474: my %javafiles = (
3475: codebase => '',
3476: code => '',
3477: archive => ''
3478: );
3479: my %mediafiles = (
3480: src => '',
3481: movie => '',
3482: );
1.648 raeburn 3483: my $p;
3484: if ($content) {
3485: $p = HTML::LCParser->new($content);
3486: } else {
1.961 raeburn 3487: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3488: }
1.641 albertel 3489: while (my $t=$p->get_token()) {
1.640 albertel 3490: if ($t->[0] eq 'S') {
3491: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3492: push(@state, $tagname);
1.648 raeburn 3493: if (lc($tagname) eq 'allow') {
3494: &add_filetype($allfiles,$attr->{'src'},'src');
3495: }
1.640 albertel 3496: if (lc($tagname) eq 'img') {
3497: &add_filetype($allfiles,$attr->{'src'},'src');
3498: }
1.886 albertel 3499: if (lc($tagname) eq 'a') {
1.1222 raeburn 3500: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3501: &add_filetype($allfiles,$attr->{'href'},'href');
3502: }
1.886 albertel 3503: }
1.645 raeburn 3504: if (lc($tagname) eq 'script') {
1.1164 raeburn 3505: my $src;
1.645 raeburn 3506: if ($attr->{'archive'} =~ /\.jar$/i) {
3507: &add_filetype($allfiles,$attr->{'archive'},'archive');
3508: } else {
1.1164 raeburn 3509: if ($attr->{'src'} ne '') {
3510: $src = $attr->{'src'};
3511: &add_filetype($allfiles,$src,'src');
3512: }
3513: }
3514: my $text = $p->get_trimmed_text();
3515: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3516: my @swfargs = split(/,/,$1);
3517: foreach my $item (@swfargs) {
3518: $item =~ s/["']//g;
3519: $item =~ s/^\s+//;
3520: $item =~ s/\s+$//;
3521: }
3522: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3523: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3524: push(@{$related{$swfargs[0]}},$swfargs[2]);
3525: } else {
3526: $related{$swfargs[0]} = [$swfargs[2]];
3527: }
3528: }
1.645 raeburn 3529: }
3530: }
3531: if (lc($tagname) eq 'link') {
3532: if (lc($attr->{'rel'}) eq 'stylesheet') {
3533: &add_filetype($allfiles,$attr->{'href'},'href');
3534: }
3535: }
1.640 albertel 3536: if (lc($tagname) eq 'object' ||
3537: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3538: foreach my $item (keys(%javafiles)) {
3539: $javafiles{$item} = '';
3540: }
1.1164 raeburn 3541: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3542: $lastids{lc($tagname)} = $attr->{'id'};
3543: }
1.640 albertel 3544: }
3545: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3546: my $name = lc($attr->{'name'});
3547: foreach my $item (keys(%javafiles)) {
3548: if ($name eq $item) {
3549: $javafiles{$item} = $attr->{'value'};
3550: last;
3551: }
3552: }
1.1164 raeburn 3553: my $pathfrom;
1.640 albertel 3554: foreach my $item (keys(%mediafiles)) {
3555: if ($name eq $item) {
1.1164 raeburn 3556: $pathfrom = $attr->{'value'};
3557: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3558: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3559: last;
3560: }
3561: }
1.1164 raeburn 3562: if ($name eq 'flashvars') {
3563: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3564: }
3565: if ($pathfrom ne '') {
3566: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3567: $pathfrom);
3568: }
1.640 albertel 3569: }
3570: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3571: foreach my $item (keys(%javafiles)) {
3572: if ($attr->{$item}) {
3573: $javafiles{$item} = $attr->{$item};
3574: last;
3575: }
3576: }
3577: foreach my $item (keys(%mediafiles)) {
3578: if ($attr->{$item}) {
3579: &add_filetype($allfiles,$attr->{$item},$item);
3580: last;
3581: }
3582: }
1.1164 raeburn 3583: if (lc($tagname) eq 'embed') {
3584: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3585: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3586: $attr->{'src'});
3587: }
3588: }
1.640 albertel 3589: }
1.1243 raeburn 3590: if (lc($tagname) eq 'iframe') {
3591: my $src = $attr->{'src'} ;
3592: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3593: &add_filetype($allfiles,$src,'src');
3594: } elsif ($src =~ m{^/}) {
3595: if ($env{'request.course.id'}) {
3596: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3597: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3598: my $url = &hreflocation('',$fullpath);
3599: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3600: my $relpath = $1;
3601: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3602: &add_filetype($allfiles,$1,'src');
3603: }
3604: }
3605: }
3606: }
3607: }
1.1164 raeburn 3608: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3609: pop(@state);
1.1164 raeburn 3610: }
1.640 albertel 3611: } elsif ($t->[0] eq 'E') {
3612: my ($tagname) = ($t->[1]);
3613: if ($javafiles{'codebase'} ne '') {
3614: $javafiles{'codebase'} .= '/';
3615: }
3616: if (lc($tagname) eq 'applet' ||
3617: lc($tagname) eq 'object' ||
3618: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3619: ) {
3620: foreach my $item (keys(%javafiles)) {
3621: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3622: my $file=$javafiles{'codebase'}.$javafiles{$item};
3623: &add_filetype($allfiles,$file,$item);
3624: }
3625: }
3626: }
3627: pop @state;
3628: }
3629: }
1.1164 raeburn 3630: foreach my $id (sort(keys(%flashvars))) {
3631: if ($shockwave{$id} ne '') {
3632: my @pairs = split(/\&/,$flashvars{$id});
3633: foreach my $pair (@pairs) {
3634: my ($key,$value) = split(/\=/,$pair);
3635: if ($key eq 'thumb') {
3636: &add_filetype($allfiles,$value,$key);
3637: } elsif ($key eq 'content') {
3638: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3639: my ($ext) = ($value =~ /\.([^.]+)$/);
3640: if ($ext ne '') {
3641: &add_filetype($allfiles,$path.$value,$ext);
3642: }
3643: }
3644: }
3645: }
3646: }
1.637 raeburn 3647: return 'ok';
3648: }
3649:
1.639 albertel 3650: sub add_filetype {
3651: my ($allfiles,$file,$type)=@_;
3652: if (exists($allfiles->{$file})) {
3653: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3654: push(@{$allfiles->{$file}}, &escape($type));
3655: }
3656: } else {
3657: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3658: }
3659: }
3660:
1.1164 raeburn 3661: sub embedded_dependency {
3662: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3663: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3664: if (($identifier ne '') &&
3665: (ref($related->{$identifier}) eq 'ARRAY') &&
3666: ($pathfrom ne '')) {
3667: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3668: foreach my $dep (@{$related->{$identifier}}) {
3669: &add_filetype($allfiles,$path.$dep,'object');
3670: }
3671: }
3672: }
3673: return;
3674: }
3675:
1.493 albertel 3676: sub removeuploadedurl {
1.984 neumanie 3677: my ($url)=@_;
3678: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3679: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3680: }
3681:
3682: sub removeuserfile {
3683: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3684: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3685: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3686: if ($result eq 'ok') {
1.798 raeburn 3687: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3688: my $metafile = $fname.'.meta';
3689: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3690: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3691: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3692: my $sqlresult =
1.823 albertel 3693: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3694: 'portfolio_metadata',$group,
3695: 'delete');
1.798 raeburn 3696: }
3697: }
3698: return $result;
1.257 www 3699: }
1.15 www 3700:
1.530 albertel 3701: sub mkdiruserfile {
3702: my ($docuname,$docudom,$dir)=@_;
3703: my $home=&homeserver($docuname,$docudom);
3704: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3705: }
3706:
1.531 albertel 3707: sub renameuserfile {
3708: my ($docuname,$docudom,$old,$new)=@_;
3709: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3710: my $result = &reply("renameuserfile:$docudom:$docuname:".
3711: &escape("$old").':'.&escape("$new"),$home);
3712: if ($result eq 'ok') {
3713: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3714: my $oldmeta = $old.'.meta';
3715: my $newmeta = $new.'.meta';
3716: my $metaresult =
3717: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3718: my $url = "/uploaded/$docudom/$docuname/$old";
3719: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3720: my $sqlresult =
1.823 albertel 3721: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3722: 'portfolio_metadata',$group,
3723: 'delete');
1.798 raeburn 3724: }
3725: }
3726: return $result;
1.531 albertel 3727: }
3728:
1.14 www 3729: # ------------------------------------------------------------------------- Log
3730:
3731: sub log {
3732: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3733: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3734: }
3735:
3736: # ------------------------------------------------------------------ Course Log
1.352 www 3737: #
3738: # This routine flushes several buffers of non-mission-critical nature
3739: #
1.157 www 3740:
3741: sub flushcourselogs {
1.352 www 3742: &logthis('Flushing log buffers');
3743: #
3744: # course logs
3745: # This is a log of all transactions in a course, which can be used
3746: # for data mining purposes
3747: #
3748: # It also collects the courseid database, which lists last transaction
3749: # times and course titles for all courseids
3750: #
3751: my %courseidbuffer=();
1.921 raeburn 3752: foreach my $crsid (keys(%courselogs)) {
1.352 www 3753: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3754: &escape($courselogs{$crsid}),
3755: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3756: delete $courselogs{$crsid};
3757: } else {
3758: &logthis('Failed to flush log buffer for '.$crsid);
3759: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3760: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3761: " exceeded maximum size, deleting.</font>");
3762: delete $courselogs{$crsid};
3763: }
1.352 www 3764: }
1.920 raeburn 3765: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3766: 'description' => $coursedescrbuf{$crsid},
3767: 'inst_code' => $courseinstcodebuf{$crsid},
3768: 'type' => $coursetypebuf{$crsid},
3769: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3770: };
1.191 harris41 3771: }
1.352 www 3772: #
3773: # Write course id database (reverse lookup) to homeserver of courses
3774: # Is used in pickcourse
3775: #
1.840 albertel 3776: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3777: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3778: $courseidbuffer{$crs_home},
3779: $crs_home,'timeonly');
1.352 www 3780: }
3781: #
3782: # File accesses
3783: # Writes to the dynamic metadata of resources to get hit counts, etc.
3784: #
1.449 matthew 3785: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3786: if ($entry =~ /___count$/) {
3787: my ($dom,$name);
1.807 albertel 3788: ($dom,$name,undef)=
1.811 albertel 3789: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3790: if (! defined($dom) || $dom eq '' ||
3791: ! defined($name) || $name eq '') {
1.620 albertel 3792: my $cid = $env{'request.course.id'};
3793: $dom = $env{'request.'.$cid.'.domain'};
3794: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3795: }
1.450 matthew 3796: my $value = $accesshash{$entry};
3797: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3798: my %temphash=($url => $value);
1.449 matthew 3799: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3800: if ($result eq 'ok') {
3801: delete $accesshash{$entry};
3802: }
3803: } else {
1.811 albertel 3804: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3805: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3806: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3807: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3808: delete $accesshash{$entry};
3809: }
1.185 www 3810: }
1.191 harris41 3811: }
1.352 www 3812: #
3813: # Roles
3814: # Reverse lookup of user roles for course faculty/staff and co-authorship
3815: #
1.800 albertel 3816: foreach my $entry (keys(%userrolehash)) {
1.351 www 3817: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3818: split(/\:/,$entry);
3819: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3820: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3821: $rudom,$runame) eq 'ok') {
3822: delete $userrolehash{$entry};
3823: }
3824: }
1.662 raeburn 3825: #
3826: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3827: #
3828: my %domrolebuffer = ();
1.1000 raeburn 3829: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3830: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3831: if ($domrolebuffer{$rudom}) {
3832: $domrolebuffer{$rudom}.='&'.&escape($entry).
3833: '='.&escape($domainrolehash{$entry});
3834: } else {
3835: $domrolebuffer{$rudom}.=&escape($entry).
3836: '='.&escape($domainrolehash{$entry});
3837: }
3838: delete $domainrolehash{$entry};
3839: }
3840: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3841: my %servers = &get_servers($dom,'library');
3842: foreach my $tryserver (keys(%servers)) {
3843: unless (&reply('domroleput:'.$dom.':'.
3844: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3845: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3846: }
1.662 raeburn 3847: }
3848: }
1.186 www 3849: $dumpcount++;
1.157 www 3850: }
3851:
3852: sub courselog {
3853: my $what=shift;
1.158 www 3854: $what=time.':'.$what;
1.620 albertel 3855: unless ($env{'request.course.id'}) { return ''; }
3856: $coursedombuf{$env{'request.course.id'}}=
3857: $env{'course.'.$env{'request.course.id'}.'.domain'};
3858: $coursenumbuf{$env{'request.course.id'}}=
3859: $env{'course.'.$env{'request.course.id'}.'.num'};
3860: $coursehombuf{$env{'request.course.id'}}=
3861: $env{'course.'.$env{'request.course.id'}.'.home'};
3862: $coursedescrbuf{$env{'request.course.id'}}=
3863: $env{'course.'.$env{'request.course.id'}.'.description'};
3864: $courseinstcodebuf{$env{'request.course.id'}}=
3865: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3866: $courseownerbuf{$env{'request.course.id'}}=
3867: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3868: $coursetypebuf{$env{'request.course.id'}}=
3869: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3870: if (defined $courselogs{$env{'request.course.id'}}) {
3871: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3872: } else {
1.620 albertel 3873: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3874: }
1.620 albertel 3875: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3876: &flushcourselogs();
3877: }
1.158 www 3878: }
3879:
3880: sub courseacclog {
3881: my $fnsymb=shift;
1.620 albertel 3882: unless ($env{'request.course.id'}) { return ''; }
3883: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3884: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3885: $what.=':POST';
1.583 matthew 3886: # FIXME: Probably ought to escape things....
1.800 albertel 3887: foreach my $key (keys(%env)) {
3888: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3889: my $formitem = $1;
3890: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3891: $what.=':'.$formitem.'='.$env{$key};
3892: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3893: $what.=':'.$formitem.'='.$env{$key};
3894: }
1.158 www 3895: }
1.191 harris41 3896: }
1.583 matthew 3897: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3898: # FIXME: We should not be depending on a form parameter that someone
3899: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3900: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3901: $what.= ':POST';
3902: # FIXME: Probably ought to escape things....
3903: foreach my $element ('courseexp','crsfulltext','crsrelated',
3904: 'crsdiscuss') {
1.620 albertel 3905: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3906: }
3907: }
1.158 www 3908: }
3909: &courselog($what);
1.149 www 3910: }
3911:
1.185 www 3912: sub countacc {
3913: my $url=&declutter(shift);
1.458 matthew 3914: return if (! defined($url) || $url eq '');
1.620 albertel 3915: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3916: #
3917: # Mark that this url was used in this course
3918: #
1.620 albertel 3919: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3920: #
3921: # Increase the access count for this resource in this child process
3922: #
1.281 www 3923: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3924: $accesshash{$key}++;
1.185 www 3925: }
1.349 www 3926:
1.361 www 3927: sub linklog {
3928: my ($from,$to)=@_;
3929: $from=&declutter($from);
3930: $to=&declutter($to);
3931: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3932: $accesshash{$to.'___'.$from.'___goto'}=1;
3933: }
1.1160 www 3934:
3935: sub statslog {
3936: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3937: if ($users<2) { return; }
3938: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3939: 'course' => $env{'request.course.id'},
3940: 'sections' => '"all"',
3941: 'num_students' => $users,
3942: 'part' => $part,
3943: 'symb' => $symb,
3944: 'mean_tries' => $av_attempts,
3945: 'deg_of_diff' => $degdiff});
3946: foreach my $key (keys(%dynstore)) {
3947: $accesshash{$key}=$dynstore{$key};
3948: }
3949: }
1.361 www 3950:
1.349 www 3951: sub userrolelog {
3952: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3953: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3954: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3955: $userrolehash
3956: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3957: =$tend.':'.$tstart;
1.662 raeburn 3958: }
1.1169 droeschl 3959: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3960: $userrolehash
3961: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3962: =$tend.':'.$tstart;
3963: }
1.1169 droeschl 3964: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3965: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3966: $domainrolehash
3967: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3968: = $tend.':'.$tstart;
3969: }
1.351 www 3970: }
3971:
1.957 raeburn 3972: sub courserolelog {
3973: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3974: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3975: my $cdom = $1;
3976: my $cnum = $2;
3977: my $sec = $3;
3978: my $namespace = 'rolelog';
3979: my %storehash = (
3980: role => $trole,
3981: start => $tstart,
3982: end => $tend,
3983: selfenroll => $selfenroll,
3984: context => $context,
3985: );
3986: if ($trole eq 'gr') {
3987: $namespace = 'groupslog';
3988: $storehash{'group'} = $sec;
3989: } else {
3990: $storehash{'section'} = $sec;
3991: }
1.1188 raeburn 3992: &write_log('course',$namespace,\%storehash,$delflag,$username,
3993: $domain,$cnum,$cdom);
1.1184 raeburn 3994: if (($trole ne 'st') || ($sec ne '')) {
3995: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3996: }
3997: }
3998: return;
3999: }
4000:
1.1184 raeburn 4001: sub domainrolelog {
4002: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4003: if ($area =~ m{^/($match_domain)/$}) {
4004: my $cdom = $1;
4005: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4006: my $namespace = 'rolelog';
4007: my %storehash = (
4008: role => $trole,
4009: start => $tstart,
4010: end => $tend,
4011: context => $context,
4012: );
1.1188 raeburn 4013: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4014: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4015: }
4016: return;
4017:
4018: }
4019:
4020: sub coauthorrolelog {
4021: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4022: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4023: my $audom = $1;
4024: my $auname = $2;
4025: my $namespace = 'rolelog';
4026: my %storehash = (
4027: role => $trole,
4028: start => $tstart,
4029: end => $tend,
4030: context => $context,
4031: );
1.1188 raeburn 4032: &write_log('author',$namespace,\%storehash,$delflag,$username,
4033: $domain,$auname,$audom);
1.1184 raeburn 4034: }
4035: return;
4036: }
4037:
1.351 www 4038: sub get_course_adv_roles {
1.948 raeburn 4039: my ($cid,$codes) = @_;
1.620 albertel 4040: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4041: my %coursehash=&coursedescription($cid);
1.988 raeburn 4042: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4043: my %nothide=();
1.800 albertel 4044: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4045: if ($user !~ /:/) {
4046: $nothide{join(':',split(/[\@]/,$user))}=1;
4047: } else {
4048: $nothide{$user}=1;
4049: }
1.470 www 4050: }
1.1219 raeburn 4051: my @possdoms = ($coursehash{'domain'});
4052: if ($coursehash{'checkforpriv'}) {
4053: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4054: }
1.351 www 4055: my %returnhash=();
4056: my %dumphash=
4057: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4058: my $now=time;
1.997 raeburn 4059: my %privileged;
1.1000 raeburn 4060: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4061: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4062: if (($tstart) && ($tstart<0)) { next; }
4063: if (($tend) && ($tend<$now)) { next; }
4064: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4065: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4066: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4067: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4068: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4069: if ($role eq 'cr') { next; }
1.948 raeburn 4070: if ($codes) {
4071: if ($section) { $role .= ':'.$section; }
4072: if ($returnhash{$role}) {
4073: $returnhash{$role}.=','.$username.':'.$domain;
4074: } else {
4075: $returnhash{$role}=$username.':'.$domain;
4076: }
1.351 www 4077: } else {
1.988 raeburn 4078: my $key=&plaintext($role,$crstype);
1.973 bisitz 4079: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4080: if ($returnhash{$key}) {
4081: $returnhash{$key}.=','.$username.':'.$domain;
4082: } else {
4083: $returnhash{$key}=$username.':'.$domain;
4084: }
1.351 www 4085: }
1.948 raeburn 4086: }
1.400 www 4087: return %returnhash;
4088: }
4089:
4090: sub get_my_roles {
1.937 raeburn 4091: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4092: unless (defined($uname)) { $uname=$env{'user.name'}; }
4093: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4094: my (%dumphash,%nothide);
1.1086 raeburn 4095: if ($context eq 'userroles') {
1.1166 raeburn 4096: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4097: } else {
1.1219 raeburn 4098: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4099: if ($hidepriv) {
4100: my %coursehash=&coursedescription($udom.'_'.$uname);
4101: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4102: if ($user !~ /:/) {
4103: $nothide{join(':',split(/[\@]/,$user))} = 1;
4104: } else {
4105: $nothide{$user} = 1;
4106: }
4107: }
4108: }
1.858 raeburn 4109: }
1.400 www 4110: my %returnhash=();
4111: my $now=time;
1.999 raeburn 4112: my %privileged;
1.800 albertel 4113: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4114: my ($role,$tend,$tstart);
4115: if ($context eq 'userroles') {
1.1149 raeburn 4116: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4117: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4118: } else {
4119: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4120: }
1.400 www 4121: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4122: my $status = 'active';
1.939 raeburn 4123: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4124: $status = 'previous';
4125: }
4126: if (($tstart) && ($now<$tstart)) {
4127: $status = 'future';
4128: }
4129: if (ref($types) eq 'ARRAY') {
4130: if (!grep(/^\Q$status\E$/,@{$types})) {
4131: next;
4132: }
4133: } else {
4134: if ($status ne 'active') {
4135: next;
4136: }
4137: }
1.867 raeburn 4138: my ($rolecode,$username,$domain,$section,$area);
4139: if ($context eq 'userroles') {
1.1186 raeburn 4140: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4141: (undef,$domain,$username,$section) = split(/\//,$area);
4142: } else {
4143: ($role,$username,$domain,$section) = split(/\:/,$entry);
4144: }
1.832 raeburn 4145: if (ref($roledoms) eq 'ARRAY') {
4146: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4147: next;
4148: }
4149: }
4150: if (ref($roles) eq 'ARRAY') {
4151: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4152: if ($role =~ /^cr\//) {
4153: if (!grep(/^cr$/,@{$roles})) {
4154: next;
4155: }
1.1104 raeburn 4156: } elsif ($role =~ /^gr\//) {
4157: if (!grep(/^gr$/,@{$roles})) {
4158: next;
4159: }
1.922 raeburn 4160: } else {
4161: next;
4162: }
1.832 raeburn 4163: }
1.867 raeburn 4164: }
1.937 raeburn 4165: if ($hidepriv) {
1.1219 raeburn 4166: my @privroles = ('dc','su');
1.999 raeburn 4167: if ($context eq 'userroles') {
1.1219 raeburn 4168: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4169: } else {
1.1219 raeburn 4170: my $possdoms = [$domain];
4171: if (ref($roledoms) eq 'ARRAY') {
4172: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4173: }
1.1219 raeburn 4174: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4175: if (!$nothide{$username.':'.$domain}) {
4176: next;
4177: }
4178: }
1.937 raeburn 4179: }
4180: }
1.933 raeburn 4181: if ($withsec) {
4182: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4183: $tstart.':'.$tend;
4184: } else {
4185: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4186: }
1.832 raeburn 4187: }
1.373 www 4188: return %returnhash;
1.399 www 4189: }
4190:
4191: # ----------------------------------------------------- Frontpage Announcements
4192: #
4193: #
4194:
4195: sub postannounce {
4196: my ($server,$text)=@_;
1.844 albertel 4197: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4198: unless ($text=~/\w/) { $text=''; }
4199: return &reply('setannounce:'.&escape($text),$server);
4200: }
4201:
4202: sub getannounce {
1.448 albertel 4203:
4204: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4205: my $announcement='';
1.800 albertel 4206: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4207: close($fh);
1.399 www 4208: if ($announcement=~/\w/) {
4209: return
4210: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4211: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4212: } else {
4213: return '';
4214: }
4215: } else {
4216: return '';
4217: }
1.351 www 4218: }
1.353 www 4219:
4220: # ---------------------------------------------------------- Course ID routines
4221: # Deal with domain's nohist_courseid.db files
4222: #
4223:
4224: sub courseidput {
1.921 raeburn 4225: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4226: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4227: my $outcome;
4228: if ($caller eq 'timeonly') {
4229: my $cids = '';
4230: foreach my $item (keys(%$storehash)) {
4231: $cids.=&escape($item).'&';
4232: }
4233: $cids=~s/\&$//;
4234: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4235: $coursehome);
4236: } else {
4237: my $items = '';
4238: foreach my $item (keys(%$storehash)) {
4239: $items.= &escape($item).'='.
4240: &freeze_escape($$storehash{$item}).'&';
4241: }
4242: $items=~s/\&$//;
4243: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4244: $coursehome);
1.918 raeburn 4245: }
4246: if ($outcome eq 'unknown_cmd') {
4247: my $what;
4248: foreach my $cid (keys(%$storehash)) {
4249: $what .= &escape($cid).'=';
1.921 raeburn 4250: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4251: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4252: }
4253: $what =~ s/\:$/&/;
4254: }
4255: $what =~ s/\&$//;
4256: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4257: } else {
4258: return $outcome;
4259: }
1.353 www 4260: }
4261:
4262: sub courseiddump {
1.921 raeburn 4263: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4264: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4265: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4266: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4267: $hasuniquecode)=@_;
1.918 raeburn 4268: my $as_hash = 1;
4269: my %returnhash;
4270: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4271: my %libserv = &all_library();
4272: foreach my $tryserver (keys(%libserv)) {
4273: if ( ( $hostidflag == 1
4274: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4275: || (!defined($hostidflag)) ) {
4276:
1.918 raeburn 4277: if (($domfilter eq '') ||
4278: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4279: my $rep;
4280: if (grep { $_ eq $tryserver } current_machine_ids()) {
4281: $rep = LONCAPA::Lond::dump_course_id_handler(
4282: join(":", (&host_domain($tryserver), $sincefilter,
4283: &escape($descfilter), &escape($instcodefilter),
4284: &escape($ownerfilter), &escape($coursefilter),
4285: &escape($typefilter), &escape($regexp_ok),
4286: $as_hash, &escape($selfenrollonly),
4287: &escape($catfilter), $showhidden, $caller,
4288: &escape($cloner), &escape($cc_clone), $cloneonly,
4289: &escape($createdbefore), &escape($createdafter),
1.1247 raeburn 4290: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180 droeschl 4291: } else {
4292: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4293: $sincefilter.':'.&escape($descfilter).':'.
4294: &escape($instcodefilter).':'.&escape($ownerfilter).
4295: ':'.&escape($coursefilter).':'.&escape($typefilter).
4296: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4297: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4298: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4299: &escape($cc_clone).':'.$cloneonly.':'.
4300: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247 raeburn 4301: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180 droeschl 4302: $tryserver);
4303: }
4304:
1.918 raeburn 4305: my @pairs=split(/\&/,$rep);
4306: foreach my $item (@pairs) {
4307: my ($key,$value)=split(/\=/,$item,2);
4308: $key = &unescape($key);
4309: next if ($key =~ /^error: 2 /);
4310: my $result = &thaw_unescape($value);
4311: if (ref($result) eq 'HASH') {
4312: $returnhash{$key}=$result;
4313: } else {
1.921 raeburn 4314: my @responses = split(/:/,$value);
4315: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4316: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4317: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4318: }
1.1008 raeburn 4319: }
1.353 www 4320: }
4321: }
4322: }
4323: }
4324: return %returnhash;
4325: }
4326:
1.1055 raeburn 4327: sub courselastaccess {
4328: my ($cdom,$cnum,$hostidref) = @_;
4329: my %returnhash;
4330: if ($cdom && $cnum) {
4331: my $chome = &homeserver($cnum,$cdom);
4332: if ($chome ne 'no_host') {
4333: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4334: &extract_lastaccess(\%returnhash,$rep);
4335: }
4336: } else {
4337: if (!$cdom) { $cdom=''; }
4338: my %libserv = &all_library();
4339: foreach my $tryserver (keys(%libserv)) {
4340: if (ref($hostidref) eq 'ARRAY') {
4341: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4342: }
4343: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4344: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4345: &extract_lastaccess(\%returnhash,$rep);
4346: }
4347: }
4348: }
4349: return %returnhash;
4350: }
4351:
4352: sub extract_lastaccess {
4353: my ($returnhash,$rep) = @_;
4354: if (ref($returnhash) eq 'HASH') {
4355: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4356: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4357: $rep eq '') {
4358: my @pairs=split(/\&/,$rep);
4359: foreach my $item (@pairs) {
4360: my ($key,$value)=split(/\=/,$item,2);
4361: $key = &unescape($key);
4362: next if ($key =~ /^error: 2 /);
4363: $returnhash->{$key} = &thaw_unescape($value);
4364: }
4365: }
4366: }
4367: return;
4368: }
4369:
1.658 raeburn 4370: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4371:
4372: sub dcmailput {
1.685 raeburn 4373: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4374: my $status = &Apache::lonnet::critical(
1.740 www 4375: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4376: &escape($message),$server);
1.662 raeburn 4377: return $status;
4378: }
4379:
1.658 raeburn 4380: sub dcmaildump {
4381: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4382: my %returnhash=();
1.846 albertel 4383:
4384: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4385: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4386: &escape($enddate).':';
4387: my @esc_senders=map { &escape($_)} @$senders;
4388: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4389: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4390: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4391: if (($key) && ($value)) {
4392: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4393: }
4394: }
4395: }
4396: return %returnhash;
4397: }
1.662 raeburn 4398: # ---------------------------------------------------------- Domain roles
4399:
4400: sub get_domain_roles {
4401: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4402: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4403: $startdate = '.';
4404: }
1.1018 raeburn 4405: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4406: $enddate = '.';
4407: }
1.922 raeburn 4408: my $rolelist;
4409: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4410: $rolelist = join('&',@{$roles});
1.922 raeburn 4411: }
1.662 raeburn 4412: my %personnel = ();
1.841 albertel 4413:
4414: my %servers = &get_servers($dom,'library');
4415: foreach my $tryserver (keys(%servers)) {
4416: %{$personnel{$tryserver}}=();
4417: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4418: &escape($startdate).':'.
4419: &escape($enddate).':'.
4420: &escape($rolelist), $tryserver))) {
4421: my ($key,$value) = split(/\=/,$line,2);
4422: if (($key) && ($value)) {
4423: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4424: }
4425: }
1.662 raeburn 4426: }
4427: return %personnel;
4428: }
1.658 raeburn 4429:
1.1057 www 4430: # ----------------------------------------------------------- Interval timing
1.149 www 4431:
1.1153 www 4432: {
4433: # Caches needed for speedup of navmaps
4434: # We don't want to cache this for very long at all (5 seconds at most)
4435: #
4436: # The user for whom we cache
4437: my $cachedkey='';
4438: # The cached times for this user
4439: my %cachedtimes=();
4440: # When this was last done
4441: my $cachedtime=();
4442:
4443: sub load_all_first_access {
1.1154 raeburn 4444: my ($uname,$udom)=@_;
1.1156 www 4445: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4446: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4447: return;
4448: }
4449: $cachedtime=time;
4450: $cachedkey=$uname.':'.$udom;
4451: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4452: }
4453:
1.504 albertel 4454: sub get_first_access {
1.1162 raeburn 4455: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4456: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4457: if ($argsymb) { $symb=$argsymb; }
4458: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4459: if ($argmap) { $map = $argmap; }
1.926 albertel 4460: if ($type eq 'course') {
4461: $res='course';
4462: } elsif ($type eq 'map') {
1.588 albertel 4463: $res=&symbread($map);
4464: } else {
4465: $res=$symb;
4466: }
1.1153 www 4467: &load_all_first_access($uname,$udom);
4468: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4469: }
4470:
4471: sub set_first_access {
1.1162 raeburn 4472: my ($type,$interval)=@_;
1.790 albertel 4473: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4474: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4475: if ($type eq 'course') {
4476: $res='course';
4477: } elsif ($type eq 'map') {
1.588 albertel 4478: $res=&symbread($map);
4479: } else {
4480: $res=$symb;
4481: }
1.1153 www 4482: $cachedkey='';
1.1162 raeburn 4483: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4484: if (!$firstaccess) {
1.1162 raeburn 4485: my $start = time;
4486: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4487: $udom,$uname);
4488: if ($putres eq 'ok') {
4489: &put('timerinterval',{"$courseid\0$res"=>$interval},
4490: $udom,$uname);
4491: &appenv(
4492: {
4493: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4494: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4495: }
4496: );
4497: }
4498: return $putres;
1.505 albertel 4499: }
4500: return 'already_set';
1.504 albertel 4501: }
1.1153 www 4502: }
1.110 www 4503: # --------------------------------------------- Set Expire Date for Spreadsheet
4504:
4505: sub expirespread {
4506: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4507: my $cid=$env{'request.course.id'};
1.110 www 4508: if ($cid) {
4509: my $now=time;
4510: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4511: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4512: $env{'course.'.$cid.'.num'}.
1.110 www 4513: ':nohist_expirationdates:'.
4514: &escape($key).'='.$now,
1.620 albertel 4515: $env{'course.'.$cid.'.home'})
1.110 www 4516: }
4517: return 'ok';
1.14 www 4518: }
4519:
1.109 www 4520: # ----------------------------------------------------- Devalidate Spreadsheets
4521:
4522: sub devalidate {
1.325 www 4523: my ($symb,$uname,$udom)=@_;
1.620 albertel 4524: my $cid=$env{'request.course.id'};
1.109 www 4525: if ($cid) {
1.391 matthew 4526: # delete the stored spreadsheets for
4527: # - the student level sheet of this user in course's homespace
4528: # - the assessment level sheet for this resource
4529: # for this user in user's homespace
1.553 albertel 4530: # - current conditional state info
1.325 www 4531: my $key=$uname.':'.$udom.':';
1.109 www 4532: my $status=
1.299 matthew 4533: &del('nohist_calculatedsheets',
1.391 matthew 4534: [$key.'studentcalc:'],
1.620 albertel 4535: $env{'course.'.$cid.'.domain'},
4536: $env{'course.'.$cid.'.num'})
1.133 albertel 4537: .' '.
4538: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4539: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4540: unless ($status eq 'ok ok') {
4541: &logthis('Could not devalidate spreadsheet '.
1.325 www 4542: $uname.' at '.$udom.' for '.
1.109 www 4543: $symb.': '.$status);
1.133 albertel 4544: }
1.553 albertel 4545: &delenv('user.state.'.$cid);
1.109 www 4546: }
4547: }
4548:
1.265 albertel 4549: sub get_scalar {
4550: my ($string,$end) = @_;
4551: my $value;
4552: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4553: $value = $1;
4554: } elsif ($$string =~ s/^([^&]*?)&//) {
4555: $value = $1;
4556: }
4557: return &unescape($value);
4558: }
4559:
4560: sub array2str {
4561: my (@array) = @_;
4562: my $result=&arrayref2str(\@array);
4563: $result=~s/^__ARRAY_REF__//;
4564: $result=~s/__END_ARRAY_REF__$//;
4565: return $result;
4566: }
4567:
1.204 albertel 4568: sub arrayref2str {
4569: my ($arrayref) = @_;
1.265 albertel 4570: my $result='__ARRAY_REF__';
1.204 albertel 4571: foreach my $elem (@$arrayref) {
1.265 albertel 4572: if(ref($elem) eq 'ARRAY') {
4573: $result.=&arrayref2str($elem).'&';
4574: } elsif(ref($elem) eq 'HASH') {
4575: $result.=&hashref2str($elem).'&';
4576: } elsif(ref($elem)) {
4577: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4578: } else {
4579: $result.=&escape($elem).'&';
4580: }
4581: }
4582: $result=~s/\&$//;
1.265 albertel 4583: $result .= '__END_ARRAY_REF__';
1.204 albertel 4584: return $result;
4585: }
4586:
1.168 albertel 4587: sub hash2str {
1.204 albertel 4588: my (%hash) = @_;
4589: my $result=&hashref2str(\%hash);
1.265 albertel 4590: $result=~s/^__HASH_REF__//;
4591: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4592: return $result;
4593: }
4594:
4595: sub hashref2str {
4596: my ($hashref)=@_;
1.265 albertel 4597: my $result='__HASH_REF__';
1.800 albertel 4598: foreach my $key (sort(keys(%$hashref))) {
4599: if (ref($key) eq 'ARRAY') {
4600: $result.=&arrayref2str($key).'=';
4601: } elsif (ref($key) eq 'HASH') {
4602: $result.=&hashref2str($key).'=';
4603: } elsif (ref($key)) {
1.265 albertel 4604: $result.='=';
1.800 albertel 4605: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4606: } else {
1.1132 raeburn 4607: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4608: }
4609:
1.800 albertel 4610: if(ref($hashref->{$key}) eq 'ARRAY') {
4611: $result.=&arrayref2str($hashref->{$key}).'&';
4612: } elsif(ref($hashref->{$key}) eq 'HASH') {
4613: $result.=&hashref2str($hashref->{$key}).'&';
4614: } elsif(ref($hashref->{$key})) {
1.265 albertel 4615: $result.='&';
1.800 albertel 4616: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4617: } else {
1.800 albertel 4618: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4619: }
4620: }
1.168 albertel 4621: $result=~s/\&$//;
1.265 albertel 4622: $result .= '__END_HASH_REF__';
1.168 albertel 4623: return $result;
4624: }
4625:
4626: sub str2hash {
1.265 albertel 4627: my ($string)=@_;
4628: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4629: return %$hash;
4630: }
4631:
4632: sub str2hashref {
1.168 albertel 4633: my ($string) = @_;
1.265 albertel 4634:
4635: my %hash;
4636:
4637: if($string !~ /^__HASH_REF__/) {
4638: if (! ($string eq '' || !defined($string))) {
4639: $hash{'error'}='Not hash reference';
4640: }
4641: return (\%hash, $string);
4642: }
4643:
4644: $string =~ s/^__HASH_REF__//;
4645:
4646: while($string !~ /^__END_HASH_REF__/) {
4647: #key
4648: my $key='';
4649: if($string =~ /^__HASH_REF__/) {
4650: ($key, $string)=&str2hashref($string);
4651: if(defined($key->{'error'})) {
4652: $hash{'error'}='Bad data';
4653: return (\%hash, $string);
4654: }
4655: } elsif($string =~ /^__ARRAY_REF__/) {
4656: ($key, $string)=&str2arrayref($string);
4657: if($key->[0] eq 'Array reference error') {
4658: $hash{'error'}='Bad data';
4659: return (\%hash, $string);
4660: }
4661: } else {
4662: $string =~ s/^(.*?)=//;
1.267 albertel 4663: $key=&unescape($1);
1.265 albertel 4664: }
4665: $string =~ s/^=//;
4666:
4667: #value
4668: my $value='';
4669: if($string =~ /^__HASH_REF__/) {
4670: ($value, $string)=&str2hashref($string);
4671: if(defined($value->{'error'})) {
4672: $hash{'error'}='Bad data';
4673: return (\%hash, $string);
4674: }
4675: } elsif($string =~ /^__ARRAY_REF__/) {
4676: ($value, $string)=&str2arrayref($string);
4677: if($value->[0] eq 'Array reference error') {
4678: $hash{'error'}='Bad data';
4679: return (\%hash, $string);
4680: }
4681: } else {
4682: $value=&get_scalar(\$string,'__END_HASH_REF__');
4683: }
4684: $string =~ s/^&//;
4685:
4686: $hash{$key}=$value;
1.204 albertel 4687: }
1.265 albertel 4688:
4689: $string =~ s/^__END_HASH_REF__//;
4690:
4691: return (\%hash, $string);
1.204 albertel 4692: }
4693:
4694: sub str2array {
1.265 albertel 4695: my ($string)=@_;
4696: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4697: return @$array;
4698: }
4699:
4700: sub str2arrayref {
1.204 albertel 4701: my ($string) = @_;
1.265 albertel 4702: my @array;
4703:
4704: if($string !~ /^__ARRAY_REF__/) {
4705: if (! ($string eq '' || !defined($string))) {
4706: $array[0]='Array reference error';
4707: }
4708: return (\@array, $string);
4709: }
4710:
4711: $string =~ s/^__ARRAY_REF__//;
4712:
4713: while($string !~ /^__END_ARRAY_REF__/) {
4714: my $value='';
4715: if($string =~ /^__HASH_REF__/) {
4716: ($value, $string)=&str2hashref($string);
4717: if(defined($value->{'error'})) {
4718: $array[0] ='Array reference error';
4719: return (\@array, $string);
4720: }
4721: } elsif($string =~ /^__ARRAY_REF__/) {
4722: ($value, $string)=&str2arrayref($string);
4723: if($value->[0] eq 'Array reference error') {
4724: $array[0] ='Array reference error';
4725: return (\@array, $string);
4726: }
4727: } else {
4728: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4729: }
4730: $string =~ s/^&//;
4731:
4732: push(@array, $value);
1.191 harris41 4733: }
1.265 albertel 4734:
4735: $string =~ s/^__END_ARRAY_REF__//;
4736:
4737: return (\@array, $string);
1.168 albertel 4738: }
4739:
1.167 albertel 4740: # -------------------------------------------------------------------Temp Store
4741:
1.168 albertel 4742: sub tmpreset {
4743: my ($symb,$namespace,$domain,$stuname) = @_;
4744: if (!$symb) {
4745: $symb=&symbread();
1.620 albertel 4746: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4747: }
4748: $symb=escape($symb);
4749:
1.620 albertel 4750: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4751: $namespace=~s/\//\_/g;
4752: $namespace=~s/\W//g;
4753:
1.620 albertel 4754: if (!$domain) { $domain=$env{'user.domain'}; }
4755: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4756: if ($domain eq 'public' && $stuname eq 'public') {
4757: $stuname=$ENV{'REMOTE_ADDR'};
4758: }
1.1117 foxr 4759: my $path=LONCAPA::tempdir();
1.168 albertel 4760: my %hash;
4761: if (tie(%hash,'GDBM_File',
4762: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4763: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4764: foreach my $key (keys(%hash)) {
1.180 albertel 4765: if ($key=~ /:$symb/) {
1.168 albertel 4766: delete($hash{$key});
4767: }
4768: }
4769: }
4770: }
4771:
1.167 albertel 4772: sub tmpstore {
1.168 albertel 4773: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4774:
4775: if (!$symb) {
4776: $symb=&symbread();
1.620 albertel 4777: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4778: }
4779: $symb=escape($symb);
4780:
4781: if (!$namespace) {
4782: # I don't think we would ever want to store this for a course.
4783: # it seems this will only be used if we don't have a course.
1.620 albertel 4784: #$namespace=$env{'request.course.id'};
1.168 albertel 4785: #if (!$namespace) {
1.620 albertel 4786: $namespace=$env{'request.state'};
1.168 albertel 4787: #}
4788: }
4789: $namespace=~s/\//\_/g;
4790: $namespace=~s/\W//g;
1.620 albertel 4791: if (!$domain) { $domain=$env{'user.domain'}; }
4792: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4793: if ($domain eq 'public' && $stuname eq 'public') {
4794: $stuname=$ENV{'REMOTE_ADDR'};
4795: }
1.168 albertel 4796: my $now=time;
4797: my %hash;
1.1117 foxr 4798: my $path=LONCAPA::tempdir();
1.168 albertel 4799: if (tie(%hash,'GDBM_File',
4800: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4801: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4802: $hash{"version:$symb"}++;
4803: my $version=$hash{"version:$symb"};
4804: my $allkeys='';
4805: foreach my $key (keys(%$storehash)) {
4806: $allkeys.=$key.':';
1.591 albertel 4807: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4808: }
4809: $hash{"$version:$symb:timestamp"}=$now;
4810: $allkeys.='timestamp';
4811: $hash{"$version:keys:$symb"}=$allkeys;
4812: if (untie(%hash)) {
4813: return 'ok';
4814: } else {
4815: return "error:$!";
4816: }
4817: } else {
4818: return "error:$!";
4819: }
4820: }
1.167 albertel 4821:
1.168 albertel 4822: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4823:
1.168 albertel 4824: sub tmprestore {
4825: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4826:
1.168 albertel 4827: if (!$symb) {
4828: $symb=&symbread();
1.620 albertel 4829: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4830: }
4831: $symb=escape($symb);
4832:
1.620 albertel 4833: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4834:
1.620 albertel 4835: if (!$domain) { $domain=$env{'user.domain'}; }
4836: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4837: if ($domain eq 'public' && $stuname eq 'public') {
4838: $stuname=$ENV{'REMOTE_ADDR'};
4839: }
1.168 albertel 4840: my %returnhash;
4841: $namespace=~s/\//\_/g;
4842: $namespace=~s/\W//g;
4843: my %hash;
1.1117 foxr 4844: my $path=LONCAPA::tempdir();
1.168 albertel 4845: if (tie(%hash,'GDBM_File',
4846: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4847: &GDBM_READER(),0640)) {
1.168 albertel 4848: my $version=$hash{"version:$symb"};
4849: $returnhash{'version'}=$version;
4850: my $scope;
4851: for ($scope=1;$scope<=$version;$scope++) {
4852: my $vkeys=$hash{"$scope:keys:$symb"};
4853: my @keys=split(/:/,$vkeys);
4854: my $key;
4855: $returnhash{"$scope:keys"}=$vkeys;
4856: foreach $key (@keys) {
1.591 albertel 4857: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4858: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4859: }
4860: }
1.168 albertel 4861: if (!(untie(%hash))) {
4862: return "error:$!";
4863: }
4864: } else {
4865: return "error:$!";
4866: }
4867: return %returnhash;
1.167 albertel 4868: }
4869:
1.9 www 4870: # ----------------------------------------------------------------------- Store
4871:
4872: sub store {
1.1269 raeburn 4873: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4874: my $home='';
4875:
1.168 albertel 4876: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4877:
1.213 www 4878: $symb=&symbclean($symb);
1.122 albertel 4879: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4880:
1.620 albertel 4881: if (!$domain) { $domain=$env{'user.domain'}; }
4882: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4883:
4884: &devalidate($symb,$stuname,$domain);
1.109 www 4885:
4886: $symb=escape($symb);
1.187 www 4887: if (!$namespace) {
1.620 albertel 4888: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4889: return '';
4890: }
4891: }
1.620 albertel 4892: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4893:
4894: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4895: $$storehash{'host'}=$perlvar{'lonHostID'};
4896:
1.12 www 4897: my $namevalue='';
1.800 albertel 4898: foreach my $key (keys(%$storehash)) {
4899: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4900: }
1.12 www 4901: $namevalue=~s/\&$//;
1.187 www 4902: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 4903: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 4904: }
4905:
1.47 www 4906: # -------------------------------------------------------------- Critical Store
4907:
4908: sub cstore {
1.1269 raeburn 4909: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4910: my $home='';
4911:
1.168 albertel 4912: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4913:
1.213 www 4914: $symb=&symbclean($symb);
1.122 albertel 4915: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4916:
1.620 albertel 4917: if (!$domain) { $domain=$env{'user.domain'}; }
4918: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4919:
4920: &devalidate($symb,$stuname,$domain);
1.109 www 4921:
4922: $symb=escape($symb);
1.187 www 4923: if (!$namespace) {
1.620 albertel 4924: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4925: return '';
4926: }
4927: }
1.620 albertel 4928: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4929:
4930: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4931: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4932:
1.47 www 4933: my $namevalue='';
1.800 albertel 4934: foreach my $key (keys(%$storehash)) {
4935: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4936: }
1.47 www 4937: $namevalue=~s/\&$//;
1.187 www 4938: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4939: return critical
1.1269 raeburn 4940: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 4941: }
4942:
1.9 www 4943: # --------------------------------------------------------------------- Restore
4944:
4945: sub restore {
1.124 www 4946: my ($symb,$namespace,$domain,$stuname) = @_;
4947: my $home='';
4948:
1.168 albertel 4949: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4950:
1.122 albertel 4951: if (!$symb) {
1.1224 raeburn 4952: return if ($namespace eq 'courserequests');
4953: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4954: } else {
1.1224 raeburn 4955: unless ($namespace eq 'courserequests') {
4956: $symb=&escape(&symbclean($symb));
4957: }
1.122 albertel 4958: }
1.188 www 4959: if (!$namespace) {
1.620 albertel 4960: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4961: return '';
4962: }
4963: }
1.620 albertel 4964: if (!$domain) { $domain=$env{'user.domain'}; }
4965: if (!$stuname) { $stuname=$env{'user.name'}; }
4966: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4967: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4968:
1.12 www 4969: my %returnhash=();
1.800 albertel 4970: foreach my $line (split(/\&/,$answer)) {
4971: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4972: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4973: }
1.75 www 4974: my $version;
4975: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4976: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4977: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4978: }
1.75 www 4979: }
1.13 www 4980: return %returnhash;
1.34 www 4981: }
4982:
4983: # ---------------------------------------------------------- Course Description
1.1118 foxr 4984: #
4985: #
1.34 www 4986:
4987: sub coursedescription {
1.731 albertel 4988: my ($courseid,$args)=@_;
1.34 www 4989: $courseid=~s/^\///;
1.49 www 4990: $courseid=~s/\_/\//g;
1.34 www 4991: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4992: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4993: my $normalid=$cdomain.'_'.$cnum;
4994: # need to always cache even if we get errors otherwise we keep
4995: # trying and trying and trying to get the course description.
4996: my %envhash=();
4997: my %returnhash=();
1.731 albertel 4998:
4999: my $expiretime=600;
5000: if ($env{'request.course.id'} eq $normalid) {
5001: $expiretime=120;
5002: }
5003:
5004: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5005: if (!$args->{'freshen_cache'}
5006: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5007: foreach my $key (keys(%env)) {
5008: next if ($key !~ /^\Q$prefix\E(.*)/);
5009: my ($setting) = $1;
5010: $returnhash{$setting} = $env{$key};
5011: }
5012: return %returnhash;
5013: }
5014:
1.1118 foxr 5015: # get the data again
5016:
1.731 albertel 5017: if (!$args->{'one_time'}) {
5018: $envhash{'course.'.$normalid.'.last_cache'}=time;
5019: }
1.811 albertel 5020:
1.34 www 5021: if ($chome ne 'no_host') {
1.302 albertel 5022: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5023: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5024: my $username = $env{'user.name'}; # Defult username
5025: if(defined $args->{'user'}) {
5026: $username = $args->{'user'};
5027: }
1.129 albertel 5028: $returnhash{'home'}= $chome;
5029: $returnhash{'domain'} = $cdomain;
5030: $returnhash{'num'} = $cnum;
1.741 raeburn 5031: if (!defined($returnhash{'type'})) {
5032: $returnhash{'type'} = 'Course';
5033: }
1.130 albertel 5034: while (my ($name,$value) = each %returnhash) {
1.53 www 5035: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5036: }
1.270 www 5037: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5038: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5039: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5040: $envhash{'course.'.$normalid.'.home'}=$chome;
5041: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5042: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5043: }
5044: }
1.731 albertel 5045: if (!$args->{'one_time'}) {
1.949 raeburn 5046: &appenv(\%envhash);
1.731 albertel 5047: }
1.302 albertel 5048: return %returnhash;
1.461 www 5049: }
5050:
1.1080 raeburn 5051: sub update_released_required {
5052: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5053: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5054: $cid = $env{'request.course.id'};
5055: $cdom = $env{'course.'.$cid.'.domain'};
5056: $cnum = $env{'course.'.$cid.'.num'};
5057: $chome = $env{'course.'.$cid.'.home'};
5058: }
5059: if ($needsrelease) {
5060: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5061: my $needsupdate;
5062: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5063: $needsupdate = 1;
5064: } else {
5065: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5066: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5067: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5068: $needsupdate = 1;
5069: }
5070: }
5071: if ($needsupdate) {
5072: my %needshash = (
5073: 'internal.releaserequired' => $needsrelease,
5074: );
5075: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5076: if ($putresult eq 'ok') {
5077: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5078: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5079: if (ref($crsinfo{$cid}) eq 'HASH') {
5080: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5081: &courseidput($cdom,\%crsinfo,$chome,'notime');
5082: }
5083: }
5084: }
5085: }
5086: return;
5087: }
5088:
1.461 www 5089: # -------------------------------------------------See if a user is privileged
5090:
5091: sub privileged {
1.1219 raeburn 5092: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5093: my $now = time;
1.1219 raeburn 5094: my $roles;
5095: if (ref($possroles) eq 'ARRAY') {
5096: $roles = $possroles;
5097: } else {
5098: $roles = ['dc','su'];
5099: }
5100: if (ref($possdomains) eq 'ARRAY') {
5101: my %privileged = &privileged_by_domain($possdomains,$roles);
5102: foreach my $dom (@{$possdomains}) {
5103: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5104: (ref($privileged{$dom}) eq 'HASH')) {
5105: foreach my $role (@{$roles}) {
5106: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5107: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5108: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5109: return 1 unless (($end && $end < $now) ||
5110: ($start && $start > $now));
5111: }
5112: }
5113: }
5114: }
5115: }
5116: } else {
5117: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5118: my $now = time;
1.1170 droeschl 5119:
1.1275 musolffc 5120: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5121: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5122: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5123: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5124: or ($tstart && $tstart > $now);
1.1170 droeschl 5125: }
1.1219 raeburn 5126: }
5127: }
5128: return 0;
5129: }
1.1170 droeschl 5130:
1.1219 raeburn 5131: sub privileged_by_domain {
5132: my ($domains,$roles) = @_;
5133: my %privileged = ();
5134: my $cachetime = 60*60*24;
5135: my $now = time;
5136: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5137: return %privileged;
5138: }
5139: foreach my $dom (@{$domains}) {
5140: next if (ref($privileged{$dom}) eq 'HASH');
5141: my $needroles;
5142: foreach my $role (@{$roles}) {
5143: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5144: if (defined($cached)) {
5145: if (ref($result) eq 'HASH') {
5146: $privileged{$dom}{$role} = $result;
5147: }
5148: } else {
5149: $needroles = 1;
5150: }
5151: }
5152: if ($needroles) {
5153: my %dompersonnel = &get_domain_roles($dom,$roles);
5154: $privileged{$dom} = {};
5155: foreach my $server (keys(%dompersonnel)) {
5156: if (ref($dompersonnel{$server}) eq 'HASH') {
5157: foreach my $item (keys(%{$dompersonnel{$server}})) {
5158: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5159: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5160: next if ($end && $end < $now);
5161: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5162: $dompersonnel{$server}{$item};
5163: }
5164: }
5165: }
5166: if (ref($privileged{$dom}) eq 'HASH') {
5167: foreach my $role (@{$roles}) {
5168: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5169: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5170: } else {
5171: my %hash = ();
5172: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5173: }
5174: }
5175: }
5176: }
5177: }
5178: return %privileged;
1.9 www 5179: }
1.1 albertel 5180:
1.103 harris41 5181: # -------------------------------------------------------- Get user privileges
1.11 www 5182:
5183: sub rolesinit {
1.1169 droeschl 5184: my ($domain, $username) = @_;
5185: my %userroles = ('user.login.time' => time);
5186: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5187:
5188: # firstaccess and timerinterval are related to timed maps/resources.
5189: # also, blocking can be triggered by an activating timer
5190: # it's saved in the user's %env.
5191: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5192: my %timerinterval = &dump('timerinterval', $domain, $username);
5193: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5194: %timerintchk, %timerintenv);
5195:
1.1162 raeburn 5196: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5197: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5198: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5199: }
1.1169 droeschl 5200:
1.1162 raeburn 5201: foreach my $key (keys(%timerinterval)) {
5202: my ($cid,$rest) = split(/\0/,$key);
5203: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5204: }
1.1169 droeschl 5205:
1.11 www 5206: my %allroles=();
1.1162 raeburn 5207: my %allgroups=();
1.11 www 5208:
1.1274 raeburn 5209: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5210: my $role = $rolesdump{$area};
5211: $area =~ s/\_\w\w$//;
5212:
5213: my ($trole, $tend, $tstart, $group_privs);
5214:
5215: if ($role =~ /^cr/) {
5216: # Custom role, defined by a user
5217: # e.g., user.role.cr/msu/smith/mynewrole
5218: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5219: $trole = $1;
5220: ($tend, $tstart) = split('_', $2);
5221: } else {
5222: $trole = $role;
5223: }
5224: } elsif ($role =~ m|^gr/|) {
5225: # Role of member in a group, defined within a course/community
5226: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5227: ($trole, $tend, $tstart) = split(/_/, $role);
5228: next if $tstart eq '-1';
5229: ($trole, $group_privs) = split(/\//, $trole);
5230: $group_privs = &unescape($group_privs);
5231: } else {
5232: # Just a normal role, defined in roles.tab
5233: ($trole, $tend, $tstart) = split(/_/,$role);
5234: }
5235:
5236: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5237: $username);
5238: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5239:
5240: # role expired or not available yet?
5241: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5242: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5243:
5244: next if $area eq '' or $trole eq '';
5245:
5246: my $spec = "$trole.$area";
5247: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5248:
5249: if ($trole =~ /^cr\//) {
5250: # Custom role, defined by a user
5251: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5252: } elsif ($trole eq 'gr') {
5253: # Role of a member in a group, defined within a course/community
5254: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5255: next;
5256: } else {
5257: # Normal role, defined in roles.tab
5258: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5259: }
5260:
5261: my $cid = $tdomain.'_'.$trest;
5262: unless ($firstaccchk{$cid}) {
5263: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5264: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5265: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5266: $coursetimerstarts{$cid}{$item};
5267: }
5268: }
5269: $firstaccchk{$cid} = 1;
5270: }
5271: unless ($timerintchk{$cid}) {
5272: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5273: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5274: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5275: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5276: }
1.12 www 5277: }
1.1169 droeschl 5278: $timerintchk{$cid} = 1;
1.191 harris41 5279: }
1.11 www 5280: }
1.1169 droeschl 5281:
5282: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5283: \%allroles, \%allgroups);
5284: $env{'user.adv'} = $userroles{'user.adv'};
5285:
1.1162 raeburn 5286: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5287: }
5288:
1.567 raeburn 5289: sub set_arearole {
1.1215 raeburn 5290: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5291: unless ($nolog) {
1.567 raeburn 5292: # log the associated role with the area
1.1215 raeburn 5293: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5294: }
1.743 albertel 5295: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5296: }
5297:
5298: sub custom_roleprivs {
5299: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5300: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5301: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5302: if (&hostname($homsvr) ne '') {
1.567 raeburn 5303: my ($rdummy,$roledef)=
5304: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5305: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5306: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5307: if (defined($syspriv)) {
1.1043 raeburn 5308: if ($trest =~ /^$match_community$/) {
5309: $syspriv =~ s/bre\&S//;
5310: }
1.567 raeburn 5311: $$allroles{'cm./'}.=':'.$syspriv;
5312: $$allroles{$spec.'./'}.=':'.$syspriv;
5313: }
5314: if ($tdomain ne '') {
5315: if (defined($dompriv)) {
5316: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5317: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5318: }
5319: if (($trest ne '') && (defined($coursepriv))) {
5320: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5321: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5322: }
5323: }
5324: }
5325: }
5326: }
5327:
1.678 raeburn 5328: sub group_roleprivs {
5329: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5330: my $access = 1;
5331: my $now = time;
5332: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5333: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5334: if ($access) {
1.811 albertel 5335: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5336: $$allgroups{$course}{$group} .=':'.$group_privs;
5337: }
5338: }
1.567 raeburn 5339:
5340: sub standard_roleprivs {
5341: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5342: if (defined($pr{$trole.':s'})) {
5343: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5344: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5345: }
5346: if ($tdomain ne '') {
5347: if (defined($pr{$trole.':d'})) {
5348: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5349: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5350: }
5351: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5352: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5353: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5354: }
5355: }
5356: }
5357:
5358: sub set_userprivs {
1.1064 raeburn 5359: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5360: my $author=0;
5361: my $adv=0;
1.678 raeburn 5362: my %grouproles = ();
5363: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5364: my @groupkeys;
1.1000 raeburn 5365: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5366: push(@groupkeys,$role);
5367: }
5368: if (ref($groups_roles) eq 'HASH') {
5369: foreach my $key (keys(%{$groups_roles})) {
5370: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5371: push(@groupkeys,$key);
5372: }
5373: }
5374: }
5375: if (@groupkeys > 0) {
5376: foreach my $role (@groupkeys) {
5377: my ($trole,$area,$sec,$extendedarea);
5378: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5379: $trole = $1;
5380: $area = $2;
5381: $sec = $3;
5382: $extendedarea = $area.$sec;
5383: if (exists($$allgroups{$area})) {
5384: foreach my $group (keys(%{$$allgroups{$area}})) {
5385: my $spec = $trole.'.'.$extendedarea;
5386: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5387: $$allgroups{$area}{$group};
1.1064 raeburn 5388: }
1.678 raeburn 5389: }
5390: }
5391: }
5392: }
5393: }
1.800 albertel 5394: foreach my $group (keys(%grouproles)) {
5395: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5396: }
1.800 albertel 5397: foreach my $role (keys(%{$allroles})) {
5398: my %thesepriv;
1.941 raeburn 5399: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5400: foreach my $item (split(/:/,$$allroles{$role})) {
5401: if ($item ne '') {
5402: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5403: if ($restrictions eq '') {
5404: $thesepriv{$privilege}='F';
5405: } elsif ($thesepriv{$privilege} ne 'F') {
5406: $thesepriv{$privilege}.=$restrictions;
5407: }
5408: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5409: }
5410: }
5411: my $thesestr='';
1.1104 raeburn 5412: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5413: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5414: }
5415: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5416: }
5417: return ($author,$adv);
5418: }
5419:
1.994 raeburn 5420: sub role_status {
1.1104 raeburn 5421: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5422: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5423: my ($one,$two) = split(m{\./},$rolekey,2);
5424: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5425: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5426: $$where = '/'.$two;
1.994 raeburn 5427: $$trolecode=$$role.'.'.$$where;
5428: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5429: $$tstatus='is';
1.1104 raeburn 5430: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5431: $$tstatus='future';
1.1034 raeburn 5432: if ($$tstart<$now) {
5433: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5434: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5435: my (%allroles,%allgroups,$group_privs,
5436: %groups_roles,@rolecodes);
1.1002 raeburn 5437: my %userroles = (
5438: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5439: );
1.1064 raeburn 5440: @rolecodes = ('cm');
1.1002 raeburn 5441: my $spec=$$role.'.'.$$where;
5442: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5443: if ($$role =~ /^cr\//) {
5444: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5445: push(@rolecodes,'cr');
1.1002 raeburn 5446: } elsif ($$role eq 'gr') {
1.1064 raeburn 5447: push(@rolecodes,$$role);
1.1002 raeburn 5448: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5449: $env{'user.name'});
1.1064 raeburn 5450: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5451: (undef,my $group_privs) = split(/\//,$trole);
5452: $group_privs = &unescape($group_privs);
5453: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5454: 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 5455: &get_groups_roles($tdomain,$trest,
5456: \%course_roles,\@rolecodes,
5457: \%groups_roles);
1.1002 raeburn 5458: } else {
1.1064 raeburn 5459: push(@rolecodes,$$role);
1.1002 raeburn 5460: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5461: }
1.1064 raeburn 5462: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5463: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5464: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5465: }
5466: }
1.1034 raeburn 5467: $$tstatus = 'is';
1.1002 raeburn 5468: }
1.994 raeburn 5469: }
5470: if ($$tend) {
1.1104 raeburn 5471: if ($$tend<$update) {
1.994 raeburn 5472: $$tstatus='expired';
5473: } elsif ($$tend<$now) {
5474: $$tstatus='will_not';
5475: }
5476: }
5477: }
5478: }
5479: }
5480:
1.1104 raeburn 5481: sub get_groups_roles {
5482: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5483: return unless((ref($cdom_courseroles) eq 'HASH') &&
5484: (ref($rolecodes) eq 'ARRAY') &&
5485: (ref($groups_roles) eq 'HASH'));
5486: if (keys(%{$cdom_courseroles}) > 0) {
5487: my ($cnum) = ($rest =~ /^($match_courseid)/);
5488: if ($cdom ne '' && $cnum ne '') {
5489: foreach my $key (keys(%{$cdom_courseroles})) {
5490: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5491: my $crsrole = $1;
5492: my $crssec = $2;
5493: if ($crsrole =~ /^cr/) {
5494: unless (grep(/^cr$/,@{$rolecodes})) {
5495: push(@{$rolecodes},'cr');
5496: }
5497: } else {
5498: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5499: push(@{$rolecodes},$crsrole);
5500: }
5501: }
5502: my $rolekey = "$crsrole./$cdom/$cnum";
5503: if ($crssec ne '') {
5504: $rolekey .= "/$crssec";
5505: }
5506: $rolekey .= './';
5507: $groups_roles->{$rolekey} = $rolecodes;
5508: }
5509: }
5510: }
5511: }
5512: return;
5513: }
5514:
5515: sub delete_env_groupprivs {
5516: my ($where,$courseroles,$possroles) = @_;
5517: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5518: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5519: unless (ref($courseroles->{$udom}) eq 'HASH') {
5520: %{$courseroles->{$udom}} =
5521: &get_my_roles('','','userroles',['active'],
5522: $possroles,[$udom],1);
5523: }
5524: if (ref($courseroles->{$udom}) eq 'HASH') {
5525: foreach my $item (keys(%{$courseroles->{$udom}})) {
5526: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5527: my $area = '/'.$cdom.'/'.$cnum;
5528: my $privkey = "user.priv.$crsrole.$area";
5529: if ($crssec ne '') {
5530: $privkey .= '/'.$crssec;
5531: }
5532: $privkey .= ".$area/$group";
5533: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5534: }
5535: }
5536: return;
5537: }
5538:
1.994 raeburn 5539: sub check_adhoc_privs {
1.1104 raeburn 5540: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5541: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5542: my $setprivs;
1.994 raeburn 5543: if ($env{$cckey}) {
5544: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5545: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5546: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5547: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5548: $setprivs = 1;
1.994 raeburn 5549: }
5550: } else {
1.1088 raeburn 5551: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5552: $setprivs = 1;
1.994 raeburn 5553: }
1.1185 raeburn 5554: return $setprivs;
1.994 raeburn 5555: }
5556:
5557: sub set_adhoc_privileges {
5558: # role can be cc or ca
1.1088 raeburn 5559: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5560: my $area = '/'.$dcdom.'/'.$pickedcourse;
5561: my $spec = $role.'.'.$area;
5562: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5563: $env{'user.name'},1);
1.994 raeburn 5564: my %ccrole = ();
5565: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5566: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5567: &appenv(\%userroles,[$role,'cm']);
5568: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5569: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5570: &appenv( {'request.role' => $spec,
5571: 'request.role.domain' => $dcdom,
5572: 'request.course.sec' => ''
5573: }
5574: );
5575: my $tadv=0;
5576: if (&allowed('adv') eq 'F') { $tadv=1; }
5577: &appenv({'request.role.adv' => $tadv});
5578: }
1.994 raeburn 5579: }
5580:
1.12 www 5581: # --------------------------------------------------------------- get interface
5582:
5583: sub get {
1.131 albertel 5584: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5585: my $items='';
1.800 albertel 5586: foreach my $item (@$storearr) {
5587: $items.=&escape($item).'&';
1.191 harris41 5588: }
1.12 www 5589: $items=~s/\&$//;
1.620 albertel 5590: if (!$udomain) { $udomain=$env{'user.domain'}; }
5591: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5592: my $uhome=&homeserver($uname,$udomain);
5593:
1.133 albertel 5594: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5595: my @pairs=split(/\&/,$rep);
1.273 albertel 5596: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5597: return @pairs;
5598: }
1.15 www 5599: my %returnhash=();
1.42 www 5600: my $i=0;
1.800 albertel 5601: foreach my $item (@$storearr) {
5602: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5603: $i++;
1.191 harris41 5604: }
1.15 www 5605: return %returnhash;
1.27 www 5606: }
5607:
5608: # --------------------------------------------------------------- del interface
5609:
5610: sub del {
1.133 albertel 5611: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5612: my $items='';
1.800 albertel 5613: foreach my $item (@$storearr) {
5614: $items.=&escape($item).'&';
1.191 harris41 5615: }
1.984 neumanie 5616:
1.27 www 5617: $items=~s/\&$//;
1.620 albertel 5618: if (!$udomain) { $udomain=$env{'user.domain'}; }
5619: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5620: my $uhome=&homeserver($uname,$udomain);
5621: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5622: }
5623:
5624: # -------------------------------------------------------------- dump interface
5625:
1.1180 droeschl 5626: sub unserialize {
5627: my ($rep, $escapedkeys) = @_;
5628:
5629: return {} if $rep =~ /^error/;
5630:
5631: my %returnhash=();
1.1252 raeburn 5632: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5633: my ($key, $value) = split(/=/, $item, 2);
5634: $key = unescape($key) unless $escapedkeys;
5635: next if $key =~ /^error: 2 /;
1.1252 raeburn 5636: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5637: }
5638: #return %returnhash;
5639: return \%returnhash;
5640: }
5641:
5642: # see Lond::dump_with_regexp
5643: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5644: sub dump {
1.1180 droeschl 5645: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5646: if (!$udomain) { $udomain=$env{'user.domain'}; }
5647: if (!$uname) { $uname=$env{'user.name'}; }
5648: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5649:
1.1266 raeburn 5650: if ($regexp) {
5651: $regexp=&escape($regexp);
5652: } else {
5653: $regexp='.';
5654: }
1.1180 droeschl 5655: if (grep { $_ eq $uhome } current_machine_ids()) {
5656: # user is hosted on this machine
1.1266 raeburn 5657: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5658: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5659: return %{unserialize($reply, $escapedkeys)};
5660: }
1.1166 raeburn 5661: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5662: my @pairs=split(/\&/,$rep);
5663: my %returnhash=();
1.1098 foxr 5664: if (!($rep =~ /^error/ )) {
5665: foreach my $item (@pairs) {
5666: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5667: $key = unescape($key) unless $escapedkeys;
5668: #$key = &unescape($key);
1.1098 foxr 5669: next if ($key =~ /^error: 2 /);
5670: $returnhash{$key}=&thaw_unescape($value);
5671: }
1.755 albertel 5672: }
5673: return %returnhash;
1.407 www 5674: }
5675:
1.1098 foxr 5676:
1.717 albertel 5677: # --------------------------------------------------------- dumpstore interface
5678:
5679: sub dumpstore {
5680: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5681: # same as dump but keys must be escaped. They may contain colon separated
5682: # lists of values that may themself contain colons (e.g. symbs).
5683: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5684: }
5685:
1.407 www 5686: # -------------------------------------------------------------- keys interface
5687:
5688: sub getkeys {
5689: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5690: if (!$udomain) { $udomain=$env{'user.domain'}; }
5691: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5692: my $uhome=&homeserver($uname,$udomain);
5693: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5694: my @keyarray=();
1.800 albertel 5695: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5696: next if ($key =~ /^error: 2 /);
1.800 albertel 5697: push(@keyarray,&unescape($key));
1.407 www 5698: }
5699: return @keyarray;
1.318 matthew 5700: }
5701:
1.319 matthew 5702: # --------------------------------------------------------------- currentdump
5703: sub currentdump {
1.328 matthew 5704: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5705: $courseid = $env{'request.course.id'} if (! defined($courseid));
5706: $sdom = $env{'user.domain'} if (! defined($sdom));
5707: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5708: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5709: my $rep;
5710:
5711: if (grep { $_ eq $uhome } current_machine_ids()) {
5712: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5713: $courseid)));
5714: } else {
5715: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5716: }
5717:
1.318 matthew 5718: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5719: #
1.318 matthew 5720: my %returnhash=();
1.319 matthew 5721: #
5722: if ($rep eq "unknown_cmd") {
5723: # an old lond will not know currentdump
5724: # Do a dump and make it look like a currentdump
1.822 albertel 5725: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5726: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5727: my %hash = @tmp;
5728: @tmp=();
1.424 matthew 5729: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5730: } else {
5731: my @pairs=split(/\&/,$rep);
1.800 albertel 5732: foreach my $pair (@pairs) {
5733: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5734: my ($symb,$param) = split(/:/,$key);
5735: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5736: &thaw_unescape($value);
1.319 matthew 5737: }
1.191 harris41 5738: }
1.12 www 5739: return %returnhash;
1.424 matthew 5740: }
5741:
5742: sub convert_dump_to_currentdump{
5743: my %hash = %{shift()};
5744: my %returnhash;
5745: # Code ripped from lond, essentially. The only difference
5746: # here is the unescaping done by lonnet::dump(). Conceivably
5747: # we might run in to problems with parameter names =~ /^v\./
5748: while (my ($key,$value) = each(%hash)) {
5749: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5750: $symb = &unescape($symb);
5751: $param = &unescape($param);
1.424 matthew 5752: next if ($v eq 'version' || $symb eq 'keys');
5753: next if (exists($returnhash{$symb}) &&
5754: exists($returnhash{$symb}->{$param}) &&
5755: $returnhash{$symb}->{'v.'.$param} > $v);
5756: $returnhash{$symb}->{$param}=$value;
5757: $returnhash{$symb}->{'v.'.$param}=$v;
5758: }
5759: #
5760: # Remove all of the keys in the hashes which keep track of
5761: # the version of the parameter.
5762: while (my ($symb,$param_hash) = each(%returnhash)) {
5763: # use a foreach because we are going to delete from the hash.
5764: foreach my $key (keys(%$param_hash)) {
5765: delete($param_hash->{$key}) if ($key =~ /^v\./);
5766: }
5767: }
5768: return \%returnhash;
1.12 www 5769: }
5770:
1.627 albertel 5771: # ------------------------------------------------------ critical inc interface
5772:
5773: sub cinc {
5774: return &inc(@_,'critical');
5775: }
5776:
1.449 matthew 5777: # --------------------------------------------------------------- inc interface
5778:
5779: sub inc {
1.627 albertel 5780: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5781: if (!$udomain) { $udomain=$env{'user.domain'}; }
5782: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5783: my $uhome=&homeserver($uname,$udomain);
5784: my $items='';
5785: if (! ref($store)) {
5786: # got a single value, so use that instead
5787: $items = &escape($store).'=&';
5788: } elsif (ref($store) eq 'SCALAR') {
5789: $items = &escape($$store).'=&';
5790: } elsif (ref($store) eq 'ARRAY') {
5791: $items = join('=&',map {&escape($_);} @{$store});
5792: } elsif (ref($store) eq 'HASH') {
5793: while (my($key,$value) = each(%{$store})) {
5794: $items.= &escape($key).'='.&escape($value).'&';
5795: }
5796: }
5797: $items=~s/\&$//;
1.627 albertel 5798: if ($critical) {
5799: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5800: } else {
5801: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5802: }
1.449 matthew 5803: }
5804:
1.12 www 5805: # --------------------------------------------------------------- put interface
5806:
5807: sub put {
1.134 albertel 5808: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5809: if (!$udomain) { $udomain=$env{'user.domain'}; }
5810: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5811: my $uhome=&homeserver($uname,$udomain);
1.12 www 5812: my $items='';
1.800 albertel 5813: foreach my $item (keys(%$storehash)) {
5814: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5815: }
1.12 www 5816: $items=~s/\&$//;
1.134 albertel 5817: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5818: }
5819:
1.631 albertel 5820: # ------------------------------------------------------------ newput interface
5821:
5822: sub newput {
5823: my ($namespace,$storehash,$udomain,$uname)=@_;
5824: if (!$udomain) { $udomain=$env{'user.domain'}; }
5825: if (!$uname) { $uname=$env{'user.name'}; }
5826: my $uhome=&homeserver($uname,$udomain);
5827: my $items='';
5828: foreach my $key (keys(%$storehash)) {
5829: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5830: }
5831: $items=~s/\&$//;
5832: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5833: }
5834:
5835: # --------------------------------------------------------- putstore interface
5836:
1.524 raeburn 5837: sub putstore {
1.1269 raeburn 5838: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 5839: if (!$udomain) { $udomain=$env{'user.domain'}; }
5840: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5841: my $uhome=&homeserver($uname,$udomain);
5842: my $items='';
1.715 albertel 5843: foreach my $key (keys(%$storehash)) {
5844: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5845: }
1.715 albertel 5846: $items=~s/\&$//;
1.716 albertel 5847: my $esc_symb=&escape($symb);
5848: my $esc_v=&escape($version);
1.715 albertel 5849: my $reply =
1.716 albertel 5850: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5851: $uhome);
1.1269 raeburn 5852: if (($tolog) && ($reply eq 'ok')) {
5853: my $namevalue='';
5854: foreach my $key (keys(%{$storehash})) {
5855: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5856: }
5857: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
5858: '&host='.&escape($perlvar{'lonHostID'}).
5859: '&version='.$esc_v.
5860: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
5861: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
5862: }
1.715 albertel 5863: if ($reply eq 'unknown_cmd') {
1.716 albertel 5864: # gfall back to way things use to be done
1.715 albertel 5865: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5866: $uname);
1.524 raeburn 5867: }
1.715 albertel 5868: return $reply;
5869: }
5870:
5871: sub old_putstore {
1.716 albertel 5872: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5873: if (!$udomain) { $udomain=$env{'user.domain'}; }
5874: if (!$uname) { $uname=$env{'user.name'}; }
5875: my $uhome=&homeserver($uname,$udomain);
5876: my %newstorehash;
1.800 albertel 5877: foreach my $item (keys(%$storehash)) {
5878: my $key = $version.':'.&escape($symb).':'.$item;
5879: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5880: }
5881: my $items='';
5882: my %allitems = ();
1.800 albertel 5883: foreach my $item (keys(%newstorehash)) {
5884: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5885: my $key = $1.':keys:'.$2;
5886: $allitems{$key} .= $3.':';
5887: }
1.800 albertel 5888: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5889: }
1.800 albertel 5890: foreach my $item (keys(%allitems)) {
5891: $allitems{$item} =~ s/\:$//;
5892: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5893: }
5894: $items=~s/\&$//;
5895: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5896: }
5897:
1.47 www 5898: # ------------------------------------------------------ critical put interface
5899:
5900: sub cput {
1.134 albertel 5901: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5902: if (!$udomain) { $udomain=$env{'user.domain'}; }
5903: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5904: my $uhome=&homeserver($uname,$udomain);
1.47 www 5905: my $items='';
1.800 albertel 5906: foreach my $item (keys(%$storehash)) {
5907: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5908: }
1.47 www 5909: $items=~s/\&$//;
1.134 albertel 5910: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5911: }
5912:
5913: # -------------------------------------------------------------- eget interface
5914:
5915: sub eget {
1.133 albertel 5916: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5917: my $items='';
1.800 albertel 5918: foreach my $item (@$storearr) {
5919: $items.=&escape($item).'&';
1.191 harris41 5920: }
1.12 www 5921: $items=~s/\&$//;
1.620 albertel 5922: if (!$udomain) { $udomain=$env{'user.domain'}; }
5923: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5924: my $uhome=&homeserver($uname,$udomain);
5925: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5926: my @pairs=split(/\&/,$rep);
5927: my %returnhash=();
1.42 www 5928: my $i=0;
1.800 albertel 5929: foreach my $item (@$storearr) {
5930: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5931: $i++;
1.191 harris41 5932: }
1.12 www 5933: return %returnhash;
5934: }
5935:
1.667 albertel 5936: # ------------------------------------------------------------ tmpput interface
5937: sub tmpput {
1.802 raeburn 5938: my ($storehash,$server,$context)=@_;
1.667 albertel 5939: my $items='';
1.800 albertel 5940: foreach my $item (keys(%$storehash)) {
5941: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5942: }
5943: $items=~s/\&$//;
1.802 raeburn 5944: if (defined($context)) {
5945: $items .= ':'.&escape($context);
5946: }
1.667 albertel 5947: return &reply("tmpput:$items",$server);
5948: }
5949:
5950: # ------------------------------------------------------------ tmpget interface
5951: sub tmpget {
1.688 albertel 5952: my ($token,$server)=@_;
5953: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5954: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5955: my %returnhash;
5956: foreach my $item (split(/\&/,$rep)) {
5957: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5958: next if ($key =~ /^error: 2 /);
1.667 albertel 5959: $returnhash{&unescape($key)}=&thaw_unescape($value);
5960: }
5961: return %returnhash;
5962: }
5963:
1.1113 raeburn 5964: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5965: sub tmpdel {
5966: my ($token,$server)=@_;
5967: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5968: return &reply("tmpdel:$token",$server);
5969: }
5970:
1.1198 raeburn 5971: # ------------------------------------------------------------ get_timebased_id
5972:
5973: sub get_timebased_id {
5974: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5975: $maxtries) = @_;
5976: my ($newid,$error,$dellock);
5977: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5978: return ('','ok','invalid call to get suffix');
5979: }
5980:
5981: # set defaults for any optional args for which values were not supplied
5982: if ($who eq '') {
5983: $who = $env{'user.name'}.':'.$env{'user.domain'};
5984: }
5985: if (!$locktries) {
5986: $locktries = 3;
5987: }
5988: if (!$maxtries) {
5989: $maxtries = 10;
5990: }
5991:
5992: if (($cdom eq '') || ($cnum eq '')) {
5993: if ($env{'request.course.id'}) {
5994: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5995: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5996: }
5997: if (($cdom eq '') || ($cnum eq '')) {
5998: return ('','ok','call to get suffix not in course context');
5999: }
6000: }
6001:
6002: # construct locking item
6003: my $lockhash = {
6004: $prefix."\0".'locked_'.$keyid => $who,
6005: };
6006: my $tries = 0;
6007:
6008: # attempt to get lock on nohist_$namespace file
6009: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6010: while (($gotlock ne 'ok') && $tries <$locktries) {
6011: $tries ++;
6012: sleep 1;
6013: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6014: }
6015:
6016: # attempt to get unique identifier, based on current timestamp
6017: if ($gotlock eq 'ok') {
6018: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6019: my $id = time;
6020: $newid = $id;
1.1268 raeburn 6021: if ($idtype eq 'addcode') {
6022: $newid .= &sixnum_code();
6023: }
1.1198 raeburn 6024: my $idtries = 0;
6025: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6026: if ($idtype eq 'concat') {
6027: $newid = $id.$idtries;
1.1268 raeburn 6028: } elsif ($idtype eq 'addcode') {
6029: $newid = $newid.&sixnum_code();
1.1198 raeburn 6030: } else {
6031: $newid ++;
6032: }
6033: $idtries ++;
6034: }
6035: if (!exists($inuse{$prefix."\0".$newid})) {
6036: my %new_item = (
6037: $prefix."\0".$newid => $who,
6038: );
6039: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6040: $cdom,$cnum);
6041: if ($putresult ne 'ok') {
6042: undef($newid);
6043: $error = 'error saving new item: '.$putresult;
6044: }
6045: } else {
1.1268 raeburn 6046: undef($newid);
1.1198 raeburn 6047: $error = ('error: no unique suffix available for the new item ');
6048: }
6049: # remove lock
6050: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6051: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6052: } else {
6053: $error = "error: could not obtain lockfile\n";
6054: $dellock = 'ok';
1.1276 raeburn 6055: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6056: $dellock = 'nolock';
6057: }
1.1198 raeburn 6058: }
6059: return ($newid,$dellock,$error);
6060: }
6061:
1.1268 raeburn 6062: sub sixnum_code {
6063: my $code;
6064: for (0..6) {
6065: $code .= int( rand(9) );
6066: }
6067: return $code;
6068: }
6069:
1.765 albertel 6070: # -------------------------------------------------- portfolio access checking
6071:
6072: sub portfolio_access {
1.1270 raeburn 6073: my ($requrl,$clientip) = @_;
1.765 albertel 6074: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6075: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6076: if ($result) {
6077: my %setters;
6078: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6079: my ($startblock,$endblock) =
6080: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6081: if ($startblock && $endblock) {
6082: return 'B';
6083: }
6084: } else {
6085: my ($startblock,$endblock) =
6086: &Apache::loncommon::blockcheck(\%setters,'port');
6087: if ($startblock && $endblock) {
6088: return 'B';
6089: }
6090: }
6091: }
1.765 albertel 6092: if ($result eq 'ok') {
1.766 albertel 6093: return 'F';
1.765 albertel 6094: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6095: return 'A';
1.765 albertel 6096: }
1.766 albertel 6097: return '';
1.765 albertel 6098: }
6099:
6100: sub get_portfolio_access {
1.1270 raeburn 6101: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6102:
6103: if (!ref($access_hash)) {
6104: my $current_perms = &get_portfile_permissions($udom,$unum);
6105: my %access_controls = &get_access_controls($current_perms,$group,
6106: $file_name);
6107: $access_hash = $access_controls{$file_name};
6108: }
6109:
1.1270 raeburn 6110: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6111: my $now = time;
6112: if (ref($access_hash) eq 'HASH') {
6113: foreach my $key (keys(%{$access_hash})) {
6114: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6115: if ($start > $now) {
6116: next;
6117: }
6118: if ($end && $end<$now) {
6119: next;
6120: }
6121: if ($scope eq 'public') {
6122: $public = $key;
6123: last;
6124: } elsif ($scope eq 'guest') {
6125: $guest = $key;
6126: } elsif ($scope eq 'domains') {
6127: push(@domains,$key);
6128: } elsif ($scope eq 'users') {
6129: push(@users,$key);
6130: } elsif ($scope eq 'course') {
6131: push(@courses,$key);
6132: } elsif ($scope eq 'group') {
6133: push(@groups,$key);
1.1270 raeburn 6134: } elsif ($scope eq 'ip') {
6135: push(@ips,$key);
1.765 albertel 6136: }
6137: }
6138: if ($public) {
6139: return 'ok';
1.1270 raeburn 6140: } elsif (@ips > 0) {
6141: my $allowed;
6142: foreach my $ipkey (@ips) {
6143: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6144: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6145: $allowed = 1;
6146: last;
6147: }
6148: }
6149: }
6150: if ($allowed) {
6151: return 'ok';
6152: }
1.765 albertel 6153: }
6154: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6155: if ($guest) {
6156: return $guest;
6157: }
6158: } else {
6159: if (@domains > 0) {
6160: foreach my $domkey (@domains) {
6161: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6162: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6163: return 'ok';
6164: }
6165: }
6166: }
6167: }
6168: if (@users > 0) {
6169: foreach my $userkey (@users) {
1.865 raeburn 6170: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6171: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6172: if (ref($item) eq 'HASH') {
6173: if (($item->{'uname'} eq $env{'user.name'}) &&
6174: ($item->{'udom'} eq $env{'user.domain'})) {
6175: return 'ok';
6176: }
6177: }
6178: }
6179: }
1.765 albertel 6180: }
6181: }
6182: my %roleshash;
6183: my @courses_and_groups = @courses;
6184: push(@courses_and_groups,@groups);
6185: if (@courses_and_groups > 0) {
6186: my (%allgroups,%allroles);
6187: my ($start,$end,$role,$sec,$group);
6188: foreach my $envkey (%env) {
1.1060 raeburn 6189: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6190: my $cid = $2.'_'.$3;
6191: if ($1 eq 'gr') {
6192: $group = $4;
6193: $allgroups{$cid}{$group} = $env{$envkey};
6194: } else {
6195: if ($4 eq '') {
6196: $sec = 'none';
6197: } else {
6198: $sec = $4;
6199: }
6200: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6201: }
1.811 albertel 6202: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6203: my $cid = $2.'_'.$3;
6204: if ($4 eq '') {
6205: $sec = 'none';
6206: } else {
6207: $sec = $4;
6208: }
6209: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6210: }
6211: }
6212: if (keys(%allroles) == 0) {
6213: return;
6214: }
6215: foreach my $key (@courses_and_groups) {
6216: my %content = %{$$access_hash{$key}};
6217: my $cnum = $content{'number'};
6218: my $cdom = $content{'domain'};
6219: my $cid = $cdom.'_'.$cnum;
6220: if (!exists($allroles{$cid})) {
6221: next;
6222: }
6223: foreach my $role_id (keys(%{$content{'roles'}})) {
6224: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6225: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6226: my @status = @{$content{'roles'}{$role_id}{'access'}};
6227: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6228: foreach my $role (keys(%{$allroles{$cid}})) {
6229: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6230: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6231: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6232: if (grep/^all$/,@sections) {
6233: return 'ok';
6234: } else {
6235: if (grep/^$sec$/,@sections) {
6236: return 'ok';
6237: }
6238: }
6239: }
6240: }
6241: if (keys(%{$allgroups{$cid}}) == 0) {
6242: if (grep/^none$/,@groups) {
6243: return 'ok';
6244: }
6245: } else {
6246: if (grep/^all$/,@groups) {
6247: return 'ok';
6248: }
6249: foreach my $group (keys(%{$allgroups{$cid}})) {
6250: if (grep/^$group$/,@groups) {
6251: return 'ok';
6252: }
6253: }
6254: }
6255: }
6256: }
6257: }
6258: }
6259: }
6260: if ($guest) {
6261: return $guest;
6262: }
6263: }
6264: }
6265: return;
6266: }
6267:
6268: sub course_group_datechecker {
6269: my ($dates,$now,$status) = @_;
6270: my ($start,$end) = split(/\./,$dates);
6271: if (!$start && !$end) {
6272: return 'ok';
6273: }
6274: if (grep/^active$/,@{$status}) {
6275: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6276: return 'ok';
6277: }
6278: }
6279: if (grep/^previous$/,@{$status}) {
6280: if ($end > $now ) {
6281: return 'ok';
6282: }
6283: }
6284: if (grep/^future$/,@{$status}) {
6285: if ($start > $now) {
6286: return 'ok';
6287: }
6288: }
6289: return;
6290: }
6291:
6292: sub parse_portfolio_url {
6293: my ($url) = @_;
6294:
6295: my ($type,$udom,$unum,$group,$file_name);
6296:
1.823 albertel 6297: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6298: $type = 1;
6299: $udom = $1;
6300: $unum = $2;
6301: $file_name = $3;
1.823 albertel 6302: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6303: $type = 2;
6304: $udom = $1;
6305: $unum = $2;
6306: $group = $3;
6307: $file_name = $3.'/'.$4;
6308: }
6309: if (wantarray) {
6310: return ($type,$udom,$unum,$file_name,$group);
6311: }
6312: return $type;
6313: }
6314:
6315: sub is_portfolio_url {
6316: my ($url) = @_;
6317: return scalar(&parse_portfolio_url($url));
6318: }
6319:
1.798 raeburn 6320: sub is_portfolio_file {
6321: my ($file) = @_;
1.820 raeburn 6322: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6323: return 1;
6324: }
6325: return;
6326: }
6327:
1.976 raeburn 6328: sub usertools_access {
1.1084 raeburn 6329: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6330: my ($access,%tools);
6331: if ($context eq '') {
6332: $context = 'tools';
6333: }
6334: if ($context eq 'requestcourses') {
6335: %tools = (
6336: official => 1,
6337: unofficial => 1,
1.1006 raeburn 6338: community => 1,
1.1246 raeburn 6339: textbook => 1,
1.985 raeburn 6340: );
1.1183 raeburn 6341: } elsif ($context eq 'requestauthor') {
6342: %tools = (
6343: requestauthor => 1,
6344: );
1.985 raeburn 6345: } else {
6346: %tools = (
6347: aboutme => 1,
6348: blog => 1,
1.1177 raeburn 6349: webdav => 1,
1.985 raeburn 6350: portfolio => 1,
6351: );
6352: }
1.976 raeburn 6353: return if (!defined($tools{$tool}));
6354:
1.1242 raeburn 6355: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6356: $udom = $env{'user.domain'};
6357: $uname = $env{'user.name'};
6358: }
6359:
1.978 raeburn 6360: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6361: if ($action ne 'reload') {
1.985 raeburn 6362: if ($context eq 'requestcourses') {
6363: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6364: } elsif ($context eq 'requestauthor') {
6365: return $env{'environment.canrequest.author'};
1.985 raeburn 6366: } else {
6367: return $env{'environment.availabletools.'.$tool};
6368: }
6369: }
1.976 raeburn 6370: }
6371:
1.1183 raeburn 6372: my ($toolstatus,$inststatus,$envkey);
6373: if ($context eq 'requestauthor') {
6374: $envkey = $context;
6375: } else {
6376: $envkey = $context.'.'.$tool;
6377: }
1.976 raeburn 6378:
1.985 raeburn 6379: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6380: ($action ne 'reload')) {
1.1183 raeburn 6381: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6382: $inststatus = $env{'environment.inststatus'};
6383: } else {
1.1084 raeburn 6384: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6385: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6386: $inststatus = $userenvref->{'inststatus'};
6387: } else {
1.1183 raeburn 6388: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6389: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6390: $inststatus = $userenv{'inststatus'};
6391: }
1.976 raeburn 6392: }
6393:
6394: if ($toolstatus ne '') {
6395: if ($toolstatus) {
6396: $access = 1;
6397: } else {
6398: $access = 0;
6399: }
6400: return $access;
6401: }
6402:
1.1084 raeburn 6403: my ($is_adv,%domdef);
6404: if (ref($is_advref) eq 'HASH') {
6405: $is_adv = $is_advref->{'is_adv'};
6406: } else {
6407: $is_adv = &is_advanced_user($udom,$uname);
6408: }
6409: if (ref($domdefref) eq 'HASH') {
6410: %domdef = %{$domdefref};
6411: } else {
6412: %domdef = &get_domain_defaults($udom);
6413: }
1.976 raeburn 6414: if (ref($domdef{$tool}) eq 'HASH') {
6415: if ($is_adv) {
6416: if ($domdef{$tool}{'_LC_adv'} ne '') {
6417: if ($domdef{$tool}{'_LC_adv'}) {
6418: $access = 1;
6419: } else {
6420: $access = 0;
6421: }
6422: return $access;
6423: }
6424: }
6425: if ($inststatus ne '') {
6426: my ($hasaccess,$hasnoaccess);
6427: foreach my $affiliation (split(/:/,$inststatus)) {
6428: if ($domdef{$tool}{$affiliation} ne '') {
6429: if ($domdef{$tool}{$affiliation}) {
6430: $hasaccess = 1;
6431: } else {
6432: $hasnoaccess = 1;
6433: }
6434: }
6435: }
6436: if ($hasaccess || $hasnoaccess) {
6437: if ($hasaccess) {
6438: $access = 1;
6439: } elsif ($hasnoaccess) {
6440: $access = 0;
6441: }
6442: return $access;
6443: }
6444: } else {
6445: if ($domdef{$tool}{'default'} ne '') {
6446: if ($domdef{$tool}{'default'}) {
6447: $access = 1;
6448: } elsif ($domdef{$tool}{'default'} == 0) {
6449: $access = 0;
6450: }
6451: return $access;
6452: }
6453: }
6454: } else {
1.1177 raeburn 6455: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6456: $access = 1;
6457: } else {
6458: $access = 0;
6459: }
1.976 raeburn 6460: return $access;
6461: }
6462: }
6463:
1.1050 raeburn 6464: sub is_course_owner {
6465: my ($cdom,$cnum,$udom,$uname) = @_;
6466: if (($udom eq '') || ($uname eq '')) {
6467: $udom = $env{'user.domain'};
6468: $uname = $env{'user.name'};
6469: }
6470: unless (($udom eq '') || ($uname eq '')) {
6471: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6472: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6473: return 1;
6474: } else {
6475: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6476: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6477: return 1;
6478: }
6479: }
6480: }
6481: }
6482: return;
6483: }
6484:
1.976 raeburn 6485: sub is_advanced_user {
6486: my ($udom,$uname) = @_;
1.1085 raeburn 6487: if ($udom ne '' && $uname ne '') {
6488: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6489: if (wantarray) {
6490: return ($env{'user.adv'},$env{'user.author'});
6491: } else {
6492: return $env{'user.adv'};
6493: }
1.1085 raeburn 6494: }
6495: }
1.976 raeburn 6496: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6497: my %allroles;
1.1128 raeburn 6498: my ($is_adv,$is_author);
1.976 raeburn 6499: foreach my $role (keys(%roleshash)) {
6500: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6501: my $area = '/'.$tdomain.'/'.$trest;
6502: if ($sec ne '') {
6503: $area .= '/'.$sec;
6504: }
6505: if (($area ne '') && ($trole ne '')) {
6506: my $spec=$trole.'.'.$area;
6507: if ($trole =~ /^cr\//) {
6508: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6509: } elsif ($trole ne 'gr') {
6510: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6511: }
1.1128 raeburn 6512: if ($trole eq 'au') {
6513: $is_author = 1;
6514: }
1.976 raeburn 6515: }
6516: }
6517: foreach my $role (keys(%allroles)) {
6518: last if ($is_adv);
6519: foreach my $item (split(/:/,$allroles{$role})) {
6520: if ($item ne '') {
6521: my ($privilege,$restrictions)=split(/&/,$item);
6522: if ($privilege eq 'adv') {
6523: $is_adv = 1;
6524: last;
6525: }
6526: }
6527: }
6528: }
1.1128 raeburn 6529: if (wantarray) {
6530: return ($is_adv,$is_author);
6531: }
1.976 raeburn 6532: return $is_adv;
6533: }
1.798 raeburn 6534:
1.1035 raeburn 6535: sub check_can_request {
1.1036 raeburn 6536: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6537: my $canreq = 0;
6538: my ($types,$typename) = &Apache::loncommon::course_types();
6539: my @options = ('approval','validate','autolimit');
6540: my $optregex = join('|',@options);
6541: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6542: foreach my $type (@{$types}) {
6543: if (&usertools_access($env{'user.name'},
6544: $env{'user.domain'},
6545: $type,undef,'requestcourses')) {
6546: $canreq ++;
1.1036 raeburn 6547: if (ref($request_domains) eq 'HASH') {
6548: push(@{$request_domains->{$type}},$env{'user.domain'});
6549: }
1.1035 raeburn 6550: if ($dom eq $env{'user.domain'}) {
6551: $can_request->{$type} = 1;
6552: }
6553: }
6554: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6555: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6556: if (@curr > 0) {
1.1036 raeburn 6557: foreach my $item (@curr) {
6558: if (ref($request_domains) eq 'HASH') {
6559: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6560: if ($otherdom ne '') {
6561: if (ref($request_domains->{$type}) eq 'ARRAY') {
6562: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6563: push(@{$request_domains->{$type}},$otherdom);
6564: }
6565: } else {
6566: push(@{$request_domains->{$type}},$otherdom);
6567: }
6568: }
6569: }
6570: }
6571: unless($dom eq $env{'user.domain'}) {
6572: $canreq ++;
1.1035 raeburn 6573: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6574: $can_request->{$type} = 1;
6575: }
6576: }
6577: }
6578: }
6579: }
6580: }
6581: return $canreq;
6582: }
6583:
1.341 www 6584: # ---------------------------------------------- Custom access rule evaluation
6585:
6586: sub customaccess {
6587: my ($priv,$uri)=@_;
1.807 albertel 6588: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6589: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6590: $udom = &LONCAPA::clean_domain($udom);
6591: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6592: my $access=0;
1.800 albertel 6593: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6594: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6595: if ($type eq 'user') {
6596: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6597: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6598: if ($tdom) {
6599: if ($tdom ne $env{'user.domain'}) { next; }
6600: }
1.896 albertel 6601: if ($tuname) {
6602: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6603: }
6604: $access=($effect eq 'allow');
6605: last;
6606: }
6607: } else {
6608: if ($role) {
6609: if ($role ne $urole) { next; }
6610: }
6611: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6612: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6613: if ($tdom) {
6614: if ($tdom ne $udom) { next; }
6615: }
6616: if ($tcrs) {
6617: if ($tcrs ne $ucrs) { next; }
6618: }
6619: if ($tsec) {
6620: if ($tsec ne $usec) { next; }
6621: }
6622: $access=($effect eq 'allow');
6623: last;
6624: }
6625: if ($realm eq '' && $role eq '') {
6626: $access=($effect eq 'allow');
6627: }
1.402 bowersj2 6628: }
1.341 www 6629: }
6630: return $access;
6631: }
6632:
1.103 harris41 6633: # ------------------------------------------------- Check for a user privilege
1.12 www 6634:
6635: sub allowed {
1.1270 raeburn 6636: my ($priv,$uri,$symb,$role,$clientip)=@_;
1.705 albertel 6637: my $ver_orguri=$uri;
1.439 www 6638: $uri=&deversion($uri);
1.152 www 6639: my $orguri=$uri;
1.52 www 6640: $uri=&declutter($uri);
1.809 raeburn 6641:
1.810 raeburn 6642: if ($priv eq 'evb') {
6643: # Evade communication block restrictions for specified role in a course
6644: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6645: return $1;
6646: } else {
6647: return;
6648: }
6649: }
6650:
1.620 albertel 6651: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6652: # Free bre access to adm and meta resources
1.775 albertel 6653: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6654: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6655: && ($priv eq 'bre')) {
1.14 www 6656: return 'F';
1.159 www 6657: }
6658:
1.545 banghart 6659: # Free bre access to user's own portfolio contents
1.714 raeburn 6660: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6661: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6662: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6663: my %setters;
6664: my ($startblock,$endblock) =
6665: &Apache::loncommon::blockcheck(\%setters,'port');
6666: if ($startblock && $endblock) {
6667: return 'B';
6668: } else {
6669: return 'F';
6670: }
1.545 banghart 6671: }
6672:
1.762 raeburn 6673: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6674: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6675: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6676: if (exists($env{'request.course.id'})) {
6677: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6678: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6679: if (($domain eq $cdom) && ($name eq $cnum)) {
6680: my $courseprivid=$env{'request.course.id'};
6681: $courseprivid=~s/\_/\//;
6682: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6683: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6684: return $1;
1.762 raeburn 6685: } else {
6686: if ($env{'request.course.sec'}) {
6687: $courseprivid.='/'.$env{'request.course.sec'};
6688: }
6689: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6690: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6691: return $2;
6692: }
1.714 raeburn 6693: }
6694: }
6695: }
6696: }
6697:
1.159 www 6698: # Free bre to public access
6699:
6700: if ($priv eq 'bre') {
1.238 www 6701: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6702: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6703: return 'F';
6704: }
1.238 www 6705: if ($copyright eq 'priv') {
6706: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6707: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6708: return '';
6709: }
6710: }
6711: if ($copyright eq 'domain') {
6712: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6713: unless (($env{'user.domain'} eq $1) ||
6714: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6715: return '';
6716: }
1.262 matthew 6717: }
1.620 albertel 6718: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6719: # Library role, so allow browsing of resources in this domain.
6720: return 'F';
1.238 www 6721: }
1.341 www 6722: if ($copyright eq 'custom') {
6723: unless (&customaccess($priv,$uri)) { return ''; }
6724: }
1.14 www 6725: }
1.264 matthew 6726: # Domain coordinator is trying to create a course
1.620 albertel 6727: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6728: # uri is the requested domain in this case.
6729: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6730: # a role of dc for the domain in question.
1.620 albertel 6731: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6732: }
1.29 www 6733:
1.52 www 6734: my $thisallowed='';
6735: my $statecond=0;
6736: my $courseprivid='';
6737:
1.1039 raeburn 6738: my $ownaccess;
1.1043 raeburn 6739: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6740: if (($priv eq 'bro') && ($env{'user.author'})) {
6741: if ($uri eq '') {
6742: $ownaccess = 1;
6743: } else {
6744: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6745: my $udom = $env{'user.domain'};
6746: my $uname = $env{'user.name'};
6747: if ($uri =~ m{^\Q$udom\E/?$}) {
6748: $ownaccess = 1;
1.1040 raeburn 6749: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6750: unless ($uri =~ m{\.\./}) {
6751: $ownaccess = 1;
6752: }
6753: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6754: my $now = time;
6755: if ($uri =~ m{^([^/]+)/?$}) {
6756: my $adom = $1;
6757: foreach my $key (keys(%env)) {
1.1042 raeburn 6758: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6759: my ($start,$end) = split('.',$env{$key});
6760: if (($now >= $start) && (!$end || $end < $now)) {
6761: $ownaccess = 1;
6762: last;
6763: }
6764: }
6765: }
6766: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6767: my $adom = $1;
6768: my $aname = $2;
1.1042 raeburn 6769: foreach my $role ('ca','aa') {
6770: if ($env{"user.role.$role./$adom/$aname"}) {
6771: my ($start,$end) =
6772: split('.',$env{"user.role.$role./$adom/$aname"});
6773: if (($now >= $start) && (!$end || $end < $now)) {
6774: $ownaccess = 1;
6775: last;
6776: }
1.1039 raeburn 6777: }
6778: }
6779: }
6780: }
6781: }
6782: }
6783: }
6784:
1.52 www 6785: # Course
6786:
1.620 albertel 6787: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6788: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6789: $thisallowed.=$1;
6790: }
1.52 www 6791: }
1.29 www 6792:
1.52 www 6793: # Domain
6794:
1.620 albertel 6795: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6796: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6797: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6798: $thisallowed.=$1;
6799: }
1.12 www 6800: }
1.52 www 6801:
1.1141 raeburn 6802: # User who is not author or co-author might still be able to edit
6803: # resource of an author in the domain (e.g., if Domain Coordinator).
6804: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6805: (&allowed('mdc',$env{'request.course.id'}))) {
6806: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6807: $thisallowed.=$1;
6808: }
6809: }
6810:
1.52 www 6811: # Course: uri itself is a course
1.66 www 6812: my $courseuri=$uri;
6813: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6814: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6815:
1.620 albertel 6816: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6817: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6818: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6819: $thisallowed.=$1;
6820: }
1.12 www 6821: }
1.29 www 6822:
1.665 albertel 6823: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6824: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6825: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6826: $thisallowed='';
1.671 raeburn 6827: my ($match)=&is_on_map($uri);
6828: if ($match) {
6829: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6830: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6831: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6832: if (@blockers > 0) {
6833: $thisallowed = 'B';
6834: } else {
6835: $thisallowed.=$1;
6836: }
1.671 raeburn 6837: }
6838: } else {
1.705 albertel 6839: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6840: if ($refuri) {
6841: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6842: $thisallowed='F';
1.671 raeburn 6843: } else {
6844: $refuri=&declutter($refuri);
6845: my ($match) = &is_on_map($refuri);
6846: if ($match) {
1.1162 raeburn 6847: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6848: if (@blockers > 0) {
6849: $thisallowed = 'B';
6850: } else {
6851: $thisallowed='F';
6852: }
1.671 raeburn 6853: }
1.669 raeburn 6854: }
1.671 raeburn 6855: }
6856: }
1.314 www 6857: }
1.492 albertel 6858:
1.766 albertel 6859: if ($priv eq 'bre'
6860: && $thisallowed ne 'F'
6861: && $thisallowed ne '2'
6862: && &is_portfolio_url($uri)) {
1.1270 raeburn 6863: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 6864: }
1.1250 raeburn 6865:
1.52 www 6866: # Full access at system, domain or course-wide level? Exit.
1.29 www 6867: if ($thisallowed=~/F/) {
6868: return 'F';
6869: }
6870:
1.52 www 6871: # If this is generating or modifying users, exit with special codes
1.29 www 6872:
1.643 www 6873: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6874: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6875: my ($audom,$auname)=split('/',$uri);
1.643 www 6876: # no author name given, so this just checks on the general right to make a co-author in this domain
6877: unless ($auname) { return $thisallowed; }
6878: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6879: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6880: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6881: ($audom ne $env{'request.role.domain'}))) { return ''; }
6882: }
1.52 www 6883: return $thisallowed;
6884: }
6885: #
1.103 harris41 6886: # Gathered so far: system, domain and course wide privileges
1.52 www 6887: #
6888: # Course: See if uri or referer is an individual resource that is part of
6889: # the course
6890:
1.620 albertel 6891: if ($env{'request.course.id'}) {
1.232 www 6892:
1.620 albertel 6893: $courseprivid=$env{'request.course.id'};
6894: if ($env{'request.course.sec'}) {
6895: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6896: }
6897: $courseprivid=~s/\_/\//;
6898: my $checkreferer=1;
1.232 www 6899: my ($match,$cond)=&is_on_map($uri);
6900: if ($match) {
6901: $statecond=$cond;
1.620 albertel 6902: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6903: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6904: my $value = $1;
6905: if ($priv eq 'bre') {
6906: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6907: if (@blockers > 0) {
6908: $thisallowed = 'B';
6909: } else {
6910: $thisallowed.=$value;
6911: }
6912: } else {
6913: $thisallowed.=$value;
6914: }
1.52 www 6915: $checkreferer=0;
6916: }
1.29 www 6917: }
1.83 www 6918:
1.148 www 6919: if ($checkreferer) {
1.620 albertel 6920: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6921: unless ($refuri) {
1.800 albertel 6922: foreach my $key (keys(%env)) {
6923: if ($key=~/^httpref\..*\*/) {
6924: my $pattern=$key;
1.156 www 6925: $pattern=~s/^httpref\.\/res\///;
1.148 www 6926: $pattern=~s/\*/\[\^\/\]\+/g;
6927: $pattern=~s/\//\\\//g;
1.152 www 6928: if ($orguri=~/$pattern/) {
1.800 albertel 6929: $refuri=$env{$key};
1.148 www 6930: }
6931: }
1.191 harris41 6932: }
1.148 www 6933: }
1.232 www 6934:
1.148 www 6935: if ($refuri) {
1.152 www 6936: $refuri=&declutter($refuri);
1.232 www 6937: my ($match,$cond)=&is_on_map($refuri);
6938: if ($match) {
6939: my $refstatecond=$cond;
1.620 albertel 6940: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6941: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6942: my $value = $1;
6943: if ($priv eq 'bre') {
6944: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6945: if (@blockers > 0) {
6946: $thisallowed = 'B';
6947: } else {
6948: $thisallowed.=$value;
6949: }
6950: } else {
6951: $thisallowed.=$value;
6952: }
1.53 www 6953: $uri=$refuri;
6954: $statecond=$refstatecond;
1.52 www 6955: }
6956: }
1.148 www 6957: }
1.29 www 6958: }
1.52 www 6959: }
1.29 www 6960:
1.52 www 6961: #
1.103 harris41 6962: # Gathered now: all privileges that could apply, and condition number
1.52 www 6963: #
6964: #
6965: # Full or no access?
6966: #
1.29 www 6967:
1.52 www 6968: if ($thisallowed=~/F/) {
6969: return 'F';
6970: }
1.29 www 6971:
1.52 www 6972: unless ($thisallowed) {
6973: return '';
6974: }
1.29 www 6975:
1.52 www 6976: # Restrictions exist, deal with them
6977: #
6978: # C:according to course preferences
6979: # R:according to resource settings
6980: # L:unless locked
6981: # X:according to user session state
6982: #
6983:
6984: # Possibly locked functionality, check all courses
1.54 www 6985: # Locks might take effect only after 10 minutes cache expiration for other
6986: # courses, and 2 minutes for current course
1.52 www 6987:
6988: my $envkey;
6989: if ($thisallowed=~/L/) {
1.1000 raeburn 6990: foreach $envkey (keys(%env)) {
1.54 www 6991: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6992: my $courseid=$2;
6993: my $roleid=$1.'.'.$2;
1.92 www 6994: $courseid=~s/^\///;
1.54 www 6995: my $expiretime=600;
1.620 albertel 6996: if ($env{'request.role'} eq $roleid) {
1.54 www 6997: $expiretime=120;
6998: }
6999: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7000: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7001: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7002: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7003: }
1.620 albertel 7004: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7005: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7006: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7007: &log($env{'user.domain'},$env{'user.name'},
7008: $env{'user.home'},
1.57 www 7009: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7010: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7011: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7012: return '';
7013: }
7014: }
1.620 albertel 7015: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7016: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7017: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7018: &log($env{'user.domain'},$env{'user.name'},
7019: $env{'user.home'},
1.57 www 7020: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7021: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7022: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7023: return '';
7024: }
7025: }
7026: }
1.29 www 7027: }
1.52 www 7028: }
7029:
7030: #
7031: # Rest of the restrictions depend on selected course
7032: #
7033:
1.620 albertel 7034: unless ($env{'request.course.id'}) {
1.766 albertel 7035: if ($thisallowed eq 'A') {
7036: return 'A';
1.814 raeburn 7037: } elsif ($thisallowed eq 'B') {
7038: return 'B';
1.766 albertel 7039: } else {
7040: return '1';
7041: }
1.52 www 7042: }
1.29 www 7043:
1.52 www 7044: #
7045: # Now user is definitely in a course
7046: #
1.53 www 7047:
7048:
7049: # Course preferences
7050:
7051: if ($thisallowed=~/C/) {
1.620 albertel 7052: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7053: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7054: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7055: =~/\Q$rolecode\E/) {
1.1103 raeburn 7056: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7057: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7058: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7059: $env{'request.course.id'});
7060: }
1.237 www 7061: return '';
7062: }
7063:
1.620 albertel 7064: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7065: =~/\Q$unamedom\E/) {
1.1103 raeburn 7066: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7067: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7068: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7069: $env{'request.course.id'});
7070: }
1.54 www 7071: return '';
7072: }
1.53 www 7073: }
7074:
7075: # Resource preferences
7076:
7077: if ($thisallowed=~/R/) {
1.620 albertel 7078: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7079: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7080: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7081: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7082: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7083: }
7084: return '';
1.54 www 7085: }
1.53 www 7086: }
1.30 www 7087:
1.246 www 7088: # Restricted by state or randomout?
1.30 www 7089:
1.52 www 7090: if ($thisallowed=~/X/) {
1.620 albertel 7091: if ($env{'acc.randomout'}) {
1.579 albertel 7092: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7093: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7094: return '';
7095: }
1.247 www 7096: }
7097: if (&condval($statecond)) {
1.52 www 7098: return '2';
7099: } else {
7100: return '';
7101: }
7102: }
1.30 www 7103:
1.766 albertel 7104: if ($thisallowed eq 'A') {
7105: return 'A';
1.814 raeburn 7106: } elsif ($thisallowed eq 'B') {
7107: return 'B';
1.766 albertel 7108: }
1.52 www 7109: return 'F';
1.232 www 7110: }
1.1162 raeburn 7111:
1.1192 raeburn 7112: # ------------------------------------------- Check construction space access
7113:
7114: sub constructaccess {
7115: my ($url,$setpriv)=@_;
7116:
7117: # We do not allow editing of previous versions of files
7118: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7119:
7120: # Get username and domain from URL
7121: my ($ownername,$ownerdomain,$ownerhome);
7122:
7123: ($ownerdomain,$ownername) =
7124: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7125:
7126: # The URL does not really point to any authorspace, forget it
7127: unless (($ownername) && ($ownerdomain)) { return ''; }
7128:
7129: # Now we need to see if the user has access to the authorspace of
7130: # $ownername at $ownerdomain
7131:
7132: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7133: # Real author for this?
7134: $ownerhome = $env{'user.home'};
7135: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7136: return ($ownername,$ownerdomain,$ownerhome);
7137: }
7138: } else {
7139: # Co-author for this?
7140: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7141: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7142: $ownerhome = &homeserver($ownername,$ownerdomain);
7143: return ($ownername,$ownerdomain,$ownerhome);
7144: }
7145: }
7146:
7147: # We don't have any access right now. If we are not possibly going to do anything about this,
7148: # we might as well leave
7149: unless ($setpriv) { return ''; }
7150:
7151: # Backdoor access?
7152: my $allowed=&allowed('eco',$ownerdomain);
7153: # Nope
7154: unless ($allowed) { return ''; }
7155: # Looks like we may have access, but could be locked by the owner of the construction space
7156: if ($allowed eq 'U') {
7157: my %blocked=&get('environment',['domcoord.author'],
7158: $ownerdomain,$ownername);
7159: # Is blocked by owner
7160: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7161: }
7162: if (($allowed eq 'F') || ($allowed eq 'U')) {
7163: # Grant temporary access
7164: my $then=$env{'user.login.time'};
1.1209 raeburn 7165: my $update=$env{'user.update.time'};
1.1192 raeburn 7166: if (!$update) { $update = $then; }
7167: my $refresh=$env{'user.refresh.time'};
7168: if (!$refresh) { $refresh = $update; }
7169: my $now = time;
7170: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7171: $now,'ca','constructaccess');
7172: $ownerhome = &homeserver($ownername,$ownerdomain);
7173: return($ownername,$ownerdomain,$ownerhome);
7174: }
7175: # No business here
7176: return '';
7177: }
7178:
1.1162 raeburn 7179: sub get_comm_blocks {
7180: my ($cdom,$cnum) = @_;
7181: if ($cdom eq '' || $cnum eq '') {
7182: return unless ($env{'request.course.id'});
7183: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7184: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7185: }
7186: my %commblocks;
7187: my $hashid=$cdom.'_'.$cnum;
7188: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7189: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7190: %commblocks = %{$blocksref};
7191: } else {
7192: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7193: my $cachetime = 600;
7194: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7195: }
7196: return %commblocks;
7197: }
7198:
7199: sub has_comm_blocking {
7200: my ($priv,$symb,$uri,$blocks) = @_;
7201: return unless ($env{'request.course.id'});
7202: return unless ($priv eq 'bre');
7203: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7204: my %commblocks;
7205: if (ref($blocks) eq 'HASH') {
7206: %commblocks = %{$blocks};
7207: } else {
7208: %commblocks = &get_comm_blocks();
7209: }
7210: return unless (keys(%commblocks) > 0);
7211: if (!$symb) { $symb=&symbread($uri,1); }
7212: my ($map,$resid,undef)=&decode_symb($symb);
7213: my %tocheck = (
7214: maps => $map,
7215: resources => $symb,
7216: );
7217: my @blockers;
7218: my $now = time;
1.1163 raeburn 7219: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7220: foreach my $block (keys(%commblocks)) {
7221: if ($block =~ /^(\d+)____(\d+)$/) {
7222: my ($start,$end) = ($1,$2);
7223: if ($start <= $now && $end >= $now) {
7224: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7225: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7226: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7227: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7228: unless (grep(/^\Q$block\E$/,@blockers)) {
7229: push(@blockers,$block);
7230: }
7231: }
7232: }
7233: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7234: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7235: unless (grep(/^\Q$block\E$/,@blockers)) {
7236: push(@blockers,$block);
7237: }
7238: }
7239: }
7240: }
7241: }
7242: }
7243: } elsif ($block =~ /^firstaccess____(.+)$/) {
7244: my $item = $1;
1.1163 raeburn 7245: my @to_test;
1.1162 raeburn 7246: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7247: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7248: my $check_interval;
7249: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7250: my @interval;
7251: my $type = 'map';
7252: if ($item eq 'course') {
7253: $type = 'course';
7254: @interval=&EXT("resource.0.interval");
7255: } else {
7256: if ($item =~ /___\d+___/) {
7257: $type = 'resource';
7258: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7259: if (ref($navmap)) {
7260: my $res = $navmap->getBySymb($item);
7261: push(@to_test,$res);
7262: }
1.1162 raeburn 7263: } else {
7264: my $mapsymb = &symbread($item,1);
7265: if ($mapsymb) {
7266: if (ref($navmap)) {
7267: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7268: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7269: foreach my $res (@to_test) {
1.1162 raeburn 7270: my $symb = $res->symb();
7271: next if ($symb eq $mapsymb);
7272: if ($symb ne '') {
7273: @interval=&EXT("resource.0.interval",$symb);
7274: last;
7275: }
7276: }
7277: }
7278: }
7279: }
7280: }
7281: if ($interval[0] =~ /\d+/) {
7282: my $first_access;
7283: if ($type eq 'resource') {
7284: $first_access=&get_first_access($interval[1],$item);
7285: } elsif ($type eq 'map') {
7286: $first_access=&get_first_access($interval[1],undef,$item);
7287: } else {
7288: $first_access=&get_first_access($interval[1]);
7289: }
7290: if ($first_access) {
7291: my $timesup = $first_access+$interval[0];
7292: if ($timesup > $now) {
1.1163 raeburn 7293: foreach my $res (@to_test) {
7294: if ($res->is_problem()) {
7295: if ($res->completable()) {
7296: unless (grep(/^\Q$block\E$/,@blockers)) {
7297: push(@blockers,$block);
7298: }
7299: last;
7300: }
7301: }
1.1162 raeburn 7302: }
7303: }
7304: }
7305: }
7306: }
7307: }
7308: }
7309: }
7310: }
7311: return @blockers;
7312: }
7313:
7314: sub check_docs_block {
7315: my ($docsblock,$tocheck) =@_;
7316: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7317: return;
7318: }
7319: if (ref($docsblock->{'maps'}) eq 'HASH') {
7320: if ($tocheck->{'maps'}) {
7321: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7322: return 1;
7323: }
7324: }
7325: }
7326: if (ref($docsblock->{'resources'}) eq 'HASH') {
7327: if ($tocheck->{'resources'}) {
7328: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7329: return 1;
7330: }
7331: }
7332: }
7333: return;
7334: }
7335:
1.1133 foxr 7336: #
7337: # Removes the versino from a URI and
7338: # splits it in to its filename and path to the filename.
7339: # Seems like File::Basename could have done this more clearly.
7340: # Parameters:
7341: # $uri - input URI
7342: # Returns:
7343: # Two element list consisting of
7344: # $pathname - the URI up to and excluding the trailing /
7345: # $filename - The part of the URI following the last /
7346: # NOTE:
7347: # Another realization of this is simply:
7348: # use File::Basename;
7349: # ...
7350: # $uri = shift;
7351: # $filename = basename($uri);
7352: # $path = dirname($uri);
7353: # return ($filename, $path);
7354: #
7355: # The implementation below is probably faster however.
7356: #
1.710 albertel 7357: sub split_uri_for_cond {
7358: my $uri=&deversion(&declutter(shift));
7359: my @uriparts=split(/\//,$uri);
7360: my $filename=pop(@uriparts);
7361: my $pathname=join('/',@uriparts);
7362: return ($pathname,$filename);
7363: }
1.232 www 7364: # --------------------------------------------------- Is a resource on the map?
7365:
7366: sub is_on_map {
1.710 albertel 7367: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7368: #Trying to find the conditional for the file
1.620 albertel 7369: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7370: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7371: if ($match) {
1.289 bowersj2 7372: return (1,$1);
7373: } else {
1.434 www 7374: return (0,0);
1.289 bowersj2 7375: }
1.12 www 7376: }
7377:
1.427 www 7378: # --------------------------------------------------------- Get symb from alias
7379:
7380: sub get_symb_from_alias {
7381: my $symb=shift;
7382: my ($map,$resid,$url)=&decode_symb($symb);
7383: # Already is a symb
7384: if ($url) { return $symb; }
7385: # Must be an alias
7386: my $aliassymb='';
7387: my %bighash;
1.620 albertel 7388: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7389: &GDBM_READER(),0640)) {
7390: my $rid=$bighash{'mapalias_'.$symb};
7391: if ($rid) {
7392: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7393: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7394: $resid,$bighash{'src_'.$rid});
1.427 www 7395: }
7396: untie %bighash;
7397: }
7398: return $aliassymb;
7399: }
7400:
1.12 www 7401: # ----------------------------------------------------------------- Define Role
7402:
7403: sub definerole {
7404: if (allowed('mcr','/')) {
7405: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7406: foreach my $role (split(':',$sysrole)) {
7407: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7408: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7409: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7410: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7411: return "refused:s:$crole&$cqual";
7412: }
7413: }
1.191 harris41 7414: }
1.800 albertel 7415: foreach my $role (split(':',$domrole)) {
7416: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7417: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7418: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7419: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7420: return "refused:d:$crole&$cqual";
7421: }
7422: }
1.191 harris41 7423: }
1.800 albertel 7424: foreach my $role (split(':',$courole)) {
7425: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7426: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7427: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7428: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7429: return "refused:c:$crole&$cqual";
7430: }
7431: }
1.191 harris41 7432: }
1.620 albertel 7433: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7434: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7435: "rolesdef_$rolename=".
7436: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7437: return reply($command,$env{'user.home'});
1.12 www 7438: } else {
7439: return 'refused';
7440: }
1.105 harris41 7441: }
7442:
7443: # ---------------- Make a metadata query against the network of library servers
7444:
7445: sub metadata_query {
1.1237 raeburn 7446: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7447: my %rhash;
1.845 albertel 7448: my %libserv = &all_library();
1.244 matthew 7449: my @server_list = (defined($server_array) ? @$server_array
7450: : keys(%libserv) );
7451: for my $server (@server_list) {
1.1237 raeburn 7452: my $domains = '';
7453: if (ref($domains_hash) eq 'HASH') {
7454: $domains = $domains_hash->{$server};
7455: }
1.118 harris41 7456: unless ($custom or $customshow) {
1.1237 raeburn 7457: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7458: $rhash{$server}=$reply;
7459: }
7460: else {
7461: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7462: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7463: $server);
7464: $rhash{$server}=$reply;
7465: }
1.112 harris41 7466: }
1.118 harris41 7467: return \%rhash;
1.240 www 7468: }
7469:
7470: # ----------------------------------------- Send log queries and wait for reply
7471:
7472: sub log_query {
7473: my ($uname,$udom,$query,%filters)=@_;
7474: my $uhome=&homeserver($uname,$udom);
7475: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7476: my $uhost=&hostname($uhome);
1.800 albertel 7477: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7478: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7479: $uhome);
1.479 albertel 7480: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7481: return get_query_reply($queryid);
7482: }
7483:
1.818 raeburn 7484: # -------------------------- Update MySQL table for portfolio file
7485:
7486: sub update_portfolio_table {
1.821 raeburn 7487: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7488: if ($group ne '') {
7489: $file_name =~s /^\Q$group\E//;
7490: }
1.818 raeburn 7491: my $homeserver = &homeserver($uname,$udom);
7492: my $queryid=
1.821 raeburn 7493: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7494: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7495: my $reply = &get_query_reply($queryid);
7496: return $reply;
7497: }
7498:
1.899 raeburn 7499: # -------------------------- Update MySQL allusers table
7500:
7501: sub update_allusers_table {
7502: my ($uname,$udom,$names) = @_;
7503: my $homeserver = &homeserver($uname,$udom);
7504: my $queryid=
7505: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7506: 'lastname='.&escape($names->{'lastname'}).'%%'.
7507: 'firstname='.&escape($names->{'firstname'}).'%%'.
7508: 'middlename='.&escape($names->{'middlename'}).'%%'.
7509: 'generation='.&escape($names->{'generation'}).'%%'.
7510: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7511: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7512: return;
1.899 raeburn 7513: }
7514:
1.508 raeburn 7515: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7516:
7517: sub fetch_enrollment_query {
1.511 raeburn 7518: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7519: my $homeserver;
1.547 raeburn 7520: my $maxtries = 1;
1.508 raeburn 7521: if ($context eq 'automated') {
7522: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7523: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7524: } else {
7525: $homeserver = &homeserver($cnum,$dom);
7526: }
1.838 albertel 7527: my $host=&hostname($homeserver);
1.506 raeburn 7528: my $cmd = '';
1.1000 raeburn 7529: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7530: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7531: }
7532: $cmd =~ s/%%$//;
7533: $cmd = &escape($cmd);
7534: my $query = 'fetchenrollment';
1.620 albertel 7535: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7536: unless ($queryid=~/^\Q$host\E\_/) {
7537: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7538: return 'error: '.$queryid;
7539: }
1.506 raeburn 7540: my $reply = &get_query_reply($queryid);
1.547 raeburn 7541: my $tries = 1;
7542: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7543: $reply = &get_query_reply($queryid);
7544: $tries ++;
7545: }
1.526 raeburn 7546: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7547: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7548: } else {
1.901 albertel 7549: my @responses = split(/:/,$reply);
1.515 raeburn 7550: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7551: foreach my $line (@responses) {
7552: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7553: $$replyref{$key} = $value;
7554: }
7555: } else {
1.1117 foxr 7556: my $pathname = LONCAPA::tempdir();
1.800 albertel 7557: foreach my $line (@responses) {
7558: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7559: $$replyref{$key} = $value;
7560: if ($value > 0) {
1.800 albertel 7561: foreach my $item (@{$$affiliatesref{$key}}) {
7562: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7563: my $destname = $pathname.'/'.$filename;
7564: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7565: if ($xml_classlist =~ /^error/) {
7566: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7567: } else {
1.506 raeburn 7568: if ( open(FILE,">$destname") ) {
7569: print FILE &unescape($xml_classlist);
7570: close(FILE);
1.526 raeburn 7571: } else {
7572: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7573: }
7574: }
7575: }
7576: }
7577: }
7578: }
7579: return 'ok';
7580: }
7581: return 'error';
7582: }
7583:
1.242 www 7584: sub get_query_reply {
7585: my $queryid=shift;
1.1117 foxr 7586: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7587: my $reply='';
7588: for (1..100) {
7589: sleep 2;
7590: if (-e $replyfile.'.end') {
1.448 albertel 7591: if (open(my $fh,$replyfile)) {
1.904 albertel 7592: $reply = join('',<$fh>);
7593: close($fh);
1.240 www 7594: } else { return 'error: reply_file_error'; }
1.242 www 7595: return &unescape($reply);
7596: }
1.240 www 7597: }
1.242 www 7598: return 'timeout:'.$queryid;
1.240 www 7599: }
7600:
7601: sub courselog_query {
1.241 www 7602: #
7603: # possible filters:
7604: # url: url or symb
7605: # username
7606: # domain
7607: # action: view, submit, grade
7608: # start: timestamp
7609: # end: timestamp
7610: #
1.240 www 7611: my (%filters)=@_;
1.620 albertel 7612: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7613: if ($filters{'url'}) {
7614: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7615: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7616: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7617: }
1.620 albertel 7618: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7619: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7620: return &log_query($cname,$cdom,'courselog',%filters);
7621: }
7622:
7623: sub userlog_query {
1.858 raeburn 7624: #
7625: # possible filters:
7626: # action: log check role
7627: # start: timestamp
7628: # end: timestamp
7629: #
1.240 www 7630: my ($uname,$udom,%filters)=@_;
7631: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7632: }
7633:
1.506 raeburn 7634: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7635:
7636: sub auto_run {
1.508 raeburn 7637: my ($cnum,$cdom) = @_;
1.876 raeburn 7638: my $response = 0;
7639: my $settings;
7640: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7641: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7642: $settings = $domconfig{'autoenroll'};
7643: if ($settings->{'run'} eq '1') {
7644: $response = 1;
7645: }
7646: } else {
1.934 raeburn 7647: my $homeserver;
7648: if (&is_course($cdom,$cnum)) {
7649: $homeserver = &homeserver($cnum,$cdom);
7650: } else {
7651: $homeserver = &domain($cdom,'primary');
7652: }
7653: if ($homeserver ne 'no_host') {
7654: $response = &reply('autorun:'.$cdom,$homeserver);
7655: }
1.876 raeburn 7656: }
1.506 raeburn 7657: return $response;
7658: }
1.776 albertel 7659:
1.506 raeburn 7660: sub auto_get_sections {
1.508 raeburn 7661: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7662: my $homeserver;
7663: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7664: $homeserver = &homeserver($cnum,$cdom);
7665: }
7666: if (!defined($homeserver)) {
7667: if ($cdom =~ /^$match_domain$/) {
7668: $homeserver = &domain($cdom,'primary');
7669: }
7670: }
7671: my @secs;
7672: if (defined($homeserver)) {
7673: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7674: unless ($response eq 'refused') {
7675: @secs = split(/:/,$response);
7676: }
1.506 raeburn 7677: }
7678: return @secs;
7679: }
1.776 albertel 7680:
1.506 raeburn 7681: sub auto_new_course {
1.1099 raeburn 7682: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7683: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7684: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7685: return $response;
7686: }
1.776 albertel 7687:
1.506 raeburn 7688: sub auto_validate_courseID {
1.508 raeburn 7689: my ($cnum,$cdom,$inst_course_id) = @_;
7690: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7691: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7692: return $response;
7693: }
1.776 albertel 7694:
1.1007 raeburn 7695: sub auto_validate_instcode {
1.1020 raeburn 7696: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7697: my ($homeserver,$response);
7698: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7699: $homeserver = &homeserver($cnum,$cdom);
7700: }
7701: if (!defined($homeserver)) {
7702: if ($cdom =~ /^$match_domain$/) {
7703: $homeserver = &domain($cdom,'primary');
7704: }
7705: }
1.1065 raeburn 7706: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7707: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7708: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7709: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7710: }
7711:
1.506 raeburn 7712: sub auto_create_password {
1.873 raeburn 7713: my ($cnum,$cdom,$authparam,$udom) = @_;
7714: my ($homeserver,$response);
1.506 raeburn 7715: my $create_passwd = 0;
7716: my $authchk = '';
1.873 raeburn 7717: if ($udom =~ /^$match_domain$/) {
7718: $homeserver = &domain($udom,'primary');
7719: }
7720: if ($homeserver eq '') {
7721: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7722: $homeserver = &homeserver($cnum,$cdom);
7723: }
7724: }
7725: if ($homeserver eq '') {
7726: $authchk = 'nodomain';
1.506 raeburn 7727: } else {
1.873 raeburn 7728: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7729: if ($response eq 'refused') {
7730: $authchk = 'refused';
7731: } else {
1.901 albertel 7732: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7733: }
1.506 raeburn 7734: }
7735: return ($authparam,$create_passwd,$authchk);
7736: }
7737:
1.706 raeburn 7738: sub auto_photo_permission {
7739: my ($cnum,$cdom,$students) = @_;
7740: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7741: my ($outcome,$perm_reqd,$conditions) =
7742: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7743: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7744: return (undef,undef);
7745: }
1.706 raeburn 7746: return ($outcome,$perm_reqd,$conditions);
7747: }
7748:
7749: sub auto_checkphotos {
7750: my ($uname,$udom,$pid) = @_;
7751: my $homeserver = &homeserver($uname,$udom);
7752: my ($result,$resulttype);
7753: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7754: &escape($uname).':'.&escape($pid),
7755: $homeserver));
1.709 albertel 7756: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7757: return (undef,undef);
7758: }
1.706 raeburn 7759: if ($outcome) {
7760: ($result,$resulttype) = split(/:/,$outcome);
7761: }
7762: return ($result,$resulttype);
7763: }
7764:
7765: sub auto_photochoice {
7766: my ($cnum,$cdom) = @_;
7767: my $homeserver = &homeserver($cnum,$cdom);
7768: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7769: &escape($cdom),
7770: $homeserver)));
1.709 albertel 7771: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7772: return (undef,undef);
7773: }
1.706 raeburn 7774: return ($update,$comment);
7775: }
7776:
7777: sub auto_photoupdate {
7778: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7779: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7780: my $host=&hostname($homeserver);
1.706 raeburn 7781: my $cmd = '';
7782: my $maxtries = 1;
1.800 albertel 7783: foreach my $affiliate (keys(%{$affiliatesref})) {
7784: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7785: }
7786: $cmd =~ s/%%$//;
7787: $cmd = &escape($cmd);
7788: my $query = 'institutionalphotos';
7789: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7790: unless ($queryid=~/^\Q$host\E\_/) {
7791: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7792: return 'error: '.$queryid;
7793: }
7794: my $reply = &get_query_reply($queryid);
7795: my $tries = 1;
7796: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7797: $reply = &get_query_reply($queryid);
7798: $tries ++;
7799: }
7800: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7801: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7802: } else {
7803: my @responses = split(/:/,$reply);
7804: my $outcome = shift(@responses);
7805: foreach my $item (@responses) {
7806: my ($key,$value) = split(/=/,$item);
7807: $$photo{$key} = $value;
7808: }
7809: return $outcome;
7810: }
7811: return 'error';
7812: }
7813:
1.521 raeburn 7814: sub auto_instcode_format {
1.793 albertel 7815: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7816: $cat_order) = @_;
1.521 raeburn 7817: my $courses = '';
1.772 raeburn 7818: my @homeservers;
1.521 raeburn 7819: if ($caller eq 'global') {
1.841 albertel 7820: my %servers = &get_servers($codedom,'library');
7821: foreach my $tryserver (keys(%servers)) {
7822: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7823: push(@homeservers,$tryserver);
7824: }
1.584 raeburn 7825: }
1.1022 raeburn 7826: } elsif ($caller eq 'requests') {
7827: if ($codedom =~ /^$match_domain$/) {
7828: my $chome = &domain($codedom,'primary');
7829: unless ($chome eq 'no_host') {
7830: push(@homeservers,$chome);
7831: }
7832: }
1.521 raeburn 7833: } else {
1.772 raeburn 7834: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7835: }
1.793 albertel 7836: foreach my $code (keys(%{$instcodes})) {
7837: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7838: }
7839: chop($courses);
1.772 raeburn 7840: my $ok_response = 0;
7841: my $response;
7842: while (@homeservers > 0 && $ok_response == 0) {
7843: my $server = shift(@homeservers);
7844: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7845: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7846: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7847: split(/:/,$response);
1.772 raeburn 7848: %{$codes} = (%{$codes},&str2hash($codes_str));
7849: push(@{$codetitles},&str2array($codetitles_str));
7850: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7851: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7852: $ok_response = 1;
7853: }
7854: }
7855: if ($ok_response) {
1.521 raeburn 7856: return 'ok';
1.772 raeburn 7857: } else {
7858: return $response;
1.521 raeburn 7859: }
7860: }
7861:
1.792 raeburn 7862: sub auto_instcode_defaults {
7863: my ($domain,$returnhash,$code_order) = @_;
7864: my @homeservers;
1.841 albertel 7865:
7866: my %servers = &get_servers($domain,'library');
7867: foreach my $tryserver (keys(%servers)) {
7868: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7869: push(@homeservers,$tryserver);
7870: }
1.792 raeburn 7871: }
1.841 albertel 7872:
1.792 raeburn 7873: my $response;
1.841 albertel 7874: foreach my $server (@homeservers) {
1.792 raeburn 7875: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7876: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7877:
7878: foreach my $pair (split(/\&/,$response)) {
7879: my ($name,$value)=split(/\=/,$pair);
7880: if ($name eq 'code_order') {
7881: @{$code_order} = split(/\&/,&unescape($value));
7882: } else {
7883: $returnhash->{&unescape($name)}=&unescape($value);
7884: }
7885: }
7886: return 'ok';
1.792 raeburn 7887: }
1.841 albertel 7888:
7889: return $response;
1.1003 raeburn 7890: }
7891:
7892: sub auto_possible_instcodes {
1.1007 raeburn 7893: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7894: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7895: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7896: return;
7897: }
1.1003 raeburn 7898: my (@homeservers,$uhome);
7899: if (defined(&domain($domain,'primary'))) {
7900: $uhome=&domain($domain,'primary');
7901: push(@homeservers,&domain($domain,'primary'));
7902: } else {
7903: my %servers = &get_servers($domain,'library');
7904: foreach my $tryserver (keys(%servers)) {
7905: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7906: push(@homeservers,$tryserver);
7907: }
7908: }
7909: }
7910: my $response;
7911: foreach my $server (@homeservers) {
7912: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7913: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7914: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7915: split(':',$response);
7916: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7917: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7918: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7919: my ($name,$value)=split('=',$item);
7920: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7921: }
7922: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7923: my ($name,$value)=split('=',$item);
7924: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7925: }
7926: return 'ok';
7927: }
7928: return $response;
7929: }
1.792 raeburn 7930:
1.1010 raeburn 7931: sub auto_courserequest_checks {
7932: my ($dom) = @_;
1.1020 raeburn 7933: my ($homeserver,%validations);
7934: if ($dom =~ /^$match_domain$/) {
7935: $homeserver = &domain($dom,'primary');
7936: }
7937: unless ($homeserver eq 'no_host') {
7938: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7939: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7940: my @items = split(/&/,$response);
7941: foreach my $item (@items) {
7942: my ($key,$value) = split('=',$item);
7943: $validations{&unescape($key)} = &thaw_unescape($value);
7944: }
7945: }
7946: }
1.1010 raeburn 7947: return %validations;
7948: }
7949:
1.1020 raeburn 7950: sub auto_courserequest_validation {
1.1255 raeburn 7951: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 7952: my ($homeserver,$response);
7953: if ($dom =~ /^$match_domain$/) {
7954: $homeserver = &domain($dom,'primary');
7955: }
1.1255 raeburn 7956: unless ($homeserver eq 'no_host') {
7957: my $customdata;
7958: if (ref($custominfo) eq 'HASH') {
7959: $customdata = &freeze_escape($custominfo);
7960: }
1.1020 raeburn 7961: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7962: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 7963: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7964: $customdata,$homeserver));
1.1020 raeburn 7965: }
7966: return $response;
7967: }
7968:
1.777 albertel 7969: sub auto_validate_class_sec {
1.918 raeburn 7970: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7971: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7972: my $ownerlist;
7973: if (ref($owners) eq 'ARRAY') {
7974: $ownerlist = join(',',@{$owners});
7975: } else {
7976: $ownerlist = $owners;
7977: }
1.773 raeburn 7978: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7979: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7980: return $response;
7981: }
7982:
1.1248 raeburn 7983: sub auto_crsreq_update {
7984: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 7985: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 7986: my ($homeserver,%crsreqresponse);
7987: if ($cdom =~ /^$match_domain$/) {
7988: $homeserver = &domain($cdom,'primary');
7989: }
7990: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7991: my $info;
7992: if (ref($inbound) eq 'HASH') {
7993: $info = &freeze_escape($inbound);
7994: }
7995: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7996: ':'.&escape($action).':'.&escape($ownername).':'.
7997: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 7998: &escape($title).':'.&escape($code).':'.
7999: &escape($accessstart).':'.&escape($accessend).':'.$info,
8000: $homeserver);
1.1248 raeburn 8001: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8002: my @items = split(/&/,$response);
8003: foreach my $item (@items) {
8004: my ($key,$value) = split('=',$item);
8005: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8006: }
8007: }
8008: }
8009: return \%crsreqresponse;
8010: }
8011:
1.679 raeburn 8012: # ------------------------------------------------------- Course Group routines
8013:
8014: sub get_coursegroups {
1.809 raeburn 8015: my ($cdom,$cnum,$group,$namespace) = @_;
8016: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8017: }
8018:
1.679 raeburn 8019: sub modify_coursegroup {
8020: my ($cdom,$cnum,$groupsettings) = @_;
8021: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8022: }
8023:
1.809 raeburn 8024: sub toggle_coursegroup_status {
8025: my ($cdom,$cnum,$group,$action) = @_;
8026: my ($from_namespace,$to_namespace);
8027: if ($action eq 'delete') {
8028: $from_namespace = 'coursegroups';
8029: $to_namespace = 'deleted_groups';
8030: } else {
8031: $from_namespace = 'deleted_groups';
8032: $to_namespace = 'coursegroups';
8033: }
8034: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8035: if (my $tmp = &error(%curr_group)) {
8036: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8037: return ('read error',$tmp);
8038: } else {
8039: my %savedsettings = %curr_group;
1.809 raeburn 8040: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8041: my $deloutcome;
8042: if ($result eq 'ok') {
1.809 raeburn 8043: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8044: } else {
8045: return ('write error',$result);
8046: }
8047: if ($deloutcome eq 'ok') {
8048: return 'ok';
8049: } else {
8050: return ('delete error',$deloutcome);
8051: }
8052: }
8053: }
8054:
1.679 raeburn 8055: sub modify_group_roles {
1.957 raeburn 8056: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8057: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8058: my $role = 'gr/'.&escape($userprivs);
8059: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8060: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8061: if ($result eq 'ok') {
8062: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8063: }
1.679 raeburn 8064: return $result;
8065: }
8066:
8067: sub modify_coursegroup_membership {
8068: my ($cdom,$cnum,$membership) = @_;
8069: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8070: return $result;
8071: }
8072:
1.682 raeburn 8073: sub get_active_groups {
8074: my ($udom,$uname,$cdom,$cnum) = @_;
8075: my $now = time;
8076: my %groups = ();
8077: foreach my $key (keys(%env)) {
1.811 albertel 8078: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8079: my ($start,$end) = split(/\./,$env{$key});
8080: if (($end!=0) && ($end<$now)) { next; }
8081: if (($start!=0) && ($start>$now)) { next; }
8082: if ($1 eq $cdom && $2 eq $cnum) {
8083: $groups{$3} = $env{$key} ;
8084: }
8085: }
8086: }
8087: return %groups;
8088: }
8089:
1.683 raeburn 8090: sub get_group_membership {
8091: my ($cdom,$cnum,$group) = @_;
8092: return(&dump('groupmembership',$cdom,$cnum,$group));
8093: }
8094:
8095: sub get_users_groups {
8096: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8097: my @usersgroups;
1.683 raeburn 8098: my $cachetime=1800;
8099:
8100: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8101: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8102: if (defined($cached)) {
1.734 albertel 8103: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8104: } else {
8105: $grouplist = '';
1.816 raeburn 8106: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8107: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8108: my $access_end = $env{'course.'.$courseid.
8109: '.default_enrollment_end_date'};
8110: my $now = time;
8111: foreach my $key (keys(%roleshash)) {
8112: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8113: my $group = $1;
8114: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8115: my $start = $2;
8116: my $end = $1;
8117: if ($start == -1) { next; } # deleted from group
8118: if (($start!=0) && ($start>$now)) { next; }
8119: if (($end!=0) && ($end<$now)) {
8120: if ($access_end && $access_end < $now) {
8121: if ($access_end - $end < 86400) {
8122: push(@usersgroups,$group);
1.733 raeburn 8123: }
8124: }
1.817 raeburn 8125: next;
1.733 raeburn 8126: }
1.817 raeburn 8127: push(@usersgroups,$group);
1.683 raeburn 8128: }
8129: }
8130: }
1.817 raeburn 8131: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8132: $grouplist = join(':',@usersgroups);
8133: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8134: }
1.733 raeburn 8135: return @usersgroups;
1.683 raeburn 8136: }
8137:
8138: sub devalidate_getgroups_cache {
8139: my ($udom,$uname,$cdom,$cnum)=@_;
8140: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8141:
1.683 raeburn 8142: my $hashid="$udom:$uname:$courseid";
8143: &devalidate_cache_new('getgroups',$hashid);
8144: }
8145:
1.12 www 8146: # ------------------------------------------------------------------ Plain Text
8147:
8148: sub plaintext {
1.988 raeburn 8149: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8150: if ($short =~ m{^cr/}) {
1.758 albertel 8151: return (split('/',$short))[-1];
8152: }
1.742 raeburn 8153: if (!defined($cid)) {
8154: $cid = $env{'request.course.id'};
8155: }
8156: my %rolenames = (
1.1008 raeburn 8157: Course => 'std',
8158: Community => 'alt1',
1.742 raeburn 8159: );
1.1037 raeburn 8160: if ($cid ne '') {
8161: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8162: unless ($forcedefault) {
8163: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8164: &Apache::lonlocal::mt_escape(\$roletext);
8165: return &Apache::lonlocal::mt($roletext);
8166: }
8167: }
8168: }
8169: if ((defined($type)) && (defined($rolenames{$type})) &&
8170: (defined($rolenames{$type})) &&
8171: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8172: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8173: } elsif ($cid ne '') {
8174: my $crstype = $env{'course.'.$cid.'.type'};
8175: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8176: (defined($prp{$short}{$rolenames{$crstype}}))) {
8177: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8178: }
1.742 raeburn 8179: }
1.1037 raeburn 8180: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8181: }
8182:
8183: # ----------------------------------------------------------------- Assign Role
8184:
8185: sub assignrole {
1.957 raeburn 8186: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8187: $context)=@_;
1.21 www 8188: my $mrole;
8189: if ($role =~ /^cr\//) {
1.393 www 8190: my $cwosec=$url;
1.811 albertel 8191: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8192: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8193: my $refused = 1;
8194: if ($context eq 'requestcourses') {
8195: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8196: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8197: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8198: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8199: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8200: if ($crsenv{'internal.courseowner'} eq
8201: $env{'user.name'}.':'.$env{'user.domain'}) {
8202: $refused = '';
8203: }
8204: }
8205: }
8206: }
8207: }
8208: if ($refused) {
8209: &logthis('Refused custom assignrole: '.
8210: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8211: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8212: return 'refused';
8213: }
1.104 www 8214: }
1.21 www 8215: $mrole='cr';
1.678 raeburn 8216: } elsif ($role =~ /^gr\//) {
8217: my $cwogrp=$url;
1.811 albertel 8218: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8219: unless (&allowed('mdg',$cwogrp)) {
8220: &logthis('Refused group assignrole: '.
8221: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8222: $env{'user.name'}.' at '.$env{'user.domain'});
8223: return 'refused';
8224: }
8225: $mrole='gr';
1.21 www 8226: } else {
1.82 www 8227: my $cwosec=$url;
1.811 albertel 8228: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8229: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8230: my $refused;
8231: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8232: if (!(&allowed('c'.$role,$url))) {
8233: $refused = 1;
8234: }
8235: } else {
8236: $refused = 1;
8237: }
1.947 raeburn 8238: if ($refused) {
1.1045 raeburn 8239: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8240: if (!$selfenroll && $context eq 'course') {
8241: my %crsenv;
8242: if ($role eq 'cc' || $role eq 'co') {
8243: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8244: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8245: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8246: if ($crsenv{'internal.courseowner'} eq
8247: $env{'user.name'}.':'.$env{'user.domain'}) {
8248: $refused = '';
8249: }
8250: }
8251: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8252: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8253: if ($crsenv{'internal.courseowner'} eq
8254: $env{'user.name'}.':'.$env{'user.domain'}) {
8255: $refused = '';
8256: }
8257: }
8258: }
8259: }
8260: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8261: $refused = '';
1.1017 raeburn 8262: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8263: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8264: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8265: my $wrongcc;
8266: if ($cnum =~ /^$match_community$/) {
8267: $wrongcc = 1 if ($role eq 'cc');
8268: } else {
8269: $wrongcc = 1 if ($role eq 'co');
8270: }
8271: unless ($wrongcc) {
8272: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8273: if ($crsenv{'internal.courseowner'} eq
8274: $env{'user.name'}.':'.$env{'user.domain'}) {
8275: $refused = '';
8276: }
1.1017 raeburn 8277: }
8278: }
1.1183 raeburn 8279: } elsif ($context eq 'requestauthor') {
8280: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8281: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8282: if ($env{'environment.requestauthor'} eq 'automatic') {
8283: $refused = '';
8284: } else {
8285: my %domdefaults = &get_domain_defaults($udom);
8286: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8287: my $checkbystatus;
8288: if ($env{'user.adv'}) {
8289: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8290: if ($disposition eq 'automatic') {
8291: $refused = '';
8292: } elsif ($disposition eq '') {
8293: $checkbystatus = 1;
8294: }
8295: } else {
8296: $checkbystatus = 1;
8297: }
8298: if ($checkbystatus) {
8299: if ($env{'environment.inststatus'}) {
8300: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8301: foreach my $type (@inststatuses) {
8302: if (($type ne '') &&
8303: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8304: $refused = '';
8305: }
8306: }
8307: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8308: $refused = '';
8309: }
8310: }
8311: }
8312: }
8313: }
1.1017 raeburn 8314: }
8315: if ($refused) {
1.947 raeburn 8316: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8317: ' '.$role.' '.$end.' '.$start.' by '.
8318: $env{'user.name'}.' at '.$env{'user.domain'});
8319: return 'refused';
8320: }
1.932 raeburn 8321: }
1.1131 raeburn 8322: } elsif ($role eq 'au') {
8323: if ($url ne '/'.$udom.'/') {
8324: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8325: ' to assign author role for '.$uname.':'.$udom.
8326: ' in domain: '.$url.' refused (wrong domain).');
8327: return 'refused';
8328: }
1.104 www 8329: }
1.21 www 8330: $mrole=$role;
8331: }
1.620 albertel 8332: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8333: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8334: if ($end) { $command.='_'.$end; }
1.21 www 8335: if ($start) {
8336: if ($end) {
1.81 www 8337: $command.='_'.$start;
1.21 www 8338: } else {
1.81 www 8339: $command.='_0_'.$start;
1.21 www 8340: }
8341: }
1.739 raeburn 8342: my $origstart = $start;
8343: my $origend = $end;
1.957 raeburn 8344: my $delflag;
1.357 www 8345: # actually delete
8346: if ($deleteflag) {
1.373 www 8347: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8348: # modify command to delete the role
1.620 albertel 8349: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8350: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8351: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8352: # set start and finish to negative values for userrolelog
8353: $start=-1;
8354: $end=-1;
1.957 raeburn 8355: $delflag = 1;
1.357 www 8356: }
8357: }
8358: # send command
1.349 www 8359: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8360: # log new user role if status is ok
1.349 www 8361: if ($answer eq 'ok') {
1.663 raeburn 8362: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8363: if (($role eq 'cc') || ($role eq 'in') ||
8364: ($role eq 'ep') || ($role eq 'ad') ||
8365: ($role eq 'ta') || ($role eq 'st') ||
8366: ($role=~/^cr/) || ($role eq 'gr') ||
8367: ($role eq 'co')) {
1.1200 raeburn 8368: # for course roles, perform group memberships changes triggered by role change.
8369: unless ($role =~ /^gr/) {
8370: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8371: $origstart,$selfenroll,$context);
8372: }
1.1184 raeburn 8373: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8374: $selfenroll,$context);
8375: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8376: ($role eq 'au') || ($role eq 'dc')) {
8377: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8378: $context);
8379: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8380: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8381: $context);
8382: }
1.1053 raeburn 8383: if ($role eq 'cc') {
8384: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8385: }
1.349 www 8386: }
8387: return $answer;
1.169 harris41 8388: }
8389:
1.1053 raeburn 8390: sub autoupdate_coowners {
8391: my ($url,$end,$start,$uname,$udom) = @_;
8392: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8393: if (($cdom ne '') && ($cnum ne '')) {
8394: my $now = time;
8395: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8396: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8397: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8398: my $instcode = $coursehash{'internal.coursecode'};
8399: if ($instcode ne '') {
1.1056 raeburn 8400: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8401: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8402: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8403: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8404: if ($result eq 'valid') {
8405: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8406: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8407: push(@newcoowners,$coowner);
8408: }
8409: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8410: push(@newcoowners,$uname.':'.$udom);
8411: }
8412: @newcoowners = sort(@newcoowners);
8413: } else {
8414: push(@newcoowners,$uname.':'.$udom);
8415: }
8416: } else {
8417: if ($coursehash{'internal.co-owners'}) {
8418: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8419: unless ($coowner eq $uname.':'.$udom) {
8420: push(@newcoowners,$coowner);
8421: }
8422: }
8423: unless (@newcoowners > 0) {
8424: $delcoowners = 1;
8425: $coowners = '';
8426: }
8427: }
8428: }
8429: if (@newcoowners || $delcoowners) {
8430: &store_coowners($cdom,$cnum,$coursehash{'home'},
8431: $delcoowners,@newcoowners);
8432: }
8433: }
8434: }
8435: }
8436: }
8437: }
8438: }
8439:
8440: sub store_coowners {
8441: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8442: my $cid = $cdom.'_'.$cnum;
8443: my ($coowners,$delresult,$putresult);
8444: if (@newcoowners) {
8445: $coowners = join(',',@newcoowners);
8446: my %coownershash = (
8447: 'internal.co-owners' => $coowners,
8448: );
8449: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8450: if ($putresult eq 'ok') {
8451: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8452: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8453: }
8454: }
8455: }
8456: if ($delcoowners) {
8457: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8458: if ($delresult eq 'ok') {
8459: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8460: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8461: }
8462: }
8463: }
8464: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8465: my %crsinfo =
8466: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8467: if (ref($crsinfo{$cid}) eq 'HASH') {
8468: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8469: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8470: }
8471: }
8472: }
8473:
1.169 harris41 8474: # -------------------------------------------------- Modify user authentication
1.197 www 8475: # Overrides without validation
8476:
1.169 harris41 8477: sub modifyuserauth {
8478: my ($udom,$uname,$umode,$upass)=@_;
8479: my $uhome=&homeserver($uname,$udom);
1.197 www 8480: unless (&allowed('mau',$udom)) { return 'refused'; }
8481: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8482: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8483: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8484: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8485: &escape($upass),$uhome);
1.620 albertel 8486: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8487: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8488: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8489: &log($udom,,$uname,$uhome,
1.620 albertel 8490: 'Authentication changed by '.$env{'user.domain'}.', '.
8491: $env{'user.name'}.', '.$umode.
1.197 www 8492: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8493: unless ($reply eq 'ok') {
1.197 www 8494: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8495: return 'error: '.$reply;
8496: }
1.170 harris41 8497: return 'ok';
1.80 www 8498: }
8499:
1.81 www 8500: # --------------------------------------------------------------- Modify a user
1.80 www 8501:
1.81 www 8502: sub modifyuser {
1.206 matthew 8503: my ($udom, $uname, $uid,
8504: $umode, $upass, $first,
8505: $middle, $last, $gene,
1.1058 raeburn 8506: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8507: $udom= &LONCAPA::clean_domain($udom);
8508: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8509: my $showcandelete = 'none';
8510: if (ref($candelete) eq 'ARRAY') {
8511: if (@{$candelete} > 0) {
8512: $showcandelete = join(', ',@{$candelete});
8513: }
8514: }
1.81 www 8515: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8516: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8517: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8518: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8519: ' desiredhome not specified').
1.620 albertel 8520: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8521: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8522: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8523: my $newuser;
8524: if ($uhome eq 'no_host') {
8525: $newuser = 1;
8526: }
1.80 www 8527: # ----------------------------------------------------------------- Create User
1.406 albertel 8528: if (($uhome eq 'no_host') &&
8529: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8530: my $unhome='';
1.844 albertel 8531: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8532: $unhome = $desiredhome;
1.620 albertel 8533: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8534: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8535: } else { # load balancing routine for determining $unhome
1.81 www 8536: my $loadm=10000000;
1.841 albertel 8537: my %servers = &get_servers($udom,'library');
8538: foreach my $tryserver (keys(%servers)) {
8539: my $answer=reply('load',$tryserver);
8540: if (($answer=~/\d+/) && ($answer<$loadm)) {
8541: $loadm=$answer;
8542: $unhome=$tryserver;
8543: }
1.80 www 8544: }
8545: }
8546: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8547: return 'error: unable to find a home server for '.$uname.
8548: ' in domain '.$udom;
1.80 www 8549: }
8550: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8551: &escape($upass),$unhome);
8552: unless ($reply eq 'ok') {
8553: return 'error: '.$reply;
8554: }
1.230 stredwic 8555: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8556: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8557: return 'error: unable verify users home machine.';
1.80 www 8558: }
1.209 matthew 8559: } # End of creation of new user
1.80 www 8560: # ---------------------------------------------------------------------- Add ID
8561: if ($uid) {
8562: $uid=~tr/A-Z/a-z/;
8563: my %uidhash=&idrget($udom,$uname);
1.196 www 8564: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8565: && (!$forceid)) {
1.80 www 8566: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8567: return 'error: user id "'.$uid.'" does not match '.
8568: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8569: }
8570: } else {
8571: &idput($udom,($uname => $uid));
8572: }
8573: }
8574: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8575: my @tmp=&get('environment',
1.899 raeburn 8576: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8577: 'permanentemail','inststatus'],
1.134 albertel 8578: $udom,$uname);
1.1075 raeburn 8579: my (%names,%oldnames);
1.313 matthew 8580: if ($tmp[0] =~ m/^error:.*/) {
8581: %names=();
8582: } else {
8583: %names = @tmp;
1.1075 raeburn 8584: %oldnames = %names;
1.313 matthew 8585: }
1.388 www 8586: #
1.1058 raeburn 8587: # If name, email and/or uid are blank (e.g., because an uploaded file
8588: # of users did not contain them), do not overwrite existing values
8589: # unless field is in $candelete array ref.
8590: #
8591:
8592: my @fields = ('firstname','middlename','lastname','generation',
8593: 'permanentemail','id');
8594: my %newvalues;
8595: if (ref($candelete) eq 'ARRAY') {
8596: foreach my $field (@fields) {
8597: if (grep(/^\Q$field\E$/,@{$candelete})) {
8598: if ($field eq 'firstname') {
8599: $names{$field} = $first;
8600: } elsif ($field eq 'middlename') {
8601: $names{$field} = $middle;
8602: } elsif ($field eq 'lastname') {
8603: $names{$field} = $last;
8604: } elsif ($field eq 'generation') {
8605: $names{$field} = $gene;
8606: } elsif ($field eq 'permanentemail') {
8607: $names{$field} = $email;
8608: } elsif ($field eq 'id') {
8609: $names{$field} = $uid;
8610: }
8611: }
8612: }
8613: }
1.388 www 8614: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8615: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8616: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8617: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8618: if ($email) {
8619: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8620: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8621: }
1.899 raeburn 8622: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8623: if (defined($inststatus)) {
8624: $names{'inststatus'} = '';
8625: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8626: if (ref($usertypes) eq 'HASH') {
8627: my @okstatuses;
8628: foreach my $item (split(/:/,$inststatus)) {
8629: if (defined($usertypes->{$item})) {
8630: push(@okstatuses,$item);
8631: }
8632: }
8633: if (@okstatuses) {
8634: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8635: }
8636: }
8637: }
1.1075 raeburn 8638: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8639: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8640: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8641: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8642: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8643: } else {
8644: $logmsg .= ' during self creation';
8645: }
1.1075 raeburn 8646: my $changed;
8647: if ($newuser) {
8648: $changed = 1;
8649: } else {
8650: foreach my $field (@fields) {
8651: if ($names{$field} ne $oldnames{$field}) {
8652: $changed = 1;
8653: last;
8654: }
8655: }
8656: }
8657: unless ($changed) {
8658: $logmsg = 'No changes in user information needed for: '.$logmsg;
8659: &logthis($logmsg);
8660: return 'ok';
8661: }
8662: my $reply = &put('environment', \%names, $udom,$uname);
8663: if ($reply ne 'ok') {
8664: return 'error: '.$reply;
8665: }
1.1087 raeburn 8666: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8667: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8668: }
1.1075 raeburn 8669: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8670: &devalidate_cache_new('namescache',$uname.':'.$udom);
8671: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8672: &logthis($logmsg);
1.134 albertel 8673: return 'ok';
1.80 www 8674: }
8675:
1.81 www 8676: # -------------------------------------------------------------- Modify student
1.80 www 8677:
1.81 www 8678: sub modifystudent {
8679: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8680: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8681: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8682: if (!$cid) {
1.620 albertel 8683: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8684: return 'not_in_class';
8685: }
1.80 www 8686: }
8687: # --------------------------------------------------------------- Make the user
1.81 www 8688: my $reply=&modifyuser
1.209 matthew 8689: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8690: $desiredhome,$email,$inststatus);
1.80 www 8691: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8692: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8693: # student's environment
1.297 matthew 8694: $uid = undef if (!$forceid);
1.455 albertel 8695: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8696: $gene,$usec,$end,$start,$type,$locktype,
8697: $cid,$selfenroll,$context,$credits);
1.297 matthew 8698: return $reply;
8699: }
8700:
8701: sub modify_student_enrollment {
1.1216 raeburn 8702: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8703: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8704: my ($cdom,$cnum,$chome);
8705: if (!$cid) {
1.620 albertel 8706: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8707: return 'not_in_class';
8708: }
1.620 albertel 8709: $cdom=$env{'course.'.$cid.'.domain'};
8710: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8711: } else {
8712: ($cdom,$cnum)=split(/_/,$cid);
8713: }
1.620 albertel 8714: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8715: if (!$chome) {
1.457 raeburn 8716: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8717: }
1.455 albertel 8718: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8719: # Make sure the user exists
1.81 www 8720: my $uhome=&homeserver($uname,$udom);
8721: if (($uhome eq '') || ($uhome eq 'no_host')) {
8722: return 'error: no such user';
8723: }
1.297 matthew 8724: # Get student data if we were not given enough information
8725: if (!defined($first) || $first eq '' ||
8726: !defined($last) || $last eq '' ||
8727: !defined($uid) || $uid eq '' ||
8728: !defined($middle) || $middle eq '' ||
8729: !defined($gene) || $gene eq '') {
1.294 matthew 8730: # They did not supply us with enough data to enroll the student, so
8731: # we need to pick up more information.
1.297 matthew 8732: my %tmp = &get('environment',
1.294 matthew 8733: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8734: ,$udom,$uname);
8735:
1.800 albertel 8736: #foreach my $key (keys(%tmp)) {
8737: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8738: #}
1.294 matthew 8739: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8740: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8741: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8742: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8743: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8744: }
1.556 albertel 8745: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8746: my $user = "$uname:$udom";
8747: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8748: my $reply=cput('classlist',
1.1148 raeburn 8749: {$user =>
1.1216 raeburn 8750: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8751: $cdom,$cnum);
1.1148 raeburn 8752: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8753: &devalidate_getsection_cache($udom,$uname,$cid);
8754: } else {
1.81 www 8755: return 'error: '.$reply;
8756: }
1.297 matthew 8757: # Add student role to user
1.83 www 8758: my $uurl='/'.$cid;
1.81 www 8759: $uurl=~s/\_/\//g;
8760: if ($usec) {
8761: $uurl.='/'.$usec;
8762: }
1.1148 raeburn 8763: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8764: $selfenroll,$context);
8765: if ($result ne 'ok') {
8766: if ($old_entry{$user} ne '') {
8767: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8768: } else {
8769: $reply = &del('classlist',[$user],$cdom,$cnum);
8770: }
8771: }
8772: return $result;
1.21 www 8773: }
8774:
1.556 albertel 8775: sub format_name {
8776: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8777: my $name;
8778: if ($first ne 'lastname') {
8779: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8780: } else {
8781: if ($lastname=~/\S/) {
8782: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8783: $name=~s/\s+,/,/;
8784: } else {
8785: $name.= $firstname.' '.$middlename.' '.$generation;
8786: }
8787: }
8788: $name=~s/^\s+//;
8789: $name=~s/\s+$//;
8790: $name=~s/\s+/ /g;
8791: return $name;
8792: }
8793:
1.84 www 8794: # ------------------------------------------------- Write to course preferences
8795:
8796: sub writecoursepref {
8797: my ($courseid,%prefs)=@_;
8798: $courseid=~s/^\///;
8799: $courseid=~s/\_/\//g;
8800: my ($cdomain,$cnum)=split(/\//,$courseid);
8801: my $chome=homeserver($cnum,$cdomain);
8802: if (($chome eq '') || ($chome eq 'no_host')) {
8803: return 'error: no such course';
8804: }
8805: my $cstring='';
1.800 albertel 8806: foreach my $pref (keys(%prefs)) {
8807: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8808: }
1.84 www 8809: $cstring=~s/\&$//;
8810: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8811: }
8812:
8813: # ---------------------------------------------------------- Make/modify course
8814:
8815: sub createcourse {
1.741 raeburn 8816: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8817: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8818: $url=&declutter($url);
8819: my $cid='';
1.1028 raeburn 8820: if ($context eq 'requestcourses') {
8821: my $can_create = 0;
8822: my ($ownername,$ownerdom) = split(':',$course_owner);
8823: if ($udom eq $ownerdom) {
8824: if (&usertools_access($ownername,$ownerdom,$category,undef,
8825: $context)) {
8826: $can_create = 1;
8827: }
8828: } else {
8829: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8830: $category);
8831: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8832: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8833: if (@curr > 0) {
8834: my @options = qw(approval validate autolimit);
8835: my $optregex = join('|',@options);
8836: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8837: $can_create = 1;
8838: }
8839: }
8840: }
8841: }
8842: if ($can_create) {
8843: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8844: unless (&allowed('ccc',$udom)) {
8845: return 'refused';
8846: }
1.1017 raeburn 8847: }
8848: } else {
8849: return 'refused';
8850: }
1.1028 raeburn 8851: } elsif (!&allowed('ccc',$udom)) {
8852: return 'refused';
1.84 www 8853: }
1.1011 raeburn 8854: # --------------------------------------------------------------- Get Unique ID
8855: my $uname;
8856: if ($cnum =~ /^$match_courseid$/) {
8857: my $chome=&homeserver($cnum,$udom,'true');
8858: if (($chome eq '') || ($chome eq 'no_host')) {
8859: $uname = $cnum;
8860: } else {
1.1038 raeburn 8861: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8862: }
8863: } else {
1.1038 raeburn 8864: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8865: }
8866: return $uname if ($uname =~ /^error/);
8867: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8868: if (!defined($course_server)) {
8869: if (defined(&domain($udom,'primary'))) {
8870: $course_server = &domain($udom,'primary');
8871: } else {
8872: $course_server = $env{'user.home'};
8873: }
8874: }
8875: my %host_servers =
8876: &Apache::lonnet::get_servers($udom,'library');
8877: unless ($host_servers{$course_server}) {
8878: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8879: }
1.84 www 8880: # ------------------------------------------------------------- Make the course
8881: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8882: $course_server);
1.84 www 8883: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8884: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8885: if (($uhome eq '') || ($uhome eq 'no_host')) {
8886: return 'error: no such course';
8887: }
1.271 www 8888: # ----------------------------------------------------------------- Course made
1.516 raeburn 8889: # log existence
1.1029 raeburn 8890: my $now = time;
1.918 raeburn 8891: my $newcourse = {
8892: $udom.'_'.$uname => {
1.921 raeburn 8893: description => $description,
8894: inst_code => $inst_code,
8895: owner => $course_owner,
8896: type => $crstype,
1.1029 raeburn 8897: creator => $env{'user.name'}.':'.
8898: $env{'user.domain'},
8899: created => $now,
8900: context => $context,
1.918 raeburn 8901: },
8902: };
1.921 raeburn 8903: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8904: # set toplevel url
1.271 www 8905: my $topurl=$url;
8906: unless ($nonstandard) {
8907: # ------------------------------------------ For standard courses, make top url
8908: my $mapurl=&clutter($url);
1.278 www 8909: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8910: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8911: <map>
8912: <resource id="1" type="start"></resource>
8913: <resource id="2" src="$mapurl"></resource>
8914: <resource id="3" type="finish"></resource>
8915: <link index="1" from="1" to="2"></link>
8916: <link index="2" from="2" to="3"></link>
8917: </map>
8918: ENDINITMAP
8919: $topurl=&declutter(
1.638 albertel 8920: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8921: );
8922: }
8923: # ----------------------------------------------------------- Write preferences
1.84 www 8924: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8925: ('description' => $description,
8926: 'url' => $topurl,
8927: 'internal.creator' => $env{'user.name'}.':'.
8928: $env{'user.domain'},
8929: 'internal.created' => $now,
8930: 'internal.creationcontext' => $context)
8931: );
1.84 www 8932: return '/'.$udom.'/'.$uname;
8933: }
8934:
1.1011 raeburn 8935: # ------------------------------------------------------------------- Create ID
8936: sub generate_coursenum {
1.1038 raeburn 8937: my ($udom,$crstype) = @_;
1.1011 raeburn 8938: my $domdesc = &domain($udom);
8939: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8940: my $first;
8941: if ($crstype eq 'Community') {
8942: $first = '0';
8943: } else {
8944: $first = int(1+rand(9));
8945: }
8946: my $uname=$first.
1.1011 raeburn 8947: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8948: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8949: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8950: # ----------------------------------------------- Make sure that does not exist
8951: my $uhome=&homeserver($uname,$udom,'true');
8952: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8953: if ($crstype eq 'Community') {
8954: $first = '0';
8955: } else {
8956: $first = int(1+rand(9));
8957: }
8958: $uname=$first.
1.1011 raeburn 8959: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8960: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8961: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8962: $uhome=&homeserver($uname,$udom,'true');
8963: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8964: return 'error: unable to generate unique course-ID';
8965: }
8966: }
8967: return $uname;
8968: }
8969:
1.813 albertel 8970: sub is_course {
1.1167 droeschl 8971: my ($cdom, $cnum) = scalar(@_) == 1 ?
8972: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8973:
8974: return unless $cdom and $cnum;
8975:
8976: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8977: '.');
8978:
1.1219 raeburn 8979: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8980: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8981: }
8982:
1.1015 raeburn 8983: sub store_userdata {
8984: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8985: my $result;
1.1016 raeburn 8986: if ($datakey ne '') {
1.1013 raeburn 8987: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8988: if ($udom eq '' || $uname eq '') {
8989: $udom = $env{'user.domain'};
8990: $uname = $env{'user.name'};
8991: }
8992: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8993: if (($uhome eq '') || ($uhome eq 'no_host')) {
8994: $result = 'error: no_host';
8995: } else {
8996: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8997: $storehash->{'host'} = $perlvar{'lonHostID'};
8998:
8999: my $namevalue='';
9000: foreach my $key (keys(%{$storehash})) {
9001: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9002: }
9003: $namevalue=~s/\&$//;
1.1224 raeburn 9004: unless ($namespace eq 'courserequests') {
9005: $datakey = &escape($datakey);
9006: }
1.1105 raeburn 9007: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9008: $namevalue,$uhome);
1.1013 raeburn 9009: }
9010: } else {
9011: $result = 'error: data to store was not a hash reference';
9012: }
9013: } else {
9014: $result= 'error: invalid requestkey';
9015: }
9016: return $result;
9017: }
9018:
1.21 www 9019: # ---------------------------------------------------------- Assign Custom Role
9020:
9021: sub assigncustomrole {
1.957 raeburn 9022: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9023: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9024: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9025: }
9026:
9027: # ----------------------------------------------------------------- Revoke Role
9028:
9029: sub revokerole {
1.957 raeburn 9030: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9031: my $now=time;
1.965 raeburn 9032: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9033: }
9034:
9035: # ---------------------------------------------------------- Revoke Custom Role
9036:
9037: sub revokecustomrole {
1.957 raeburn 9038: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9039: my $now=time;
1.357 www 9040: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9041: $deleteflag,$selfenroll,$context);
1.17 www 9042: }
9043:
1.533 banghart 9044: # ------------------------------------------------------------ Disk usage
1.535 albertel 9045: sub diskusage {
1.955 raeburn 9046: my ($udom,$uname,$directorypath,$getpropath)=@_;
9047: $directorypath =~ s/\/$//;
9048: my $listing=&reply('du2:'.&escape($directorypath).':'
9049: .&escape($getpropath).':'.&escape($uname).':'
9050: .&escape($udom),homeserver($uname,$udom));
9051: if ($listing eq 'unknown_cmd') {
9052: if ($getpropath) {
9053: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9054: }
9055: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9056: }
1.514 albertel 9057: return $listing;
1.512 banghart 9058: }
9059:
1.566 banghart 9060: sub is_locked {
1.1096 raeburn 9061: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9062: my @check;
9063: my $is_locked;
1.1093 raeburn 9064: push (@check,$file_name);
1.613 albertel 9065: my %locked = &get('file_permissions',\@check,
1.620 albertel 9066: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9067: my ($tmp)=keys(%locked);
9068: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9069:
1.566 banghart 9070: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9071: $is_locked = 'false';
9072: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9073: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9074: $is_locked = 'true';
1.1096 raeburn 9075: if (ref($which) eq 'ARRAY') {
9076: push(@{$which},$entry);
9077: } else {
9078: last;
9079: }
1.745 raeburn 9080: }
9081: }
1.566 banghart 9082: } else {
9083: $is_locked = 'false';
9084: }
1.1093 raeburn 9085: return $is_locked;
1.566 banghart 9086: }
9087:
1.759 albertel 9088: sub declutter_portfile {
9089: my ($file) = @_;
1.833 albertel 9090: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9091: return $file;
9092: }
9093:
1.559 banghart 9094: # ------------------------------------------------------------- Mark as Read Only
9095:
9096: sub mark_as_readonly {
9097: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9098: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9099: my ($tmp)=keys(%current_permissions);
9100: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9101: foreach my $file (@{$files}) {
1.759 albertel 9102: $file = &declutter_portfile($file);
1.561 banghart 9103: push(@{$current_permissions{$file}},$what);
1.559 banghart 9104: }
1.613 albertel 9105: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9106: return;
9107: }
9108:
1.572 banghart 9109: # ------------------------------------------------------------Save Selected Files
9110:
9111: sub save_selected_files {
9112: my ($user, $path, @files) = @_;
9113: my $filename = $user."savedfiles";
1.573 banghart 9114: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9115: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9116: foreach my $file (@files) {
1.620 albertel 9117: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9118: }
9119: foreach my $file (@other_files) {
1.574 banghart 9120: print (OUT $file."\n");
1.572 banghart 9121: }
1.574 banghart 9122: close (OUT);
1.572 banghart 9123: return 'ok';
9124: }
9125:
1.574 banghart 9126: sub clear_selected_files {
9127: my ($user) = @_;
9128: my $filename = $user."savedfiles";
1.1117 foxr 9129: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9130: print (OUT undef);
9131: close (OUT);
9132: return ("ok");
9133: }
9134:
1.572 banghart 9135: sub files_in_path {
9136: my ($user, $path) = @_;
9137: my $filename = $user."savedfiles";
9138: my %return_files;
1.1117 foxr 9139: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9140: while (my $line_in = <IN>) {
1.574 banghart 9141: chomp ($line_in);
9142: my @paths_and_file = split (m!/!, $line_in);
9143: my $file_part = pop (@paths_and_file);
9144: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9145: $path_part.='/';
9146: my $path_and_file = $path_part.$file_part;
9147: if ($path_part eq $path) {
9148: $return_files{$file_part}= 'selected';
9149: }
9150: }
1.574 banghart 9151: close (IN);
9152: return (\%return_files);
1.572 banghart 9153: }
9154:
9155: # called in portfolio select mode, to show files selected NOT in current directory
9156: sub files_not_in_path {
9157: my ($user, $path) = @_;
9158: my $filename = $user."savedfiles";
9159: my @return_files;
9160: my $path_part;
1.1117 foxr 9161: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9162: while (my $line = <IN>) {
1.572 banghart 9163: #ok, I know it's clunky, but I want it to work
1.800 albertel 9164: my @paths_and_file = split(m|/|, $line);
9165: my $file_part = pop(@paths_and_file);
9166: chomp($file_part);
9167: my $path_part = join('/', @paths_and_file);
1.572 banghart 9168: $path_part .= '/';
9169: my $path_and_file = $path_part.$file_part;
9170: if ($path_part ne $path) {
1.800 albertel 9171: push(@return_files, ($path_and_file));
1.572 banghart 9172: }
9173: }
1.800 albertel 9174: close(OUT);
1.574 banghart 9175: return (@return_files);
1.572 banghart 9176: }
9177:
1.1273 raeburn 9178: #------------------------------Submitted/Handedback Portfolio Files Versioning
9179:
9180: sub portfiles_versioning {
9181: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9182: my $portfolio_root = '/userfiles/portfolio';
9183: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9184: foreach my $file (@{$portfiles}) {
9185: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9186: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9187: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9188: my $getpropath = 1;
9189: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9190: $stu_name,$getpropath);
9191: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9192: my $new_answer =
9193: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9194: if ($new_answer ne 'problem getting file') {
9195: push(@{$versioned_portfiles}, $directory.$new_answer);
9196: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9197: [$symb,$env{'request.course.id'},'graded']);
9198: }
9199: }
9200: }
9201:
9202: sub get_next_version {
9203: my ($answer_name, $answer_ext, $dir_list) = @_;
9204: my $version;
9205: if (ref($dir_list) eq 'ARRAY') {
9206: foreach my $row (@{$dir_list}) {
9207: my ($file) = split(/\&/,$row,2);
9208: my ($file_name,$file_version,$file_ext) =
9209: &file_name_version_ext($file);
9210: if (($file_name eq $answer_name) &&
9211: ($file_ext eq $answer_ext)) {
9212: # gets here if filename and extension match,
9213: # regardless of version
9214: if ($file_version ne '') {
9215: # a versioned file is found so save it for later
9216: if ($file_version > $version) {
9217: $version = $file_version;
9218: }
9219: }
9220: }
9221: }
9222: }
9223: $version ++;
9224: return($version);
9225: }
9226:
9227: sub version_selected_portfile {
9228: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9229: my ($answer_name,$answer_ver,$answer_ext) =
9230: &file_name_version_ext($file_name);
9231: my $new_answer;
9232: $env{'form.copy'} =
9233: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9234: if($env{'form.copy'} eq '-1') {
9235: $new_answer = 'problem getting file';
9236: } else {
9237: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9238: my $copy_result =
9239: &finishuserfileupload($stu_name,$domain,'copy',
9240: '/portfolio'.$directory.$new_answer);
9241: }
9242: undef($env{'form.copy'});
9243: return ($new_answer);
9244: }
9245:
9246: sub file_name_version_ext {
9247: my ($file)=@_;
9248: my @file_parts = split(/\./, $file);
9249: my ($name,$version,$ext);
9250: if (@file_parts > 1) {
9251: $ext=pop(@file_parts);
9252: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9253: $version=pop(@file_parts);
9254: }
9255: $name=join('.',@file_parts);
9256: } else {
9257: $name=join('.',@file_parts);
9258: }
9259: return($name,$version,$ext);
9260: }
9261:
1.745 raeburn 9262: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9263:
1.745 raeburn 9264: sub get_portfile_permissions {
9265: my ($domain,$user) = @_;
1.613 albertel 9266: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9267: my ($tmp)=keys(%current_permissions);
9268: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9269: return \%current_permissions;
9270: }
9271:
9272: #---------------------------------------------Get portfolio file access controls
9273:
1.749 raeburn 9274: sub get_access_controls {
1.745 raeburn 9275: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9276: my %access;
9277: my $real_file = $file;
9278: $file =~ s/\.meta$//;
1.745 raeburn 9279: if (defined($file)) {
1.749 raeburn 9280: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9281: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9282: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9283: }
9284: }
1.745 raeburn 9285: } else {
1.749 raeburn 9286: foreach my $key (keys(%{$current_permissions})) {
9287: if ($key =~ /\0accesscontrol$/) {
9288: if (defined($group)) {
9289: if ($key !~ m-^\Q$group\E/-) {
9290: next;
9291: }
9292: }
9293: my ($fullpath) = split(/\0/,$key);
9294: if (ref($$current_permissions{$key}) eq 'HASH') {
9295: foreach my $control (keys(%{$$current_permissions{$key}})) {
9296: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9297: }
9298: }
9299: }
9300: }
9301: }
9302: return %access;
9303: }
9304:
9305: sub modify_access_controls {
9306: my ($file_name,$changes,$domain,$user)=@_;
9307: my ($outcome,$deloutcome);
9308: my %store_permissions;
9309: my %new_values;
9310: my %new_control;
9311: my %translation;
9312: my @deletions = ();
9313: my $now = time;
9314: if (exists($$changes{'activate'})) {
9315: if (ref($$changes{'activate'}) eq 'HASH') {
9316: my @newitems = sort(keys(%{$$changes{'activate'}}));
9317: my $numnew = scalar(@newitems);
9318: for (my $i=0; $i<$numnew; $i++) {
9319: my $newkey = $newitems[$i];
9320: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9321: if ($newkey =~ /^\d+:/) {
9322: $newkey =~ s/^(\d+)/$newid/;
9323: $translation{$1} = $newid;
9324: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9325: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9326: $translation{$1} = $newid;
9327: }
1.749 raeburn 9328: $new_values{$file_name."\0".$newkey} =
9329: $$changes{'activate'}{$newitems[$i]};
9330: $new_control{$newkey} = $now;
9331: }
9332: }
9333: }
9334: my %todelete;
9335: my %changed_items;
9336: foreach my $action ('delete','update') {
9337: if (exists($$changes{$action})) {
9338: if (ref($$changes{$action}) eq 'HASH') {
9339: foreach my $key (keys(%{$$changes{$action}})) {
9340: my ($itemnum) = ($key =~ /^([^:]+):/);
9341: if ($action eq 'delete') {
9342: $todelete{$itemnum} = 1;
9343: } else {
9344: $changed_items{$itemnum} = $key;
9345: }
9346: }
1.745 raeburn 9347: }
9348: }
1.749 raeburn 9349: }
9350: # get lock on access controls for file.
9351: my $lockhash = {
9352: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9353: ':'.$env{'user.domain'},
9354: };
9355: my $tries = 0;
9356: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9357:
9358: while (($gotlock ne 'ok') && $tries <3) {
9359: $tries ++;
9360: sleep 1;
9361: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9362: }
9363: if ($gotlock eq 'ok') {
9364: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9365: my ($tmp)=keys(%curr_permissions);
9366: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9367: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9368: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9369: if (ref($curr_controls) eq 'HASH') {
9370: foreach my $control_item (keys(%{$curr_controls})) {
9371: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9372: if (defined($todelete{$itemnum})) {
9373: push(@deletions,$file_name."\0".$control_item);
9374: } else {
9375: if (defined($changed_items{$itemnum})) {
9376: $new_control{$changed_items{$itemnum}} = $now;
9377: push(@deletions,$file_name."\0".$control_item);
9378: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9379: } else {
9380: $new_control{$control_item} = $$curr_controls{$control_item};
9381: }
9382: }
1.745 raeburn 9383: }
9384: }
9385: }
1.970 raeburn 9386: my ($group);
9387: if (&is_course($domain,$user)) {
9388: ($group,my $file) = split(/\//,$file_name,2);
9389: }
1.749 raeburn 9390: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9391: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9392: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9393: # remove lock
9394: my @del_lock = ($file_name."\0".'locked_access_records');
9395: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9396: my $sqlresult =
1.970 raeburn 9397: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9398: $group);
1.749 raeburn 9399: } else {
9400: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9401: }
1.749 raeburn 9402: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9403: }
9404:
1.827 raeburn 9405: sub make_public_indefinitely {
1.1271 raeburn 9406: my (@requrl) = @_;
9407: return &automated_portfile_access('public',\@requrl);
9408: }
9409:
9410: sub automated_portfile_access {
9411: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9412: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9413: return 'invalid';
9414: }
1.1271 raeburn 9415: my %urls;
9416: if (ref($addsref) eq 'ARRAY') {
9417: foreach my $requrl (@{$addsref}) {
9418: if (&is_portfolio_url($requrl)) {
9419: unless (exists($urls{$requrl})) {
9420: $urls{$requrl} = 'add';
9421: }
9422: }
9423: }
9424: }
9425: if (ref($delsref) eq 'ARRAY') {
9426: foreach my $requrl (@{$delsref}) {
9427: if (&is_portfolio_url($requrl)) {
9428: unless (exists($urls{$requrl})) {
9429: $urls{$requrl} = 'delete';
9430: }
9431: }
9432: }
9433: }
9434: unless (keys(%urls)) {
9435: return 'invalid';
9436: }
9437: my $ip;
9438: if ($accesstype eq 'ip') {
9439: if (ref($info) eq 'HASH') {
9440: if ($info->{'ip'} ne '') {
9441: $ip = $info->{'ip'};
9442: }
9443: }
9444: if ($ip eq '') {
9445: return 'invalid';
9446: }
9447: }
9448: my $errors;
1.827 raeburn 9449: my $now = time;
1.1271 raeburn 9450: my %current_perms;
9451: foreach my $requrl (sort(keys(%urls))) {
9452: my $action;
9453: if ($urls{$requrl} eq 'add') {
9454: $action = 'activate';
9455: } else {
9456: $action = 'none';
9457: }
9458: my $aclnum = 0;
1.827 raeburn 9459: my (undef,$udom,$unum,$file_name,$group) =
9460: &parse_portfolio_url($requrl);
1.1271 raeburn 9461: unless (exists($current_perms{$unum.':'.$udom})) {
9462: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9463: }
9464: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9465: $group,$file_name);
9466: foreach my $key (keys(%{$access_controls{$file_name}})) {
9467: my ($num,$scope,$end,$start) =
9468: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9469: if ($scope eq $accesstype) {
9470: if (($start <= $now) && ($end == 0)) {
9471: if ($accesstype eq 'ip') {
9472: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9473: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9474: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9475: if ($urls{$requrl} eq 'add') {
9476: $action = 'none';
9477: last;
9478: } else {
9479: $action = 'delete';
9480: $aclnum = $num;
9481: last;
9482: }
9483: }
9484: }
9485: }
9486: } elsif ($accesstype eq 'public') {
9487: if ($urls{$requrl} eq 'add') {
9488: $action = 'none';
9489: last;
9490: } else {
9491: $action = 'delete';
9492: $aclnum = $num;
9493: last;
9494: }
9495: }
9496: } elsif ($accesstype eq 'public') {
1.827 raeburn 9497: $action = 'update';
9498: $aclnum = $num;
1.1271 raeburn 9499: last;
1.827 raeburn 9500: }
9501: }
9502: }
9503: if ($action eq 'none') {
1.1271 raeburn 9504: next;
1.827 raeburn 9505: } else {
9506: my %changes;
9507: my $newend = 0;
9508: my $newstart = $now;
1.1271 raeburn 9509: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 9510: $changes{$action}{$newkey} = {
1.1271 raeburn 9511: type => $accesstype,
1.827 raeburn 9512: time => {
9513: start => $newstart,
9514: end => $newend,
9515: },
9516: };
1.1271 raeburn 9517: if ($accesstype eq 'ip') {
9518: $changes{$action}{$newkey}{'ip'} = [$ip];
9519: }
1.827 raeburn 9520: my ($outcome,$deloutcome,$new_values,$translation) =
9521: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 9522: unless ($outcome eq 'ok') {
9523: $errors .= $outcome.' ';
9524: }
1.827 raeburn 9525: }
1.1271 raeburn 9526: }
9527: if ($errors) {
9528: $errors =~ s/\s$//;
9529: return $errors;
1.827 raeburn 9530: } else {
1.1271 raeburn 9531: return 'ok';
1.827 raeburn 9532: }
9533: }
9534:
1.745 raeburn 9535: #------------------------------------------------------Get Marked as Read Only
9536:
9537: sub get_marked_as_readonly {
9538: my ($domain,$user,$what,$group) = @_;
9539: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9540: my @readonly_files;
1.629 banghart 9541: my $cmp1=$what;
9542: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9543: while (my ($file_name,$value) = each(%{$current_permissions})) {
9544: if (defined($group)) {
9545: if ($file_name !~ m-^\Q$group\E/-) {
9546: next;
9547: }
9548: }
1.561 banghart 9549: if (ref($value) eq "ARRAY"){
9550: foreach my $stored_what (@{$value}) {
1.629 banghart 9551: my $cmp2=$stored_what;
1.759 albertel 9552: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9553: $cmp2=join('',@{$stored_what});
1.745 raeburn 9554: }
1.629 banghart 9555: if ($cmp1 eq $cmp2) {
1.561 banghart 9556: push(@readonly_files, $file_name);
1.745 raeburn 9557: last;
1.563 banghart 9558: } elsif (!defined($what)) {
9559: push(@readonly_files, $file_name);
1.745 raeburn 9560: last;
1.561 banghart 9561: }
9562: }
1.745 raeburn 9563: }
1.561 banghart 9564: }
9565: return @readonly_files;
9566: }
1.577 banghart 9567: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9568:
1.577 banghart 9569: sub get_marked_as_readonly_hash {
1.745 raeburn 9570: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9571: my %readonly_files;
1.745 raeburn 9572: while (my ($file_name,$value) = each(%{$current_permissions})) {
9573: if (defined($group)) {
9574: if ($file_name !~ m-^\Q$group\E/-) {
9575: next;
9576: }
9577: }
1.577 banghart 9578: if (ref($value) eq "ARRAY"){
9579: foreach my $stored_what (@{$value}) {
1.745 raeburn 9580: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9581: foreach my $lock_descriptor(@{$stored_what}) {
9582: if ($lock_descriptor eq 'graded') {
9583: $readonly_files{$file_name} = 'graded';
9584: } elsif ($lock_descriptor eq 'handback') {
9585: $readonly_files{$file_name} = 'handback';
9586: } else {
9587: if (!exists($readonly_files{$file_name})) {
9588: $readonly_files{$file_name} = 'locked';
9589: }
9590: }
1.745 raeburn 9591: }
1.750 banghart 9592: }
1.577 banghart 9593: }
9594: }
9595: }
9596: return %readonly_files;
9597: }
1.559 banghart 9598: # ------------------------------------------------------------ Unmark as Read Only
9599:
9600: sub unmark_as_readonly {
1.629 banghart 9601: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9602: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9603: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9604: $file_name = &declutter_portfile($file_name);
1.634 albertel 9605: my $symb_crs = $what;
9606: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9607: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9608: my ($tmp)=keys(%current_permissions);
9609: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9610: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9611: foreach my $file (@readonly_files) {
1.759 albertel 9612: my $clean_file = &declutter_portfile($file);
9613: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9614: my $current_locks = $current_permissions{$file};
1.563 banghart 9615: my @new_locks;
9616: my @del_keys;
9617: if (ref($current_locks) eq "ARRAY"){
9618: foreach my $locker (@{$current_locks}) {
1.632 albertel 9619: my $compare=$locker;
1.749 raeburn 9620: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9621: $compare=join('',@{$locker});
1.746 raeburn 9622: if ($compare ne $symb_crs) {
9623: push(@new_locks, $locker);
9624: }
1.563 banghart 9625: }
9626: }
1.650 albertel 9627: if (scalar(@new_locks) > 0) {
1.563 banghart 9628: $current_permissions{$file} = \@new_locks;
9629: } else {
9630: push(@del_keys, $file);
1.613 albertel 9631: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9632: delete($current_permissions{$file});
1.563 banghart 9633: }
9634: }
1.561 banghart 9635: }
1.613 albertel 9636: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9637: return;
9638: }
1.512 banghart 9639:
1.17 www 9640: # ------------------------------------------------------------ Directory lister
9641:
9642: sub dirlist {
1.955 raeburn 9643: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9644: $uri=~s/^\///;
9645: $uri=~s/\/$//;
1.253 stredwic 9646: my ($udom, $uname);
1.955 raeburn 9647: if ($getuserdir) {
1.253 stredwic 9648: $udom = $userdomain;
9649: $uname = $username;
1.955 raeburn 9650: } else {
9651: (undef,$udom,$uname)=split(/\//,$uri);
9652: if(defined($userdomain)) {
9653: $udom = $userdomain;
9654: }
9655: if(defined($username)) {
9656: $uname = $username;
9657: }
1.253 stredwic 9658: }
1.955 raeburn 9659: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9660:
1.955 raeburn 9661: $dirRoot = $perlvar{'lonDocRoot'};
9662: if (defined($getpropath)) {
9663: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9664: $dirRoot =~ s/\/$//;
1.955 raeburn 9665: } elsif (defined($getuserdir)) {
9666: my $subdir=$uname.'__';
9667: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9668: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9669: ."/$udom/$subdir/$uname";
9670: } elsif (defined($alternateRoot)) {
9671: $dirRoot = $alternateRoot;
1.751 banghart 9672: }
1.253 stredwic 9673:
9674: if($udom) {
9675: if($uname) {
1.1135 raeburn 9676: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9677: if ($uhome eq 'no_host') {
9678: return ([],'no_host');
9679: }
1.955 raeburn 9680: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9681: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9682: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9683: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9684: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9685: } else {
9686: @listing_results = map { &unescape($_); } split(/:/,$listing);
9687: }
1.605 matthew 9688: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9689: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9690: @listing_results = split(/:/,$listing);
9691: } else {
9692: @listing_results = map { &unescape($_); } split(/:/,$listing);
9693: }
1.1135 raeburn 9694: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9695: ($listing eq 'rejected') || ($listing eq 'refused') ||
9696: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9697: return ([],$listing);
9698: } else {
9699: return (\@listing_results);
1.1135 raeburn 9700: }
1.955 raeburn 9701: } elsif(!$alternateRoot) {
1.1136 raeburn 9702: my (%allusers,%listerror);
1.841 albertel 9703: my %servers = &get_servers($udom,'library');
1.955 raeburn 9704: foreach my $tryserver (keys(%servers)) {
9705: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9706: &escape($udom),$tryserver);
9707: if ($listing eq 'unknown_cmd') {
9708: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9709: $udom, $tryserver);
9710: } else {
9711: @listing_results = map { &unescape($_); } split(/:/,$listing);
9712: }
1.841 albertel 9713: if ($listing eq 'unknown_cmd') {
9714: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9715: $udom, $tryserver);
9716: @listing_results = split(/:/,$listing);
9717: } else {
9718: @listing_results =
9719: map { &unescape($_); } split(/:/,$listing);
9720: }
1.1136 raeburn 9721: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9722: ($listing eq 'rejected') || ($listing eq 'refused') ||
9723: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9724: $listerror{$tryserver} = $listing;
9725: } else {
1.841 albertel 9726: foreach my $line (@listing_results) {
9727: my ($entry) = split(/&/,$line,2);
9728: $allusers{$entry} = 1;
9729: }
9730: }
1.253 stredwic 9731: }
1.1136 raeburn 9732: my @alluserslist=();
1.800 albertel 9733: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9734: push(@alluserslist,$user.'&user');
1.253 stredwic 9735: }
1.1136 raeburn 9736: return (\@alluserslist);
1.253 stredwic 9737: } else {
1.1136 raeburn 9738: return ([],'missing username');
1.253 stredwic 9739: }
1.955 raeburn 9740: } elsif(!defined($getpropath)) {
1.1136 raeburn 9741: my $path = $perlvar{'lonDocRoot'}.'/res/';
9742: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9743: return (\@all_domains);
1.955 raeburn 9744: } else {
1.1136 raeburn 9745: return ([],'missing domain');
1.275 stredwic 9746: }
9747: }
9748:
9749: # --------------------------------------------- GetFileTimestamp
9750: # This function utilizes dirlist and returns the date stamp for
9751: # when it was last modified. It will also return an error of -1
9752: # if an error occurs
9753:
9754: sub GetFileTimestamp {
1.955 raeburn 9755: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9756: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9757: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9758: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9759: undef,$getuserdir);
9760: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9761: return -1;
9762: }
9763: if (ref($fileref) eq 'ARRAY') {
9764: my @stats = split('&',$fileref->[0]);
1.375 matthew 9765: # @stats contains first the filename, then the stat output
9766: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9767: } else {
9768: return -1;
1.253 stredwic 9769: }
1.26 www 9770: }
9771:
1.712 albertel 9772: sub stat_file {
9773: my ($uri) = @_;
1.787 albertel 9774: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9775:
1.955 raeburn 9776: my ($udom,$uname,$file);
1.712 albertel 9777: if ($uri =~ m-^/(uploaded|editupload)/-) {
9778: ($udom,$uname,$file) =
1.811 albertel 9779: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9780: $file = 'userfiles/'.$file;
9781: }
9782: if ($uri =~ m-^/res/-) {
9783: ($udom,$uname) =
1.807 albertel 9784: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9785: $file = $uri;
9786: }
9787:
9788: if (!$udom || !$uname || !$file) {
9789: # unable to handle the uri
9790: return ();
9791: }
1.956 raeburn 9792: my $getpropath;
9793: if ($file =~ /^userfiles\//) {
9794: $getpropath = 1;
9795: }
1.1136 raeburn 9796: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9797: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9798: return ();
9799: } else {
9800: if (ref($listref) eq 'ARRAY') {
9801: my @stats = split('&',$listref->[0]);
9802: shift(@stats); #filename is first
9803: return @stats;
9804: }
1.712 albertel 9805: }
9806: return ();
9807: }
9808:
1.26 www 9809: # -------------------------------------------------------- Value of a Condition
9810:
1.713 albertel 9811: # gets the value of a specific preevaluated condition
9812: # stored in the string $env{user.state.<cid>}
9813: # or looks up a condition reference in the bighash and if if hasn't
9814: # already been evaluated recurses into docondval to get the value of
9815: # the condition, then memoizing it to
9816: # $env{user.state.<cid>.<condition>}
1.40 www 9817: sub directcondval {
9818: my $number=shift;
1.620 albertel 9819: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9820: &Apache::lonuserstate::evalstate();
9821: }
1.713 albertel 9822: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9823: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9824: } elsif ($number =~ /^_/) {
9825: my $sub_condition;
9826: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9827: &GDBM_READER(),0640)) {
9828: $sub_condition=$bighash{'conditions'.$number};
9829: untie(%bighash);
9830: }
9831: my $value = &docondval($sub_condition);
1.949 raeburn 9832: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9833: return $value;
9834: }
1.620 albertel 9835: if ($env{'user.state.'.$env{'request.course.id'}}) {
9836: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9837: } else {
9838: return 2;
9839: }
9840: }
9841:
1.713 albertel 9842: # get the collection of conditions for this resource
1.26 www 9843: sub condval {
9844: my $condidx=shift;
1.54 www 9845: my $allpathcond='';
1.713 albertel 9846: foreach my $cond (split(/\|/,$condidx)) {
9847: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9848: $allpathcond.=
9849: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9850: }
1.191 harris41 9851: }
1.54 www 9852: $allpathcond=~s/\|$//;
1.713 albertel 9853: return &docondval($allpathcond);
9854: }
9855:
9856: #evaluates an expression of conditions
9857: sub docondval {
9858: my ($allpathcond) = @_;
9859: my $result=0;
9860: if ($env{'request.course.id'}
9861: && defined($allpathcond)) {
9862: my $operand='|';
9863: my @stack;
9864: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9865: if ($chunk eq '(') {
9866: push @stack,($operand,$result);
9867: } elsif ($chunk eq ')') {
9868: my $before=pop @stack;
9869: if (pop @stack eq '&') {
9870: $result=$result>$before?$before:$result;
9871: } else {
9872: $result=$result>$before?$result:$before;
9873: }
9874: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9875: $operand=$chunk;
9876: } else {
9877: my $new=directcondval($chunk);
9878: if ($operand eq '&') {
9879: $result=$result>$new?$new:$result;
9880: } else {
9881: $result=$result>$new?$result:$new;
9882: }
9883: }
9884: }
1.26 www 9885: }
9886: return $result;
1.421 albertel 9887: }
9888:
9889: # ---------------------------------------------------- Devalidate courseresdata
9890:
9891: sub devalidatecourseresdata {
9892: my ($coursenum,$coursedomain)=@_;
9893: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9894: &devalidate_cache_new('courseres',$hashid);
1.28 www 9895: }
9896:
1.763 www 9897:
1.200 www 9898: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9899: #
9900: # Parameters:
9901: # $coursenum - Number of the course.
9902: # $coursedomain - Domain at which the course was created.
9903: # Returns:
9904: # A hash of the course parameters along (I think) with timestamps
9905: # and version info.
1.877 foxr 9906:
1.624 albertel 9907: sub get_courseresdata {
9908: my ($coursenum,$coursedomain)=@_;
1.200 www 9909: my $coursehom=&homeserver($coursenum,$coursedomain);
9910: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9911: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9912: my %dumpreply;
1.417 albertel 9913: unless (defined($cached)) {
1.624 albertel 9914: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9915: $result=\%dumpreply;
1.251 albertel 9916: my ($tmp) = keys(%dumpreply);
9917: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9918: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9919: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9920: return $tmp;
1.416 albertel 9921: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9922: $result=undef;
1.599 albertel 9923: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9924: }
9925: }
1.624 albertel 9926: return $result;
9927: }
9928:
1.633 albertel 9929: sub devalidateuserresdata {
9930: my ($uname,$udom)=@_;
9931: my $hashid="$udom:$uname";
9932: &devalidate_cache_new('userres',$hashid);
9933: }
9934:
1.624 albertel 9935: sub get_userresdata {
9936: my ($uname,$udom)=@_;
9937: #most student don\'t have any data set, check if there is some data
9938: if (&EXT_cache_status($udom,$uname)) { return undef; }
9939:
9940: my $hashid="$udom:$uname";
9941: my ($result,$cached)=&is_cached_new('userres',$hashid);
9942: if (!defined($cached)) {
9943: my %resourcedata=&dump('resourcedata',$udom,$uname);
9944: $result=\%resourcedata;
9945: &do_cache_new('userres',$hashid,$result,600);
9946: }
9947: my ($tmp)=keys(%$result);
9948: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9949: return $result;
9950: }
9951: #error 2 occurs when the .db doesn't exist
9952: if ($tmp!~/error: 2 /) {
1.672 albertel 9953: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9954: " Trying to get resource data for ".
9955: $uname." at ".$udom.": ".
9956: $tmp."</font>");
9957: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9958: #&EXT_cache_set($udom,$uname);
9959: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9960: undef($tmp); # not really an error so don't send it back
1.624 albertel 9961: }
9962: return $tmp;
9963: }
1.879 foxr 9964: #----------------------------------------------- resdata - return resource data
9965: # Purpose:
9966: # Return resource data for either users or for a course.
9967: # Parameters:
9968: # $name - Course/user name.
9969: # $domain - Name of the domain the user/course is registered on.
9970: # $type - Type of thing $name is (must be 'course' or 'user'
9971: # @which - Array of names of resources desired.
9972: # Returns:
9973: # The value of the first reasource in @which that is found in the
9974: # resource hash.
9975: # Exceptional Conditions:
9976: # If the $type passed in is not valid (not the string 'course' or
9977: # 'user', an undefined reference is returned.
9978: # If none of the resources are found, an undef is returned
1.624 albertel 9979: sub resdata {
9980: my ($name,$domain,$type,@which)=@_;
9981: my $result;
9982: if ($type eq 'course') {
9983: $result=&get_courseresdata($name,$domain);
9984: } elsif ($type eq 'user') {
9985: $result=&get_userresdata($name,$domain);
9986: }
9987: if (!ref($result)) { return $result; }
1.251 albertel 9988: foreach my $item (@which) {
1.927 albertel 9989: if (defined($result->{$item->[0]})) {
9990: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9991: }
1.250 albertel 9992: }
1.291 albertel 9993: return undef;
1.200 www 9994: }
9995:
1.1236 raeburn 9996: sub get_numsuppfiles {
9997: my ($cnum,$cdom,$ignorecache)=@_;
9998: my $hashid=$cnum.':'.$cdom;
9999: my ($suppcount,$cached);
10000: unless ($ignorecache) {
10001: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10002: }
10003: unless (defined($cached)) {
10004: my $chome=&homeserver($cnum,$cdom);
10005: unless ($chome eq 'no_host') {
10006: ($suppcount,my $errors) = (0,0);
10007: my $suppmap = 'supplemental.sequence';
10008: ($suppcount,$errors) =
10009: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10010: }
10011: &do_cache_new('suppcount',$hashid,$suppcount,600);
10012: }
10013: return $suppcount;
10014: }
10015:
1.379 matthew 10016: #
10017: # EXT resource caching routines
10018: #
10019:
10020: sub clear_EXT_cache_status {
1.383 albertel 10021: &delenv('cache.EXT.');
1.379 matthew 10022: }
10023:
10024: sub EXT_cache_status {
10025: my ($target_domain,$target_user) = @_;
1.383 albertel 10026: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10027: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10028: # We know already the user has no data
10029: return 1;
10030: } else {
10031: return 0;
10032: }
10033: }
10034:
10035: sub EXT_cache_set {
10036: my ($target_domain,$target_user) = @_;
1.383 albertel 10037: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10038: #&appenv({$cachename => time});
1.379 matthew 10039: }
10040:
1.28 www 10041: # --------------------------------------------------------- Value of a Variable
1.58 www 10042: sub EXT {
1.715 albertel 10043:
1.1228 raeburn 10044: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10045: unless ($varname) { return ''; }
1.218 albertel 10046: #get real user name/domain, courseid and symb
10047: my $courseid;
1.359 albertel 10048: my $publicuser;
1.427 www 10049: if ($symbparm) {
10050: $symbparm=&get_symb_from_alias($symbparm);
10051: }
1.218 albertel 10052: if (!($uname && $udom)) {
1.790 albertel 10053: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10054: if (!$symbparm) { $symbparm=$cursymb; }
10055: } else {
1.620 albertel 10056: $courseid=$env{'request.course.id'};
1.218 albertel 10057: }
1.48 www 10058: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10059: my $rest;
1.320 albertel 10060: if (defined($therest[0])) {
1.48 www 10061: $rest=join('.',@therest);
10062: } else {
10063: $rest='';
10064: }
1.320 albertel 10065:
1.57 www 10066: my $qualifierrest=$qualifier;
10067: if ($rest) { $qualifierrest.='.'.$rest; }
10068: my $spacequalifierrest=$space;
10069: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10070: if ($realm eq 'user') {
1.48 www 10071: # --------------------------------------------------------------- user.resource
10072: if ($space eq 'resource') {
1.651 albertel 10073: if ( (defined($Apache::lonhomework::parsing_a_problem)
10074: || defined($Apache::lonhomework::parsing_a_task))
10075: &&
1.744 albertel 10076: ($symbparm eq &symbread()) ) {
10077: # if we are in the middle of processing the resource the
10078: # get the value we are planning on committing
10079: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10080: return $Apache::lonhomework::results{$qualifierrest};
10081: } else {
10082: return $Apache::lonhomework::history{$qualifierrest};
10083: }
1.335 albertel 10084: } else {
1.359 albertel 10085: my %restored;
1.620 albertel 10086: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10087: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10088: } else {
10089: %restored=&restore($symbparm,$courseid,$udom,$uname);
10090: }
1.335 albertel 10091: return $restored{$qualifierrest};
10092: }
1.48 www 10093: # ----------------------------------------------------------------- user.access
10094: } elsif ($space eq 'access') {
1.218 albertel 10095: # FIXME - not supporting calls for a specific user
1.48 www 10096: return &allowed($qualifier,$rest);
10097: # ------------------------------------------ user.preferences, user.environment
10098: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10099: if (($uname eq $env{'user.name'}) &&
10100: ($udom eq $env{'user.domain'})) {
10101: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10102: } else {
1.359 albertel 10103: my %returnhash;
10104: if (!$publicuser) {
10105: %returnhash=&userenvironment($udom,$uname,
10106: $qualifierrest);
10107: }
1.218 albertel 10108: return $returnhash{$qualifierrest};
10109: }
1.48 www 10110: # ----------------------------------------------------------------- user.course
10111: } elsif ($space eq 'course') {
1.218 albertel 10112: # FIXME - not supporting calls for a specific user
1.620 albertel 10113: return $env{join('.',('request.course',$qualifier))};
1.48 www 10114: # ------------------------------------------------------------------- user.role
10115: } elsif ($space eq 'role') {
1.218 albertel 10116: # FIXME - not supporting calls for a specific user
1.620 albertel 10117: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10118: if ($qualifier eq 'value') {
10119: return $role;
10120: } elsif ($qualifier eq 'extent') {
10121: return $where;
10122: }
10123: # ----------------------------------------------------------------- user.domain
10124: } elsif ($space eq 'domain') {
1.218 albertel 10125: return $udom;
1.48 www 10126: # ------------------------------------------------------------------- user.name
10127: } elsif ($space eq 'name') {
1.218 albertel 10128: return $uname;
1.48 www 10129: # ---------------------------------------------------- Any other user namespace
1.29 www 10130: } else {
1.359 albertel 10131: my %reply;
10132: if (!$publicuser) {
10133: %reply=&get($space,[$qualifierrest],$udom,$uname);
10134: }
10135: return $reply{$qualifierrest};
1.48 www 10136: }
1.236 www 10137: } elsif ($realm eq 'query') {
10138: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10139: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10140: [$spacequalifierrest]);
1.620 albertel 10141: return $env{'form.'.$spacequalifierrest};
1.236 www 10142: } elsif ($realm eq 'request') {
1.48 www 10143: # ------------------------------------------------------------- request.browser
10144: if ($space eq 'browser') {
1.1145 bisitz 10145: return $env{'browser.'.$qualifier};
1.57 www 10146: # ------------------------------------------------------------ request.filename
10147: } else {
1.620 albertel 10148: return $env{'request.'.$spacequalifierrest};
1.29 www 10149: }
1.28 www 10150: } elsif ($realm eq 'course') {
1.48 www 10151: # ---------------------------------------------------------- course.description
1.620 albertel 10152: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10153: } elsif ($realm eq 'resource') {
1.165 www 10154:
1.620 albertel 10155: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10156: if (!$symbparm) { $symbparm=&symbread(); }
10157: }
1.693 albertel 10158:
1.1232 raeburn 10159: if ($qualifier eq '') {
10160: if ($space eq 'title') {
10161: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10162: return &gettitle($symbparm);
10163: }
1.693 albertel 10164:
1.1232 raeburn 10165: if ($space eq 'map') {
10166: my ($map) = &decode_symb($symbparm);
10167: return &symbread($map);
10168: }
10169: if ($space eq 'maptitle') {
10170: my ($map) = &decode_symb($symbparm);
10171: return &gettitle($map);
10172: }
10173: if ($space eq 'filename') {
10174: if ($symbparm) {
10175: return &clutter((&decode_symb($symbparm))[2]);
10176: }
10177: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10178: }
1.1232 raeburn 10179:
1.1233 raeburn 10180: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10181: if ($space eq 'visibleparts') {
10182: my $navmap = Apache::lonnavmaps::navmap->new();
10183: my $item;
10184: if (ref($navmap)) {
10185: my $res = $navmap->getBySymb($symbparm);
10186: my $parts = $res->parts();
10187: if (ref($parts) eq 'ARRAY') {
10188: $item = join(',',@{$parts});
10189: }
10190: undef($navmap);
1.1232 raeburn 10191: }
1.1233 raeburn 10192: return $item;
1.1232 raeburn 10193: }
10194: }
10195: }
1.693 albertel 10196:
10197: my ($section, $group, @groups);
1.593 albertel 10198: my ($courselevelm,$courselevel);
1.1228 raeburn 10199: if (($courseid eq '') && ($cid)) {
10200: $courseid = $cid;
10201: }
10202: if (($symbparm && $courseid) &&
10203: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10204:
1.218 albertel 10205: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10206:
1.60 www 10207: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10208: my $symbp=$symbparm;
1.735 albertel 10209: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10210:
10211: my $symbparm=$symbp.'.'.$spacequalifierrest;
10212: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10213:
1.620 albertel 10214: if (($env{'user.name'} eq $uname) &&
10215: ($env{'user.domain'} eq $udom)) {
10216: $section=$env{'request.course.sec'};
1.733 raeburn 10217: @groups = split(/:/,$env{'request.course.groups'});
10218: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10219: } else {
1.539 albertel 10220: if (! defined($usection)) {
1.551 albertel 10221: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10222: } else {
10223: $section = $usection;
10224: }
1.733 raeburn 10225: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10226: }
10227:
10228: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10229: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10230: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10231:
1.593 albertel 10232: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10233: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10234: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10235:
1.60 www 10236: # ----------------------------------------------------------- first, check user
1.624 albertel 10237:
10238: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10239: ([$courselevelr,'resource'],
10240: [$courselevelm,'map' ],
10241: [$courselevel, 'course' ]));
1.931 albertel 10242: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10243:
1.594 albertel 10244: # ------------------------------------------------ second, check some of course
1.684 raeburn 10245: my $coursereply;
1.691 raeburn 10246: if (@groups > 0) {
10247: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10248: $mapparm,$spacequalifierrest);
1.927 albertel 10249: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10250: }
1.96 www 10251:
1.684 raeburn 10252: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10253: $env{'course.'.$courseid.'.domain'},
10254: 'course',
10255: ([$seclevelr, 'resource'],
10256: [$seclevelm, 'map' ],
10257: [$seclevel, 'course' ],
10258: [$courselevelr,'resource']));
10259: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10260:
1.60 www 10261: # ------------------------------------------------------ third, check map parms
1.218 albertel 10262: my %parmhash=();
10263: my $thisparm='';
10264: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10265: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10266: &GDBM_READER(),0640)) {
1.218 albertel 10267: $thisparm=$parmhash{$symbparm};
10268: untie(%parmhash);
10269: }
1.927 albertel 10270: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10271: }
1.594 albertel 10272: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10273:
1.218 albertel 10274: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10275: my $filename;
10276: if (!$symbparm) { $symbparm=&symbread(); }
10277: if ($symbparm) {
1.409 www 10278: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10279: } else {
1.620 albertel 10280: $filename=$env{'request.filename'};
1.282 albertel 10281: }
10282: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10283: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10284: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10285: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10286:
1.927 albertel 10287: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10288: if ($symbparm && defined($courseid) &&
1.620 albertel 10289: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10290: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10291: $env{'course.'.$courseid.'.domain'},
10292: 'course',
1.927 albertel 10293: ([$courselevelm,'map' ],
10294: [$courselevel, 'course']));
10295: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10296: }
1.145 www 10297: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10298: unless ($space eq '0') {
1.336 albertel 10299: my @parts=split(/_/,$space);
10300: my $id=pop(@parts);
10301: my $part=join('_',@parts);
10302: if ($part eq '') { $part='0'; }
1.927 albertel 10303: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10304: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10305: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10306: }
1.395 albertel 10307: if ($recurse) { return undef; }
10308: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10309: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10310: # ---------------------------------------------------- Any other user namespace
10311: } elsif ($realm eq 'environment') {
10312: # ----------------------------------------------------------------- environment
1.620 albertel 10313: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10314: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10315: } else {
1.770 albertel 10316: if ($uname eq 'anonymous' && $udom eq '') {
10317: return '';
10318: }
1.219 albertel 10319: my %returnhash=&userenvironment($udom,$uname,
10320: $spacequalifierrest);
10321: return $returnhash{$spacequalifierrest};
10322: }
1.28 www 10323: } elsif ($realm eq 'system') {
1.48 www 10324: # ----------------------------------------------------------------- system.time
10325: if ($space eq 'time') {
10326: return time;
10327: }
1.696 albertel 10328: } elsif ($realm eq 'server') {
10329: # ----------------------------------------------------------------- system.time
10330: if ($space eq 'name') {
10331: return $ENV{'SERVER_NAME'};
10332: }
1.28 www 10333: }
1.48 www 10334: return '';
1.61 www 10335: }
10336:
1.927 albertel 10337: sub get_reply {
10338: my ($reply_value) = @_;
1.940 raeburn 10339: if (ref($reply_value) eq 'ARRAY') {
10340: if (wantarray) {
10341: return @$reply_value;
10342: }
10343: return $reply_value->[0];
10344: } else {
10345: return $reply_value;
1.927 albertel 10346: }
10347: }
10348:
1.691 raeburn 10349: sub check_group_parms {
10350: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10351: my @groupitems = ();
10352: my $resultitem;
1.927 albertel 10353: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10354: foreach my $group (@{$groups}) {
10355: foreach my $level (@levels) {
1.927 albertel 10356: my $item = $courseid.'.['.$group.'].'.$level->[0];
10357: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10358: }
10359: }
10360: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10361: $env{'course.'.$courseid.'.domain'},
10362: 'course',@groupitems);
10363: return $coursereply;
10364: }
10365:
10366: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10367: my ($courseid,@groups) = @_;
10368: @groups = sort(@groups);
1.691 raeburn 10369: return @groups;
10370: }
10371:
1.395 albertel 10372: sub packages_tab_default {
10373: my ($uri,$varname)=@_;
10374: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10375:
10376: my (@extension,@specifics,$do_default);
10377: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10378: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10379: if ($pack_type eq 'default') {
10380: $do_default=1;
10381: } elsif ($pack_type eq 'extension') {
10382: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10383: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10384: # only look at packages defaults for packages that this id is
1.738 albertel 10385: push(@specifics,[$package,$pack_type,$pack_part]);
10386: }
10387: }
10388: # first look for a package that matches the requested part id
10389: foreach my $package (@specifics) {
10390: my (undef,$pack_type,$pack_part)=@{$package};
10391: next if ($pack_part ne $part);
10392: if (defined($packagetab{"$pack_type&$name&default"})) {
10393: return $packagetab{"$pack_type&$name&default"};
10394: }
10395: }
10396: # look for any possible matching non extension_ package
10397: foreach my $package (@specifics) {
10398: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10399: if (defined($packagetab{"$pack_type&$name&default"})) {
10400: return $packagetab{"$pack_type&$name&default"};
10401: }
1.585 albertel 10402: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10403: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10404: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10405: }
10406: }
1.738 albertel 10407: # look for any posible extension_ match
10408: foreach my $package (@extension) {
10409: my ($package,$pack_type)=@{$package};
10410: if (defined($packagetab{"$pack_type&$name&default"})) {
10411: return $packagetab{"$pack_type&$name&default"};
10412: }
10413: if (defined($packagetab{$package."&$name&default"})) {
10414: return $packagetab{$package."&$name&default"};
10415: }
10416: }
10417: # look for a global default setting
10418: if ($do_default && defined($packagetab{"default&$name&default"})) {
10419: return $packagetab{"default&$name&default"};
10420: }
1.395 albertel 10421: return undef;
10422: }
10423:
1.334 albertel 10424: sub add_prefix_and_part {
10425: my ($prefix,$part)=@_;
10426: my $keyroot;
10427: if (defined($prefix) && $prefix !~ /^__/) {
10428: # prefix that has a part already
10429: $keyroot=$prefix;
10430: } elsif (defined($prefix)) {
10431: # prefix that is missing a part
10432: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10433: } else {
10434: # no prefix at all
10435: if (defined($part)) { $keyroot='_'.$part; }
10436: }
10437: return $keyroot;
10438: }
10439:
1.71 www 10440: # ---------------------------------------------------------------- Get metadata
10441:
1.599 albertel 10442: my %metaentry;
1.1070 www 10443: my %importedpartids;
1.71 www 10444: sub metadata {
1.176 www 10445: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10446: $uri=&declutter($uri);
1.288 albertel 10447: # if it is a non metadata possible uri return quickly
1.529 albertel 10448: if (($uri eq '') ||
10449: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10450: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10451: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10452: return undef;
10453: }
1.1261 raeburn 10454: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10455: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10456: return undef;
1.288 albertel 10457: }
1.73 www 10458: my $filename=$uri;
10459: $uri=~s/\.meta$//;
1.172 www 10460: #
10461: # Is the metadata already cached?
1.177 www 10462: # Look at timestamp of caching
1.172 www 10463: # Everything is cached by the main uri, libraries are never directly cached
10464: #
1.428 albertel 10465: if (!defined($liburi)) {
1.599 albertel 10466: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10467: if (defined($cached)) { return $result->{':'.$what}; }
10468: }
10469: {
1.1069 www 10470: # Imported parts would go here
1.1070 www 10471: my %importedids=();
10472: my @origfileimportpartids=();
1.1069 www 10473: my $importedparts=0;
1.172 www 10474: #
10475: # Is this a recursive call for a library?
10476: #
1.599 albertel 10477: # if (! exists($metacache{$uri})) {
10478: # $metacache{$uri}={};
10479: # }
1.924 albertel 10480: my $cachetime = 60*60;
1.171 www 10481: if ($liburi) {
10482: $liburi=&declutter($liburi);
10483: $filename=$liburi;
1.401 bowersj2 10484: } else {
1.599 albertel 10485: &devalidate_cache_new('meta',$uri);
10486: undef(%metaentry);
1.401 bowersj2 10487: }
1.140 www 10488: my %metathesekeys=();
1.73 www 10489: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10490: my $metastring;
1.1140 www 10491: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10492: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10493: $metastring =
1.929 albertel 10494: &Apache::lonnet::ssi_body($which,
1.924 albertel 10495: ('grade_target' => 'meta'));
10496: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10497: } elsif (($uri !~ m -^(editupload)/-) &&
10498: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10499: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10500: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10501: $metastring=&getfile($file);
1.489 albertel 10502: }
1.208 albertel 10503: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10504: my $token;
1.140 www 10505: undef %metathesekeys;
1.71 www 10506: while ($token=$parser->get_token) {
1.339 albertel 10507: if ($token->[0] eq 'S') {
10508: if (defined($token->[2]->{'package'})) {
1.172 www 10509: #
10510: # This is a package - get package info
10511: #
1.339 albertel 10512: my $package=$token->[2]->{'package'};
10513: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10514: if (defined($token->[2]->{'id'})) {
10515: $keyroot.='_'.$token->[2]->{'id'};
10516: }
1.599 albertel 10517: if ($metaentry{':packages'}) {
10518: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10519: } else {
1.599 albertel 10520: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10521: }
1.736 albertel 10522: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10523: my $part=$keyroot;
10524: $part=~s/^\_//;
1.736 albertel 10525: if ($pack_entry=~/^\Q$package\E\&/ ||
10526: $pack_entry=~/^\Q$package\E_0\&/) {
10527: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10528: # ignore package.tab specified default values
10529: # here &package_tab_default() will fetch those
10530: if ($subp eq 'default') { next; }
1.736 albertel 10531: my $value=$packagetab{$pack_entry};
1.432 albertel 10532: my $unikey;
10533: if ($pack =~ /_0$/) {
10534: $unikey='parameter_0_'.$name;
10535: $part=0;
10536: } else {
10537: $unikey='parameter'.$keyroot.'_'.$name;
10538: }
1.339 albertel 10539: if ($subp eq 'display') {
10540: $value.=' [Part: '.$part.']';
10541: }
1.599 albertel 10542: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10543: $metathesekeys{$unikey}=1;
1.599 albertel 10544: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10545: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10546: }
1.599 albertel 10547: if (defined($metaentry{':'.$unikey.'.default'})) {
10548: $metaentry{':'.$unikey}=
10549: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10550: }
1.339 albertel 10551: }
10552: }
10553: } else {
1.172 www 10554: #
10555: # This is not a package - some other kind of start tag
1.339 albertel 10556: #
10557: my $entry=$token->[1];
1.1068 www 10558: my $unikey='';
1.175 www 10559:
1.339 albertel 10560: if ($entry eq 'import') {
1.175 www 10561: #
10562: # Importing a library here
1.339 albertel 10563: #
1.1067 www 10564: my $location=$parser->get_text('/import');
10565: my $dir=$filename;
10566: $dir=~s|[^/]*$||;
10567: $location=&filelocation($dir,$location);
1.1069 www 10568:
1.1068 www 10569: my $importmode=$token->[2]->{'importmode'};
10570: if ($importmode eq 'problem') {
1.1069 www 10571: # Import as problem/response
1.1068 www 10572: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10573: } elsif ($importmode eq 'part') {
10574: # Import as part(s)
1.1069 www 10575: $importedparts=1;
10576: # We need to get the original file and the imported file to get the part order correct
10577: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10578: # Load and inspect original file
1.1070 www 10579: if ($#origfileimportpartids<0) {
10580: undef(%importedpartids);
10581: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10582: my $origfile=&getfile($origfilelocation);
10583: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10584: }
10585:
1.1069 www 10586: # Load and inspect imported file
10587: my $impfile=&getfile($location);
10588: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10589: if ($#impfilepartids>=0) {
10590: # This problem had parts
1.1070 www 10591: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10592: } else {
10593: # Importing by turning a single problem into a problem part
10594: # It gets the import-tags ID as part-ID
10595: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10596: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10597: }
1.1068 www 10598: } else {
10599: # Normal import
10600: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10601: if (defined($token->[2]->{'id'})) {
10602: $unikey.='_'.$token->[2]->{'id'};
10603: }
1.1067 www 10604: }
10605:
1.339 albertel 10606: if ($depthcount<20) {
1.736 albertel 10607: my $metadata =
10608: &metadata($uri,'keys', $location,$unikey,
10609: $depthcount+1);
10610: foreach my $meta (split(',',$metadata)) {
10611: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10612: $metathesekeys{$meta}=1;
1.339 albertel 10613: }
1.1068 www 10614:
10615: }
1.1067 www 10616: } else {
10617: #
10618: # Not importing, some other kind of non-package, non-library start tag
10619: #
10620: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10621: if (defined($token->[2]->{'id'})) {
10622: $unikey.='_'.$token->[2]->{'id'};
10623: }
1.339 albertel 10624: if (defined($token->[2]->{'name'})) {
10625: $unikey.='_'.$token->[2]->{'name'};
10626: }
10627: $metathesekeys{$unikey}=1;
1.736 albertel 10628: foreach my $param (@{$token->[3]}) {
10629: $metaentry{':'.$unikey.'.'.$param} =
10630: $token->[2]->{$param};
1.339 albertel 10631: }
10632: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10633: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10634: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10635: # only ws inside the tag, and not in default, so use default
10636: # as value
1.599 albertel 10637: $metaentry{':'.$unikey}=$default;
1.908 albertel 10638: } elsif ( $internaltext =~ /\S/ ) {
10639: # something interesting inside the tag
10640: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10641: } else {
1.908 albertel 10642: # no interesting values, don't set a default
1.339 albertel 10643: }
1.172 www 10644: # end of not-a-package not-a-library import
1.339 albertel 10645: }
1.172 www 10646: # end of not-a-package start tag
1.339 albertel 10647: }
1.172 www 10648: # the next is the end of "start tag"
1.339 albertel 10649: }
10650: }
1.483 albertel 10651: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10652: $extension = lc($extension);
10653: if ($extension eq 'htm') { $extension='html'; }
10654:
1.737 albertel 10655: foreach my $key (keys(%packagetab)) {
1.483 albertel 10656: #no specific packages #how's our extension
10657: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10658: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10659: \%metathesekeys);
10660: }
1.883 albertel 10661:
10662: if (!exists($metaentry{':packages'})
10663: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10664: foreach my $key (keys(%packagetab)) {
1.483 albertel 10665: #no specific packages well let's get default then
10666: if ($key!~/^default&/) { next; }
1.488 albertel 10667: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10668: \%metathesekeys);
10669: }
10670: }
1.338 www 10671: # are there custom rights to evaluate
1.599 albertel 10672: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10673:
1.338 www 10674: #
10675: # Importing a rights file here
1.339 albertel 10676: #
10677: unless ($depthcount) {
1.599 albertel 10678: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10679: my $dir=$filename;
10680: $dir=~s|[^/]*$||;
10681: $location=&filelocation($dir,$location);
1.736 albertel 10682: my $rights_metadata =
10683: &metadata($uri,'keys',$location,'_rights',
10684: $depthcount+1);
10685: foreach my $rights (split(',',$rights_metadata)) {
10686: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10687: $metathesekeys{$rights}=1;
1.339 albertel 10688: }
10689: }
10690: }
1.737 albertel 10691: # uniqifiy package listing
10692: my %seen;
10693: my @uniq_packages =
10694: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10695: $metaentry{':packages'} = join(',',@uniq_packages);
10696:
1.1070 www 10697: if ($importedparts) {
10698: # We had imported parts and need to rebuild partorder
10699: $metaentry{':partorder'}='';
10700: $metathesekeys{'partorder'}=1;
10701: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10702: if ($origfileimportpartids[$index] eq 'part') {
10703: # original part, part of the problem
10704: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10705: } else {
10706: # we have imported parts at this position
10707: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10708: }
10709: }
10710: $metaentry{':partorder'}=~s/^\,//;
10711: }
10712:
1.737 albertel 10713: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10714: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 10715: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10716: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10717: # this is the end of "was not already recently cached
1.71 www 10718: }
1.599 albertel 10719: return $metaentry{':'.$what};
1.261 albertel 10720: }
10721:
1.488 albertel 10722: sub metadata_create_package_def {
1.483 albertel 10723: my ($uri,$key,$package,$metathesekeys)=@_;
10724: my ($pack,$name,$subp)=split(/\&/,$key);
10725: if ($subp eq 'default') { next; }
10726:
1.599 albertel 10727: if (defined($metaentry{':packages'})) {
10728: $metaentry{':packages'}.=','.$package;
1.483 albertel 10729: } else {
1.599 albertel 10730: $metaentry{':packages'}=$package;
1.483 albertel 10731: }
10732: my $value=$packagetab{$key};
10733: my $unikey;
10734: $unikey='parameter_0_'.$name;
1.599 albertel 10735: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10736: $$metathesekeys{$unikey}=1;
1.599 albertel 10737: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10738: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10739: }
1.599 albertel 10740: if (defined($metaentry{':'.$unikey.'.default'})) {
10741: $metaentry{':'.$unikey}=
10742: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10743: }
10744: }
10745:
1.261 albertel 10746: sub metadata_generate_part0 {
10747: my ($metadata,$metacache,$uri) = @_;
10748: my %allnames;
1.737 albertel 10749: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10750: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10751: my $part=$$metacache{':'.$metakey.'.part'};
10752: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10753: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10754: $allnames{$name}=$part;
10755: }
10756: }
10757: }
10758: foreach my $name (keys(%allnames)) {
10759: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10760: my $key=":parameter_0_$name";
1.261 albertel 10761: $$metacache{"$key.part"}='0';
10762: $$metacache{"$key.name"}=$name;
1.428 albertel 10763: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10764: $allnames{$name}.'_'.$name.
10765: '.type'};
1.428 albertel 10766: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10767: '.display'};
1.644 www 10768: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10769: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10770: $$metacache{"$key.display"}=$olddis;
10771: }
1.71 www 10772: }
10773:
1.764 albertel 10774: # ------------------------------------------------------ Devalidate title cache
10775:
10776: sub devalidate_title_cache {
10777: my ($url)=@_;
10778: if (!$env{'request.course.id'}) { return; }
10779: my $symb=&symbread($url);
10780: if (!$symb) { return; }
10781: my $key=$env{'request.course.id'}."\0".$symb;
10782: &devalidate_cache_new('title',$key);
10783: }
10784:
1.1014 droeschl 10785: # ------------------------------------------------- Get the title of a course
10786:
10787: sub current_course_title {
10788: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10789: }
1.301 www 10790: # ------------------------------------------------- Get the title of a resource
10791:
10792: sub gettitle {
10793: my $urlsymb=shift;
10794: my $symb=&symbread($urlsymb);
1.534 albertel 10795: if ($symb) {
1.620 albertel 10796: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10797: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10798: if (defined($cached)) {
10799: return $result;
10800: }
1.534 albertel 10801: my ($map,$resid,$url)=&decode_symb($symb);
10802: my $title='';
1.907 albertel 10803: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10804: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10805: } else {
10806: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10807: &GDBM_READER(),0640)) {
10808: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10809: $title=$bighash{'title_'.$mapid.'.'.$resid};
10810: untie(%bighash);
10811: }
1.534 albertel 10812: }
10813: $title=~s/\&colon\;/\:/gs;
10814: if ($title) {
1.1159 www 10815: # Remember both $symb and $title for dynamic metadata
10816: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10817: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10818: # Cache this title and then return it
1.599 albertel 10819: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10820: }
10821: $urlsymb=$url;
10822: }
10823: my $title=&metadata($urlsymb,'title');
10824: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10825: return $title;
1.301 www 10826: }
1.613 albertel 10827:
1.614 albertel 10828: sub get_slot {
10829: my ($which,$cnum,$cdom)=@_;
10830: if (!$cnum || !$cdom) {
1.790 albertel 10831: (undef,my $courseid)=&whichuser();
1.620 albertel 10832: $cdom=$env{'course.'.$courseid.'.domain'};
10833: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10834: }
1.703 albertel 10835: my $key=join("\0",'slots',$cdom,$cnum,$which);
10836: my %slotinfo;
10837: if (exists($remembered{$key})) {
10838: $slotinfo{$which} = $remembered{$key};
10839: } else {
10840: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10841: &Apache::lonhomework::showhash(%slotinfo);
10842: my ($tmp)=keys(%slotinfo);
10843: if ($tmp=~/^error:/) { return (); }
10844: $remembered{$key} = $slotinfo{$which};
10845: }
1.616 albertel 10846: if (ref($slotinfo{$which}) eq 'HASH') {
10847: return %{$slotinfo{$which}};
10848: }
10849: return $slotinfo{$which};
1.614 albertel 10850: }
1.1150 raeburn 10851:
10852: sub get_reservable_slots {
10853: my ($cnum,$cdom,$uname,$udom) = @_;
10854: my $now = time;
10855: my $reservable_info;
10856: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10857: if (exists($remembered{$key})) {
10858: $reservable_info = $remembered{$key};
10859: } else {
10860: my %resv;
10861: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10862: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10863: $reservable_info = \%resv;
10864: $remembered{$key} = $reservable_info;
10865: }
10866: return $reservable_info;
10867: }
10868:
10869: sub get_course_slots {
10870: my ($cnum,$cdom) = @_;
10871: my $hashid=$cnum.':'.$cdom;
10872: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10873: if (defined($cached)) {
10874: if (ref($result) eq 'HASH') {
10875: return %{$result};
10876: }
10877: } else {
10878: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10879: my ($tmp) = keys(%slots);
10880: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10881: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10882: return %slots;
10883: }
10884: }
10885: return;
10886: }
10887:
10888: sub devalidate_slots_cache {
10889: my ($cnum,$cdom)=@_;
10890: my $hashid=$cnum.':'.$cdom;
10891: &devalidate_cache_new('allslots',$hashid);
10892: }
10893:
1.1181 raeburn 10894: sub get_coursechange {
10895: my ($cdom,$cnum) = @_;
10896: if ($cdom eq '' || $cnum eq '') {
10897: return unless ($env{'request.course.id'});
10898: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10899: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10900: }
10901: my $hashid=$cdom.'_'.$cnum;
10902: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10903: if ((defined($cached)) && ($change ne '')) {
10904: return $change;
10905: } else {
10906: my %crshash;
10907: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10908: if ($crshash{'internal.contentchange'} eq '') {
10909: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10910: if ($change eq '') {
10911: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10912: $change = $crshash{'internal.created'};
10913: }
10914: } else {
10915: $change = $crshash{'internal.contentchange'};
10916: }
10917: my $cachetime = 600;
10918: &do_cache_new('crschange',$hashid,$change,$cachetime);
10919: }
10920: return $change;
10921: }
10922:
10923: sub devalidate_coursechange_cache {
10924: my ($cnum,$cdom)=@_;
10925: my $hashid=$cnum.':'.$cdom;
10926: &devalidate_cache_new('crschange',$hashid);
10927: }
10928:
1.31 www 10929: # ------------------------------------------------- Update symbolic store links
10930:
10931: sub symblist {
10932: my ($mapname,%newhash)=@_;
1.438 www 10933: $mapname=&deversion(&declutter($mapname));
1.31 www 10934: my %hash;
1.620 albertel 10935: if (($env{'request.course.fn'}) && (%newhash)) {
10936: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10937: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10938: foreach my $url (keys(%newhash)) {
1.711 albertel 10939: next if ($url eq 'last_known'
10940: && $env{'form.no_update_last_known'});
10941: $hash{declutter($url)}=&encode_symb($mapname,
10942: $newhash{$url}->[1],
10943: $newhash{$url}->[0]);
1.191 harris41 10944: }
1.31 www 10945: if (untie(%hash)) {
10946: return 'ok';
10947: }
10948: }
10949: }
10950: return 'error';
1.212 www 10951: }
10952:
10953: # --------------------------------------------------------------- Verify a symb
10954:
10955: sub symbverify {
1.1190 raeburn 10956: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10957: my $thisfn=$thisurl;
1.439 www 10958: $thisfn=&declutter($thisfn);
1.215 www 10959: # direct jump to resource in page or to a sequence - will construct own symbs
10960: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10961: # check URL part
1.409 www 10962: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10963:
1.431 www 10964: unless ($url eq $thisfn) { return 0; }
1.213 www 10965:
1.216 www 10966: $symb=&symbclean($symb);
1.510 www 10967: $thisurl=&deversion($thisurl);
1.439 www 10968: $thisfn=&deversion($thisfn);
1.213 www 10969:
10970: my %bighash;
10971: my $okay=0;
1.431 www 10972:
1.620 albertel 10973: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10974: &GDBM_READER(),0640)) {
1.1204 raeburn 10975: my $noclutter;
1.1032 raeburn 10976: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10977: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10978: if ($map =~ m{^uploaded/.+\.page$}) {
10979: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10980: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10981: $noclutter = 1;
10982: }
10983: }
10984: my $ids;
10985: if ($noclutter) {
10986: $ids=$bighash{'ids_'.$thisurl};
10987: } else {
10988: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10989: }
1.1102 raeburn 10990: unless ($ids) {
10991: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10992: $ids=$bighash{$idkey};
1.216 www 10993: }
10994: if ($ids) {
10995: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10996: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10997: $symb =~ s/\?.+$//;
1.1202 raeburn 10998: }
1.800 albertel 10999: foreach my $id (split(/\,/,$ids)) {
11000: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11001: if (
11002: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11003: eq $symb) {
11004: if (ref($encstate)) {
11005: $$encstate = $bighash{'encrypted_'.$id};
11006: }
1.620 albertel 11007: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11008: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11009: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11010: $okay=1;
1.1202 raeburn 11011: last;
1.582 albertel 11012: }
11013: }
1.216 www 11014: }
11015: }
1.213 www 11016: untie(%bighash);
11017: }
11018: return $okay;
1.31 www 11019: }
11020:
1.210 www 11021: # --------------------------------------------------------------- Clean-up symb
11022:
11023: sub symbclean {
11024: my $symb=shift;
1.568 albertel 11025: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11026: # remove version from map
11027: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11028:
1.210 www 11029: # remove version from URL
11030: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11031:
1.507 www 11032: # remove wrapper
11033:
1.510 www 11034: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11035: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11036: return $symb;
1.409 www 11037: }
11038:
11039: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11040:
11041: sub encode_symb {
11042: my ($map,$resid,$url)=@_;
11043: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11044: }
1.409 www 11045:
11046: sub decode_symb {
1.568 albertel 11047: my $symb=shift;
11048: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11049: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11050: return (&fixversion($map),$resid,&fixversion($url));
11051: }
11052:
11053: sub fixversion {
11054: my $fn=shift;
1.609 banghart 11055: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11056: my %bighash;
11057: my $uri=&clutter($fn);
1.620 albertel 11058: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11059: # is this cached?
1.599 albertel 11060: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11061: if (defined($cached)) { return $result; }
11062: # unfortunately not cached, or expired
1.620 albertel 11063: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11064: &GDBM_READER(),0640)) {
11065: if ($bighash{'version_'.$uri}) {
11066: my $version=$bighash{'version_'.$uri};
1.444 www 11067: unless (($version eq 'mostrecent') ||
11068: ($version==&getversion($uri))) {
1.440 www 11069: $uri=~s/\.(\w+)$/\.$version\.$1/;
11070: }
11071: }
11072: untie %bighash;
1.413 www 11073: }
1.599 albertel 11074: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11075: }
11076:
11077: sub deversion {
11078: my $url=shift;
11079: $url=~s/\.\d+\.(\w+)$/\.$1/;
11080: return $url;
1.210 www 11081: }
11082:
1.31 www 11083: # ------------------------------------------------------ Return symb list entry
11084:
11085: sub symbread {
1.249 www 11086: my ($thisfn,$donotrecurse)=@_;
1.1265 raeburn 11087: my $cache_str='request.symbread.cached.'.$thisfn;
11088: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 11089: # no filename provided? try from environment
1.1265 raeburn 11090: unless ($thisfn) {
1.620 albertel 11091: if ($env{'request.symb'}) {
11092: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11093: }
1.620 albertel 11094: $thisfn=$env{'request.filename'};
1.44 www 11095: }
1.569 albertel 11096: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11097: # is that filename actually a symb? Verify, clean, and return
11098: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11099: if (&symbverify($thisfn,$1)) {
1.620 albertel 11100: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11101: }
1.242 www 11102: }
1.44 www 11103: $thisfn=declutter($thisfn);
1.31 www 11104: my %hash;
1.37 www 11105: my %bighash;
11106: my $syval='';
1.620 albertel 11107: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11108: my $targetfn = $thisfn;
1.609 banghart 11109: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11110: $targetfn = 'adm/wrapper/'.$thisfn;
11111: }
1.687 albertel 11112: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11113: $targetfn=$1;
11114: }
1.620 albertel 11115: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11116: &GDBM_READER(),0640)) {
1.481 raeburn 11117: $syval=$hash{$targetfn};
1.37 www 11118: untie(%hash);
11119: }
11120: # ---------------------------------------------------------- There was an entry
11121: if ($syval) {
1.601 albertel 11122: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11123: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11124: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11125: #return $env{$cache_str}='';
1.601 albertel 11126: #}
11127: #$syval.=$1;
11128: #}
1.37 www 11129: } else {
11130: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11131: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11132: &GDBM_READER(),0640)) {
1.37 www 11133: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11134: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11135: unless ($ids) {
11136: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11137: }
11138: unless ($ids) {
11139: # alias?
11140: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11141: }
1.37 www 11142: if ($ids) {
11143: # ------------------------------------------------------------------- Has ID(s)
11144: my @possibilities=split(/\,/,$ids);
1.39 www 11145: if ($#possibilities==0) {
11146: # ----------------------------------------------- There is only one possibility
1.37 www 11147: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11148: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11149: $resid,$thisfn);
1.249 www 11150: } elsif (!$donotrecurse) {
1.39 www 11151: # ------------------------------------------ There is more than one possibility
11152: my $realpossible=0;
1.800 albertel 11153: foreach my $id (@possibilities) {
11154: my $file=$bighash{'src_'.$id};
1.39 www 11155: if (&allowed('bre',$file)) {
1.800 albertel 11156: my ($mapid,$resid)=split(/\./,$id);
1.39 www 11157: if ($bighash{'map_type_'.$mapid} ne 'page') {
11158: $realpossible++;
1.626 albertel 11159: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11160: $resid,$thisfn);
1.39 www 11161: }
11162: }
1.191 harris41 11163: }
1.39 www 11164: if ($realpossible!=1) { $syval=''; }
1.249 www 11165: } else {
11166: $syval='';
1.37 www 11167: }
11168: }
11169: untie(%bighash)
1.481 raeburn 11170: }
1.31 www 11171: }
1.62 www 11172: if ($syval) {
1.620 albertel 11173: return $env{$cache_str}=$syval;
1.62 www 11174: }
1.31 www 11175: }
1.949 raeburn 11176: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11177: return $env{$cache_str}='';
1.31 www 11178: }
11179:
11180: # ---------------------------------------------------------- Return random seed
11181:
1.32 www 11182: sub numval {
11183: my $txt=shift;
11184: $txt=~tr/A-J/0-9/;
11185: $txt=~tr/a-j/0-9/;
11186: $txt=~tr/K-T/0-9/;
11187: $txt=~tr/k-t/0-9/;
11188: $txt=~tr/U-Z/0-5/;
11189: $txt=~tr/u-z/0-5/;
11190: $txt=~s/\D//g;
1.564 albertel 11191: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11192: return int($txt);
1.368 albertel 11193: }
11194:
1.484 albertel 11195: sub numval2 {
11196: my $txt=shift;
11197: $txt=~tr/A-J/0-9/;
11198: $txt=~tr/a-j/0-9/;
11199: $txt=~tr/K-T/0-9/;
11200: $txt=~tr/k-t/0-9/;
11201: $txt=~tr/U-Z/0-5/;
11202: $txt=~tr/u-z/0-5/;
11203: $txt=~s/\D//g;
11204: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11205: my $total;
11206: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11207: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11208: return int($total);
11209: }
11210:
1.575 albertel 11211: sub numval3 {
11212: use integer;
11213: my $txt=shift;
11214: $txt=~tr/A-J/0-9/;
11215: $txt=~tr/a-j/0-9/;
11216: $txt=~tr/K-T/0-9/;
11217: $txt=~tr/k-t/0-9/;
11218: $txt=~tr/U-Z/0-5/;
11219: $txt=~tr/u-z/0-5/;
11220: $txt=~s/\D//g;
11221: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11222: my $total;
11223: foreach my $val (@txts) { $total+=$val; }
11224: if ($_64bit) { $total=(($total<<32)>>32); }
11225: return $total;
11226: }
11227:
1.675 albertel 11228: sub digest {
11229: my ($data)=@_;
11230: my $digest=&Digest::MD5::md5($data);
11231: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11232: my ($e,$f);
11233: {
11234: use integer;
11235: $e=($a+$b);
11236: $f=($c+$d);
11237: if ($_64bit) {
11238: $e=(($e<<32)>>32);
11239: $f=(($f<<32)>>32);
11240: }
11241: }
11242: if (wantarray) {
11243: return ($e,$f);
11244: } else {
11245: my $g;
11246: {
11247: use integer;
11248: $g=($e+$f);
11249: if ($_64bit) {
11250: $g=(($g<<32)>>32);
11251: }
11252: }
11253: return $g;
11254: }
11255: }
11256:
1.368 albertel 11257: sub latest_rnd_algorithm_id {
1.675 albertel 11258: return '64bit5';
1.366 albertel 11259: }
1.32 www 11260:
1.503 albertel 11261: sub get_rand_alg {
11262: my ($courseid)=@_;
1.790 albertel 11263: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11264: if ($courseid) {
1.620 albertel 11265: return $env{"course.$courseid.rndseed"};
1.503 albertel 11266: }
11267: return &latest_rnd_algorithm_id();
11268: }
11269:
1.562 albertel 11270: sub validCODE {
11271: my ($CODE)=@_;
11272: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11273: return 0;
11274: }
11275:
1.491 albertel 11276: sub getCODE {
1.620 albertel 11277: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11278: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11279: defined($Apache::lonhomework::parsing_a_task) ) &&
11280: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11281: return $Apache::lonhomework::history{'resource.CODE'};
11282: }
11283: return undef;
11284: }
1.1133 foxr 11285: #
11286: # Determines the random seed for a specific context:
11287: #
11288: # parameters:
11289: # symb - in course context the symb for the seed.
11290: # course_id - The course id of the form domain_coursenum.
11291: # domain - Domain for the user.
11292: # course - Course for the user.
11293: # cenv - environment of the course.
11294: #
11295: # NOTE:
11296: # All parameters are picked out of the environment if missing
11297: # or not defined.
11298: # If a symb cannot be determined the current time is used instead.
11299: #
11300: # For a given well defined symb, courside, domain, username,
11301: # and course environment, the seed is reproducible.
11302: #
1.31 www 11303: sub rndseed {
1.1133 foxr 11304: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11305: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11306: if (!defined($symb)) {
1.366 albertel 11307: unless ($symb=$wsymb) { return time; }
11308: }
1.1146 foxr 11309: if (!defined $courseid) {
11310: $courseid=$wcourseid;
11311: }
11312: if (!defined $domain) { $domain=$wdomain; }
11313: if (!defined $username) { $username=$wusername }
1.1133 foxr 11314:
11315: my $which;
11316: if (defined($cenv->{'rndseed'})) {
11317: $which = $cenv->{'rndseed'};
11318: } else {
11319: $which =&get_rand_alg($courseid);
11320: }
1.491 albertel 11321: if (defined(&getCODE())) {
1.1133 foxr 11322:
1.675 albertel 11323: if ($which eq '64bit5') {
11324: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11325: } elsif ($which eq '64bit4') {
1.575 albertel 11326: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11327: } else {
11328: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11329: }
1.675 albertel 11330: } elsif ($which eq '64bit5') {
11331: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11332: } elsif ($which eq '64bit4') {
11333: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11334: } elsif ($which eq '64bit3') {
11335: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11336: } elsif ($which eq '64bit2') {
11337: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11338: } elsif ($which eq '64bit') {
11339: return &rndseed_64bit($symb,$courseid,$domain,$username);
11340: }
11341: return &rndseed_32bit($symb,$courseid,$domain,$username);
11342: }
11343:
11344: sub rndseed_32bit {
11345: my ($symb,$courseid,$domain,$username)=@_;
11346: {
11347: use integer;
11348: my $symbchck=unpack("%32C*",$symb) << 27;
11349: my $symbseed=numval($symb) << 22;
11350: my $namechck=unpack("%32C*",$username) << 17;
11351: my $nameseed=numval($username) << 12;
11352: my $domainseed=unpack("%32C*",$domain) << 7;
11353: my $courseseed=unpack("%32C*",$courseid);
11354: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11355: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11356: #&logthis("rndseed :$num:$symb");
1.564 albertel 11357: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11358: return $num;
11359: }
11360: }
11361:
11362: sub rndseed_64bit {
11363: my ($symb,$courseid,$domain,$username)=@_;
11364: {
11365: use integer;
11366: my $symbchck=unpack("%32S*",$symb) << 21;
11367: my $symbseed=numval($symb) << 10;
11368: my $namechck=unpack("%32S*",$username);
11369:
11370: my $nameseed=numval($username) << 21;
11371: my $domainseed=unpack("%32S*",$domain) << 10;
11372: my $courseseed=unpack("%32S*",$courseid);
11373:
11374: my $num1=$symbchck+$symbseed+$namechck;
11375: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11376: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11377: #&logthis("rndseed :$num:$symb");
1.564 albertel 11378: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11379: return "$num1,$num2";
1.155 albertel 11380: }
1.366 albertel 11381: }
11382:
1.443 albertel 11383: sub rndseed_64bit2 {
11384: my ($symb,$courseid,$domain,$username)=@_;
11385: {
11386: use integer;
11387: # strings need to be an even # of cahracters long, it it is odd the
11388: # last characters gets thrown away
11389: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11390: my $symbseed=numval($symb) << 10;
11391: my $namechck=unpack("%32S*",$username.' ');
11392:
11393: my $nameseed=numval($username) << 21;
1.501 albertel 11394: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11395: my $courseseed=unpack("%32S*",$courseid.' ');
11396:
11397: my $num1=$symbchck+$symbseed+$namechck;
11398: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11399: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11400: #&logthis("rndseed :$num:$symb");
1.803 albertel 11401: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11402: return "$num1,$num2";
11403: }
11404: }
11405:
11406: sub rndseed_64bit3 {
11407: my ($symb,$courseid,$domain,$username)=@_;
11408: {
11409: use integer;
11410: # strings need to be an even # of cahracters long, it it is odd the
11411: # last characters gets thrown away
11412: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11413: my $symbseed=numval2($symb) << 10;
11414: my $namechck=unpack("%32S*",$username.' ');
11415:
11416: my $nameseed=numval2($username) << 21;
1.443 albertel 11417: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11418: my $courseseed=unpack("%32S*",$courseid.' ');
11419:
11420: my $num1=$symbchck+$symbseed+$namechck;
11421: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11422: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11423: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11424: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11425:
1.503 albertel 11426: return "$num1:$num2";
1.443 albertel 11427: }
11428: }
11429:
1.575 albertel 11430: sub rndseed_64bit4 {
11431: my ($symb,$courseid,$domain,$username)=@_;
11432: {
11433: use integer;
11434: # strings need to be an even # of cahracters long, it it is odd the
11435: # last characters gets thrown away
11436: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11437: my $symbseed=numval3($symb) << 10;
11438: my $namechck=unpack("%32S*",$username.' ');
11439:
11440: my $nameseed=numval3($username) << 21;
11441: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11442: my $courseseed=unpack("%32S*",$courseid.' ');
11443:
11444: my $num1=$symbchck+$symbseed+$namechck;
11445: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11446: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11447: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11448: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11449:
1.575 albertel 11450: return "$num1:$num2";
11451: }
11452: }
11453:
1.675 albertel 11454: sub rndseed_64bit5 {
11455: my ($symb,$courseid,$domain,$username)=@_;
11456: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11457: return "$num1:$num2";
11458: }
11459:
1.366 albertel 11460: sub rndseed_CODE_64bit {
11461: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11462: {
1.366 albertel 11463: use integer;
1.443 albertel 11464: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11465: my $symbseed=numval2($symb);
1.491 albertel 11466: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11467: my $CODEseed=numval(&getCODE());
1.443 albertel 11468: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11469: my $num1=$symbseed+$CODEchck;
11470: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11471: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11472: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11473: if ($_64bit) { $num1=(($num1<<32)>>32); }
11474: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11475: return "$num1:$num2";
1.366 albertel 11476: }
11477: }
11478:
1.575 albertel 11479: sub rndseed_CODE_64bit4 {
11480: my ($symb,$courseid,$domain,$username)=@_;
11481: {
11482: use integer;
11483: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11484: my $symbseed=numval3($symb);
11485: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11486: my $CODEseed=numval3(&getCODE());
11487: my $courseseed=unpack("%32S*",$courseid.' ');
11488: my $num1=$symbseed+$CODEchck;
11489: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11490: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11491: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11492: if ($_64bit) { $num1=(($num1<<32)>>32); }
11493: if ($_64bit) { $num2=(($num2<<32)>>32); }
11494: return "$num1:$num2";
11495: }
11496: }
11497:
1.675 albertel 11498: sub rndseed_CODE_64bit5 {
11499: my ($symb,$courseid,$domain,$username)=@_;
11500: my $code = &getCODE();
11501: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11502: return "$num1:$num2";
11503: }
11504:
1.366 albertel 11505: sub setup_random_from_rndseed {
11506: my ($rndseed)=@_;
1.503 albertel 11507: if ($rndseed =~/([,:])/) {
1.1262 raeburn 11508: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11509: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11510: &Math::Random::random_set_seed_from_phrase($rndseed);
11511: } else {
11512: &Math::Random::random_set_seed($num1,$num2);
11513: }
1.366 albertel 11514: } else {
11515: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11516: }
1.36 albertel 11517: }
11518:
1.474 albertel 11519: sub latest_receipt_algorithm_id {
1.835 albertel 11520: return 'receipt3';
1.474 albertel 11521: }
11522:
1.480 www 11523: sub recunique {
11524: my $fucourseid=shift;
11525: my $unique;
1.835 albertel 11526: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11527: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11528: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11529: } else {
11530: $unique=$perlvar{'lonReceipt'};
11531: }
11532: return unpack("%32C*",$unique);
11533: }
11534:
11535: sub recprefix {
11536: my $fucourseid=shift;
11537: my $prefix;
1.835 albertel 11538: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11539: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11540: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11541: } else {
11542: $prefix=$perlvar{'lonHostID'};
11543: }
11544: return unpack("%32C*",$prefix);
11545: }
11546:
1.76 www 11547: sub ireceipt {
1.474 albertel 11548: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11549:
11550: my $return =&recprefix($fucourseid).'-';
11551:
11552: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11553: $env{'request.state'} eq 'construct') {
11554: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11555: return $return;
11556: }
11557:
1.76 www 11558: my $cuname=unpack("%32C*",$funame);
11559: my $cudom=unpack("%32C*",$fudom);
11560: my $cucourseid=unpack("%32C*",$fucourseid);
11561: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11562: my $cunique=&recunique($fucourseid);
1.474 albertel 11563: my $cpart=unpack("%32S*",$part);
1.835 albertel 11564: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11565:
1.790 albertel 11566: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11567:
11568: $return.= ($cunique%$cuname+
11569: $cunique%$cudom+
11570: $cusymb%$cuname+
11571: $cusymb%$cudom+
11572: $cucourseid%$cuname+
11573: $cucourseid%$cudom+
11574: $cpart%$cuname+
11575: $cpart%$cudom);
11576: } else {
11577: $return.= ($cunique%$cuname+
11578: $cunique%$cudom+
11579: $cusymb%$cuname+
11580: $cusymb%$cudom+
11581: $cucourseid%$cuname+
11582: $cucourseid%$cudom);
11583: }
11584: return $return;
1.76 www 11585: }
11586:
11587: sub receipt {
1.474 albertel 11588: my ($part)=@_;
1.790 albertel 11589: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11590: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11591: }
1.260 ng 11592:
1.790 albertel 11593: sub whichuser {
11594: my ($passedsymb)=@_;
11595: my ($symb,$courseid,$domain,$name,$publicuser);
11596: if (defined($env{'form.grade_symb'})) {
11597: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11598: my $allowed=&allowed('vgr',$tmp_courseid);
11599: if (!$allowed &&
11600: exists($env{'request.course.sec'}) &&
11601: $env{'request.course.sec'} !~ /^\s*$/) {
11602: $allowed=&allowed('vgr',$tmp_courseid.
11603: '/'.$env{'request.course.sec'});
11604: }
11605: if ($allowed) {
11606: ($symb)=&get_env_multiple('form.grade_symb');
11607: $courseid=$tmp_courseid;
11608: ($domain)=&get_env_multiple('form.grade_domain');
11609: ($name)=&get_env_multiple('form.grade_username');
11610: return ($symb,$courseid,$domain,$name,$publicuser);
11611: }
11612: }
11613: if (!$passedsymb) {
11614: $symb=&symbread();
11615: } else {
11616: $symb=$passedsymb;
11617: }
11618: $courseid=$env{'request.course.id'};
11619: $domain=$env{'user.domain'};
11620: $name=$env{'user.name'};
11621: if ($name eq 'public' && $domain eq 'public') {
11622: if (!defined($env{'form.username'})) {
11623: $env{'form.username'}.=time.rand(10000000);
11624: }
11625: $name.=$env{'form.username'};
11626: }
11627: return ($symb,$courseid,$domain,$name,$publicuser);
11628:
11629: }
11630:
1.36 albertel 11631: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11632: # returns either the contents of the file or
11633: # -1 if the file doesn't exist
1.481 raeburn 11634: #
11635: # if the target is a file that was uploaded via DOCS,
11636: # a check will be made to see if a current copy exists on the local server,
11637: # if it does this will be served, otherwise a copy will be retrieved from
11638: # the home server for the course and stored in /home/httpd/html/userfiles on
11639: # the local server.
1.472 albertel 11640:
1.36 albertel 11641: sub getfile {
1.538 albertel 11642: my ($file) = @_;
1.609 banghart 11643: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11644: &repcopy($file);
11645: return &readfile($file);
11646: }
11647:
11648: sub repcopy_userfile {
11649: my ($file)=@_;
1.1142 raeburn 11650: my $londocroot = $perlvar{'lonDocRoot'};
11651: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11652: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11653: my ($cdom,$cnum,$filename) =
1.811 albertel 11654: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11655: my $uri="/uploaded/$cdom/$cnum/$filename";
11656: if (-e "$file") {
1.828 www 11657: # we already have a local copy, check it out
1.538 albertel 11658: my @fileinfo = stat($file);
1.828 www 11659: my $rtncode;
11660: my $info;
1.538 albertel 11661: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11662: if ($lwpresp ne 'ok') {
1.828 www 11663: # there is no such file anymore, even though we had a local copy
1.482 albertel 11664: if ($rtncode eq '404') {
1.538 albertel 11665: unlink($file);
1.482 albertel 11666: }
11667: return -1;
11668: }
11669: if ($info < $fileinfo[9]) {
1.828 www 11670: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11671: return 'ok';
1.828 www 11672: } else {
11673: # the file is outdated, get rid of it
11674: unlink($file);
1.482 albertel 11675: }
1.828 www 11676: }
11677: # one way or the other, at this point, we don't have the file
11678: # construct the correct path for the file
11679: my @parts = ($cdom,$cnum);
11680: if ($filename =~ m|^(.+)/[^/]+$|) {
11681: push @parts, split(/\//,$1);
11682: }
11683: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11684: foreach my $part (@parts) {
11685: $path .= '/'.$part;
11686: if (!-e $path) {
11687: mkdir($path,0770);
1.482 albertel 11688: }
11689: }
1.828 www 11690: # now the path exists for sure
11691: # get a user agent
11692: my $ua=new LWP::UserAgent;
11693: my $transferfile=$file.'.in.transfer';
11694: # FIXME: this should flock
11695: if (-e $transferfile) { return 'ok'; }
11696: my $request;
11697: $uri=~s/^\///;
1.980 raeburn 11698: my $homeserver = &homeserver($cnum,$cdom);
11699: my $protocol = $protocol{$homeserver};
11700: $protocol = 'http' if ($protocol ne 'https');
11701: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11702: my $response=$ua->request($request,$transferfile);
11703: # did it work?
11704: if ($response->is_error()) {
11705: unlink($transferfile);
11706: &logthis("Userfile repcopy failed for $uri");
11707: return -1;
11708: }
11709: # worked, rename the transfer file
11710: rename($transferfile,$file);
1.607 raeburn 11711: return 'ok';
1.481 raeburn 11712: }
11713:
1.517 albertel 11714: sub tokenwrapper {
11715: my $uri=shift;
1.980 raeburn 11716: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11717: $uri=~s|^/||;
1.620 albertel 11718: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11719: my $token=$1;
1.552 albertel 11720: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11721: if ($udom && $uname && $file) {
11722: $file=~s|(\?\.*)*$||;
1.949 raeburn 11723: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11724: my $homeserver = &homeserver($uname,$udom);
11725: my $protocol = $protocol{$homeserver};
11726: $protocol = 'http' if ($protocol ne 'https');
11727: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11728: (($uri=~/\?/)?'&':'?').'token='.$token.
11729: '&tokenissued='.$perlvar{'lonHostID'};
11730: } else {
11731: return '/adm/notfound.html';
11732: }
11733: }
11734:
1.828 www 11735: # call with reqtype HEAD: get last modification time
11736: # call with reqtype GET: get the file contents
11737: # Do not call this with reqtype GET for large files! It loads everything into memory
11738: #
1.481 raeburn 11739: sub getuploaded {
11740: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11741: $uri=~s/^\///;
1.980 raeburn 11742: my $homeserver = &homeserver($cnum,$cdom);
11743: my $protocol = $protocol{$homeserver};
11744: $protocol = 'http' if ($protocol ne 'https');
11745: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11746: my $ua=new LWP::UserAgent;
11747: my $request=new HTTP::Request($reqtype,$uri);
11748: my $response=$ua->request($request);
11749: $$rtncode = $response->code;
1.482 albertel 11750: if (! $response->is_success()) {
11751: return 'failed';
11752: }
11753: if ($reqtype eq 'HEAD') {
1.486 www 11754: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11755: } elsif ($reqtype eq 'GET') {
11756: $$info = $response->content;
1.472 albertel 11757: }
1.482 albertel 11758: return 'ok';
1.36 albertel 11759: }
11760:
1.481 raeburn 11761: sub readfile {
11762: my $file = shift;
11763: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11764: my $fh;
11765: open($fh,"<$file");
11766: my $a='';
1.800 albertel 11767: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11768: return $a;
11769: }
11770:
1.36 albertel 11771: sub filelocation {
1.590 banghart 11772: my ($dir,$file) = @_;
11773: my $location;
11774: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11775:
11776: if ($file =~ m-^/adm/-) {
11777: $file=~s-^/adm/wrapper/-/-;
11778: $file=~s-^/adm/coursedocs/showdoc/-/-;
11779: }
1.882 albertel 11780:
1.1139 www 11781: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11782: $location = $file;
1.609 banghart 11783: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11784: my ($udom,$uname,$filename)=
1.811 albertel 11785: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11786: my $home=&homeserver($uname,$udom);
11787: my $is_me=0;
11788: my @ids=¤t_machine_ids();
11789: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11790: if ($is_me) {
1.1117 foxr 11791: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11792: } else {
11793: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11794: $udom.'/'.$uname.'/'.$filename;
11795: }
1.882 albertel 11796: } elsif ($file =~ m-^/adm/-) {
11797: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11798: } else {
11799: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11800: $file=~s:^/(res|priv)/:/:;
11801: my $space=$1;
1.590 banghart 11802: if ( !( $file =~ m:^/:) ) {
11803: $location = $dir. '/'.$file;
11804: } else {
1.1142 raeburn 11805: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11806: }
1.59 albertel 11807: }
1.590 banghart 11808: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11809: while ($location=~m{/\.\./}) {
11810: if ($location =~ m{/[^/]+/\.\./}) {
11811: $location=~ s{/[^/]+/\.\./}{/}g;
11812: } else {
11813: $location=~ s{/\.\./}{/}g;
11814: }
11815: } #remove dir/..
1.590 banghart 11816: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11817: return $location;
1.46 www 11818: }
1.36 albertel 11819:
1.46 www 11820: sub hreflocation {
11821: my ($dir,$file)=@_;
1.980 raeburn 11822: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11823: $file=filelocation($dir,$file);
1.700 albertel 11824: } elsif ($file=~m-^/adm/-) {
11825: $file=~s-^/adm/wrapper/-/-;
11826: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11827: }
11828: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11829: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11830: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11831: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11832: {/uploaded/$1/$2/}x;
1.46 www 11833: }
1.913 albertel 11834: if ($file=~ m{^/userfiles/}) {
11835: $file =~ s{^/userfiles/}{/uploaded/};
11836: }
1.462 albertel 11837: return $file;
1.465 albertel 11838: }
11839:
1.1139 www 11840:
11841:
11842:
11843:
1.465 albertel 11844: sub current_machine_domains {
1.853 albertel 11845: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11846: }
11847:
11848: sub machine_domains {
11849: my ($hostname) = @_;
1.465 albertel 11850: my @domains;
1.838 albertel 11851: my %hostname = &all_hostnames();
1.465 albertel 11852: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11853: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11854: if ($hostname eq $name) {
1.844 albertel 11855: push(@domains,&host_domain($id));
1.465 albertel 11856: }
11857: }
11858: return @domains;
11859: }
11860:
11861: sub current_machine_ids {
1.853 albertel 11862: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11863: }
11864:
11865: sub machine_ids {
11866: my ($hostname) = @_;
11867: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11868: my @ids;
1.888 albertel 11869: my %name_to_host = &all_names();
1.889 albertel 11870: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11871: return @{ $name_to_host{$hostname} };
11872: }
11873: return;
1.31 www 11874: }
11875:
1.824 raeburn 11876: sub additional_machine_domains {
11877: my @domains;
11878: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11879: while( my $line = <$fh>) {
11880: $line =~ s/\s//g;
11881: push(@domains,$line);
11882: }
11883: return @domains;
11884: }
11885:
11886: sub default_login_domain {
11887: my $domain = $perlvar{'lonDefDomain'};
11888: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11889: foreach my $posdom (¤t_machine_domains(),
11890: &additional_machine_domains()) {
11891: if (lc($posdom) eq lc($testdomain)) {
11892: $domain=$posdom;
11893: last;
11894: }
11895: }
11896: return $domain;
11897: }
11898:
1.31 www 11899: # ------------------------------------------------------------- Declutters URLs
11900:
11901: sub declutter {
11902: my $thisfn=shift;
1.569 albertel 11903: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 11904: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11905: $thisfn=~s{^/home/httpd/html}{};
11906: }
1.31 www 11907: $thisfn=~s/^\///;
1.697 albertel 11908: $thisfn=~s|^adm/wrapper/||;
11909: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11910: $thisfn=~s/^res\///;
1.1172 bisitz 11911: $thisfn=~s/^priv\///;
1.1032 raeburn 11912: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11913: $thisfn=~s/\?.+$//;
11914: }
1.268 www 11915: return $thisfn;
11916: }
11917:
11918: # ------------------------------------------------------------- Clutter up URLs
11919:
11920: sub clutter {
11921: my $thisfn='/'.&declutter(shift);
1.887 albertel 11922: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11923: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11924: $thisfn='/res'.$thisfn;
11925: }
1.1031 raeburn 11926: if ($thisfn !~m|^/adm|) {
11927: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11928: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11929: } else {
11930: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11931: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11932: if ($embstyle eq 'ssi'
11933: || ($embstyle eq 'hdn')
11934: || ($embstyle eq 'rat')
11935: || ($embstyle eq 'prv')
11936: || ($embstyle eq 'ign')) {
11937: #do nothing with these
11938: } elsif (($embstyle eq 'img')
1.695 albertel 11939: || ($embstyle eq 'emb')
11940: || ($embstyle eq 'wrp')) {
11941: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11942: } elsif ($embstyle eq 'unk'
11943: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11944: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11945: } else {
1.718 www 11946: # &logthis("Got a blank emb style");
1.695 albertel 11947: }
1.694 albertel 11948: }
11949: }
1.31 www 11950: return $thisfn;
1.12 www 11951: }
11952:
1.787 albertel 11953: sub clutter_with_no_wrapper {
11954: my $uri = &clutter(shift);
11955: if ($uri =~ m-^/adm/-) {
11956: $uri =~ s-^/adm/wrapper/-/-;
11957: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11958: }
11959: return $uri;
11960: }
11961:
1.557 albertel 11962: sub freeze_escape {
11963: my ($value)=@_;
11964: if (ref($value)) {
11965: $value=&nfreeze($value);
11966: return '__FROZEN__'.&escape($value);
11967: }
11968: return &escape($value);
11969: }
11970:
1.11 www 11971:
1.557 albertel 11972: sub thaw_unescape {
11973: my ($value)=@_;
11974: if ($value =~ /^__FROZEN__/) {
11975: substr($value,0,10,undef);
11976: $value=&unescape($value);
11977: return &thaw($value);
11978: }
11979: return &unescape($value);
11980: }
11981:
1.436 albertel 11982: sub correct_line_ends {
11983: my ($result)=@_;
11984: $$result =~s/\r\n/\n/mg;
11985: $$result =~s/\r/\n/mg;
1.415 albertel 11986: }
1.1 albertel 11987: # ================================================================ Main Program
11988:
1.184 www 11989: sub goodbye {
1.204 albertel 11990: &logthis("Starting Shut down");
1.443 albertel 11991: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11992: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11993: #converted
1.599 albertel 11994: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11995: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11996: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11997: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11998: #1.1 only
1.870 albertel 11999: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12000: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12001: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12002: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12003: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12004: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12005: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12006: &flushcourselogs();
12007: &logthis("Shutting down");
12008: }
12009:
1.852 albertel 12010: sub get_dns {
1.1210 raeburn 12011: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12012: if (!$ignore_cache) {
12013: my ($content,$cached)=
12014: &Apache::lonnet::is_cached_new('dns',$url);
12015: if ($cached) {
1.1210 raeburn 12016: &$func($content,$hashref);
1.869 albertel 12017: return;
12018: }
12019: }
12020:
12021: my %alldns;
1.852 albertel 12022: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12023: foreach my $dns (<$config>) {
12024: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12025: my $line = $1;
12026: my ($host,$protocol) = split(/:/,$line);
12027: if ($protocol ne 'https') {
12028: $protocol = 'http';
12029: }
12030: $alldns{$host} = $protocol;
1.869 albertel 12031: }
12032: while (%alldns) {
1.1263 raeburn 12033: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12034: my $ua=new LWP::UserAgent;
1.1134 raeburn 12035: $ua->timeout(30);
1.979 raeburn 12036: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12037: my $response=$ua->request($request);
1.979 raeburn 12038: delete($alldns{$dns});
1.852 albertel 12039: next if ($response->is_error());
12040: my @content = split("\n",$response->content);
1.1210 raeburn 12041: unless ($nocache) {
1.1219 raeburn 12042: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12043: }
12044: &$func(\@content,$hashref);
1.869 albertel 12045: return;
1.852 albertel 12046: }
12047: close($config);
1.871 albertel 12048: my $which = (split('/',$url))[3];
12049: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12050: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12051: my @content = <$config>;
1.1210 raeburn 12052: &$func(\@content,$hashref);
12053: return;
12054: }
12055:
12056: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12057: sub parse_dns_checksums_tab {
1.1210 raeburn 12058: my ($lines,$hashref) = @_;
1.1264 raeburn 12059: my $lonhost = $perlvar{'lonHostID'};
12060: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12061: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12062: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12063: my $webconfdir = '/etc/httpd/conf';
12064: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12065: $webconfdir = '/etc/apache2';
12066: } elsif ($distro =~ /^sles(\d+)$/) {
12067: if ($1 >= 10) {
12068: $webconfdir = '/etc/apache2';
12069: }
12070: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12071: if ($1 >= 10.0) {
12072: $webconfdir = '/etc/apache2';
12073: }
12074: }
1.1210 raeburn 12075: my ($release,$timestamp) = split(/\-/,$loncaparev);
12076: my (%chksum,%revnum);
12077: if (ref($lines) eq 'ARRAY') {
12078: chomp(@{$lines});
1.1238 raeburn 12079: my $version = shift(@{$lines});
12080: if ($version eq $release) {
1.1210 raeburn 12081: foreach my $line (@{$lines}) {
1.1238 raeburn 12082: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12083: if ($file =~ m{^/etc/httpd/conf}) {
12084: if ($webconfdir eq '/etc/apache2') {
12085: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12086: }
12087: }
1.1238 raeburn 12088: $chksum{$file} = $shasum;
12089: $revnum{$file} = $version;
1.1210 raeburn 12090: }
12091: if (ref($hashref) eq 'HASH') {
12092: %{$hashref} = (
12093: sums => \%chksum,
12094: versions => \%revnum,
12095: );
12096: }
12097: }
12098: }
1.869 albertel 12099: return;
1.852 albertel 12100: }
1.1210 raeburn 12101:
12102: sub fetch_dns_checksums {
1.1238 raeburn 12103: my %checksums;
12104: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12105: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12106: my ($release,$timestamp) = split(/\-/,$loncaparev);
12107: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12108: \%checksums);
1.1210 raeburn 12109: return \%checksums;
12110: }
12111:
1.327 albertel 12112: # ------------------------------------------------------------ Read domain file
12113: {
1.852 albertel 12114: my $loaded;
1.846 albertel 12115: my %domain;
12116:
1.852 albertel 12117: sub parse_domain_tab {
12118: my ($lines) = @_;
12119: foreach my $line (@$lines) {
12120: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12121:
1.846 albertel 12122: chomp($line);
1.852 albertel 12123: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12124: my %this_domain;
12125: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12126: 'lang_def', 'city', 'longi', 'lati',
12127: 'primary') {
12128: $this_domain{$field} = shift(@elements);
12129: }
12130: $domain{$name} = \%this_domain;
1.852 albertel 12131: }
12132: }
1.864 albertel 12133:
12134: sub reset_domain_info {
12135: undef($loaded);
12136: undef(%domain);
12137: }
12138:
1.852 albertel 12139: sub load_domain_tab {
1.869 albertel 12140: my ($ignore_cache) = @_;
12141: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 12142: my $fh;
12143: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12144: my @lines = <$fh>;
12145: &parse_domain_tab(\@lines);
1.448 albertel 12146: }
1.852 albertel 12147: close($fh);
12148: $loaded = 1;
1.327 albertel 12149: }
1.846 albertel 12150:
12151: sub domain {
1.852 albertel 12152: &load_domain_tab() if (!$loaded);
12153:
1.846 albertel 12154: my ($name,$what) = @_;
12155: return if ( !exists($domain{$name}) );
12156:
12157: if (!$what) {
12158: return $domain{$name}{'description'};
12159: }
12160: return $domain{$name}{$what};
12161: }
1.974 raeburn 12162:
12163: sub domain_info {
12164: &load_domain_tab() if (!$loaded);
12165: return %domain;
12166: }
12167:
1.327 albertel 12168: }
12169:
12170:
1.1 albertel 12171: # ------------------------------------------------------------- Read hosts file
12172: {
1.838 albertel 12173: my %hostname;
1.844 albertel 12174: my %hostdom;
1.845 albertel 12175: my %libserv;
1.852 albertel 12176: my $loaded;
1.888 albertel 12177: my %name_to_host;
1.1074 raeburn 12178: my %internetdom;
1.1107 raeburn 12179: my %LC_dns_serv;
1.852 albertel 12180:
12181: sub parse_hosts_tab {
12182: my ($file) = @_;
12183: foreach my $configline (@$file) {
12184: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12185: chomp($configline);
12186: if ($configline =~ /^\^/) {
12187: if ($configline =~ /^\^([\w.\-]+)/) {
12188: $LC_dns_serv{$1} = 1;
12189: }
12190: next;
12191: }
1.1074 raeburn 12192: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12193: $name=~s/\s//g;
12194: if ($id && $domain && $role && $name) {
12195: $hostname{$id}=$name;
1.888 albertel 12196: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12197: $hostdom{$id}=$domain;
12198: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12199: if (defined($protocol)) {
12200: if ($protocol eq 'https') {
12201: $protocol{$id} = $protocol;
12202: } else {
12203: $protocol{$id} = 'http';
12204: }
1.968 raeburn 12205: } else {
1.969 raeburn 12206: $protocol{$id} = 'http';
1.968 raeburn 12207: }
1.1074 raeburn 12208: if (defined($intdom)) {
12209: $internetdom{$id} = $intdom;
12210: }
1.852 albertel 12211: }
12212: }
12213: }
1.864 albertel 12214:
12215: sub reset_hosts_info {
1.897 albertel 12216: &purge_remembered();
1.864 albertel 12217: &reset_domain_info();
12218: &reset_hosts_ip_info();
1.892 albertel 12219: undef(%name_to_host);
1.864 albertel 12220: undef(%hostname);
12221: undef(%hostdom);
12222: undef(%libserv);
12223: undef($loaded);
12224: }
1.1 albertel 12225:
1.852 albertel 12226: sub load_hosts_tab {
1.869 albertel 12227: my ($ignore_cache) = @_;
12228: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12229: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12230: my @config = <$config>;
12231: &parse_hosts_tab(\@config);
12232: close($config);
12233: $loaded=1;
1.1 albertel 12234: }
1.852 albertel 12235:
1.838 albertel 12236: sub hostname {
1.852 albertel 12237: &load_hosts_tab() if (!$loaded);
12238:
1.838 albertel 12239: my ($lonid) = @_;
12240: return $hostname{$lonid};
12241: }
1.845 albertel 12242:
1.838 albertel 12243: sub all_hostnames {
1.852 albertel 12244: &load_hosts_tab() if (!$loaded);
12245:
1.838 albertel 12246: return %hostname;
12247: }
1.845 albertel 12248:
1.888 albertel 12249: sub all_names {
12250: &load_hosts_tab() if (!$loaded);
12251:
12252: return %name_to_host;
12253: }
12254:
1.974 raeburn 12255: sub all_host_domain {
12256: &load_hosts_tab() if (!$loaded);
12257: return %hostdom;
12258: }
12259:
1.845 albertel 12260: sub is_library {
1.852 albertel 12261: &load_hosts_tab() if (!$loaded);
12262:
1.845 albertel 12263: return exists($libserv{$_[0]});
12264: }
12265:
12266: sub all_library {
1.852 albertel 12267: &load_hosts_tab() if (!$loaded);
12268:
1.845 albertel 12269: return %libserv;
12270: }
12271:
1.1062 droeschl 12272: sub unique_library {
12273: #2x reverse removes all hostnames that appear more than once
12274: my %unique = reverse &all_library();
12275: return reverse %unique;
12276: }
12277:
1.841 albertel 12278: sub get_servers {
1.852 albertel 12279: &load_hosts_tab() if (!$loaded);
12280:
1.841 albertel 12281: my ($domain,$type) = @_;
12282: my %possible_hosts = ($type eq 'library') ? %libserv
12283: : %hostname;
12284: my %result;
1.842 albertel 12285: if (ref($domain) eq 'ARRAY') {
12286: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12287: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12288: $result{$host} = $hostname;
12289: }
12290: }
12291: } else {
12292: while ( my ($host,$hostname) = each(%possible_hosts)) {
12293: if ($hostdom{$host} eq $domain) {
12294: $result{$host} = $hostname;
12295: }
1.841 albertel 12296: }
12297: }
12298: return %result;
12299: }
1.845 albertel 12300:
1.1062 droeschl 12301: sub get_unique_servers {
12302: my %unique = reverse &get_servers(@_);
12303: return reverse %unique;
12304: }
12305:
1.844 albertel 12306: sub host_domain {
1.852 albertel 12307: &load_hosts_tab() if (!$loaded);
12308:
1.844 albertel 12309: my ($lonid) = @_;
12310: return $hostdom{$lonid};
12311: }
12312:
1.841 albertel 12313: sub all_domains {
1.852 albertel 12314: &load_hosts_tab() if (!$loaded);
12315:
1.841 albertel 12316: my %seen;
12317: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12318: return @uniq;
12319: }
1.1074 raeburn 12320:
12321: sub internet_dom {
12322: &load_hosts_tab() if (!$loaded);
12323:
12324: my ($lonid) = @_;
12325: return $internetdom{$lonid};
12326: }
1.1107 raeburn 12327:
12328: sub is_LC_dns {
12329: &load_hosts_tab() if (!$loaded);
12330:
12331: my ($hostname) = @_;
12332: return exists($LC_dns_serv{$hostname});
12333: }
12334:
1.1 albertel 12335: }
12336:
1.847 albertel 12337: {
12338: my %iphost;
1.856 albertel 12339: my %name_to_ip;
12340: my %lonid_to_ip;
1.869 albertel 12341:
1.847 albertel 12342: sub get_hosts_from_ip {
12343: my ($ip) = @_;
12344: my %iphosts = &get_iphost();
12345: if (ref($iphosts{$ip})) {
12346: return @{$iphosts{$ip}};
12347: }
12348: return;
1.839 albertel 12349: }
1.864 albertel 12350:
12351: sub reset_hosts_ip_info {
12352: undef(%iphost);
12353: undef(%name_to_ip);
12354: undef(%lonid_to_ip);
12355: }
1.856 albertel 12356:
12357: sub get_host_ip {
12358: my ($lonid) = @_;
12359: if (exists($lonid_to_ip{$lonid})) {
12360: return $lonid_to_ip{$lonid};
12361: }
12362: my $name=&hostname($lonid);
12363: my $ip = gethostbyname($name);
12364: return if (!$ip || length($ip) ne 4);
12365: $ip=inet_ntoa($ip);
12366: $name_to_ip{$name} = $ip;
12367: $lonid_to_ip{$lonid} = $ip;
12368: return $ip;
12369: }
1.847 albertel 12370:
12371: sub get_iphost {
1.869 albertel 12372: my ($ignore_cache) = @_;
1.894 albertel 12373:
1.869 albertel 12374: if (!$ignore_cache) {
12375: if (%iphost) {
12376: return %iphost;
12377: }
12378: my ($ip_info,$cached)=
12379: &Apache::lonnet::is_cached_new('iphost','iphost');
12380: if ($cached) {
12381: %iphost = %{$ip_info->[0]};
12382: %name_to_ip = %{$ip_info->[1]};
12383: %lonid_to_ip = %{$ip_info->[2]};
12384: return %iphost;
12385: }
12386: }
1.894 albertel 12387:
12388: # get yesterday's info for fallback
12389: my %old_name_to_ip;
12390: my ($ip_info,$cached)=
12391: &Apache::lonnet::is_cached_new('iphost','iphost');
12392: if ($cached) {
12393: %old_name_to_ip = %{$ip_info->[1]};
12394: }
12395:
1.888 albertel 12396: my %name_to_host = &all_names();
12397: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12398: my $ip;
12399: if (!exists($name_to_ip{$name})) {
12400: $ip = gethostbyname($name);
12401: if (!$ip || length($ip) ne 4) {
1.894 albertel 12402: if (defined($old_name_to_ip{$name})) {
12403: $ip = $old_name_to_ip{$name};
12404: &logthis("Can't find $name defaulting to old $ip");
12405: } else {
12406: &logthis("Name $name no IP found");
12407: next;
12408: }
12409: } else {
12410: $ip=inet_ntoa($ip);
1.847 albertel 12411: }
12412: $name_to_ip{$name} = $ip;
12413: } else {
12414: $ip = $name_to_ip{$name};
1.653 albertel 12415: }
1.888 albertel 12416: foreach my $id (@{ $name_to_host{$name} }) {
12417: $lonid_to_ip{$id} = $ip;
12418: }
12419: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12420: }
1.1219 raeburn 12421: &do_cache_new('iphost','iphost',
12422: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12423: 48*60*60);
1.869 albertel 12424:
1.847 albertel 12425: return %iphost;
1.598 albertel 12426: }
12427:
1.992 raeburn 12428: #
12429: # Given a DNS returns the loncapa host name for that DNS
12430: #
12431: sub host_from_dns {
12432: my ($dns) = @_;
12433: my @hosts;
12434: my $ip;
12435:
1.993 raeburn 12436: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12437: $ip = $name_to_ip{$dns};
12438: }
12439: if (!$ip) {
12440: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12441: if (length($ip) == 4) {
12442: $ip = &IO::Socket::inet_ntoa($ip);
12443: }
12444: }
12445: if ($ip) {
12446: @hosts = get_hosts_from_ip($ip);
12447: return $hosts[0];
12448: }
12449: return undef;
1.986 foxr 12450: }
1.992 raeburn 12451:
1.1074 raeburn 12452: sub get_internet_names {
12453: my ($lonid) = @_;
12454: return if ($lonid eq '');
12455: my ($idnref,$cached)=
12456: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12457: if ($cached) {
12458: return $idnref;
12459: }
12460: my $ip = &get_host_ip($lonid);
12461: my @hosts = &get_hosts_from_ip($ip);
12462: my %iphost = &get_iphost();
12463: my (@idns,%seen);
12464: foreach my $id (@hosts) {
12465: my $dom = &host_domain($id);
12466: my $prim_id = &domain($dom,'primary');
12467: my $prim_ip = &get_host_ip($prim_id);
12468: next if ($seen{$prim_ip});
12469: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12470: foreach my $id (@{$iphost{$prim_ip}}) {
12471: my $intdom = &internet_dom($id);
12472: unless (grep(/^\Q$intdom\E$/,@idns)) {
12473: push(@idns,$intdom);
12474: }
12475: }
12476: }
12477: $seen{$prim_ip} = 1;
12478: }
1.1219 raeburn 12479: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12480: }
12481:
1.986 foxr 12482: }
12483:
1.1079 raeburn 12484: sub all_loncaparevs {
1.1249 raeburn 12485: 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 2.11);
1.1079 raeburn 12486: }
12487:
1.1227 raeburn 12488: # ---------------------------------------------------------- Read loncaparev table
12489: {
12490: sub load_loncaparevs {
12491: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12492: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12493: while (my $configline=<$config>) {
12494: chomp($configline);
12495: my ($hostid,$loncaparev)=split(/:/,$configline);
12496: $loncaparevs{$hostid}=$loncaparev;
12497: }
12498: close($config);
12499: }
12500: }
12501: }
12502: }
12503:
12504: # ---------------------------------------------------------- Read serverhostID table
12505: {
12506: sub load_serverhomeIDs {
12507: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12508: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12509: while (my $configline=<$config>) {
12510: chomp($configline);
12511: my ($name,$id)=split(/:/,$configline);
12512: $serverhomeIDs{$name}=$id;
12513: }
12514: close($config);
12515: }
12516: }
12517: }
12518: }
12519:
12520:
1.862 albertel 12521: BEGIN {
12522:
12523: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12524: unless ($readit) {
12525: {
12526: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12527: %perlvar = (%perlvar,%{$configvars});
12528: }
12529:
12530:
1.1 albertel 12531: # ------------------------------------------------------ Read spare server file
12532: {
1.448 albertel 12533: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12534:
12535: while (my $configline=<$config>) {
12536: chomp($configline);
1.284 matthew 12537: if ($configline) {
1.784 albertel 12538: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12539: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12540: push(@{ $spareid{$type} }, $host);
1.1 albertel 12541: }
12542: }
1.448 albertel 12543: close($config);
1.1 albertel 12544: }
1.11 www 12545: # ------------------------------------------------------------ Read permissions
12546: {
1.448 albertel 12547: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12548:
12549: while (my $configline=<$config>) {
1.448 albertel 12550: chomp($configline);
12551: if ($configline) {
12552: my ($role,$perm)=split(/ /,$configline);
12553: if ($perm ne '') { $pr{$role}=$perm; }
12554: }
1.11 www 12555: }
1.448 albertel 12556: close($config);
1.11 www 12557: }
12558:
12559: # -------------------------------------------- Read plain texts for permissions
12560: {
1.448 albertel 12561: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12562:
12563: while (my $configline=<$config>) {
1.448 albertel 12564: chomp($configline);
12565: if ($configline) {
1.742 raeburn 12566: my ($short,@plain)=split(/:/,$configline);
12567: %{$prp{$short}} = ();
12568: if (@plain > 0) {
12569: $prp{$short}{'std'} = $plain[0];
12570: for (my $i=1; $i<@plain; $i++) {
12571: $prp{$short}{'alt'.$i} = $plain[$i];
12572: }
12573: }
1.448 albertel 12574: }
1.135 www 12575: }
1.448 albertel 12576: close($config);
1.135 www 12577: }
12578:
12579: # ---------------------------------------------------------- Read package table
12580: {
1.448 albertel 12581: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12582:
12583: while (my $configline=<$config>) {
1.483 albertel 12584: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12585: chomp($configline);
12586: my ($short,$plain)=split(/:/,$configline);
12587: my ($pack,$name)=split(/\&/,$short);
12588: if ($plain ne '') {
12589: $packagetab{$pack.'&'.$name.'&name'}=$name;
12590: $packagetab{$short}=$plain;
12591: }
1.11 www 12592: }
1.448 albertel 12593: close($config);
1.329 matthew 12594: }
12595:
1.1073 raeburn 12596: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12597:
12598: &load_loncaparevs();
1.1073 raeburn 12599:
1.1074 raeburn 12600: # ---------------------------------------------------------- Read serverhostID table
12601:
1.1227 raeburn 12602: &load_serverhomeIDs();
12603:
12604: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12605: {
12606: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12607: if (-e $file) {
12608: my $parser = HTML::LCParser->new($file);
12609: while (my $token = $parser->get_token()) {
12610: if ($token->[0] eq 'S') {
12611: my $item = $token->[1];
12612: my $name = $token->[2]{'name'};
12613: my $value = $token->[2]{'value'};
12614: if ($item ne '' && $name ne '' && $value ne '') {
12615: my $release = $parser->get_text();
12616: $release =~ s/(^\s*|\s*$ )//gx;
12617: $needsrelease{$item.':'.$name.':'.$value} = $release;
12618: }
12619: }
12620: }
12621: }
1.1073 raeburn 12622: }
12623:
1.1138 raeburn 12624: # ---------------------------------------------------------- Read managers table
12625: {
12626: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12627: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12628: while (my $configline=<$config>) {
12629: chomp($configline);
12630: next if ($configline =~ /^\#/);
12631: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12632: $managerstab{$configline} = 1;
12633: }
12634: }
12635: close($config);
12636: }
12637: }
12638: }
12639:
1.329 matthew 12640: # ------------- set up temporary directory
12641: {
1.1117 foxr 12642: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12643:
1.11 www 12644: }
12645:
1.794 albertel 12646: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12647: 'compress_threshold'=> 20_000,
12648: });
1.185 www 12649:
1.281 www 12650: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12651: $dumpcount=0;
1.958 www 12652: $locknum=0;
1.22 www 12653:
1.163 harris41 12654: &logtouch();
1.672 albertel 12655: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12656: $readit=1;
1.564 albertel 12657: {
12658: use integer;
12659: my $test=(2**32)+1;
1.568 albertel 12660: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12661: &logthis(" Detected 64bit platform ($_64bit)");
12662: }
1.195 www 12663: }
1.1 albertel 12664: }
1.179 www 12665:
1.1 albertel 12666: 1;
1.191 harris41 12667: __END__
12668:
1.243 albertel 12669: =pod
12670:
1.191 harris41 12671: =head1 NAME
12672:
1.243 albertel 12673: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12674:
12675: =head1 SYNOPSIS
12676:
1.243 albertel 12677: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12678:
12679: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12680:
1.243 albertel 12681: Common parameters:
12682:
12683: =over 4
12684:
12685: =item *
12686:
12687: $uname : an internal username (if $cname expecting a course Id specifically)
12688:
12689: =item *
12690:
12691: $udom : a domain (if $cdom expecting a course's domain specifically)
12692:
12693: =item *
12694:
12695: $symb : a resource instance identifier
12696:
12697: =item *
12698:
12699: $namespace : the name of a .db file that contains the data needed or
12700: being set.
12701:
12702: =back
12703:
1.394 bowersj2 12704: =head1 OVERVIEW
1.191 harris41 12705:
1.394 bowersj2 12706: lonnet provides subroutines which interact with the
12707: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12708: about classes, users, and resources.
1.243 albertel 12709:
12710: For many of these objects you can also use this to store data about
12711: them or modify them in various ways.
1.191 harris41 12712:
1.394 bowersj2 12713: =head2 Symbs
1.191 harris41 12714:
1.394 bowersj2 12715: To identify a specific instance of a resource, LON-CAPA uses symbols
12716: or "symbs"X<symb>. These identifiers are built from the URL of the
12717: map, the resource number of the resource in the map, and the URL of
12718: the resource itself. The latter is somewhat redundant, but might help
12719: if maps change.
12720:
12721: An example is
12722:
12723: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12724:
12725: The respective map entry is
12726:
12727: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12728: title="Problem 2">
12729: </resource>
12730:
12731: Symbs are used by the random number generator, as well as to store and
12732: restore data specific to a certain instance of for example a problem.
12733:
12734: =head2 Storing And Retrieving Data
12735:
12736: X<store()>X<cstore()>X<restore()>Three of the most important functions
12737: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12738: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12739: is is the non-critical message twin of cstore. These functions are for
12740: handlers to store a perl hash to a user's permanent data space in an
12741: easy manner, and to retrieve it again on another call. It is expected
12742: that a handler would use this once at the beginning to retrieve data,
12743: and then again once at the end to send only the new data back.
12744:
12745: The data is stored in the user's data directory on the user's
12746: homeserver under the ID of the course.
12747:
12748: The hash that is returned by restore will have all of the previous
12749: value for all of the elements of the hash.
12750:
12751: Example:
12752:
12753: #creating a hash
12754: my %hash;
12755: $hash{'foo'}='bar';
12756:
12757: #storing it
12758: &Apache::lonnet::cstore(\%hash);
12759:
12760: #changing a value
12761: $hash{'foo'}='notbar';
12762:
12763: #adding a new value
12764: $hash{'bar'}='foo';
12765: &Apache::lonnet::cstore(\%hash);
12766:
12767: #retrieving the hash
12768: my %history=&Apache::lonnet::restore();
12769:
12770: #print the hash
12771: foreach my $key (sort(keys(%history))) {
12772: print("\%history{$key} = $history{$key}");
12773: }
12774:
12775: Will print out:
1.191 harris41 12776:
1.394 bowersj2 12777: %history{1:foo} = bar
12778: %history{1:keys} = foo:timestamp
12779: %history{1:timestamp} = 990455579
12780: %history{2:bar} = foo
12781: %history{2:foo} = notbar
12782: %history{2:keys} = foo:bar:timestamp
12783: %history{2:timestamp} = 990455580
12784: %history{bar} = foo
12785: %history{foo} = notbar
12786: %history{timestamp} = 990455580
12787: %history{version} = 2
12788:
12789: Note that the special hash entries C<keys>, C<version> and
12790: C<timestamp> were added to the hash. C<version> will be equal to the
12791: total number of versions of the data that have been stored. The
12792: C<timestamp> attribute will be the UNIX time the hash was
12793: stored. C<keys> is available in every historical section to list which
12794: keys were added or changed at a specific historical revision of a
12795: hash.
12796:
12797: B<Warning>: do not store the hash that restore returns directly. This
12798: will cause a mess since it will restore the historical keys as if the
12799: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12800:
1.394 bowersj2 12801: Calling convention:
1.191 harris41 12802:
1.1225 raeburn 12803: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 12804: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 12805:
1.394 bowersj2 12806: For more detailed information, see lonnet specific documentation.
1.191 harris41 12807:
1.394 bowersj2 12808: =head1 RETURN MESSAGES
1.191 harris41 12809:
1.394 bowersj2 12810: =over 4
1.191 harris41 12811:
1.394 bowersj2 12812: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12813:
1.394 bowersj2 12814: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12815: when the connection is brought back up
1.191 harris41 12816:
1.394 bowersj2 12817: =item * B<con_failed>: unable to contact remote host and unable to save message
12818: for later delivery
1.191 harris41 12819:
1.967 bisitz 12820: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12821:
1.394 bowersj2 12822: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12823: that was requested
1.191 harris41 12824:
1.243 albertel 12825: =back
1.191 harris41 12826:
1.243 albertel 12827: =head1 PUBLIC SUBROUTINES
1.191 harris41 12828:
1.243 albertel 12829: =head2 Session Environment Functions
1.191 harris41 12830:
1.243 albertel 12831: =over 4
1.191 harris41 12832:
1.394 bowersj2 12833: =item *
12834: X<appenv()>
1.949 raeburn 12835: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12836: the user envirnoment file, and will be restored for each access this
1.620 albertel 12837: user makes during this session, also modifies the %env for the current
1.949 raeburn 12838: process. Optional rolesarrayref - if defined contains a reference to an array
12839: of roles which are exempt from the restriction on modifying user.role entries
12840: in the user's environment.db and in %env.
1.191 harris41 12841:
12842: =item *
1.394 bowersj2 12843: X<delenv()>
1.987 raeburn 12844: B<delenv($delthis,$regexp)>: removes all items from the session
12845: environment file that begin with $delthis. If the
12846: optional second arg - $regexp - is true, $delthis is treated as a
12847: regular expression, otherwise \Q$delthis\E is used.
12848: The values are also deleted from the current processes %env.
1.191 harris41 12849:
1.795 albertel 12850: =item * get_env_multiple($name)
12851:
12852: gets $name from the %env hash, it seemlessly handles the cases where multiple
12853: values may be defined and end up as an array ref.
12854:
12855: returns an array of values
12856:
1.243 albertel 12857: =back
12858:
12859: =head2 User Information
1.191 harris41 12860:
1.243 albertel 12861: =over 4
1.191 harris41 12862:
12863: =item *
1.394 bowersj2 12864: X<queryauthenticate()>
12865: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12866: authentication scheme
12867:
12868: =item *
1.394 bowersj2 12869: X<authenticate()>
1.1073 raeburn 12870: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12871: authenticate user from domain's lib servers (first use the current
12872: one). C<$upass> should be the users password.
1.1073 raeburn 12873: $checkdefauth is optional (value is 1 if a check should be made to
12874: authenticate user using default authentication method, and allow
12875: account creation if username does not have account in the domain).
12876: $clientcancheckhost is optional (value is 1 if checking whether the
12877: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12878:
12879: =item *
1.394 bowersj2 12880: X<homeserver()>
12881: B<homeserver($uname,$udom)>: find the server which has
12882: the user's directory and files (there must be only one), this caches
12883: the answer, and also caches if there is a borken connection.
1.191 harris41 12884:
12885: =item *
1.394 bowersj2 12886: X<idget()>
12887: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12888: (IDs are a unique resource in a domain, there must be only 1 ID per
12889: username, and only 1 username per ID in a specific domain) (returns
12890: hash: id=>name,id=>name)
1.191 harris41 12891:
12892: =item *
1.394 bowersj2 12893: X<idrget()>
12894: B<idrget($udom,@unames)>: find the IDs behind a list of
12895: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12896:
12897: =item *
1.394 bowersj2 12898: X<idput()>
12899: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12900:
12901: =item *
1.394 bowersj2 12902: X<rolesinit()>
1.1169 droeschl 12903: B<rolesinit($udom,$username)>: get user privileges.
12904: returns user role, first access and timer interval hashes
1.243 albertel 12905:
12906: =item *
1.1171 droeschl 12907: X<privileged()>
12908: B<privileged($username,$domain)>: returns a true if user has a
12909: privileged and active role (i.e. su or dc), false otherwise.
12910:
12911: =item *
1.551 albertel 12912: X<getsection()>
12913: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12914: course $cname, return section name/number or '' for "not in course"
12915: and '-1' for "no section"
12916:
12917: =item *
1.394 bowersj2 12918: X<userenvironment()>
12919: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12920: passed in @what from the requested user's environment, returns a hash
12921:
1.858 raeburn 12922: =item *
12923: X<userlog_query()>
1.859 albertel 12924: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12925: activity.log file. %filters defines filters applied when parsing the
12926: log file. These can be start or end timestamps, or the type of action
12927: - log to look for Login or Logout events, check for Checkin or
12928: Checkout, role for role selection. The response is in the form
12929: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12930: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12931:
1.243 albertel 12932: =back
12933:
12934: =head2 User Roles
12935:
12936: =over 4
12937:
12938: =item *
12939:
1.810 raeburn 12940: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12941: F: full access
12942: U,I,K: authentication modes (cxx only)
12943: '': forbidden
12944: 1: user needs to choose course
12945: 2: browse allowed
1.766 albertel 12946: A: passphrase authentication needed
1.243 albertel 12947:
12948: =item *
12949:
1.1192 raeburn 12950: constructaccess($url,$setpriv) : check for access to construction space URL
12951:
12952: See if the owner domain and name in the URL match those in the
12953: expected environment. If so, return three element list
12954: ($ownername,$ownerdomain,$ownerhome).
12955:
12956: Otherwise return the null string.
12957:
12958: If second argument 'setpriv' is true, it assigns the privileges,
12959: and returns the same three element list, unless the owner has
12960: blocked "ad hoc" Domain Coordinator access to the Author Space,
12961: in which case the null string is returned.
12962:
12963: =item *
12964:
1.243 albertel 12965: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12966: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12967: and course level
12968:
12969: =item *
12970:
1.988 raeburn 12971: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12972: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12973: $type is Course (default) or Community.
1.988 raeburn 12974: If $forcedefault evaluates to true, text returned will be default
12975: text for $type. Otherwise, if this is a course, the text returned
12976: will be a custom name for the role (if defined in the course's
12977: environment). If no custom name is defined the default is returned.
12978:
1.832 raeburn 12979: =item *
12980:
1.1219 raeburn 12981: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12982: All arguments are optional. Returns a hash of a roles, either for
12983: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12984: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12985: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12986: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12987: For each key, value is set to colon-separated start and end times for
12988: the role. If no username and domain are specified, will default to
1.934 raeburn 12989: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12990: of role statuses (active, future or previous), roles
12991: (e.g., cc,in, st etc.) and domains of the roles which can be used
12992: to restrict the list of roles reported. If no array ref is
12993: provided for types, will default to return only active roles.
1.834 albertel 12994:
1.1195 raeburn 12995: =item *
12996:
12997: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12998: user: $uname:$udom has a role in the course: $cdom_$cnum.
12999:
13000: Additional optional arguments are: $type (if role checking is to be restricted
13001: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13002: available roles) or future (roles available in the future), and
13003: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13004: have active Domain Coordinator role in course's domain or in additional
13005: domains (specified in 'Domains to check for privileged users' in course
13006: environment -- set via: Course Settings -> Classlists and staff listing).
13007:
13008: =item *
13009:
13010: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13011: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13012: $possdomains and $possroles are optional array refs -- to domains to check and
13013: roles to check. If $possdomains is not specified, a dump will be done of the
13014: users' roles.db to check for a dc or su role in any domain. This can be
13015: time consuming if &privileged is called repeatedly (e.g., when displaying a
13016: classlist), so in such cases, supplying a $possdomains array is preferred, as
13017: this then allows &privileged_by_domain() to be used, which caches the identity
13018: of privileged users, eliminating the need for repeated calls to &dump().
13019:
13020: =item *
13021:
13022: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13023: where the outer hash keys are domains specified in the $possdomains array ref,
13024: next inner hash keys are privileged roles specified in the $roles array ref,
13025: and the innermost hash contains key = value pairs for username:domain = end:start
13026: for active or future "privileged" users with that role in that domain. To avoid
13027: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13028: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13029:
1.243 albertel 13030: =back
13031:
13032: =head2 User Modification
13033:
13034: =over 4
13035:
13036: =item *
13037:
1.957 raeburn 13038: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13039: user for the level given by URL. Optional start and end dates (leave empty
13040: string or zero for "no date")
1.191 harris41 13041:
13042: =item *
13043:
1.243 albertel 13044: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13045: change a users, password, possible return values are: ok,
13046: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13047: refused
1.191 harris41 13048:
13049: =item *
13050:
1.243 albertel 13051: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13052:
13053: =item *
13054:
1.1058 raeburn 13055: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13056: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13057:
13058: will update user information (firstname,middlename,lastname,generation,
13059: permanentemail), and if forceid is true, student/employee ID also.
13060: A user's institutional affiliation(s) can also be updated.
13061: User information fields will not be overwritten with empty entries
13062: unless the field is included in the $candelete array reference.
13063: This array is included when a single user is modified via "Manage Users",
13064: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13065:
13066: =item *
13067:
1.286 matthew 13068: modifystudent
13069:
1.957 raeburn 13070: modify a student's enrollment and identification information.
1.1235 raeburn 13071: The course id is resolved based on the current user's environment.
13072: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13073: associated with a course.
13074:
1.297 matthew 13075: This call is essentially a wrapper for lonnet::modifyuser and
13076: lonnet::modify_student_enrollment
1.286 matthew 13077:
13078: Inputs:
13079:
13080: =over 4
13081:
1.957 raeburn 13082: =item B<$udom> Student's loncapa domain
1.286 matthew 13083:
1.957 raeburn 13084: =item B<$uname> Student's loncapa login name
1.286 matthew 13085:
1.964 bisitz 13086: =item B<$uid> Student/Employee ID
1.286 matthew 13087:
1.957 raeburn 13088: =item B<$umode> Student's authentication mode
1.286 matthew 13089:
1.957 raeburn 13090: =item B<$upass> Student's password
1.286 matthew 13091:
1.957 raeburn 13092: =item B<$first> Student's first name
1.286 matthew 13093:
1.957 raeburn 13094: =item B<$middle> Student's middle name
1.286 matthew 13095:
1.957 raeburn 13096: =item B<$last> Student's last name
1.286 matthew 13097:
1.957 raeburn 13098: =item B<$gene> Student's generation
1.286 matthew 13099:
1.957 raeburn 13100: =item B<$usec> Student's section in course
1.286 matthew 13101:
13102: =item B<$end> Unix time of the roles expiration
13103:
13104: =item B<$start> Unix time of the roles start date
13105:
13106: =item B<$forceid> If defined, allow $uid to be changed
13107:
13108: =item B<$desiredhome> server to use as home server for student
13109:
1.957 raeburn 13110: =item B<$email> Student's permanent e-mail address
13111:
13112: =item B<$type> Type of enrollment (auto or manual)
13113:
1.963 raeburn 13114: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13115:
13116: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13117:
1.963 raeburn 13118: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13119:
1.963 raeburn 13120: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13121:
1.1216 raeburn 13122: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13123:
13124: =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 13125:
1.286 matthew 13126: =back
1.297 matthew 13127:
13128: =item *
13129:
13130: modify_student_enrollment
13131:
1.1235 raeburn 13132: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13133: 'role.request.course' must be defined for this function to proceed.
13134:
13135: Inputs:
13136:
13137: =over 4
13138:
1.1235 raeburn 13139: =item $udom, student's domain
1.297 matthew 13140:
1.1235 raeburn 13141: =item $uname, student's name
1.297 matthew 13142:
1.1235 raeburn 13143: =item $uid, student's user id
1.297 matthew 13144:
1.1235 raeburn 13145: =item $first, student's first name
1.297 matthew 13146:
13147: =item $middle
13148:
13149: =item $last
13150:
13151: =item $gene
13152:
13153: =item $usec
13154:
13155: =item $end
13156:
13157: =item $start
13158:
1.957 raeburn 13159: =item $type
13160:
13161: =item $locktype
13162:
13163: =item $cid
13164:
13165: =item $selfenroll
13166:
13167: =item $context
13168:
1.1216 raeburn 13169: =item $credits, number of credits student will earn from this class
13170:
1.297 matthew 13171: =back
13172:
1.191 harris41 13173:
13174: =item *
13175:
1.243 albertel 13176: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13177: custom role; give a custom role to a user for the level given by URL. Specify
13178: name and domain of role author, and role name
1.191 harris41 13179:
13180: =item *
13181:
1.243 albertel 13182: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13183:
13184: =item *
13185:
1.243 albertel 13186: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13187:
13188: =back
13189:
13190: =head2 Course Infomation
13191:
13192: =over 4
1.191 harris41 13193:
13194: =item *
13195:
1.1118 foxr 13196: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13197: specified course id, including all environment settings for the
13198: course, the description of the course will be in the hash under the
13199: key 'description'
1.191 harris41 13200:
1.1118 foxr 13201: $options is an optional parameter that if supplied is a hash reference that controls
13202: what how this function works. It has the following key/values:
13203:
13204: =over 4
13205:
13206: =item freshen_cache
13207:
13208: If defined, and the environment cache for the course is valid, it is
13209: returned in the returned hash.
13210:
13211: =item one_time
13212:
13213: If defined, the last cache time is set to _now_
13214:
13215: =item user
13216:
13217: If defined, the supplied username is used instead of the current user.
13218:
13219:
13220: =back
13221:
1.191 harris41 13222: =item *
13223:
1.624 albertel 13224: resdata($name,$domain,$type,@which) : request for current parameter
13225: setting for a specific $type, where $type is either 'course' or 'user',
13226: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 13227: answers for 10 minutes.
1.243 albertel 13228:
1.877 foxr 13229: =item *
13230:
13231: get_courseresdata($courseid, $domain) : dump the entire course resource
13232: data base, returning a hash that is keyed by the resource name and has
13233: values that are the resource value. I believe that the timestamps and
13234: versions are also returned.
13235:
1.1236 raeburn 13236: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13237: supplemental content area. This routine caches the number of files for
13238: 10 minutes.
13239:
1.243 albertel 13240: =back
13241:
13242: =head2 Course Modification
13243:
13244: =over 4
1.191 harris41 13245:
13246: =item *
13247:
1.243 albertel 13248: writecoursepref($courseid,%prefs) : write preferences (environment
13249: database) for a course
1.191 harris41 13250:
13251: =item *
13252:
1.1011 raeburn 13253: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13254:
13255: =item *
13256:
1.1038 raeburn 13257: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13258:
1.1167 droeschl 13259: =item *
13260:
13261: is_course($courseid), is_course($cdom, $cnum)
13262:
13263: Accepts either a combined $courseid (in the form of domain_courseid) or the
13264: two component version $cdom, $cnum. It checks if the specified course exists.
13265:
13266: Returns:
13267: undef if the course doesn't exist, otherwise
13268: in scalar context the combined courseid.
13269: in list context the two components of the course identifier, domain and
13270: courseid.
13271:
1.243 albertel 13272: =back
13273:
13274: =head2 Resource Subroutines
13275:
13276: =over 4
1.191 harris41 13277:
13278: =item *
13279:
1.243 albertel 13280: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13281:
13282: =item *
13283:
1.243 albertel 13284: repcopy($filename) : subscribes to the requested file, and attempts to
13285: replicate from the owning library server, Might return
1.607 raeburn 13286: 'unavailable', 'not_found', 'forbidden', 'ok', or
13287: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13288: resource. Expects the local filesystem pathname
13289: (/home/httpd/html/res/....)
13290:
13291: =back
13292:
13293: =head2 Resource Information
13294:
13295: =over 4
1.191 harris41 13296:
13297: =item *
13298:
1.1228 raeburn 13299: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13300: and returns the value of a variety of different possible values,
13301: $varname should be a request string, and the other parameters can be
13302: used to specify who and what one is asking about. Ordinarily, $cid
13303: does not need to be specified, as it is retrived from
13304: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13305: within lonuserstate::loadmap() when initializing a course, before
13306: $env{'request.course.id'} has been set, so it needs to be provided
13307: in that one case.
1.243 albertel 13308:
13309: Possible values for $varname are environment.lastname (or other item
13310: from the envirnment hash), user.name (or someother aspect about the
13311: user), resource.0.maxtries (or some other part and parameter of a
13312: resource)
1.204 albertel 13313:
13314: =item *
13315:
1.243 albertel 13316: directcondval($number) : get current value of a condition; reads from a state
13317: string
1.204 albertel 13318:
13319: =item *
13320:
1.243 albertel 13321: condval($condidx) : value of condition index based on state
1.204 albertel 13322:
13323: =item *
13324:
1.243 albertel 13325: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13326: resource's metadata, $what should be either a specific key, or either
13327: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13328: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13329:
13330: this function automatically caches all requests
1.191 harris41 13331:
13332: =item *
13333:
1.243 albertel 13334: metadata_query($query,$custom,$customshow) : make a metadata query against the
13335: network of library servers; returns file handle of where SQL and regex results
13336: will be stored for query
1.191 harris41 13337:
13338: =item *
13339:
1.243 albertel 13340: symbread($filename) : return symbolic list entry (filename argument optional);
13341: returns the data handle
1.191 harris41 13342:
13343: =item *
13344:
1.1190 raeburn 13345: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13346: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13347: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13348: on failure, user must be in a course, as it assumes the existence of
13349: the course initial hash, and uses $env('request.course.id'}. The third
13350: arg is an optional reference to a scalar. If this arg is passed in the
13351: call to symbverify, it will be set to 1 if the symb has been set to be
13352: encrypted; otherwise it will be null.
1.191 harris41 13353:
13354: =item *
13355:
1.243 albertel 13356: symbclean($symb) : removes versions numbers from a symb, returns the
13357: cleaned symb
1.191 harris41 13358:
13359: =item *
13360:
1.243 albertel 13361: is_on_map($uri) : checks if the $uri is somewhere on the current
13362: course map, user must be in a course for it to work.
1.191 harris41 13363:
13364: =item *
13365:
1.243 albertel 13366: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13367:
13368: =item *
13369:
1.243 albertel 13370: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13371: a random seed, all arguments are optional, if they aren't sent it uses the
13372: environment to derive them. Note: if symb isn't sent and it can't get one
13373: from &symbread it will use the current time as its return value
1.191 harris41 13374:
13375: =item *
13376:
1.243 albertel 13377: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13378: unfakeable, receipt
1.191 harris41 13379:
13380: =item *
13381:
1.620 albertel 13382: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13383:
13384: =item *
13385:
1.243 albertel 13386: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13387:
13388: =item *
13389:
1.243 albertel 13390: 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 13391:
13392: =item *
13393:
1.243 albertel 13394: 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 13395:
13396: =item *
13397:
1.243 albertel 13398: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13399:
13400: =item *
13401:
1.243 albertel 13402: devalidate($symb) : devalidate temporary spreadsheet calculations,
13403: forcing spreadsheet to reevaluate the resource scores next time.
13404:
1.1195 raeburn 13405: =item *
13406:
1.1196 raeburn 13407: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13408: when viewing in course context.
1.1195 raeburn 13409:
1.1196 raeburn 13410: input: six args -- filename (decluttered), course number, course domain,
13411: url, symb (if registered) and group (if this is a
13412: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13413:
1.1196 raeburn 13414: output: array of five scalars --
1.1195 raeburn 13415: $cfile -- url for file editing if editable on current server
13416: $home -- homeserver of resource (i.e., for author if published,
13417: or course if uploaded.).
13418: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13419: $forceedit -- 1 if icon/link should be to go to edit mode
13420: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13421:
13422: =item *
13423:
13424: is_course_upload($file,$cnum,$cdom)
13425:
13426: Used in course context to determine if current file was uploaded to
13427: the course (i.e., would be found in /userfiles/docs on the course's
13428: homeserver.
13429:
13430: input: 3 args -- filename (decluttered), course number and course domain.
13431: output: boolean -- 1 if file was uploaded.
13432:
1.243 albertel 13433: =back
13434:
13435: =head2 Storing/Retreiving Data
13436:
13437: =over 4
1.191 harris41 13438:
13439: =item *
13440:
1.1269 raeburn 13441: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13442: permanently for this url; hashref needs to be given and should be a \%hashname;
13443: the remaining args aren't required and if they aren't passed or are '' they will
13444: be derived from the env (with the exception of $laststore, which is an
13445: optional arg used when a user's submission is stored in grading).
13446: $laststore is $version=$timestamp, where $version is the most recent version
13447: number retrieved for the corresponding $symb in the $namespace db file, and
13448: $timestamp is the timestamp for that transaction (UNIX time).
13449: $laststore is currently only passed when cstore() is called by
13450: structuretags::finalize_storage().
1.191 harris41 13451:
13452: =item *
13453:
1.1269 raeburn 13454: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13455: but uses critical subroutine
1.191 harris41 13456:
13457: =item *
13458:
1.243 albertel 13459: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13460: all args are optional
1.191 harris41 13461:
13462: =item *
13463:
1.717 albertel 13464: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13465: dumps the complete (or key matching regexp) namespace into a hash
13466: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13467: normally &store()ed into
13468:
13469: $range should be either an integer '100' (give me the first 100
13470: matching records)
13471: or be two integers sperated by a - with no spaces
13472: '30-50' (give me the 30th through the 50th matching
13473: records)
13474:
13475:
13476: =item *
13477:
1.1269 raeburn 13478: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13479: replaces a &store() version of data with a replacement set of data
13480: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 13481: reference. If $tolog is true, the transaction is logged in the courselog
13482: with an action=PUTSTORE.
1.717 albertel 13483:
13484: =item *
13485:
1.243 albertel 13486: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13487: works very similar to store/cstore, but all data is stored in a
13488: temporary location and can be reset using tmpreset, $storehash should
13489: be a hash reference, returns nothing on success
1.191 harris41 13490:
13491: =item *
13492:
1.243 albertel 13493: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13494: similar to restore, but all data is stored in a temporary location and
13495: can be reset using tmpreset. Returns a hash of values on success,
13496: error string otherwise.
1.191 harris41 13497:
13498: =item *
13499:
1.243 albertel 13500: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13501: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13502:
13503: =item *
13504:
1.243 albertel 13505: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13506: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13507:
13508: =item *
13509:
1.243 albertel 13510: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13511: namesp ($udom and $uname are optional)
1.191 harris41 13512:
13513: =item *
13514:
1.702 albertel 13515: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13516: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13517: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13518:
1.702 albertel 13519: $range should be either an integer '100' (give me the first 100
13520: matching records)
13521: or be two integers sperated by a - with no spaces
13522: '30-50' (give me the 30th through the 50th matching
13523: records)
1.449 matthew 13524: =item *
13525:
13526: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13527: $store can be a scalar, an array reference, or if the amount to be
13528: incremented is > 1, a hash reference.
13529:
13530: ($udom and $uname are optional)
1.191 harris41 13531:
13532: =item *
13533:
1.243 albertel 13534: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13535: ($udom and $uname are optional)
1.191 harris41 13536:
13537: =item *
13538:
1.243 albertel 13539: cput($namespace,$storehash,$udom,$uname) : critical put
13540: ($udom and $uname are optional)
1.191 harris41 13541:
13542: =item *
13543:
1.748 albertel 13544: newput($namespace,$storehash,$udom,$uname) :
13545:
13546: Attempts to store the items in the $storehash, but only if they don't
13547: currently exist, if this succeeds you can be certain that you have
13548: successfully created a new key value pair in the $namespace db.
13549:
13550:
13551: Args:
13552: $namespace: name of database to store values to
13553: $storehash: hashref to store to the db
13554: $udom: (optional) domain of user containing the db
13555: $uname: (optional) name of user caontaining the db
13556:
13557: Returns:
13558: 'ok' -> succeeded in storing all keys of $storehash
13559: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13560: least <key> already existed in the db (other
13561: requested keys may also already exist)
1.967 bisitz 13562: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13563: 'con_lost' -> unable to contact request server
13564: 'refused' -> action was not allowed by remote machine
13565:
13566:
13567: =item *
13568:
1.243 albertel 13569: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13570: reference filled in from namesp (encrypts the return communication)
13571: ($udom and $uname are optional)
1.191 harris41 13572:
13573: =item *
13574:
1.243 albertel 13575: log($udom,$name,$home,$message) : write to permanent log for user; use
13576: critical subroutine
13577:
1.806 raeburn 13578: =item *
13579:
1.860 raeburn 13580: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13581: array reference filled in from namespace found in domain level on either
13582: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13583:
13584: =item *
13585:
1.860 raeburn 13586: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13587: domain level either on specified domain server ($uhome) or primary domain
13588: server ($udom and $uhome are optional)
1.806 raeburn 13589:
1.943 raeburn 13590: =item *
13591:
1.1240 raeburn 13592: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13593: for: authentication, language, quotas, timezone, date locale, and portal URL in
13594: the target domain.
13595:
13596: May also include additional key => value pairs for the following groups:
13597:
13598: =over
13599:
13600: =item
13601: disk quotas (MB allocated by default to portfolios and authoring spaces).
13602:
13603: =over
13604:
13605: =item defaultquota, authorquota
13606:
13607: =back
13608:
13609: =item
13610: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13611: portfolio for users).
13612:
13613: =over
13614:
13615: =item
13616: aboutme, blog, webdav, portfolio
13617:
13618: =back
13619:
13620: =item
13621: requestcourses: ability to request courses, and how requests are processed.
13622:
13623: =over
13624:
13625: =item
1.1246 raeburn 13626: official, unofficial, community, textbook
1.1240 raeburn 13627:
13628: =back
13629:
13630: =item
13631: inststatus: types of institutional affiliation, and order in which they are displayed.
13632:
13633: =over
13634:
13635: =item
1.1256 raeburn 13636: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 13637:
13638: =back
13639:
13640: =item
13641: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13642: for course's uploaded content.
13643:
13644: =over
13645:
13646: =item
1.1246 raeburn 13647: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13648: communityquota, textbookquota
1.1240 raeburn 13649:
13650: =back
13651:
13652: =item
13653: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13654: on your servers.
13655:
13656: =over
13657:
13658: =item
13659: remotesessions, hostedsessions
13660:
13661: =back
13662:
13663: =back
13664:
13665: In cases where a domain coordinator has never used the "Set Domain Configuration"
13666: utility to create a configuration.db file on a domain's primary library server
13667: only the following domain defaults: auth_def, auth_arg_def, lang_def
13668: -- corresponding values are authentication type (internal, krb4, krb5,
13669: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13670: will be available. Values are retrieved from cache (if current), unless the
13671: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13672: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13673:
13674: Typical usage:
1.943 raeburn 13675:
1.1240 raeburn 13676: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13677:
1.243 albertel 13678: =back
13679:
13680: =head2 Network Status Functions
13681:
13682: =over 4
1.191 harris41 13683:
13684: =item *
13685:
1.1137 raeburn 13686: dirlist() : return directory list based on URI (first arg).
13687:
13688: Inputs: 1 required, 5 optional.
13689:
13690: =over
13691:
13692: =item
13693: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13694:
13695: =item
13696: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13697:
13698: =item
13699: $username - username of user/course to be listed. Extracted from $uri if absent.
13700:
13701: =item
13702: $getpropath - boolean: 1 if prepend path using &propath().
13703:
13704: =item
13705: $getuserdir - boolean: 1 if prepend path for "userfiles".
13706:
13707: =item
13708: $alternateRoot - path to prepend in place of path from $uri.
13709:
13710: =back
13711:
13712: Returns: Array of up to two items.
13713:
13714: =over
13715:
13716: a reference to an array of files/subdirectories
13717:
13718: =over
13719:
13720: Each element in the array of files/subdirectories is a & separated list of
13721: item name and the result of running stat on the item. If dirlist was requested
13722: for a file instead of a directory, the item name will be ''. For a directory
13723: listing, if the item is a metadata file, the element will end &N&M
13724: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13725: default copyright set (1).
13726:
13727: =back
13728:
13729: a scalar containing error condition (if encountered).
13730:
13731: =over
13732:
13733: =item
13734: no_host (no homeserver identified for $username:$domain).
13735:
13736: =item
13737: no_such_host (server contacted for listing not identified as valid host).
13738:
13739: =item
13740: con_lost (connection to remote server failed).
13741:
13742: =item
13743: refused (invalid $username:$domain received on lond side).
13744:
13745: =item
13746: no_such_dir (directory at specified path on lond side does not exist).
13747:
13748: =item
13749: empty (directory at specified path on lond side is empty).
13750:
13751: =over
13752:
13753: This is currently not encountered because the &ls3, &ls2,
13754: &ls (_handler) routines on the lond side do not filter out
13755: . and .. from a directory listing.
13756:
13757: =back
13758:
13759: =back
13760:
13761: =back
1.191 harris41 13762:
13763: =item *
13764:
1.243 albertel 13765: spareserver() : find server with least workload from spare.tab
13766:
1.986 foxr 13767:
13768: =item *
13769:
13770: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13771: if there is no corresponding loncapa host.
13772:
1.243 albertel 13773: =back
13774:
1.986 foxr 13775:
1.243 albertel 13776: =head2 Apache Request
13777:
13778: =over 4
1.191 harris41 13779:
13780: =item *
13781:
1.243 albertel 13782: ssi($url,%hash) : server side include, does a complete request cycle on url to
13783: localhost, posts hash
13784:
13785: =back
13786:
13787: =head2 Data to String to Data
13788:
13789: =over 4
1.191 harris41 13790:
13791: =item *
13792:
1.243 albertel 13793: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13794: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13795:
13796: =item *
13797:
1.243 albertel 13798: hashref2str($hashref) : convert a hashref into a string complete with
13799: escaping and '=' and '&' separators, supports elements that are
13800: arrayrefs and hashrefs
1.191 harris41 13801:
13802: =item *
13803:
1.243 albertel 13804: arrayref2str($arrayref) : convert an arrayref into a string complete
13805: with escaping and '&' separators, supports elements that are arrayrefs
13806: and hashrefs
1.191 harris41 13807:
13808: =item *
13809:
1.243 albertel 13810: str2hash($string) : convert string to hash using unescaping and
13811: splitting on '=' and '&', supports elements that are arrayrefs and
13812: hashrefs
1.191 harris41 13813:
13814: =item *
13815:
1.243 albertel 13816: str2array($string) : convert string to hash using unescaping and
13817: splitting on '&', supports elements that are arrayrefs and hashrefs
13818:
13819: =back
13820:
13821: =head2 Logging Routines
13822:
13823:
13824: These routines allow one to make log messages in the lonnet.log and
13825: lonnet.perm logfiles.
1.191 harris41 13826:
1.1119 foxr 13827: =over 4
13828:
1.191 harris41 13829: =item *
13830:
1.243 albertel 13831: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13832:
13833: =item *
13834:
1.243 albertel 13835: logthis() : append message to the normal lonnet.log file, it gets
13836: preiodically rolled over and deleted.
1.191 harris41 13837:
13838: =item *
13839:
1.243 albertel 13840: logperm() : append a permanent message to lonnet.perm.log, this log
13841: file never gets deleted by any automated portion of the system, only
13842: messages of critical importance should go in here.
13843:
1.1119 foxr 13844:
1.243 albertel 13845: =back
13846:
13847: =head2 General File Helper Routines
13848:
13849: =over 4
1.191 harris41 13850:
13851: =item *
13852:
1.481 raeburn 13853: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13854: (a) files in /uploaded
13855: (i) If a local copy of the file exists -
13856: compares modification date of local copy with last-modified date for
13857: definitive version stored on home server for course. If local copy is
13858: stale, requests a new version from the home server and stores it.
13859: If the original has been removed from the home server, then local copy
13860: is unlinked.
13861: (ii) If local copy does not exist -
13862: requests the file from the home server and stores it.
13863:
13864: If $caller is 'uploadrep':
13865: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13866: for request for files originally uploaded via DOCS.
13867: - returns 'ok' if fresh local copy now available, -1 otherwise.
13868:
13869: Otherwise:
13870: This indicates a call from the content generation phase of the request.
13871: - returns the entire contents of the file or -1.
13872:
13873: (b) files in /res
13874: - returns the entire contents of a file or -1;
13875: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13876:
1.712 albertel 13877:
13878: =item *
13879:
13880: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13881: reference
13882:
13883: returns either a stat() list of data about the file or an empty list
13884: if the file doesn't exist or couldn't find out about it (connection
13885: problems or user unknown)
13886:
1.191 harris41 13887: =item *
13888:
1.243 albertel 13889: filelocation($dir,$file) : returns file system location of a file
13890: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13891: directory that relative $file lookups are to looked in ($dir of /a/dir
13892: and a file of ../bob will become /a/bob)
1.191 harris41 13893:
13894: =item *
13895:
13896: hreflocation($dir,$file) : returns file system location or a URL; same as
13897: filelocation except for hrefs
13898:
13899: =item *
13900:
1.1261 raeburn 13901: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13902: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 13903:
1.243 albertel 13904: =back
13905:
1.608 albertel 13906: =head2 Usererfile file routines (/uploaded*)
13907:
13908: =over 4
13909:
13910: =item *
13911:
13912: userfileupload(): main rotine for putting a file in a user or course's
13913: filespace, arguments are,
13914:
1.620 albertel 13915: formname - required - this is the name of the element in $env where the
1.608 albertel 13916: filename, and the contents of the file to create/modifed exist
1.620 albertel 13917: the filename is in $env{'form.'.$formname.'.filename'} and the
13918: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13919: context - if coursedoc, store the file in the course of the active role
13920: of the current user;
13921: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13922: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13923: subdir - required - subdirectory to put the file in under ../userfiles/
13924: if undefined, it will be placed in "unknown"
13925:
13926: (This routine calls clean_filename() to remove any dangerous
13927: characters from the filename, and then calls finuserfileupload() to
13928: complete the transaction)
13929:
13930: returns either the url of the uploaded file (/uploaded/....) if successful
13931: and /adm/notfound.html if unsuccessful
13932:
13933: =item *
13934:
13935: clean_filename(): routine for cleaing a filename up for storage in
13936: userfile space, argument is:
13937:
13938: filename - proposed filename
13939:
13940: returns: the new clean filename
13941:
13942: =item *
13943:
1.1090 raeburn 13944: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13945: userspace, probably shouldn't be called directly
13946:
13947: docuname: username or courseid of destination for the file
13948: docudom: domain of user/course of destination for the file
13949: formname: same as for userfileupload()
1.1090 raeburn 13950: fname: filename (including subdirectories) for the file
13951: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13952: allfiles: reference to hash used to store objects found by parser
13953: codebase: reference to hash used for codebases of java objects found by parser
13954: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13955: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13956: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13957: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13958: context: if 'overwrite', will move the uploaded file from its temporary location to
13959: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13960: mimetype: reference to scalar to accommodate mime type determined
13961: from File::MMagic if $parser = parse.
1.608 albertel 13962:
13963: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13964: and /adm/notfound.html if unsuccessful (or an error message if context
13965: was 'overwrite').
13966:
1.608 albertel 13967:
13968: =item *
13969:
13970: renameuserfile(): renames an existing userfile to a new name
13971:
13972: Args:
13973: docuname: username or courseid of destination for the file
13974: docudom: domain of user/course of destination for the file
13975: old: current file name (including any subdirs under userfiles)
13976: new: desired file name (including any subdirs under userfiles)
13977:
13978: =item *
13979:
13980: mkdiruserfile(): creates a directory is a userfiles dir
13981:
13982: Args:
13983: docuname: username or courseid of destination for the file
13984: docudom: domain of user/course of destination for the file
13985: dir: dir to create (including any subdirs under userfiles)
13986:
13987: =item *
13988:
13989: removeuserfile(): removes a file that exists in userfiles
13990:
13991: Args:
13992: docuname: username or courseid of destination for the file
13993: docudom: domain of user/course of destination for the file
13994: fname: filname to delete (including any subdirs under userfiles)
13995:
13996: =item *
13997:
13998: removeuploadedurl(): convience function for removeuserfile()
13999:
14000: Args:
14001: url: a full /uploaded/... url to delete
14002:
1.747 albertel 14003: =item *
14004:
14005: get_portfile_permissions():
14006: Args:
14007: domain: domain of user or course contain the portfolio files
14008: user: name of user or num of course contain the portfolio files
14009: Returns:
14010: hashref of a dump of the proper file_permissions.db
14011:
14012:
14013: =item *
14014:
14015: get_access_controls():
14016:
14017: Args:
14018: current_permissions: the hash ref returned from get_portfile_permissions()
14019: group: (optional) the group you want the files associated with
14020: file: (optional) the file you want access info on
14021:
14022: Returns:
1.749 raeburn 14023: a hash (keys are file names) of hashes containing
14024: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14025: values are XML containing access control settings (see below)
1.747 albertel 14026:
14027: Internal notes:
14028:
1.749 raeburn 14029: access controls are stored in file_permissions.db as key=value pairs.
14030: key -> path to file/file_name\0uniqueID:scope_end_start
14031: where scope -> public,guest,course,group,domains or users.
14032: end -> UNIX time for end of access (0 -> no end date)
14033: start -> UNIX time for start of access
14034:
14035: value -> XML description of access control
14036: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14037: <start></start>
14038: <end></end>
14039:
14040: <password></password> for scope type = guest
14041:
14042: <domain></domain> for scope type = course or group
14043: <number></number>
14044: <roles id="">
14045: <role></role>
14046: <access></access>
14047: <section></section>
14048: <group></group>
14049: </roles>
14050:
14051: <dom></dom> for scope type = domains
14052:
14053: <users> for scope type = users
14054: <user>
14055: <uname></uname>
14056: <udom></udom>
14057: </user>
14058: </users>
14059: </scope>
14060:
14061: Access data is also aggregated for each file in an additional key=value pair:
14062: key -> path to file/file_name\0accesscontrol
14063: value -> reference to hash
14064: hash contains key = value pairs
14065: where key = uniqueID:scope_end_start
14066: value = UNIX time record was last updated
14067:
14068: Used to improve speed of look-ups of access controls for each file.
14069:
14070: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14071:
1.1198 raeburn 14072: =item *
14073:
1.749 raeburn 14074: modify_access_controls():
14075:
14076: Modifies access controls for a portfolio file
14077: Args
14078: 1. file name
14079: 2. reference to hash of required changes,
14080: 3. domain
14081: 4. username
14082: where domain,username are the domain of the portfolio owner
14083: (either a user or a course)
14084:
14085: Returns:
14086: 1. result of additions or updates ('ok' or 'error', with error message).
14087: 2. result of deletions ('ok' or 'error', with error message).
14088: 3. reference to hash of any new or updated access controls.
14089: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14090: key = integer (inbound ID)
1.1198 raeburn 14091: value = uniqueID
14092:
14093: =item *
14094:
14095: get_timebased_id():
14096:
14097: Attempts to get a unique timestamp-based suffix for use with items added to a
14098: course via the Course Editor (e.g., folders, composite pages,
14099: group bulletin boards).
14100:
14101: Args: (first three required; six others optional)
14102:
14103: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14104: docssequence, or name of group
14105:
14106: 2. keyid (alphanumeric): name of temporary locking key in hash,
14107: e.g., num, boardids
14108:
14109: 3. namespace: name of gdbm file used to store suffixes already assigned;
14110: file will be named nohist_namespace.db
14111:
14112: 4. cdom: domain of course; default is current course domain from %env
14113:
14114: 5. cnum: course number; default is current course number from %env
14115:
14116: 6. idtype: set to concat if an additional digit is to be appended to the
14117: unix timestamp to form the suffix, if the plain timestamp is already
14118: in use. Default is to not do this, but simply increment the unix
14119: timestamp by 1 until a unique key is obtained.
14120:
14121: 7. who: holder of locking key; defaults to user:domain for user.
14122:
14123: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14124: retrying); default is 3.
14125:
14126: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14127:
14128: Returns:
14129:
14130: 1. suffix obtained (numeric)
14131:
14132: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14133:
14134: 3. error: contains (localized) error message if an error occurred.
14135:
1.747 albertel 14136:
1.608 albertel 14137: =back
14138:
1.243 albertel 14139: =head2 HTTP Helper Routines
14140:
14141: =over 4
14142:
1.191 harris41 14143: =item *
14144:
14145: escape() : unpack non-word characters into CGI-compatible hex codes
14146:
14147: =item *
14148:
14149: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14150:
1.243 albertel 14151: =back
14152:
14153: =head1 PRIVATE SUBROUTINES
14154:
14155: =head2 Underlying communication routines (Shouldn't call)
14156:
14157: =over 4
14158:
14159: =item *
14160:
14161: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14162:
14163: =item *
14164:
14165: reply() : uses subreply to send a message to remote machine, logs all failures
14166:
14167: =item *
14168:
14169: critical() : passes a critical message to another server; if cannot
14170: get through then place message in connection buffer directory and
14171: returns con_delayed, if incapable of saving message, returns
14172: con_failed
14173:
14174: =item *
14175:
14176: reconlonc() : tries to reconnect lonc client processes.
14177:
14178: =back
14179:
14180: =head2 Resource Access Logging
14181:
14182: =over 4
14183:
14184: =item *
14185:
14186: flushcourselogs() : flush (save) buffer logs and access logs
14187:
14188: =item *
14189:
14190: courselog($what) : save message for course in hash
14191:
14192: =item *
14193:
14194: courseacclog($what) : save message for course using &courselog(). Perform
14195: special processing for specific resource types (problems, exams, quizzes, etc).
14196:
1.191 harris41 14197: =item *
14198:
14199: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14200: as a PerlChildExitHandler
1.243 albertel 14201:
14202: =back
14203:
14204: =head2 Other
14205:
14206: =over 4
14207:
14208: =item *
14209:
14210: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14211:
14212: =back
14213:
14214: =cut
1.877 foxr 14215:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>