Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1277
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1277 ! raeburn 4: # $Id: lonnet.pm,v 1.1276 2014/12/21 16:26:36 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.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;
1182: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1183: if (ref($internet_names) eq 'ARRAY') {
1184: @intdoms = @{$internet_names};
1185: }
1186: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1187: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1188: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1189: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1190: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1191: $canhost = &can_host_session($udom,$try_server,$remoterev,
1192: $remotesessions,
1193: $defdomdefaults{'hostedsessions'});
1194: }
1195: return $canhost;
1196: }
1197:
1.1123 raeburn 1198: sub this_host_spares {
1199: my ($dom) = @_;
1.1126 raeburn 1200: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1201: my @hosts = ¤t_machine_ids();
1202: foreach my $lonhost (@hosts) {
1203: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1204: $dom_in_use = $dom;
1205: $lonhost_in_use = $lonhost;
1.1123 raeburn 1206: last;
1207: }
1208: }
1.1126 raeburn 1209: if ($dom_in_use ne '') {
1210: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1211: }
1212: if (ref($result) ne 'HASH') {
1213: $lonhost_in_use = $perlvar{'lonHostID'};
1214: $dom_in_use = &host_domain($lonhost_in_use);
1215: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1216: if (ref($result) ne 'HASH') {
1217: $result = \%spareid;
1218: }
1219: }
1220: return $result;
1221: }
1222:
1223: sub spares_for_offload {
1224: my ($dom_in_use,$lonhost_in_use) = @_;
1225: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1226: if (defined($cached)) {
1227: return $result;
1228: } else {
1.1126 raeburn 1229: my $cachetime = 60*60*24;
1230: my %domconfig =
1231: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1232: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1233: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1234: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1235: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1236: }
1237: }
1238: }
1239: }
1.1126 raeburn 1240: return;
1.1123 raeburn 1241: }
1242:
1.1129 raeburn 1243: sub get_lonbalancer_config {
1244: my ($servers) = @_;
1245: my ($currbalancer,$currtargets);
1246: if (ref($servers) eq 'HASH') {
1247: foreach my $server (keys(%{$servers})) {
1248: my %what = (
1249: spareid => 1,
1250: perlvar => 1,
1251: );
1252: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1253: if ($result eq 'ok') {
1254: if (ref($returnhash) eq 'HASH') {
1255: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1256: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1257: $currbalancer = $server;
1258: $currtargets = {};
1259: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1260: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1261: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1262: }
1263: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1264: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1265: }
1266: }
1267: last;
1268: }
1269: }
1270: }
1271: }
1272: }
1273: }
1274: return ($currbalancer,$currtargets);
1275: }
1276:
1277: sub check_loadbalancing {
1278: my ($uname,$udom) = @_;
1.1191 raeburn 1279: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1280: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1281: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1282: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1283: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1284: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1285: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1286: my $serverhomedom = &host_domain($lonhost);
1287:
1288: my $cachetime = 60*60*24;
1289:
1290: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1291: $dom_in_use = $udom;
1292: $homeintdom = 1;
1293: } else {
1294: $dom_in_use = $serverhomedom;
1295: }
1296: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1297: unless (defined($cached)) {
1298: my %domconfig =
1299: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1300: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1301: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1302: }
1303: }
1304: if (ref($result) eq 'HASH') {
1.1191 raeburn 1305: ($is_balancer,$currtargets,$currrules) =
1306: &check_balancer_result($result,@hosts);
1.1129 raeburn 1307: if ($is_balancer) {
1308: if (ref($currrules) eq 'HASH') {
1309: if ($homeintdom) {
1310: if ($uname ne '') {
1311: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1312: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1313: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1314: $rule_in_effect = $currrules->{'_LC_author'};
1315: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1316: $rule_in_effect = $currrules->{'_LC_adv'}
1317: }
1318: }
1319: if ($rule_in_effect eq '') {
1320: my %userenv = &userenvironment($udom,$uname,'inststatus');
1321: if ($userenv{'inststatus'} ne '') {
1322: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1323: my ($othertitle,$usertypes,$types) =
1324: &Apache::loncommon::sorted_inst_types($udom);
1325: if (ref($types) eq 'ARRAY') {
1326: foreach my $type (@{$types}) {
1327: if (grep(/^\Q$type\E$/,@statuses)) {
1328: if (exists($currrules->{$type})) {
1329: $rule_in_effect = $currrules->{$type};
1330: }
1331: }
1332: }
1333: }
1334: } else {
1335: if (exists($currrules->{'default'})) {
1336: $rule_in_effect = $currrules->{'default'};
1337: }
1338: }
1339: }
1340: } else {
1341: if (exists($currrules->{'default'})) {
1342: $rule_in_effect = $currrules->{'default'};
1343: }
1344: }
1345: } else {
1346: if ($currrules->{'_LC_external'} ne '') {
1347: $rule_in_effect = $currrules->{'_LC_external'};
1348: }
1349: }
1350: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1351: $uname,$udom);
1352: }
1353: }
1354: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1355: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1356: unless (defined($cached)) {
1357: my %domconfig =
1358: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1359: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1360: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1361: }
1362: }
1363: if (ref($result) eq 'HASH') {
1.1191 raeburn 1364: ($is_balancer,$currtargets,$currrules) =
1365: &check_balancer_result($result,@hosts);
1366: if ($is_balancer) {
1.1129 raeburn 1367: if (ref($currrules) eq 'HASH') {
1368: if ($currrules->{'_LC_internetdom'} ne '') {
1369: $rule_in_effect = $currrules->{'_LC_internetdom'};
1370: }
1371: }
1372: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1373: $uname,$udom);
1374: }
1375: } else {
1376: if ($perlvar{'lonBalancer'} eq 'yes') {
1377: $is_balancer = 1;
1378: $offloadto = &this_host_spares($dom_in_use);
1379: }
1380: }
1381: } else {
1382: if ($perlvar{'lonBalancer'} eq 'yes') {
1383: $is_balancer = 1;
1384: $offloadto = &this_host_spares($dom_in_use);
1385: }
1386: }
1.1176 raeburn 1387: if ($is_balancer) {
1388: my $lowest_load = 30000;
1389: if (ref($offloadto) eq 'HASH') {
1390: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1391: foreach my $try_server (@{$offloadto->{'primary'}}) {
1392: ($otherserver,$lowest_load) =
1393: &compare_server_load($try_server,$otherserver,$lowest_load);
1394: }
1.1129 raeburn 1395: }
1.1176 raeburn 1396: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1397:
1.1176 raeburn 1398: if (!$found_server) {
1399: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1400: foreach my $try_server (@{$offloadto->{'default'}}) {
1401: ($otherserver,$lowest_load) =
1402: &compare_server_load($try_server,$otherserver,$lowest_load);
1403: }
1404: }
1405: }
1406: } elsif (ref($offloadto) eq 'ARRAY') {
1407: if (@{$offloadto} == 1) {
1408: $otherserver = $offloadto->[0];
1409: } elsif (@{$offloadto} > 1) {
1410: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1411: ($otherserver,$lowest_load) =
1412: &compare_server_load($try_server,$otherserver,$lowest_load);
1413: }
1414: }
1415: }
1.1176 raeburn 1416: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1417: $is_balancer = 0;
1418: if ($uname ne '' && $udom ne '') {
1419: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1420:
1421: &appenv({'user.loadbalexempt' => $lonhost,
1422: 'user.loadbalcheck.time' => time});
1423: }
1.1129 raeburn 1424: }
1425: }
1426: }
1427: return ($is_balancer,$otherserver);
1428: }
1429:
1.1191 raeburn 1430: sub check_balancer_result {
1431: my ($result,@hosts) = @_;
1432: my ($is_balancer,$currtargets,$currrules);
1433: if (ref($result) eq 'HASH') {
1434: if ($result->{'lonhost'} ne '') {
1435: my $currbalancer = $result->{'lonhost'};
1436: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1437: $is_balancer = 1;
1438: $currtargets = $result->{'targets'};
1439: $currrules = $result->{'rules'};
1440: }
1441: } else {
1442: foreach my $key (keys(%{$result})) {
1443: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1444: (ref($result->{$key}) eq 'HASH')) {
1445: $is_balancer = 1;
1446: $currrules = $result->{$key}{'rules'};
1447: $currtargets = $result->{$key}{'targets'};
1448: last;
1449: }
1450: }
1451: }
1452: }
1453: return ($is_balancer,$currtargets,$currrules);
1454: }
1455:
1.1129 raeburn 1456: sub get_loadbalancer_targets {
1457: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1458: my $offloadto;
1.1175 raeburn 1459: if ($rule_in_effect eq 'none') {
1460: return [$perlvar{'lonHostID'}];
1461: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1462: $offloadto = $currtargets;
1463: } else {
1464: if ($rule_in_effect eq 'homeserver') {
1465: my $homeserver = &homeserver($uname,$udom);
1466: if ($homeserver ne 'no_host') {
1467: $offloadto = [$homeserver];
1468: }
1469: } elsif ($rule_in_effect eq 'externalbalancer') {
1470: my %domconfig =
1471: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1472: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1473: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1474: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1475: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1476: }
1477: }
1478: } else {
1.1178 raeburn 1479: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1480: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1481: if (&hostname($remotebalancer) ne '') {
1482: $offloadto = [$remotebalancer];
1483: }
1484: }
1485: } elsif (&hostname($rule_in_effect) ne '') {
1486: $offloadto = [$rule_in_effect];
1487: }
1488: }
1489: return $offloadto;
1490: }
1491:
1.1127 raeburn 1492: sub internet_dom_servers {
1493: my ($dom) = @_;
1494: my (%uniqservers,%servers);
1495: my $primaryserver = &hostname(&domain($dom,'primary'));
1496: my @machinedoms = &machine_domains($primaryserver);
1497: foreach my $mdom (@machinedoms) {
1498: my %currservers = %servers;
1499: my %server = &get_servers($mdom);
1500: %servers = (%currservers,%server);
1501: }
1502: my %by_hostname;
1503: foreach my $id (keys(%servers)) {
1504: push(@{$by_hostname{$servers{$id}}},$id);
1505: }
1506: foreach my $hostname (sort(keys(%by_hostname))) {
1507: if (@{$by_hostname{$hostname}} > 1) {
1508: my $match = 0;
1509: foreach my $id (@{$by_hostname{$hostname}}) {
1510: if (&host_domain($id) eq $dom) {
1511: $uniqservers{$id} = $hostname;
1512: $match = 1;
1513: }
1514: }
1515: unless ($match) {
1516: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1517: }
1518: } else {
1519: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1520: }
1521: }
1522: return %uniqservers;
1523: }
1524:
1.1 albertel 1525: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1526:
1.599 albertel 1527: my %homecache;
1.1 albertel 1528: sub homeserver {
1.230 stredwic 1529: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1530: my $index="$uname:$udom";
1.426 albertel 1531:
1.599 albertel 1532: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1533:
1534: my %servers = &get_servers($udom,'library');
1535: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1536: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1537: exists($badServerCache{$tryserver}));
1.841 albertel 1538:
1539: my $answer=reply("home:$udom:$uname",$tryserver);
1540: if ($answer eq 'found') {
1541: delete($badServerCache{$tryserver});
1542: return $homecache{$index}=$tryserver;
1543: } elsif ($answer eq 'no_host') {
1544: $badServerCache{$tryserver}=1;
1545: }
1.1 albertel 1546: }
1547: return 'no_host';
1.70 www 1548: }
1549:
1550: # ------------------------------------- Find the usernames behind a list of IDs
1551:
1552: sub idget {
1553: my ($udom,@ids)=@_;
1554: my %returnhash=();
1555:
1.841 albertel 1556: my %servers = &get_servers($udom,'library');
1557: foreach my $tryserver (keys(%servers)) {
1558: my $idlist=join('&',@ids);
1559: $idlist=~tr/A-Z/a-z/;
1560: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1561: my @answer=();
1562: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1563: @answer=split(/\&/,$reply);
1564: } ;
1565: my $i;
1566: for ($i=0;$i<=$#ids;$i++) {
1567: if ($answer[$i]) {
1568: $returnhash{$ids[$i]}=$answer[$i];
1569: }
1570: }
1571: }
1.70 www 1572: return %returnhash;
1573: }
1574:
1575: # ------------------------------------- Find the IDs behind a list of usernames
1576:
1577: sub idrget {
1578: my ($udom,@unames)=@_;
1579: my %returnhash=();
1.800 albertel 1580: foreach my $uname (@unames) {
1581: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1582: }
1.70 www 1583: return %returnhash;
1584: }
1585:
1586: # ------------------------------- Store away a list of names and associated IDs
1587:
1588: sub idput {
1589: my ($udom,%ids)=@_;
1590: my %servers=();
1.800 albertel 1591: foreach my $uname (keys(%ids)) {
1592: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1593: my $uhom=&homeserver($uname,$udom);
1.70 www 1594: if ($uhom ne 'no_host') {
1.800 albertel 1595: my $id=&escape($ids{$uname});
1.70 www 1596: $id=~tr/A-Z/a-z/;
1.800 albertel 1597: my $esc_unam=&escape($uname);
1.70 www 1598: if ($servers{$uhom}) {
1.800 albertel 1599: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1600: } else {
1.800 albertel 1601: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1602: }
1603: }
1.191 harris41 1604: }
1.800 albertel 1605: foreach my $server (keys(%servers)) {
1606: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1607: }
1.344 www 1608: }
1609:
1.1231 raeburn 1610: # ---------------------------------------- Delete unwanted IDs from ids.db file
1611:
1612: sub iddel {
1613: my ($udom,$idshashref,$uhome)=@_;
1614: my %result=();
1615: unless (ref($idshashref) eq 'HASH') {
1616: return %result;
1617: }
1618: my %servers=();
1619: while (my ($id,$uname) = each(%{$idshashref})) {
1620: my $uhom;
1621: if ($uhome) {
1622: $uhom = $uhome;
1623: } else {
1624: $uhom=&homeserver($uname,$udom);
1625: }
1626: if ($uhom ne 'no_host') {
1627: if ($servers{$uhom}) {
1628: $servers{$uhom}.='&'.&escape($id);
1629: } else {
1630: $servers{$uhom}=&escape($id);
1631: }
1632: }
1633: }
1634: foreach my $server (keys(%servers)) {
1635: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1636: }
1637: return %result;
1638: }
1639:
1.1023 raeburn 1640: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1641: sub dump_dom {
1.1165 droeschl 1642: my ($namespace, $udom, $regexp) = @_;
1643:
1644: $udom ||= $env{'user.domain'};
1645:
1646: return () unless $udom;
1647:
1648: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1649: }
1650:
1.1023 raeburn 1651: # ------------------------------------------ get items from domain db files
1.806 raeburn 1652:
1653: sub get_dom {
1.860 raeburn 1654: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1655: return if ($udom eq 'public');
1.806 raeburn 1656: my $items='';
1657: foreach my $item (@$storearr) {
1658: $items.=&escape($item).'&';
1659: }
1660: $items=~s/\&$//;
1.860 raeburn 1661: if (!$udom) {
1662: $udom=$env{'user.domain'};
1.1267 raeburn 1663: return if ($udom eq 'public');
1.860 raeburn 1664: if (defined(&domain($udom,'primary'))) {
1665: $uhome=&domain($udom,'primary');
1666: } else {
1.874 albertel 1667: undef($uhome);
1.860 raeburn 1668: }
1669: } else {
1670: if (!$uhome) {
1671: if (defined(&domain($udom,'primary'))) {
1672: $uhome=&domain($udom,'primary');
1673: }
1674: }
1675: }
1676: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1677: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1678: my %returnhash;
1.875 albertel 1679: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1680: return %returnhash;
1681: }
1.806 raeburn 1682: my @pairs=split(/\&/,$rep);
1683: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1684: return @pairs;
1685: }
1686: my $i=0;
1687: foreach my $item (@$storearr) {
1688: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1689: $i++;
1690: }
1691: return %returnhash;
1692: } else {
1.880 banghart 1693: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1694: }
1695: }
1696:
1697: # -------------------------------------------- put items in domain db files
1698:
1699: sub put_dom {
1.860 raeburn 1700: my ($namespace,$storehash,$udom,$uhome)=@_;
1701: if (!$udom) {
1702: $udom=$env{'user.domain'};
1703: if (defined(&domain($udom,'primary'))) {
1704: $uhome=&domain($udom,'primary');
1705: } else {
1.874 albertel 1706: undef($uhome);
1.860 raeburn 1707: }
1708: } else {
1709: if (!$uhome) {
1710: if (defined(&domain($udom,'primary'))) {
1711: $uhome=&domain($udom,'primary');
1712: }
1713: }
1714: }
1715: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1716: my $items='';
1717: foreach my $item (keys(%$storehash)) {
1718: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1719: }
1720: $items=~s/\&$//;
1721: return &reply("putdom:$udom:$namespace:$items",$uhome);
1722: } else {
1.860 raeburn 1723: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1724: }
1725: }
1726:
1.1023 raeburn 1727: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1728: sub newput_dom {
1.1023 raeburn 1729: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1730: my $result;
1731: if (!$udom) {
1732: $udom=$env{'user.domain'};
1733: }
1.1023 raeburn 1734: if ($udom) {
1735: my $uname = &get_domainconfiguser($udom);
1736: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1737: }
1738: return $result;
1739: }
1740:
1.1023 raeburn 1741: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1742: sub del_dom {
1.1023 raeburn 1743: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1744: if (ref($storearr) eq 'ARRAY') {
1745: if (!$udom) {
1746: $udom=$env{'user.domain'};
1747: }
1.1023 raeburn 1748: if ($udom) {
1749: my $uname = &get_domainconfiguser($udom);
1750: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1751: }
1752: }
1753: }
1754:
1.1023 raeburn 1755: # ----------------------------------construct domainconfig user for a domain
1756: sub get_domainconfiguser {
1757: my ($udom) = @_;
1758: return $udom.'-domainconfig';
1759: }
1760:
1.837 raeburn 1761: sub retrieve_inst_usertypes {
1762: my ($udom) = @_;
1763: my (%returnhash,@order);
1.989 raeburn 1764: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1765: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1766: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1767: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1768: } else {
1769: if (defined(&domain($udom,'primary'))) {
1770: my $uhome=&domain($udom,'primary');
1771: my $rep=&reply("inst_usertypes:$udom",$uhome);
1772: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1773: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1774: return (\%returnhash,\@order);
1775: }
1776: my ($hashitems,$orderitems) = split(/:/,$rep);
1777: my @pairs=split(/\&/,$hashitems);
1778: foreach my $item (@pairs) {
1779: my ($key,$value)=split(/=/,$item,2);
1780: $key = &unescape($key);
1781: next if ($key =~ /^error: 2 /);
1782: $returnhash{$key}=&thaw_unescape($value);
1783: }
1784: my @esc_order = split(/\&/,$orderitems);
1785: foreach my $item (@esc_order) {
1786: push(@order,&unescape($item));
1787: }
1788: } else {
1.1256 raeburn 1789: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1790: }
1.1256 raeburn 1791: return (\%returnhash,\@order);
1.837 raeburn 1792: }
1793: }
1794:
1.868 raeburn 1795: sub is_domainimage {
1796: my ($url) = @_;
1797: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1798: if (&domain($1) ne '') {
1799: return '1';
1800: }
1801: }
1802: return;
1803: }
1804:
1.899 raeburn 1805: sub inst_directory_query {
1806: my ($srch) = @_;
1807: my $udom = $srch->{'srchdomain'};
1808: my %results;
1809: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1810: my $outcome;
1.899 raeburn 1811: if ($homeserver ne '') {
1.904 albertel 1812: my $queryid=&reply("querysend:instdirsearch:".
1813: &escape($srch->{'srchby'}).':'.
1814: &escape($srch->{'srchterm'}).':'.
1815: &escape($srch->{'srchtype'}),$homeserver);
1816: my $host=&hostname($homeserver);
1817: if ($queryid !~/^\Q$host\E\_/) {
1818: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1819: return;
1820: }
1821: my $response = &get_query_reply($queryid);
1822: my $maxtries = 5;
1823: my $tries = 1;
1824: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1825: $response = &get_query_reply($queryid);
1826: $tries ++;
1827: }
1828:
1829: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1830: if ($response eq 'unavailable') {
1831: $outcome = $response;
1832: } else {
1833: $outcome = 'ok';
1834: my @matches = split(/\n/,$response);
1835: foreach my $match (@matches) {
1836: my ($key,$value) = split(/=/,$match);
1837: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1838: }
1.899 raeburn 1839: }
1840: }
1841: }
1.909 raeburn 1842: return ($outcome,%results);
1.899 raeburn 1843: }
1844:
1845: sub usersearch {
1846: my ($srch) = @_;
1847: my $dom = $srch->{'srchdomain'};
1848: my %results;
1849: my %libserv = &all_library();
1850: my $query = 'usersearch';
1851: foreach my $tryserver (keys(%libserv)) {
1852: if (&host_domain($tryserver) eq $dom) {
1853: my $host=&hostname($tryserver);
1854: my $queryid=
1.911 raeburn 1855: &reply("querysend:".&escape($query).':'.
1856: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1857: &escape($srch->{'srchtype'}).':'.
1858: &escape($srch->{'srchterm'}),$tryserver);
1859: if ($queryid !~/^\Q$host\E\_/) {
1860: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1861: next;
1.899 raeburn 1862: }
1863: my $reply = &get_query_reply($queryid);
1864: my $maxtries = 1;
1865: my $tries = 1;
1866: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1867: $reply = &get_query_reply($queryid);
1868: $tries ++;
1869: }
1870: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1871: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1872: } else {
1.911 raeburn 1873: my @matches;
1874: if ($reply =~ /\n/) {
1875: @matches = split(/\n/,$reply);
1876: } else {
1877: @matches = split(/\&/,$reply);
1878: }
1.899 raeburn 1879: foreach my $match (@matches) {
1880: my ($uname,$udom,%userhash);
1.911 raeburn 1881: foreach my $entry (split(/:/,$match)) {
1882: my ($key,$value) =
1883: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1884: $userhash{$key} = $value;
1885: if ($key eq 'username') {
1886: $uname = $value;
1887: } elsif ($key eq 'domain') {
1888: $udom = $value;
1.911 raeburn 1889: }
1.899 raeburn 1890: }
1891: $results{$uname.':'.$udom} = \%userhash;
1892: }
1893: }
1894: }
1895: }
1896: return %results;
1897: }
1898:
1.912 raeburn 1899: sub get_instuser {
1900: my ($udom,$uname,$id) = @_;
1901: my $homeserver = &domain($udom,'primary');
1902: my ($outcome,%results);
1903: if ($homeserver ne '') {
1904: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1905: &escape($id).':'.&escape($udom),$homeserver);
1906: my $host=&hostname($homeserver);
1907: if ($queryid !~/^\Q$host\E\_/) {
1908: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1909: return;
1910: }
1911: my $response = &get_query_reply($queryid);
1912: my $maxtries = 5;
1913: my $tries = 1;
1914: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1915: $response = &get_query_reply($queryid);
1916: $tries ++;
1917: }
1918: if (!&error($response) && $response ne 'refused') {
1919: if ($response eq 'unavailable') {
1920: $outcome = $response;
1921: } else {
1922: $outcome = 'ok';
1923: my @matches = split(/\n/,$response);
1924: foreach my $match (@matches) {
1925: my ($key,$value) = split(/=/,$match);
1926: $results{&unescape($key)} = &thaw_unescape($value);
1927: }
1928: }
1929: }
1930: }
1931: my %userinfo;
1932: if (ref($results{$uname}) eq 'HASH') {
1933: %userinfo = %{$results{$uname}};
1934: }
1935: return ($outcome,%userinfo);
1936: }
1937:
1938: sub inst_rulecheck {
1.923 raeburn 1939: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1940: my %returnhash;
1941: if ($udom ne '') {
1942: if (ref($rules) eq 'ARRAY') {
1943: @{$rules} = map {&escape($_);} (@{$rules});
1944: my $rulestr = join(':',@{$rules});
1945: my $homeserver=&domain($udom,'primary');
1946: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1947: my $response;
1948: if ($item eq 'username') {
1949: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1950: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1951: $homeserver));
1.923 raeburn 1952: } elsif ($item eq 'id') {
1953: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1954: ':'.&escape($id).':'.$rulestr,
1955: $homeserver));
1.945 raeburn 1956: } elsif ($item eq 'selfcreate') {
1957: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1958: &escape($udom).':'.&escape($uname).
1959: ':'.$rulestr,$homeserver));
1.923 raeburn 1960: }
1.912 raeburn 1961: if ($response ne 'refused') {
1962: my @pairs=split(/\&/,$response);
1963: foreach my $item (@pairs) {
1964: my ($key,$value)=split(/=/,$item,2);
1965: $key = &unescape($key);
1966: next if ($key =~ /^error: 2 /);
1967: $returnhash{$key}=&thaw_unescape($value);
1968: }
1969: }
1970: }
1971: }
1972: }
1973: return %returnhash;
1974: }
1975:
1976: sub inst_userrules {
1.923 raeburn 1977: my ($udom,$check) = @_;
1.912 raeburn 1978: my (%ruleshash,@ruleorder);
1979: if ($udom ne '') {
1980: my $homeserver=&domain($udom,'primary');
1981: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1982: my $response;
1983: if ($check eq 'id') {
1984: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1985: $homeserver);
1.943 raeburn 1986: } elsif ($check eq 'email') {
1987: $response=&reply('instemailrules:'.&escape($udom),
1988: $homeserver);
1.923 raeburn 1989: } else {
1990: $response=&reply('instuserrules:'.&escape($udom),
1991: $homeserver);
1992: }
1.912 raeburn 1993: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1994: ($response ne 'unknown_cmd') &&
1.912 raeburn 1995: ($response ne 'no_such_host')) {
1996: my ($hashitems,$orderitems) = split(/:/,$response);
1997: my @pairs=split(/\&/,$hashitems);
1998: foreach my $item (@pairs) {
1999: my ($key,$value)=split(/=/,$item,2);
2000: $key = &unescape($key);
2001: next if ($key =~ /^error: 2 /);
2002: $ruleshash{$key}=&thaw_unescape($value);
2003: }
2004: my @esc_order = split(/\&/,$orderitems);
2005: foreach my $item (@esc_order) {
2006: push(@ruleorder,&unescape($item));
2007: }
2008: }
2009: }
2010: }
2011: return (\%ruleshash,\@ruleorder);
2012: }
2013:
1.976 raeburn 2014: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2015:
2016: sub get_domain_defaults {
1.1240 raeburn 2017: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2018: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2019: my $cachetime = 60*60*24;
1.1240 raeburn 2020: unless ($ignore_cache) {
2021: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2022: if (defined($cached)) {
2023: if (ref($result) eq 'HASH') {
2024: return %{$result};
2025: }
1.943 raeburn 2026: }
2027: }
2028: my %domdefaults;
2029: my %domconfig =
1.989 raeburn 2030: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2031: 'requestcourses','inststatus',
1.1183 raeburn 2032: 'coursedefaults','usersessions',
1.1258 raeburn 2033: 'requestauthor','selfenrollment',
2034: 'coursecategories'],$domain);
1.1254 raeburn 2035: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2036: if (ref($domconfig{'defaults'}) eq 'HASH') {
2037: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2038: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2039: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2040: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2041: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2042: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2043: } else {
2044: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2045: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2046: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2047: }
1.976 raeburn 2048: if (ref($domconfig{'quotas'}) eq 'HASH') {
2049: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2050: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2051: } else {
2052: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2053: }
1.1177 raeburn 2054: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2055: foreach my $item (@usertools) {
2056: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2057: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2058: }
2059: }
1.1229 raeburn 2060: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2061: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2062: }
1.976 raeburn 2063: }
1.985 raeburn 2064: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246 raeburn 2065: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2066: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2067: }
2068: }
1.1183 raeburn 2069: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2070: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2071: }
1.989 raeburn 2072: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2073: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2074: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2075: }
2076: }
1.1047 raeburn 2077: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2078: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 ! raeburn 2079: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
! 2080: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
! 2081: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
! 2082: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
! 2083: }
1.1254 raeburn 2084: foreach my $type (@coursetypes) {
2085: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2086: unless ($type eq 'community') {
2087: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2088: }
2089: }
2090: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2091: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2092: }
1.1277 ! raeburn 2093: if ($domdefaults{'postsubmit'} eq 'on') {
! 2094: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
! 2095: $domdefaults{$type.'postsubtimeout'} =
! 2096: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
! 2097: }
! 2098: }
1.1230 raeburn 2099: }
1.1047 raeburn 2100: }
1.1073 raeburn 2101: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2102: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2103: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2104: }
2105: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2106: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2107: }
2108: }
1.1254 raeburn 2109: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2110: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2111: my @settings = ('types','registered','enroll_dates','access_dates','section',
2112: 'approval','limit');
2113: foreach my $type (@coursetypes) {
2114: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2115: my @mgrdc = ();
2116: foreach my $item (@settings) {
2117: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2118: push(@mgrdc,$item);
2119: }
2120: }
2121: if (@mgrdc) {
2122: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2123: }
2124: }
2125: }
2126: }
2127: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2128: foreach my $type (@coursetypes) {
2129: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2130: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2131: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2132: }
2133: }
2134: }
2135: }
2136: }
1.1258 raeburn 2137: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2138: $domdefaults{'catauth'} = 'std';
2139: $domdefaults{'catunauth'} = 'std';
2140: if ($domconfig{'coursecategories'}{'auth'}) {
2141: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2142: }
2143: if ($domconfig{'coursecategories'}{'unauth'}) {
2144: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2145: }
2146: }
1.1219 raeburn 2147: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2148: return %domdefaults;
2149: }
2150:
1.344 www 2151: # --------------------------------------------------- Assign a key to a student
2152:
2153: sub assign_access_key {
1.364 www 2154: #
2155: # a valid key looks like uname:udom#comments
2156: # comments are being appended
2157: #
1.498 www 2158: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2159: $kdom=
1.620 albertel 2160: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2161: $knum=
1.620 albertel 2162: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2163: $cdom=
1.620 albertel 2164: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2165: $cnum=
1.620 albertel 2166: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2167: $udom=$env{'user.name'} unless (defined($udom));
2168: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2169: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2170: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2171: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2172: # assigned to this person
2173: # - this should not happen,
1.345 www 2174: # unless something went wrong
2175: # the first time around
2176: # ready to assign
1.364 www 2177: $logentry=$1.'; '.$logentry;
1.496 www 2178: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2179: $kdom,$knum) eq 'ok') {
1.345 www 2180: # key now belongs to user
1.346 www 2181: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2182: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2183: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2184: return 'ok';
2185: } else {
2186: return
2187: 'error: Count not permanently assign key, will need to be re-entered later.';
2188: }
2189: } else {
2190: return 'error: Could not assign key, try again later.';
2191: }
1.364 www 2192: } elsif (!$existing{$ckey}) {
1.345 www 2193: # the key does not exist
2194: return 'error: The key does not exist';
2195: } else {
2196: # the key is somebody else's
2197: return 'error: The key is already in use';
2198: }
1.344 www 2199: }
2200:
1.364 www 2201: # ------------------------------------------ put an additional comment on a key
2202:
2203: sub comment_access_key {
2204: #
2205: # a valid key looks like uname:udom#comments
2206: # comments are being appended
2207: #
2208: my ($ckey,$cdom,$cnum,$logentry)=@_;
2209: $cdom=
1.620 albertel 2210: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2211: $cnum=
1.620 albertel 2212: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2213: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2214: if ($existing{$ckey}) {
2215: $existing{$ckey}.='; '.$logentry;
2216: # ready to assign
1.367 www 2217: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2218: $cdom,$cnum) eq 'ok') {
2219: return 'ok';
2220: } else {
2221: return 'error: Count not store comment.';
2222: }
2223: } else {
2224: # the key does not exist
2225: return 'error: The key does not exist';
2226: }
2227: }
2228:
1.344 www 2229: # ------------------------------------------------------ Generate a set of keys
2230:
2231: sub generate_access_keys {
1.364 www 2232: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2233: $cdom=
1.620 albertel 2234: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2235: $cnum=
1.620 albertel 2236: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2237: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2238: unless (($cdom) && ($cnum)) { return 0; }
2239: if ($number>10000) { return 0; }
2240: sleep(2); # make sure don't get same seed twice
2241: srand(time()^($$+($$<<15))); # from "Programming Perl"
2242: my $total=0;
2243: for (my $i=1;$i<=$number;$i++) {
2244: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2245: sprintf("%lx",int(100000*rand)).'-'.
2246: sprintf("%lx",int(100000*rand));
2247: $newkey=~s/1/g/g; # folks mix up 1 and l
2248: $newkey=~s/0/h/g; # and also 0 and O
2249: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2250: if ($existing{$newkey}) {
2251: $i--;
2252: } else {
1.364 www 2253: if (&put('accesskeys',
2254: { $newkey => '# generated '.localtime().
1.620 albertel 2255: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2256: '; '.$logentry },
2257: $cdom,$cnum) eq 'ok') {
1.344 www 2258: $total++;
2259: }
2260: }
2261: }
1.620 albertel 2262: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2263: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2264: return $total;
2265: }
2266:
2267: # ------------------------------------------------------- Validate an accesskey
2268:
2269: sub validate_access_key {
2270: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2271: $cdom=
1.620 albertel 2272: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2273: $cnum=
1.620 albertel 2274: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2275: $udom=$env{'user.domain'} unless (defined($udom));
2276: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2277: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2278: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2279: }
2280:
2281: # ------------------------------------- Find the section of student in a course
1.652 albertel 2282: sub devalidate_getsection_cache {
2283: my ($udom,$unam,$courseid)=@_;
2284: my $hashid="$udom:$unam:$courseid";
2285: &devalidate_cache_new('getsection',$hashid);
2286: }
1.298 matthew 2287:
1.815 albertel 2288: sub courseid_to_courseurl {
2289: my ($courseid) = @_;
2290: #already url style courseid
2291: return $courseid if ($courseid =~ m{^/});
2292:
2293: if (exists($env{'course.'.$courseid.'.num'})) {
2294: my $cnum = $env{'course.'.$courseid.'.num'};
2295: my $cdom = $env{'course.'.$courseid.'.domain'};
2296: return "/$cdom/$cnum";
2297: }
2298:
2299: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2300: if (exists($courseinfo{'num'})) {
2301: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2302: }
2303:
2304: return undef;
2305: }
2306:
1.298 matthew 2307: sub getsection {
2308: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2309: my $cachetime=1800;
1.551 albertel 2310:
2311: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2312: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2313: if (defined($cached)) { return $result; }
2314:
1.298 matthew 2315: my %Pending;
2316: my %Expired;
2317: #
2318: # Each role can either have not started yet (pending), be active,
2319: # or have expired.
2320: #
2321: # If there is an active role, we are done.
2322: #
2323: # If there is more than one role which has not started yet,
2324: # choose the one which will start sooner
2325: # If there is one role which has not started yet, return it.
2326: #
2327: # If there is more than one expired role, choose the one which ended last.
2328: # If there is a role which has expired, return it.
2329: #
1.815 albertel 2330: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2331: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2332: foreach my $key (keys(%roleshash)) {
1.479 albertel 2333: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2334: my $section=$1;
2335: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2336: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2337: my $now=time;
1.548 albertel 2338: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2339: $Expired{$end}=$section;
2340: next;
2341: }
1.548 albertel 2342: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2343: $Pending{$start}=$section;
2344: next;
2345: }
1.599 albertel 2346: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2347: }
2348: #
2349: # Presumedly there will be few matching roles from the above
2350: # loop and the sorting time will be negligible.
2351: if (scalar(keys(%Pending))) {
2352: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2353: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2354: }
2355: if (scalar(keys(%Expired))) {
2356: my @sorted = sort {$a <=> $b} keys(%Expired);
2357: my $time = pop(@sorted);
1.599 albertel 2358: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2359: }
1.599 albertel 2360: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2361: }
1.70 www 2362:
1.599 albertel 2363: sub save_cache {
2364: &purge_remembered();
1.722 albertel 2365: #&Apache::loncommon::validate_page();
1.620 albertel 2366: undef(%env);
1.780 albertel 2367: undef($env_loaded);
1.599 albertel 2368: }
1.452 albertel 2369:
1.599 albertel 2370: my $to_remember=-1;
2371: my %remembered;
2372: my %accessed;
2373: my $kicks=0;
2374: my $hits=0;
1.849 albertel 2375: sub make_key {
2376: my ($name,$id) = @_;
1.872 albertel 2377: if (length($id) > 65
2378: && length(&escape($id)) > 200) {
2379: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2380: }
1.849 albertel 2381: return &escape($name.':'.$id);
2382: }
2383:
1.599 albertel 2384: sub devalidate_cache_new {
2385: my ($name,$id,$debug) = @_;
2386: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2387: $id=&make_key($name,$id);
1.599 albertel 2388: $memcache->delete($id);
2389: delete($remembered{$id});
2390: delete($accessed{$id});
2391: }
2392:
2393: sub is_cached_new {
2394: my ($name,$id,$debug) = @_;
1.849 albertel 2395: $id=&make_key($name,$id);
1.599 albertel 2396: if (exists($remembered{$id})) {
1.1133 foxr 2397: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2398: $accessed{$id}=[&gettimeofday()];
2399: $hits++;
2400: return ($remembered{$id},1);
2401: }
2402: my $value = $memcache->get($id);
2403: if (!(defined($value))) {
2404: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2405: return (undef,undef);
1.416 albertel 2406: }
1.599 albertel 2407: if ($value eq '__undef__') {
2408: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2409: $value=undef;
2410: }
2411: &make_room($id,$value,$debug);
2412: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2413: return ($value,1);
2414: }
2415:
2416: sub do_cache_new {
2417: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2418: $id=&make_key($name,$id);
1.599 albertel 2419: my $setvalue=$value;
2420: if (!defined($setvalue)) {
2421: $setvalue='__undef__';
2422: }
1.623 albertel 2423: if (!defined($time) ) {
2424: $time=600;
2425: }
1.599 albertel 2426: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2427: my $result = $memcache->set($id,$setvalue,$time);
2428: if (! $result) {
1.872 albertel 2429: &logthis("caching of id -> $id failed");
1.910 albertel 2430: $memcache->disconnect_all();
1.872 albertel 2431: }
1.600 albertel 2432: # need to make a copy of $value
1.919 albertel 2433: &make_room($id,$value,$debug);
1.599 albertel 2434: return $value;
2435: }
2436:
2437: sub make_room {
2438: my ($id,$value,$debug)=@_;
1.919 albertel 2439:
2440: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2441: : $value;
1.599 albertel 2442: if ($to_remember<0) { return; }
2443: $accessed{$id}=[&gettimeofday()];
2444: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2445: my $to_kick;
2446: my $max_time=0;
2447: foreach my $other (keys(%accessed)) {
2448: if (&tv_interval($accessed{$other}) > $max_time) {
2449: $to_kick=$other;
2450: $max_time=&tv_interval($accessed{$other});
2451: }
2452: }
2453: delete($remembered{$to_kick});
2454: delete($accessed{$to_kick});
2455: $kicks++;
2456: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2457: return;
2458: }
2459:
1.599 albertel 2460: sub purge_remembered {
1.604 albertel 2461: #&logthis("Tossing ".scalar(keys(%remembered)));
2462: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2463: undef(%remembered);
2464: undef(%accessed);
1.428 albertel 2465: }
1.70 www 2466: # ------------------------------------- Read an entry from a user's environment
2467:
2468: sub userenvironment {
2469: my ($udom,$unam,@what)=@_;
1.976 raeburn 2470: my $items;
2471: foreach my $item (@what) {
2472: $items.=&escape($item).'&';
2473: }
2474: $items=~s/\&$//;
1.70 www 2475: my %returnhash=();
1.1009 raeburn 2476: my $uhome = &homeserver($unam,$udom);
2477: unless ($uhome eq 'no_host') {
2478: my @answer=split(/\&/,
2479: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2480: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2481: return %returnhash;
2482: }
1.1009 raeburn 2483: my $i;
2484: for ($i=0;$i<=$#what;$i++) {
2485: $returnhash{$what[$i]}=&unescape($answer[$i]);
2486: }
1.70 www 2487: }
2488: return %returnhash;
1.1 albertel 2489: }
2490:
1.617 albertel 2491: # ---------------------------------------------------------- Get a studentphoto
2492: sub studentphoto {
2493: my ($udom,$unam,$ext) = @_;
2494: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2495: if (defined($env{'request.course.id'})) {
1.708 raeburn 2496: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2497: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2498: return(&retrievestudentphoto($udom,$unam,$ext));
2499: } else {
2500: my ($result,$perm_reqd)=
1.707 albertel 2501: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2502: if ($result eq 'ok') {
2503: if (!($perm_reqd eq 'yes')) {
2504: return(&retrievestudentphoto($udom,$unam,$ext));
2505: }
2506: }
2507: }
2508: }
2509: } else {
2510: my ($result,$perm_reqd) =
1.707 albertel 2511: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2512: if ($result eq 'ok') {
2513: if (!($perm_reqd eq 'yes')) {
2514: return(&retrievestudentphoto($udom,$unam,$ext));
2515: }
2516: }
2517: }
2518: return '/adm/lonKaputt/lonlogo_broken.gif';
2519: }
2520:
2521: sub retrievestudentphoto {
2522: my ($udom,$unam,$ext,$type) = @_;
2523: my $home=&Apache::lonnet::homeserver($unam,$udom);
2524: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2525: if ($ret eq 'ok') {
2526: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2527: if ($type eq 'thumbnail') {
2528: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2529: }
2530: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2531: return $tokenurl;
2532: } else {
2533: if ($type eq 'thumbnail') {
2534: return '/adm/lonKaputt/genericstudent_tn.gif';
2535: } else {
2536: return '/adm/lonKaputt/lonlogo_broken.gif';
2537: }
1.617 albertel 2538: }
2539: }
2540:
1.263 www 2541: # -------------------------------------------------------------------- New chat
2542:
2543: sub chatsend {
1.724 raeburn 2544: my ($newentry,$anon,$group)=@_;
1.620 albertel 2545: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2546: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2547: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2548: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2549: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2550: &escape($newentry)).':'.$group,$chome);
1.292 www 2551: }
2552:
2553: # ------------------------------------------ Find current version of a resource
2554:
2555: sub getversion {
2556: my $fname=&clutter(shift);
1.1189 raeburn 2557: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2558: return ¤tversion(&filelocation('',$fname));
2559: }
2560:
2561: sub currentversion {
2562: my $fname=shift;
2563: my $author=$fname;
2564: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2565: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2566: my $home=&homeserver($uname,$udom);
1.292 www 2567: if ($home eq 'no_host') {
2568: return -1;
2569: }
1.1112 www 2570: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2571: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2572: return -1;
2573: }
1.1112 www 2574: return $answer;
1.263 www 2575: }
2576:
1.1111 www 2577: #
2578: # Return special version number of resource if set by override, empty otherwise
2579: #
2580: sub usedversion {
2581: my $fname=shift;
2582: unless ($fname) { $fname=$env{'request.uri'}; }
2583: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2584: if ($urlversion) { return $urlversion; }
2585: return '';
2586: }
2587:
1.1 albertel 2588: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2589:
1.1 albertel 2590: sub subscribe {
2591: my $fname=shift;
1.761 raeburn 2592: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2593: $fname=~s/[\n\r]//g;
1.1 albertel 2594: my $author=$fname;
2595: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2596: my ($udom,$uname)=split(/\//,$author);
2597: my $home=homeserver($uname,$udom);
1.335 albertel 2598: if ($home eq 'no_host') {
2599: return 'not_found';
1.1 albertel 2600: }
2601: my $answer=reply("sub:$fname",$home);
1.64 www 2602: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2603: $answer.=' by '.$home;
2604: }
1.1 albertel 2605: return $answer;
2606: }
2607:
1.8 www 2608: # -------------------------------------------------------------- Replicate file
2609:
2610: sub repcopy {
2611: my $filename=shift;
1.23 www 2612: $filename=~s/\/+/\//g;
1.1142 raeburn 2613: my $londocroot = $perlvar{'lonDocRoot'};
2614: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2615: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2616: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2617: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2618: return &repcopy_userfile($filename);
2619: }
1.532 albertel 2620: $filename=~s/[\n\r]//g;
1.8 www 2621: my $transname="$filename.in.transfer";
1.828 www 2622: # FIXME: this should flock
1.607 raeburn 2623: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2624: my $remoteurl=subscribe($filename);
1.64 www 2625: if ($remoteurl =~ /^con_lost by/) {
2626: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2627: return 'unavailable';
1.8 www 2628: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2629: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2630: return 'not_found';
1.64 www 2631: } elsif ($remoteurl =~ /^rejected by/) {
2632: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2633: return 'forbidden';
1.20 www 2634: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2635: return 'ok';
1.8 www 2636: } else {
1.290 www 2637: my $author=$filename;
2638: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2639: my ($udom,$uname)=split(/\//,$author);
2640: my $home=homeserver($uname,$udom);
2641: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2642: my @parts=split(/\//,$filename);
2643: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2644: if ($path ne "$londocroot/res") {
1.8 www 2645: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2646: return 'bad_request';
1.8 www 2647: }
2648: my $count;
2649: for ($count=5;$count<$#parts;$count++) {
2650: $path.="/$parts[$count]";
2651: if ((-e $path)!=1) {
2652: mkdir($path,0777);
2653: }
2654: }
2655: my $ua=new LWP::UserAgent;
2656: my $request=new HTTP::Request('GET',"$remoteurl");
2657: my $response=$ua->request($request,$transname);
2658: if ($response->is_error()) {
2659: unlink($transname);
2660: my $message=$response->status_line;
1.672 albertel 2661: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2662: ." LWP get: $message: $filename</font>");
1.607 raeburn 2663: return 'unavailable';
1.8 www 2664: } else {
1.16 www 2665: if ($remoteurl!~/\.meta$/) {
2666: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2667: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2668: if ($mresponse->is_error()) {
2669: unlink($filename.'.meta');
2670: &logthis(
1.672 albertel 2671: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2672: }
2673: }
1.8 www 2674: rename($transname,$filename);
1.607 raeburn 2675: return 'ok';
1.8 www 2676: }
1.290 www 2677: }
1.8 www 2678: }
1.330 www 2679: }
2680:
2681: # ------------------------------------------------ Get server side include body
2682: sub ssi_body {
1.381 albertel 2683: my ($filelink,%form)=@_;
1.606 matthew 2684: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2685: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2686: }
1.953 www 2687: my $output='';
2688: my $response;
1.980 raeburn 2689: if ($filelink=~/^https?\:/) {
1.954 raeburn 2690: ($output,$response)=&externalssi($filelink);
1.953 www 2691: } else {
1.1004 droeschl 2692: $filelink .= $filelink=~/\?/ ? '&' : '?';
2693: $filelink .= 'inhibitmenu=yes';
1.953 www 2694: ($output,$response)=&ssi($filelink,%form);
2695: }
1.778 albertel 2696: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2697: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2698: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2699: if (wantarray) {
2700: return ($output, $response);
2701: } else {
2702: return $output;
2703: }
1.8 www 2704: }
2705:
1.15 www 2706: # --------------------------------------------------------- Server Side Include
2707:
1.782 albertel 2708: sub absolute_url {
2709: my ($host_name) = @_;
2710: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2711: if ($host_name eq '') {
2712: $host_name = $ENV{'SERVER_NAME'};
2713: }
2714: return $protocol.$host_name;
2715: }
2716:
1.942 foxr 2717: #
2718: # Server side include.
2719: # Parameters:
2720: # fn Possibly encrypted resource name/id.
2721: # form Hash that describes how the rendering should be done
2722: # and other things.
1.944 foxr 2723: # Returns:
1.950 raeburn 2724: # Scalar context: The content of the response.
2725: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2726: #
1.15 www 2727: sub ssi {
2728:
1.944 foxr 2729: my ($fn,%form)=@_;
1.15 www 2730: my $ua=new LWP::UserAgent;
1.23 www 2731: my $request;
1.711 albertel 2732:
2733: $form{'no_update_last_known'}=1;
1.895 albertel 2734: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2735: if (%form) {
1.782 albertel 2736: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 2737: $request->content(join('&',map {
2738: my $name = escape($_);
2739: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2740: ? join("&$name=", map {escape($_) } @{$form{$_}})
2741: : &escape($form{$_}) );
2742: } keys(%form)));
1.23 www 2743: } else {
1.782 albertel 2744: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2745: }
2746:
1.15 www 2747: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2748: my $response= $ua->request($request);
1.1182 foxr 2749: my $content = $response->content;
2750:
2751:
1.944 foxr 2752: if (wantarray) {
1.1173 foxr 2753: return ($content, $response);
1.944 foxr 2754: } else {
1.1173 foxr 2755: return $content;
1.942 foxr 2756: }
1.324 www 2757: }
2758:
2759: sub externalssi {
2760: my ($url)=@_;
2761: my $ua=new LWP::UserAgent;
2762: my $request=new HTTP::Request('GET',$url);
2763: my $response=$ua->request($request);
1.954 raeburn 2764: if (wantarray) {
2765: return ($response->content, $response);
2766: } else {
2767: return $response->content;
2768: }
1.15 www 2769: }
1.254 www 2770:
1.492 albertel 2771: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2772:
2773: sub allowuploaded {
2774: my ($srcurl,$url)=@_;
2775: $url=&clutter(&declutter($url));
2776: my $dir=$url;
2777: $dir=~s/\/[^\/]+$//;
2778: my %httpref=();
2779: my $httpurl=&hreflocation('',$url);
2780: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2781: &Apache::lonnet::appenv(\%httpref);
1.254 www 2782: }
1.477 raeburn 2783:
1.1193 raeburn 2784: #
2785: # Determine if the current user should be able to edit a particular resource,
2786: # when viewing in course context.
2787: # (a) When viewing resource used to determine if "Edit" item is included in
2788: # Functions.
2789: # (b) When displaying folder contents in course editor, used to determine if
2790: # "Edit" link will be displayed alongside resource.
2791: #
1.1196 raeburn 2792: # input: six args -- filename (decluttered), course number, course domain,
2793: # url, symb (if registered) and group (if this is a group
2794: # item -- e.g., bulletin board, group page etc.).
2795: # output: array of five scalars --
1.1193 raeburn 2796: # $cfile -- url for file editing if editable on current server
2797: # $home -- homeserver of resource (i.e., for author if published,
2798: # or course if uploaded.).
2799: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2800: # $forceedit -- 1 if icon/link should be to go to edit mode
2801: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2802: #
2803:
2804: sub can_edit_resource {
1.1194 raeburn 2805: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2806: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2807: #
2808: # For aboutme pages user can only edit his/her own.
2809: #
1.1199 raeburn 2810: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2811: my ($sdom,$sname) = ($1,$2);
2812: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2813: $home = $env{'user.home'};
2814: $cfile = $resurl;
2815: if ($env{'form.forceedit'}) {
2816: $forceview = 1;
2817: } else {
2818: $forceedit = 1;
2819: }
2820: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2821: } else {
2822: return;
2823: }
2824: }
2825:
2826: if ($env{'request.course.id'}) {
2827: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2828: if ($group ne '') {
2829: # if this is a group homepage or group bulletin board, check group privs
2830: my $allowed = 0;
1.1197 raeburn 2831: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2832: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2833: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2834: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2835: $allowed = 1;
2836: }
1.1197 raeburn 2837: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2838: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2839: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2840: $allowed = 1;
2841: }
2842: }
2843: if ($allowed) {
2844: $home=&homeserver($cnum,$cdom);
2845: if ($env{'form.forceedit'}) {
2846: $forceview = 1;
2847: } else {
2848: $forceedit = 1;
2849: }
2850: $cfile = $resurl;
2851: } else {
2852: return;
2853: }
2854: } else {
1.1208 raeburn 2855: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2856: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2857: return;
2858: }
2859: } elsif (!$crsedit) {
1.1194 raeburn 2860: #
2861: # No edit allowed where CC has switched to student role.
2862: #
2863: return;
2864: }
2865: }
2866: }
2867:
1.1193 raeburn 2868: if ($file ne '') {
2869: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2870: if (&is_course_upload($file,$cnum,$cdom)) {
2871: $uploaded = 1;
2872: $incourse = 1;
1.1193 raeburn 2873: if ($file =~/\.(htm|html|css|js|txt)$/) {
2874: $cfile = &hreflocation('',$file);
1.1201 raeburn 2875: if ($env{'form.forceedit'}) {
2876: $forceview = 1;
2877: } else {
2878: $forceedit = 1;
2879: }
1.1194 raeburn 2880: }
2881: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2882: $incourse = 1;
2883: if ($env{'form.forceedit'}) {
2884: $forceview = 1;
2885: } else {
2886: $forceedit = 1;
2887: }
2888: $cfile = $resurl;
2889: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2890: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2891: $incourse = 1;
2892: if ($env{'form.forceedit'}) {
2893: $forceview = 1;
2894: } else {
2895: $forceedit = 1;
2896: }
2897: $cfile = $resurl;
1.1199 raeburn 2898: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2899: $incourse = 1;
2900: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2901: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2902: $incourse = 1;
1.1199 raeburn 2903: if ($env{'form.forceedit'}) {
2904: $forceview = 1;
2905: } else {
2906: $forceedit = 1;
2907: }
2908: $cfile = $resurl;
1.1208 raeburn 2909: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2910: $incourse = 1;
2911: if ($env{'form.forceedit'}) {
2912: $forceview = 1;
2913: } else {
2914: $forceedit = 1;
2915: }
2916: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2917: }
2918: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2919: my $template = '/res/lib/templates/simpleproblem.problem';
2920: if (&is_on_map($template)) {
2921: $incourse = 1;
2922: $forceview = 1;
2923: $cfile = $template;
1.1193 raeburn 2924: }
1.1199 raeburn 2925: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2926: $incourse = 1;
2927: if ($env{'form.forceedit'}) {
2928: $forceview = 1;
2929: } else {
2930: $forceedit = 1;
2931: }
2932: $cfile = $resurl;
2933: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2934: $incourse = 1;
2935: $forceview = 1;
2936: if ($symb) {
2937: my ($map,$id,$res)=&decode_symb($symb);
2938: $env{'request.symb'} = $symb;
2939: $cfile = &clutter($res);
2940: } else {
2941: $cfile = $env{'form.suppurl'};
2942: $cfile =~ s{^http://}{};
2943: $cfile = '/adm/wrapper/ext/'.$cfile;
2944: }
1.1234 raeburn 2945: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2946: if ($env{'form.forceedit'}) {
2947: $forceview = 1;
2948: } else {
2949: $forceedit = 1;
2950: }
2951: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2952: }
2953: }
1.1194 raeburn 2954: if ($uploaded || $incourse) {
2955: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2956: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2957: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2958: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2959: # Check that the user has permission to edit this resource
2960: my $setpriv = 1;
2961: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2962: if (defined($cfudom)) {
2963: $home=&homeserver($cfuname,$cfudom);
2964: $cfile=$file;
2965: }
2966: }
1.1194 raeburn 2967: if (($cfile ne '') && (!$incourse || $uploaded) &&
2968: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2969: my @ids=¤t_machine_ids();
2970: unless (grep(/^\Q$home\E$/,@ids)) {
2971: $switchserver=1;
2972: }
2973: }
2974: }
1.1194 raeburn 2975: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2976: }
2977:
2978: sub is_course_upload {
2979: my ($file,$cnum,$cdom) = @_;
2980: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2981: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2982: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2983: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2984: return 1;
2985: }
2986: return;
2987: }
2988:
1.1194 raeburn 2989: sub in_course {
1.1195 raeburn 2990: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2991: if ($hideprivileged) {
2992: my $skipuser;
1.1219 raeburn 2993: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2994: my @possdoms = ($cdom);
2995: if ($coursehash{'checkforpriv'}) {
2996: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2997: }
2998: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 2999: $skipuser = 1;
3000: if ($coursehash{'nothideprivileged'}) {
3001: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3002: my $user;
3003: if ($item =~ /:/) {
3004: $user = $item;
3005: } else {
3006: $user = join(':',split(/[\@]/,$item));
3007: }
3008: if ($user eq $uname.':'.$udom) {
3009: undef($skipuser);
3010: last;
3011: }
3012: }
3013: }
3014: if ($skipuser) {
3015: return 0;
3016: }
3017: }
3018: }
1.1194 raeburn 3019: $type ||= 'any';
3020: if (!defined($cdom) || !defined($cnum)) {
3021: my $cid = $env{'request.course.id'};
3022: $cdom = $env{'course.'.$cid.'.domain'};
3023: $cnum = $env{'course.'.$cid.'.num'};
3024: }
3025: my $typesref;
1.1195 raeburn 3026: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3027: $typesref = ['active','previous','future'];
3028: } elsif ($type eq 'previous' || $type eq 'future') {
3029: $typesref = [$type];
3030: }
3031: my %roles = &get_my_roles($uname,$udom,'userroles',
3032: $typesref,undef,[$cdom]);
3033: my ($tmp) = keys(%roles);
3034: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3035: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3036: if (@course_roles > 0) {
3037: return 1;
3038: }
3039: return 0;
3040: }
3041:
1.478 albertel 3042: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3043: # input: action, courseID, current domain, intended
1.637 raeburn 3044: # path to file, source of file, instruction to parse file for objects,
3045: # ref to hash for embedded objects,
3046: # ref to hash for codebase of java objects.
1.1095 raeburn 3047: # reference to scalar to accommodate mime type determined
3048: # from File::MMagic if $parser = parse.
1.637 raeburn 3049: #
1.485 raeburn 3050: # output: url to file (if action was uploaddoc),
3051: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3052: #
1.478 albertel 3053: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3054: # course.
1.477 raeburn 3055: #
1.478 albertel 3056: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3057: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3058: # course's home server.
1.477 raeburn 3059: #
1.478 albertel 3060: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3061: # be copied from $source (current location) to
3062: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3063: # and will then be copied to
3064: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3065: # course's home server.
1.485 raeburn 3066: #
1.481 raeburn 3067: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3068: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3069: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3070: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3071: # in course's home server.
1.637 raeburn 3072: #
1.477 raeburn 3073:
3074: sub process_coursefile {
1.1095 raeburn 3075: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3076: $mimetype)=@_;
1.477 raeburn 3077: my $fetchresult;
1.638 albertel 3078: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3079: if ($action eq 'propagate') {
1.638 albertel 3080: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3081: $home);
1.481 raeburn 3082: } else {
1.477 raeburn 3083: my $fpath = '';
3084: my $fname = $file;
1.478 albertel 3085: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3086: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3087: my $filepath = &build_filepath($fpath);
1.481 raeburn 3088: if ($action eq 'copy') {
3089: if ($source eq '') {
3090: $fetchresult = 'no source file';
3091: return $fetchresult;
3092: } else {
3093: my $destination = $filepath.'/'.$fname;
3094: rename($source,$destination);
3095: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3096: $home);
1.481 raeburn 3097: }
3098: } elsif ($action eq 'uploaddoc') {
3099: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3100: print $fh $env{'form.'.$source};
1.481 raeburn 3101: close($fh);
1.637 raeburn 3102: if ($parser eq 'parse') {
1.1024 raeburn 3103: my $mm = new File::MMagic;
1.1095 raeburn 3104: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3105: if ($type eq 'text/html') {
1.1024 raeburn 3106: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3107: unless ($parse_result eq 'ok') {
3108: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3109: }
1.637 raeburn 3110: }
1.1095 raeburn 3111: if (ref($mimetype)) {
3112: $$mimetype = $type;
3113: }
1.637 raeburn 3114: }
1.477 raeburn 3115: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3116: $home);
1.481 raeburn 3117: if ($fetchresult eq 'ok') {
3118: return '/uploaded/'.$fpath.'/'.$fname;
3119: } else {
3120: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3121: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3122: return '/adm/notfound.html';
3123: }
1.477 raeburn 3124: }
3125: }
1.485 raeburn 3126: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3127: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3128: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3129: }
3130: return $fetchresult;
3131: }
3132:
1.637 raeburn 3133: sub build_filepath {
3134: my ($fpath) = @_;
3135: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3136: unless ($fpath eq '') {
3137: my @parts=split('/',$fpath);
3138: foreach my $part (@parts) {
3139: $filepath.= '/'.$part;
3140: if ((-e $filepath)!=1) {
3141: mkdir($filepath,0777);
3142: }
3143: }
3144: }
3145: return $filepath;
3146: }
3147:
3148: sub store_edited_file {
1.638 albertel 3149: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3150: my $file = $primary_url;
3151: $file =~ s#^/uploaded/$docudom/$docuname/##;
3152: my $fpath = '';
3153: my $fname = $file;
3154: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3155: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3156: my $filepath = &build_filepath($fpath);
3157: open(my $fh,'>'.$filepath.'/'.$fname);
3158: print $fh $content;
3159: close($fh);
1.638 albertel 3160: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3161: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3162: $home);
1.637 raeburn 3163: if ($$fetchresult eq 'ok') {
3164: return '/uploaded/'.$fpath.'/'.$fname;
3165: } else {
1.638 albertel 3166: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3167: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3168: return '/adm/notfound.html';
3169: }
3170: }
3171:
1.531 albertel 3172: sub clean_filename {
1.831 albertel 3173: my ($fname,$args)=@_;
1.315 www 3174: # Replace Windows backslashes by forward slashes
1.257 www 3175: $fname=~s/\\/\//g;
1.831 albertel 3176: if (!$args->{'keep_path'}) {
3177: # Get rid of everything but the actual filename
3178: $fname=~s/^.*\/([^\/]+)$/$1/;
3179: }
1.315 www 3180: # Replace spaces by underscores
3181: $fname=~s/\s+/\_/g;
3182: # Replace all other weird characters by nothing
1.831 albertel 3183: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3184: # Replace all .\d. sequences with _\d. so they no longer look like version
3185: # numbers
3186: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3187: return $fname;
3188: }
1.1051 raeburn 3189: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3190: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3191: # image with the same aspect ratio as the original, but with dimensions which do
3192: # not exceed $resizewidth and $resizeheight.
3193:
1.984 neumanie 3194: sub resizeImage {
1.1051 raeburn 3195: my ($img_path,$resizewidth,$resizeheight) = @_;
3196: my $ima = Image::Magick->new;
3197: my $resized;
3198: if (-e $img_path) {
3199: $ima->Read($img_path);
3200: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3201: my $width = $ima->Get('width');
3202: my $height = $ima->Get('height');
3203: if ($width > $resizewidth) {
3204: my $factor = $width/$resizewidth;
3205: my $newheight = $height/$factor;
3206: $ima->Scale(width=>$resizewidth,height=>$newheight);
3207: $resized = 1;
3208: }
3209: }
3210: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3211: my $width = $ima->Get('width');
3212: my $height = $ima->Get('height');
3213: if ($height > $resizeheight) {
3214: my $factor = $height/$resizeheight;
3215: my $newwidth = $width/$factor;
3216: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3217: $resized = 1;
3218: }
3219: }
3220: if ($resized) {
3221: $ima->Write($img_path);
3222: }
3223: }
3224: return;
1.977 amueller 3225: }
3226:
1.608 albertel 3227: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3228: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3229: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3230: # $context - possible values: coursedoc, existingfile, overwrite,
3231: # canceloverwrite, or ''.
3232: # if 'coursedoc': upload to the current course
3233: # if 'existingfile': write file to tmp/overwrites directory
3234: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3235: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3236: # $subdir - directory in userfile to store the file into
1.858 raeburn 3237: # $parser - instruction to parse file for objects ($parser = parse)
3238: # $allfiles - reference to hash for embedded objects
3239: # $codebase - reference to hash for codebase of java objects
3240: # $desuname - username for permanent storage of uploaded file
3241: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3242: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3243: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3244: # $resizewidth - width (pixels) to which to resize uploaded image
3245: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3246: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3247: # from File::MMagic.
1.858 raeburn 3248: #
1.686 albertel 3249: # output: url of file in userspace, or error: <message>
3250: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3251:
1.531 albertel 3252: sub userfileupload {
1.1090 raeburn 3253: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3254: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3255: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3256: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3257: $fname=&clean_filename($fname);
1.1090 raeburn 3258: # See if there is anything left
1.257 www 3259: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3260: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3261: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3262: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3263: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3264: my $now = time;
1.1090 raeburn 3265: my $filepath;
1.1095 raeburn 3266: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3267: $filepath = 'tmp/helprequests/'.$now;
3268: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3269: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3270: '_'.$env{'user.domain'}.'/pending';
3271: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3272: my ($docuname,$docudom);
3273: if ($destudom) {
3274: $docudom = $destudom;
3275: } else {
3276: $docudom = $env{'user.domain'};
3277: }
3278: if ($destuname) {
3279: $docuname = $destuname;
3280: } else {
3281: $docuname = $env{'user.name'};
3282: }
3283: if (exists($env{'form.group'})) {
3284: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3285: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3286: }
3287: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3288: if ($context eq 'canceloverwrite') {
3289: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3290: if (-e $tempfile) {
3291: my @info = stat($tempfile);
3292: if ($info[9] eq $env{'form.timestamp'}) {
3293: unlink($tempfile);
3294: }
3295: }
3296: return;
1.523 raeburn 3297: }
3298: }
1.1090 raeburn 3299: # Create the directory if not present
1.741 raeburn 3300: my @parts=split(/\//,$filepath);
3301: my $fullpath = $perlvar{'lonDaemons'};
3302: for (my $i=0;$i<@parts;$i++) {
3303: $fullpath .= '/'.$parts[$i];
3304: if ((-e $fullpath)!=1) {
3305: mkdir($fullpath,0777);
3306: }
3307: }
3308: open(my $fh,'>'.$fullpath.'/'.$fname);
3309: print $fh $env{'form.'.$formname};
3310: close($fh);
1.1090 raeburn 3311: if ($context eq 'existingfile') {
3312: my @info = stat($fullpath.'/'.$fname);
3313: return ($fullpath.'/'.$fname,$info[9]);
3314: } else {
3315: return $fullpath.'/'.$fname;
3316: }
1.523 raeburn 3317: }
1.995 raeburn 3318: if ($subdir eq 'scantron') {
3319: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3320: } else {
1.995 raeburn 3321: $fname="$subdir/$fname";
3322: }
1.1090 raeburn 3323: if ($context eq 'coursedoc') {
1.638 albertel 3324: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3325: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3326: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3327: return &finishuserfileupload($docuname,$docudom,
3328: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3329: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3330: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3331: } else {
1.1218 raeburn 3332: if ($env{'form.folder'}) {
3333: $fname=$env{'form.folder'}.'/'.$fname;
3334: }
1.638 albertel 3335: return &process_coursefile('uploaddoc',$docuname,$docudom,
3336: $fname,$formname,$parser,
1.1095 raeburn 3337: $allfiles,$codebase,$mimetype);
1.481 raeburn 3338: }
1.719 banghart 3339: } elsif (defined($destuname)) {
3340: my $docuname=$destuname;
3341: my $docudom=$destudom;
1.860 raeburn 3342: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3343: $parser,$allfiles,$codebase,
1.1051 raeburn 3344: $thumbwidth,$thumbheight,
1.1095 raeburn 3345: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3346: } else {
1.638 albertel 3347: my $docuname=$env{'user.name'};
3348: my $docudom=$env{'user.domain'};
1.1220 raeburn 3349: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3350: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3351: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3352: }
1.860 raeburn 3353: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3354: $parser,$allfiles,$codebase,
1.1051 raeburn 3355: $thumbwidth,$thumbheight,
1.1095 raeburn 3356: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3357: }
1.271 www 3358: }
3359:
3360: sub finishuserfileupload {
1.860 raeburn 3361: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3362: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3363: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3364: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3365:
1.860 raeburn 3366: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3367: $file=$fname;
3368: if ($fname=~m|/|) {
3369: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3370: $path.=$fnamepath.'/';
3371: }
1.259 www 3372: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3373: my $count;
3374: for ($count=4;$count<=$#parts;$count++) {
3375: $filepath.="/$parts[$count]";
3376: if ((-e $filepath)!=1) {
3377: mkdir($filepath,0777);
3378: }
3379: }
1.984 neumanie 3380:
1.258 www 3381: # Save the file
3382: {
1.701 albertel 3383: if (!open(FH,'>'.$filepath.'/'.$file)) {
3384: &logthis('Failed to create '.$filepath.'/'.$file);
3385: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3386: return '/adm/notfound.html';
3387: }
1.1090 raeburn 3388: if ($context eq 'overwrite') {
1.1117 foxr 3389: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3390: my $target = $filepath.'/'.$file;
3391: if (-e $source) {
3392: my @info = stat($source);
3393: if ($info[9] eq $env{'form.timestamp'}) {
3394: unless (&File::Copy::move($source,$target)) {
3395: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3396: return "Moving from $source failed";
3397: }
3398: } else {
3399: return "Temporary file: $source had unexpected date/time for last modification";
3400: }
3401: } else {
3402: return "Temporary file: $source missing";
3403: }
3404: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3405: &logthis('Failed to write to '.$filepath.'/'.$file);
3406: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3407: return '/adm/notfound.html';
3408: }
1.570 albertel 3409: close(FH);
1.1051 raeburn 3410: if ($resizewidth && $resizeheight) {
3411: my $mm = new File::MMagic;
3412: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3413: if ($mime_type =~ m{^image/}) {
3414: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3415: }
1.977 amueller 3416: }
1.258 www 3417: }
1.1152 raeburn 3418: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3419: if (ref($mimetype)) {
3420: if ($$mimetype eq '') {
3421: my $mm = new File::MMagic;
3422: my $type = $mm->checktype_filename($filepath.'/'.$file);
3423: $$mimetype = $type;
3424: }
3425: }
3426: }
1.637 raeburn 3427: if ($parser eq 'parse') {
1.1152 raeburn 3428: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3429: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3430: $allfiles,$codebase);
3431: unless ($parse_result eq 'ok') {
3432: &logthis('Failed to parse '.$filepath.$file.
3433: ' for embedded media: '.$parse_result);
3434: }
1.637 raeburn 3435: }
3436: }
1.860 raeburn 3437: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3438: my $input = $filepath.'/'.$file;
3439: my $output = $filepath.'/'.'tn-'.$file;
3440: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3441: system("convert -sample $thumbsize $input $output");
3442: if (-e $filepath.'/'.'tn-'.$file) {
3443: $fetchthumb = 1;
3444: }
3445: }
1.858 raeburn 3446:
1.259 www 3447: # Notify homeserver to grep it
3448: #
1.984 neumanie 3449: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3450: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3451: if ($fetchresult eq 'ok') {
1.860 raeburn 3452: if ($fetchthumb) {
3453: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3454: if ($thumbresult ne 'ok') {
3455: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3456: $docuhome.': '.$thumbresult);
3457: }
3458: }
1.259 www 3459: #
1.258 www 3460: # Return the URL to it
1.494 albertel 3461: return '/uploaded/'.$path.$file;
1.263 www 3462: } else {
1.494 albertel 3463: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3464: ': '.$fetchresult);
1.263 www 3465: return '/adm/notfound.html';
1.858 raeburn 3466: }
1.493 albertel 3467: }
3468:
1.637 raeburn 3469: sub extract_embedded_items {
1.961 raeburn 3470: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3471: my @state = ();
1.1164 raeburn 3472: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3473: my %javafiles = (
3474: codebase => '',
3475: code => '',
3476: archive => ''
3477: );
3478: my %mediafiles = (
3479: src => '',
3480: movie => '',
3481: );
1.648 raeburn 3482: my $p;
3483: if ($content) {
3484: $p = HTML::LCParser->new($content);
3485: } else {
1.961 raeburn 3486: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3487: }
1.641 albertel 3488: while (my $t=$p->get_token()) {
1.640 albertel 3489: if ($t->[0] eq 'S') {
3490: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3491: push(@state, $tagname);
1.648 raeburn 3492: if (lc($tagname) eq 'allow') {
3493: &add_filetype($allfiles,$attr->{'src'},'src');
3494: }
1.640 albertel 3495: if (lc($tagname) eq 'img') {
3496: &add_filetype($allfiles,$attr->{'src'},'src');
3497: }
1.886 albertel 3498: if (lc($tagname) eq 'a') {
1.1222 raeburn 3499: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3500: &add_filetype($allfiles,$attr->{'href'},'href');
3501: }
1.886 albertel 3502: }
1.645 raeburn 3503: if (lc($tagname) eq 'script') {
1.1164 raeburn 3504: my $src;
1.645 raeburn 3505: if ($attr->{'archive'} =~ /\.jar$/i) {
3506: &add_filetype($allfiles,$attr->{'archive'},'archive');
3507: } else {
1.1164 raeburn 3508: if ($attr->{'src'} ne '') {
3509: $src = $attr->{'src'};
3510: &add_filetype($allfiles,$src,'src');
3511: }
3512: }
3513: my $text = $p->get_trimmed_text();
3514: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3515: my @swfargs = split(/,/,$1);
3516: foreach my $item (@swfargs) {
3517: $item =~ s/["']//g;
3518: $item =~ s/^\s+//;
3519: $item =~ s/\s+$//;
3520: }
3521: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3522: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3523: push(@{$related{$swfargs[0]}},$swfargs[2]);
3524: } else {
3525: $related{$swfargs[0]} = [$swfargs[2]];
3526: }
3527: }
1.645 raeburn 3528: }
3529: }
3530: if (lc($tagname) eq 'link') {
3531: if (lc($attr->{'rel'}) eq 'stylesheet') {
3532: &add_filetype($allfiles,$attr->{'href'},'href');
3533: }
3534: }
1.640 albertel 3535: if (lc($tagname) eq 'object' ||
3536: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3537: foreach my $item (keys(%javafiles)) {
3538: $javafiles{$item} = '';
3539: }
1.1164 raeburn 3540: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3541: $lastids{lc($tagname)} = $attr->{'id'};
3542: }
1.640 albertel 3543: }
3544: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3545: my $name = lc($attr->{'name'});
3546: foreach my $item (keys(%javafiles)) {
3547: if ($name eq $item) {
3548: $javafiles{$item} = $attr->{'value'};
3549: last;
3550: }
3551: }
1.1164 raeburn 3552: my $pathfrom;
1.640 albertel 3553: foreach my $item (keys(%mediafiles)) {
3554: if ($name eq $item) {
1.1164 raeburn 3555: $pathfrom = $attr->{'value'};
3556: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3557: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3558: last;
3559: }
3560: }
1.1164 raeburn 3561: if ($name eq 'flashvars') {
3562: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3563: }
3564: if ($pathfrom ne '') {
3565: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3566: $pathfrom);
3567: }
1.640 albertel 3568: }
3569: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3570: foreach my $item (keys(%javafiles)) {
3571: if ($attr->{$item}) {
3572: $javafiles{$item} = $attr->{$item};
3573: last;
3574: }
3575: }
3576: foreach my $item (keys(%mediafiles)) {
3577: if ($attr->{$item}) {
3578: &add_filetype($allfiles,$attr->{$item},$item);
3579: last;
3580: }
3581: }
1.1164 raeburn 3582: if (lc($tagname) eq 'embed') {
3583: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3584: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3585: $attr->{'src'});
3586: }
3587: }
1.640 albertel 3588: }
1.1243 raeburn 3589: if (lc($tagname) eq 'iframe') {
3590: my $src = $attr->{'src'} ;
3591: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3592: &add_filetype($allfiles,$src,'src');
3593: } elsif ($src =~ m{^/}) {
3594: if ($env{'request.course.id'}) {
3595: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3596: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3597: my $url = &hreflocation('',$fullpath);
3598: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3599: my $relpath = $1;
3600: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3601: &add_filetype($allfiles,$1,'src');
3602: }
3603: }
3604: }
3605: }
3606: }
1.1164 raeburn 3607: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3608: pop(@state);
1.1164 raeburn 3609: }
1.640 albertel 3610: } elsif ($t->[0] eq 'E') {
3611: my ($tagname) = ($t->[1]);
3612: if ($javafiles{'codebase'} ne '') {
3613: $javafiles{'codebase'} .= '/';
3614: }
3615: if (lc($tagname) eq 'applet' ||
3616: lc($tagname) eq 'object' ||
3617: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3618: ) {
3619: foreach my $item (keys(%javafiles)) {
3620: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3621: my $file=$javafiles{'codebase'}.$javafiles{$item};
3622: &add_filetype($allfiles,$file,$item);
3623: }
3624: }
3625: }
3626: pop @state;
3627: }
3628: }
1.1164 raeburn 3629: foreach my $id (sort(keys(%flashvars))) {
3630: if ($shockwave{$id} ne '') {
3631: my @pairs = split(/\&/,$flashvars{$id});
3632: foreach my $pair (@pairs) {
3633: my ($key,$value) = split(/\=/,$pair);
3634: if ($key eq 'thumb') {
3635: &add_filetype($allfiles,$value,$key);
3636: } elsif ($key eq 'content') {
3637: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3638: my ($ext) = ($value =~ /\.([^.]+)$/);
3639: if ($ext ne '') {
3640: &add_filetype($allfiles,$path.$value,$ext);
3641: }
3642: }
3643: }
3644: }
3645: }
1.637 raeburn 3646: return 'ok';
3647: }
3648:
1.639 albertel 3649: sub add_filetype {
3650: my ($allfiles,$file,$type)=@_;
3651: if (exists($allfiles->{$file})) {
3652: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3653: push(@{$allfiles->{$file}}, &escape($type));
3654: }
3655: } else {
3656: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3657: }
3658: }
3659:
1.1164 raeburn 3660: sub embedded_dependency {
3661: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3662: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3663: if (($identifier ne '') &&
3664: (ref($related->{$identifier}) eq 'ARRAY') &&
3665: ($pathfrom ne '')) {
3666: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3667: foreach my $dep (@{$related->{$identifier}}) {
3668: &add_filetype($allfiles,$path.$dep,'object');
3669: }
3670: }
3671: }
3672: return;
3673: }
3674:
1.493 albertel 3675: sub removeuploadedurl {
1.984 neumanie 3676: my ($url)=@_;
3677: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3678: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3679: }
3680:
3681: sub removeuserfile {
3682: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3683: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3684: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3685: if ($result eq 'ok') {
1.798 raeburn 3686: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3687: my $metafile = $fname.'.meta';
3688: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3689: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3690: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3691: my $sqlresult =
1.823 albertel 3692: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3693: 'portfolio_metadata',$group,
3694: 'delete');
1.798 raeburn 3695: }
3696: }
3697: return $result;
1.257 www 3698: }
1.15 www 3699:
1.530 albertel 3700: sub mkdiruserfile {
3701: my ($docuname,$docudom,$dir)=@_;
3702: my $home=&homeserver($docuname,$docudom);
3703: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3704: }
3705:
1.531 albertel 3706: sub renameuserfile {
3707: my ($docuname,$docudom,$old,$new)=@_;
3708: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3709: my $result = &reply("renameuserfile:$docudom:$docuname:".
3710: &escape("$old").':'.&escape("$new"),$home);
3711: if ($result eq 'ok') {
3712: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3713: my $oldmeta = $old.'.meta';
3714: my $newmeta = $new.'.meta';
3715: my $metaresult =
3716: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3717: my $url = "/uploaded/$docudom/$docuname/$old";
3718: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3719: my $sqlresult =
1.823 albertel 3720: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3721: 'portfolio_metadata',$group,
3722: 'delete');
1.798 raeburn 3723: }
3724: }
3725: return $result;
1.531 albertel 3726: }
3727:
1.14 www 3728: # ------------------------------------------------------------------------- Log
3729:
3730: sub log {
3731: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3732: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3733: }
3734:
3735: # ------------------------------------------------------------------ Course Log
1.352 www 3736: #
3737: # This routine flushes several buffers of non-mission-critical nature
3738: #
1.157 www 3739:
3740: sub flushcourselogs {
1.352 www 3741: &logthis('Flushing log buffers');
3742: #
3743: # course logs
3744: # This is a log of all transactions in a course, which can be used
3745: # for data mining purposes
3746: #
3747: # It also collects the courseid database, which lists last transaction
3748: # times and course titles for all courseids
3749: #
3750: my %courseidbuffer=();
1.921 raeburn 3751: foreach my $crsid (keys(%courselogs)) {
1.352 www 3752: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3753: &escape($courselogs{$crsid}),
3754: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3755: delete $courselogs{$crsid};
3756: } else {
3757: &logthis('Failed to flush log buffer for '.$crsid);
3758: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3759: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3760: " exceeded maximum size, deleting.</font>");
3761: delete $courselogs{$crsid};
3762: }
1.352 www 3763: }
1.920 raeburn 3764: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3765: 'description' => $coursedescrbuf{$crsid},
3766: 'inst_code' => $courseinstcodebuf{$crsid},
3767: 'type' => $coursetypebuf{$crsid},
3768: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3769: };
1.191 harris41 3770: }
1.352 www 3771: #
3772: # Write course id database (reverse lookup) to homeserver of courses
3773: # Is used in pickcourse
3774: #
1.840 albertel 3775: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3776: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3777: $courseidbuffer{$crs_home},
3778: $crs_home,'timeonly');
1.352 www 3779: }
3780: #
3781: # File accesses
3782: # Writes to the dynamic metadata of resources to get hit counts, etc.
3783: #
1.449 matthew 3784: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3785: if ($entry =~ /___count$/) {
3786: my ($dom,$name);
1.807 albertel 3787: ($dom,$name,undef)=
1.811 albertel 3788: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3789: if (! defined($dom) || $dom eq '' ||
3790: ! defined($name) || $name eq '') {
1.620 albertel 3791: my $cid = $env{'request.course.id'};
3792: $dom = $env{'request.'.$cid.'.domain'};
3793: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3794: }
1.450 matthew 3795: my $value = $accesshash{$entry};
3796: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3797: my %temphash=($url => $value);
1.449 matthew 3798: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3799: if ($result eq 'ok') {
3800: delete $accesshash{$entry};
3801: }
3802: } else {
1.811 albertel 3803: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3804: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3805: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3806: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3807: delete $accesshash{$entry};
3808: }
1.185 www 3809: }
1.191 harris41 3810: }
1.352 www 3811: #
3812: # Roles
3813: # Reverse lookup of user roles for course faculty/staff and co-authorship
3814: #
1.800 albertel 3815: foreach my $entry (keys(%userrolehash)) {
1.351 www 3816: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3817: split(/\:/,$entry);
3818: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3819: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3820: $rudom,$runame) eq 'ok') {
3821: delete $userrolehash{$entry};
3822: }
3823: }
1.662 raeburn 3824: #
3825: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3826: #
3827: my %domrolebuffer = ();
1.1000 raeburn 3828: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3829: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3830: if ($domrolebuffer{$rudom}) {
3831: $domrolebuffer{$rudom}.='&'.&escape($entry).
3832: '='.&escape($domainrolehash{$entry});
3833: } else {
3834: $domrolebuffer{$rudom}.=&escape($entry).
3835: '='.&escape($domainrolehash{$entry});
3836: }
3837: delete $domainrolehash{$entry};
3838: }
3839: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3840: my %servers = &get_servers($dom,'library');
3841: foreach my $tryserver (keys(%servers)) {
3842: unless (&reply('domroleput:'.$dom.':'.
3843: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3844: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3845: }
1.662 raeburn 3846: }
3847: }
1.186 www 3848: $dumpcount++;
1.157 www 3849: }
3850:
3851: sub courselog {
3852: my $what=shift;
1.158 www 3853: $what=time.':'.$what;
1.620 albertel 3854: unless ($env{'request.course.id'}) { return ''; }
3855: $coursedombuf{$env{'request.course.id'}}=
3856: $env{'course.'.$env{'request.course.id'}.'.domain'};
3857: $coursenumbuf{$env{'request.course.id'}}=
3858: $env{'course.'.$env{'request.course.id'}.'.num'};
3859: $coursehombuf{$env{'request.course.id'}}=
3860: $env{'course.'.$env{'request.course.id'}.'.home'};
3861: $coursedescrbuf{$env{'request.course.id'}}=
3862: $env{'course.'.$env{'request.course.id'}.'.description'};
3863: $courseinstcodebuf{$env{'request.course.id'}}=
3864: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3865: $courseownerbuf{$env{'request.course.id'}}=
3866: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3867: $coursetypebuf{$env{'request.course.id'}}=
3868: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3869: if (defined $courselogs{$env{'request.course.id'}}) {
3870: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3871: } else {
1.620 albertel 3872: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3873: }
1.620 albertel 3874: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3875: &flushcourselogs();
3876: }
1.158 www 3877: }
3878:
3879: sub courseacclog {
3880: my $fnsymb=shift;
1.620 albertel 3881: unless ($env{'request.course.id'}) { return ''; }
3882: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3883: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3884: $what.=':POST';
1.583 matthew 3885: # FIXME: Probably ought to escape things....
1.800 albertel 3886: foreach my $key (keys(%env)) {
3887: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3888: my $formitem = $1;
3889: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3890: $what.=':'.$formitem.'='.$env{$key};
3891: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3892: $what.=':'.$formitem.'='.$env{$key};
3893: }
1.158 www 3894: }
1.191 harris41 3895: }
1.583 matthew 3896: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3897: # FIXME: We should not be depending on a form parameter that someone
3898: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3899: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3900: $what.= ':POST';
3901: # FIXME: Probably ought to escape things....
3902: foreach my $element ('courseexp','crsfulltext','crsrelated',
3903: 'crsdiscuss') {
1.620 albertel 3904: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3905: }
3906: }
1.158 www 3907: }
3908: &courselog($what);
1.149 www 3909: }
3910:
1.185 www 3911: sub countacc {
3912: my $url=&declutter(shift);
1.458 matthew 3913: return if (! defined($url) || $url eq '');
1.620 albertel 3914: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3915: #
3916: # Mark that this url was used in this course
3917: #
1.620 albertel 3918: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3919: #
3920: # Increase the access count for this resource in this child process
3921: #
1.281 www 3922: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3923: $accesshash{$key}++;
1.185 www 3924: }
1.349 www 3925:
1.361 www 3926: sub linklog {
3927: my ($from,$to)=@_;
3928: $from=&declutter($from);
3929: $to=&declutter($to);
3930: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3931: $accesshash{$to.'___'.$from.'___goto'}=1;
3932: }
1.1160 www 3933:
3934: sub statslog {
3935: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3936: if ($users<2) { return; }
3937: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3938: 'course' => $env{'request.course.id'},
3939: 'sections' => '"all"',
3940: 'num_students' => $users,
3941: 'part' => $part,
3942: 'symb' => $symb,
3943: 'mean_tries' => $av_attempts,
3944: 'deg_of_diff' => $degdiff});
3945: foreach my $key (keys(%dynstore)) {
3946: $accesshash{$key}=$dynstore{$key};
3947: }
3948: }
1.361 www 3949:
1.349 www 3950: sub userrolelog {
3951: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3952: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3953: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3954: $userrolehash
3955: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3956: =$tend.':'.$tstart;
1.662 raeburn 3957: }
1.1169 droeschl 3958: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3959: $userrolehash
3960: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3961: =$tend.':'.$tstart;
3962: }
1.1169 droeschl 3963: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3964: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3965: $domainrolehash
3966: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3967: = $tend.':'.$tstart;
3968: }
1.351 www 3969: }
3970:
1.957 raeburn 3971: sub courserolelog {
3972: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3973: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3974: my $cdom = $1;
3975: my $cnum = $2;
3976: my $sec = $3;
3977: my $namespace = 'rolelog';
3978: my %storehash = (
3979: role => $trole,
3980: start => $tstart,
3981: end => $tend,
3982: selfenroll => $selfenroll,
3983: context => $context,
3984: );
3985: if ($trole eq 'gr') {
3986: $namespace = 'groupslog';
3987: $storehash{'group'} = $sec;
3988: } else {
3989: $storehash{'section'} = $sec;
3990: }
1.1188 raeburn 3991: &write_log('course',$namespace,\%storehash,$delflag,$username,
3992: $domain,$cnum,$cdom);
1.1184 raeburn 3993: if (($trole ne 'st') || ($sec ne '')) {
3994: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3995: }
3996: }
3997: return;
3998: }
3999:
1.1184 raeburn 4000: sub domainrolelog {
4001: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4002: if ($area =~ m{^/($match_domain)/$}) {
4003: my $cdom = $1;
4004: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4005: my $namespace = 'rolelog';
4006: my %storehash = (
4007: role => $trole,
4008: start => $tstart,
4009: end => $tend,
4010: context => $context,
4011: );
1.1188 raeburn 4012: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4013: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4014: }
4015: return;
4016:
4017: }
4018:
4019: sub coauthorrolelog {
4020: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4021: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4022: my $audom = $1;
4023: my $auname = $2;
4024: my $namespace = 'rolelog';
4025: my %storehash = (
4026: role => $trole,
4027: start => $tstart,
4028: end => $tend,
4029: context => $context,
4030: );
1.1188 raeburn 4031: &write_log('author',$namespace,\%storehash,$delflag,$username,
4032: $domain,$auname,$audom);
1.1184 raeburn 4033: }
4034: return;
4035: }
4036:
1.351 www 4037: sub get_course_adv_roles {
1.948 raeburn 4038: my ($cid,$codes) = @_;
1.620 albertel 4039: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4040: my %coursehash=&coursedescription($cid);
1.988 raeburn 4041: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4042: my %nothide=();
1.800 albertel 4043: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4044: if ($user !~ /:/) {
4045: $nothide{join(':',split(/[\@]/,$user))}=1;
4046: } else {
4047: $nothide{$user}=1;
4048: }
1.470 www 4049: }
1.1219 raeburn 4050: my @possdoms = ($coursehash{'domain'});
4051: if ($coursehash{'checkforpriv'}) {
4052: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4053: }
1.351 www 4054: my %returnhash=();
4055: my %dumphash=
4056: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4057: my $now=time;
1.997 raeburn 4058: my %privileged;
1.1000 raeburn 4059: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4060: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4061: if (($tstart) && ($tstart<0)) { next; }
4062: if (($tend) && ($tend<$now)) { next; }
4063: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4064: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4065: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4066: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4067: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4068: if ($role eq 'cr') { next; }
1.948 raeburn 4069: if ($codes) {
4070: if ($section) { $role .= ':'.$section; }
4071: if ($returnhash{$role}) {
4072: $returnhash{$role}.=','.$username.':'.$domain;
4073: } else {
4074: $returnhash{$role}=$username.':'.$domain;
4075: }
1.351 www 4076: } else {
1.988 raeburn 4077: my $key=&plaintext($role,$crstype);
1.973 bisitz 4078: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4079: if ($returnhash{$key}) {
4080: $returnhash{$key}.=','.$username.':'.$domain;
4081: } else {
4082: $returnhash{$key}=$username.':'.$domain;
4083: }
1.351 www 4084: }
1.948 raeburn 4085: }
1.400 www 4086: return %returnhash;
4087: }
4088:
4089: sub get_my_roles {
1.937 raeburn 4090: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4091: unless (defined($uname)) { $uname=$env{'user.name'}; }
4092: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4093: my (%dumphash,%nothide);
1.1086 raeburn 4094: if ($context eq 'userroles') {
1.1166 raeburn 4095: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4096: } else {
1.1219 raeburn 4097: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4098: if ($hidepriv) {
4099: my %coursehash=&coursedescription($udom.'_'.$uname);
4100: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4101: if ($user !~ /:/) {
4102: $nothide{join(':',split(/[\@]/,$user))} = 1;
4103: } else {
4104: $nothide{$user} = 1;
4105: }
4106: }
4107: }
1.858 raeburn 4108: }
1.400 www 4109: my %returnhash=();
4110: my $now=time;
1.999 raeburn 4111: my %privileged;
1.800 albertel 4112: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4113: my ($role,$tend,$tstart);
4114: if ($context eq 'userroles') {
1.1149 raeburn 4115: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4116: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4117: } else {
4118: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4119: }
1.400 www 4120: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4121: my $status = 'active';
1.939 raeburn 4122: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4123: $status = 'previous';
4124: }
4125: if (($tstart) && ($now<$tstart)) {
4126: $status = 'future';
4127: }
4128: if (ref($types) eq 'ARRAY') {
4129: if (!grep(/^\Q$status\E$/,@{$types})) {
4130: next;
4131: }
4132: } else {
4133: if ($status ne 'active') {
4134: next;
4135: }
4136: }
1.867 raeburn 4137: my ($rolecode,$username,$domain,$section,$area);
4138: if ($context eq 'userroles') {
1.1186 raeburn 4139: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4140: (undef,$domain,$username,$section) = split(/\//,$area);
4141: } else {
4142: ($role,$username,$domain,$section) = split(/\:/,$entry);
4143: }
1.832 raeburn 4144: if (ref($roledoms) eq 'ARRAY') {
4145: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4146: next;
4147: }
4148: }
4149: if (ref($roles) eq 'ARRAY') {
4150: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4151: if ($role =~ /^cr\//) {
4152: if (!grep(/^cr$/,@{$roles})) {
4153: next;
4154: }
1.1104 raeburn 4155: } elsif ($role =~ /^gr\//) {
4156: if (!grep(/^gr$/,@{$roles})) {
4157: next;
4158: }
1.922 raeburn 4159: } else {
4160: next;
4161: }
1.832 raeburn 4162: }
1.867 raeburn 4163: }
1.937 raeburn 4164: if ($hidepriv) {
1.1219 raeburn 4165: my @privroles = ('dc','su');
1.999 raeburn 4166: if ($context eq 'userroles') {
1.1219 raeburn 4167: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4168: } else {
1.1219 raeburn 4169: my $possdoms = [$domain];
4170: if (ref($roledoms) eq 'ARRAY') {
4171: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4172: }
1.1219 raeburn 4173: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4174: if (!$nothide{$username.':'.$domain}) {
4175: next;
4176: }
4177: }
1.937 raeburn 4178: }
4179: }
1.933 raeburn 4180: if ($withsec) {
4181: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4182: $tstart.':'.$tend;
4183: } else {
4184: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4185: }
1.832 raeburn 4186: }
1.373 www 4187: return %returnhash;
1.399 www 4188: }
4189:
4190: # ----------------------------------------------------- Frontpage Announcements
4191: #
4192: #
4193:
4194: sub postannounce {
4195: my ($server,$text)=@_;
1.844 albertel 4196: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4197: unless ($text=~/\w/) { $text=''; }
4198: return &reply('setannounce:'.&escape($text),$server);
4199: }
4200:
4201: sub getannounce {
1.448 albertel 4202:
4203: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4204: my $announcement='';
1.800 albertel 4205: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4206: close($fh);
1.399 www 4207: if ($announcement=~/\w/) {
4208: return
4209: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4210: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4211: } else {
4212: return '';
4213: }
4214: } else {
4215: return '';
4216: }
1.351 www 4217: }
1.353 www 4218:
4219: # ---------------------------------------------------------- Course ID routines
4220: # Deal with domain's nohist_courseid.db files
4221: #
4222:
4223: sub courseidput {
1.921 raeburn 4224: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4225: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4226: my $outcome;
4227: if ($caller eq 'timeonly') {
4228: my $cids = '';
4229: foreach my $item (keys(%$storehash)) {
4230: $cids.=&escape($item).'&';
4231: }
4232: $cids=~s/\&$//;
4233: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4234: $coursehome);
4235: } else {
4236: my $items = '';
4237: foreach my $item (keys(%$storehash)) {
4238: $items.= &escape($item).'='.
4239: &freeze_escape($$storehash{$item}).'&';
4240: }
4241: $items=~s/\&$//;
4242: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4243: $coursehome);
1.918 raeburn 4244: }
4245: if ($outcome eq 'unknown_cmd') {
4246: my $what;
4247: foreach my $cid (keys(%$storehash)) {
4248: $what .= &escape($cid).'=';
1.921 raeburn 4249: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4250: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4251: }
4252: $what =~ s/\:$/&/;
4253: }
4254: $what =~ s/\&$//;
4255: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4256: } else {
4257: return $outcome;
4258: }
1.353 www 4259: }
4260:
4261: sub courseiddump {
1.921 raeburn 4262: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4263: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4264: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4265: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4266: $hasuniquecode)=@_;
1.918 raeburn 4267: my $as_hash = 1;
4268: my %returnhash;
4269: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4270: my %libserv = &all_library();
4271: foreach my $tryserver (keys(%libserv)) {
4272: if ( ( $hostidflag == 1
4273: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4274: || (!defined($hostidflag)) ) {
4275:
1.918 raeburn 4276: if (($domfilter eq '') ||
4277: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4278: my $rep;
4279: if (grep { $_ eq $tryserver } current_machine_ids()) {
4280: $rep = LONCAPA::Lond::dump_course_id_handler(
4281: join(":", (&host_domain($tryserver), $sincefilter,
4282: &escape($descfilter), &escape($instcodefilter),
4283: &escape($ownerfilter), &escape($coursefilter),
4284: &escape($typefilter), &escape($regexp_ok),
4285: $as_hash, &escape($selfenrollonly),
4286: &escape($catfilter), $showhidden, $caller,
4287: &escape($cloner), &escape($cc_clone), $cloneonly,
4288: &escape($createdbefore), &escape($createdafter),
1.1247 raeburn 4289: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180 droeschl 4290: } else {
4291: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4292: $sincefilter.':'.&escape($descfilter).':'.
4293: &escape($instcodefilter).':'.&escape($ownerfilter).
4294: ':'.&escape($coursefilter).':'.&escape($typefilter).
4295: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4296: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4297: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4298: &escape($cc_clone).':'.$cloneonly.':'.
4299: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247 raeburn 4300: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180 droeschl 4301: $tryserver);
4302: }
4303:
1.918 raeburn 4304: my @pairs=split(/\&/,$rep);
4305: foreach my $item (@pairs) {
4306: my ($key,$value)=split(/\=/,$item,2);
4307: $key = &unescape($key);
4308: next if ($key =~ /^error: 2 /);
4309: my $result = &thaw_unescape($value);
4310: if (ref($result) eq 'HASH') {
4311: $returnhash{$key}=$result;
4312: } else {
1.921 raeburn 4313: my @responses = split(/:/,$value);
4314: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4315: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4316: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4317: }
1.1008 raeburn 4318: }
1.353 www 4319: }
4320: }
4321: }
4322: }
4323: return %returnhash;
4324: }
4325:
1.1055 raeburn 4326: sub courselastaccess {
4327: my ($cdom,$cnum,$hostidref) = @_;
4328: my %returnhash;
4329: if ($cdom && $cnum) {
4330: my $chome = &homeserver($cnum,$cdom);
4331: if ($chome ne 'no_host') {
4332: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4333: &extract_lastaccess(\%returnhash,$rep);
4334: }
4335: } else {
4336: if (!$cdom) { $cdom=''; }
4337: my %libserv = &all_library();
4338: foreach my $tryserver (keys(%libserv)) {
4339: if (ref($hostidref) eq 'ARRAY') {
4340: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4341: }
4342: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4343: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4344: &extract_lastaccess(\%returnhash,$rep);
4345: }
4346: }
4347: }
4348: return %returnhash;
4349: }
4350:
4351: sub extract_lastaccess {
4352: my ($returnhash,$rep) = @_;
4353: if (ref($returnhash) eq 'HASH') {
4354: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4355: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4356: $rep eq '') {
4357: my @pairs=split(/\&/,$rep);
4358: foreach my $item (@pairs) {
4359: my ($key,$value)=split(/\=/,$item,2);
4360: $key = &unescape($key);
4361: next if ($key =~ /^error: 2 /);
4362: $returnhash->{$key} = &thaw_unescape($value);
4363: }
4364: }
4365: }
4366: return;
4367: }
4368:
1.658 raeburn 4369: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4370:
4371: sub dcmailput {
1.685 raeburn 4372: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4373: my $status = &Apache::lonnet::critical(
1.740 www 4374: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4375: &escape($message),$server);
1.662 raeburn 4376: return $status;
4377: }
4378:
1.658 raeburn 4379: sub dcmaildump {
4380: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4381: my %returnhash=();
1.846 albertel 4382:
4383: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4384: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4385: &escape($enddate).':';
4386: my @esc_senders=map { &escape($_)} @$senders;
4387: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4388: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4389: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4390: if (($key) && ($value)) {
4391: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4392: }
4393: }
4394: }
4395: return %returnhash;
4396: }
1.662 raeburn 4397: # ---------------------------------------------------------- Domain roles
4398:
4399: sub get_domain_roles {
4400: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4401: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4402: $startdate = '.';
4403: }
1.1018 raeburn 4404: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4405: $enddate = '.';
4406: }
1.922 raeburn 4407: my $rolelist;
4408: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4409: $rolelist = join('&',@{$roles});
1.922 raeburn 4410: }
1.662 raeburn 4411: my %personnel = ();
1.841 albertel 4412:
4413: my %servers = &get_servers($dom,'library');
4414: foreach my $tryserver (keys(%servers)) {
4415: %{$personnel{$tryserver}}=();
4416: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4417: &escape($startdate).':'.
4418: &escape($enddate).':'.
4419: &escape($rolelist), $tryserver))) {
4420: my ($key,$value) = split(/\=/,$line,2);
4421: if (($key) && ($value)) {
4422: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4423: }
4424: }
1.662 raeburn 4425: }
4426: return %personnel;
4427: }
1.658 raeburn 4428:
1.1057 www 4429: # ----------------------------------------------------------- Interval timing
1.149 www 4430:
1.1153 www 4431: {
4432: # Caches needed for speedup of navmaps
4433: # We don't want to cache this for very long at all (5 seconds at most)
4434: #
4435: # The user for whom we cache
4436: my $cachedkey='';
4437: # The cached times for this user
4438: my %cachedtimes=();
4439: # When this was last done
4440: my $cachedtime=();
4441:
4442: sub load_all_first_access {
1.1154 raeburn 4443: my ($uname,$udom)=@_;
1.1156 www 4444: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4445: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4446: return;
4447: }
4448: $cachedtime=time;
4449: $cachedkey=$uname.':'.$udom;
4450: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4451: }
4452:
1.504 albertel 4453: sub get_first_access {
1.1162 raeburn 4454: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4455: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4456: if ($argsymb) { $symb=$argsymb; }
4457: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4458: if ($argmap) { $map = $argmap; }
1.926 albertel 4459: if ($type eq 'course') {
4460: $res='course';
4461: } elsif ($type eq 'map') {
1.588 albertel 4462: $res=&symbread($map);
4463: } else {
4464: $res=$symb;
4465: }
1.1153 www 4466: &load_all_first_access($uname,$udom);
4467: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4468: }
4469:
4470: sub set_first_access {
1.1162 raeburn 4471: my ($type,$interval)=@_;
1.790 albertel 4472: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4473: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4474: if ($type eq 'course') {
4475: $res='course';
4476: } elsif ($type eq 'map') {
1.588 albertel 4477: $res=&symbread($map);
4478: } else {
4479: $res=$symb;
4480: }
1.1153 www 4481: $cachedkey='';
1.1162 raeburn 4482: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4483: if (!$firstaccess) {
1.1162 raeburn 4484: my $start = time;
4485: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4486: $udom,$uname);
4487: if ($putres eq 'ok') {
4488: &put('timerinterval',{"$courseid\0$res"=>$interval},
4489: $udom,$uname);
4490: &appenv(
4491: {
4492: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4493: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4494: }
4495: );
4496: }
4497: return $putres;
1.505 albertel 4498: }
4499: return 'already_set';
1.504 albertel 4500: }
1.1153 www 4501: }
1.110 www 4502: # --------------------------------------------- Set Expire Date for Spreadsheet
4503:
4504: sub expirespread {
4505: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4506: my $cid=$env{'request.course.id'};
1.110 www 4507: if ($cid) {
4508: my $now=time;
4509: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4510: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4511: $env{'course.'.$cid.'.num'}.
1.110 www 4512: ':nohist_expirationdates:'.
4513: &escape($key).'='.$now,
1.620 albertel 4514: $env{'course.'.$cid.'.home'})
1.110 www 4515: }
4516: return 'ok';
1.14 www 4517: }
4518:
1.109 www 4519: # ----------------------------------------------------- Devalidate Spreadsheets
4520:
4521: sub devalidate {
1.325 www 4522: my ($symb,$uname,$udom)=@_;
1.620 albertel 4523: my $cid=$env{'request.course.id'};
1.109 www 4524: if ($cid) {
1.391 matthew 4525: # delete the stored spreadsheets for
4526: # - the student level sheet of this user in course's homespace
4527: # - the assessment level sheet for this resource
4528: # for this user in user's homespace
1.553 albertel 4529: # - current conditional state info
1.325 www 4530: my $key=$uname.':'.$udom.':';
1.109 www 4531: my $status=
1.299 matthew 4532: &del('nohist_calculatedsheets',
1.391 matthew 4533: [$key.'studentcalc:'],
1.620 albertel 4534: $env{'course.'.$cid.'.domain'},
4535: $env{'course.'.$cid.'.num'})
1.133 albertel 4536: .' '.
4537: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4538: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4539: unless ($status eq 'ok ok') {
4540: &logthis('Could not devalidate spreadsheet '.
1.325 www 4541: $uname.' at '.$udom.' for '.
1.109 www 4542: $symb.': '.$status);
1.133 albertel 4543: }
1.553 albertel 4544: &delenv('user.state.'.$cid);
1.109 www 4545: }
4546: }
4547:
1.265 albertel 4548: sub get_scalar {
4549: my ($string,$end) = @_;
4550: my $value;
4551: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4552: $value = $1;
4553: } elsif ($$string =~ s/^([^&]*?)&//) {
4554: $value = $1;
4555: }
4556: return &unescape($value);
4557: }
4558:
4559: sub array2str {
4560: my (@array) = @_;
4561: my $result=&arrayref2str(\@array);
4562: $result=~s/^__ARRAY_REF__//;
4563: $result=~s/__END_ARRAY_REF__$//;
4564: return $result;
4565: }
4566:
1.204 albertel 4567: sub arrayref2str {
4568: my ($arrayref) = @_;
1.265 albertel 4569: my $result='__ARRAY_REF__';
1.204 albertel 4570: foreach my $elem (@$arrayref) {
1.265 albertel 4571: if(ref($elem) eq 'ARRAY') {
4572: $result.=&arrayref2str($elem).'&';
4573: } elsif(ref($elem) eq 'HASH') {
4574: $result.=&hashref2str($elem).'&';
4575: } elsif(ref($elem)) {
4576: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4577: } else {
4578: $result.=&escape($elem).'&';
4579: }
4580: }
4581: $result=~s/\&$//;
1.265 albertel 4582: $result .= '__END_ARRAY_REF__';
1.204 albertel 4583: return $result;
4584: }
4585:
1.168 albertel 4586: sub hash2str {
1.204 albertel 4587: my (%hash) = @_;
4588: my $result=&hashref2str(\%hash);
1.265 albertel 4589: $result=~s/^__HASH_REF__//;
4590: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4591: return $result;
4592: }
4593:
4594: sub hashref2str {
4595: my ($hashref)=@_;
1.265 albertel 4596: my $result='__HASH_REF__';
1.800 albertel 4597: foreach my $key (sort(keys(%$hashref))) {
4598: if (ref($key) eq 'ARRAY') {
4599: $result.=&arrayref2str($key).'=';
4600: } elsif (ref($key) eq 'HASH') {
4601: $result.=&hashref2str($key).'=';
4602: } elsif (ref($key)) {
1.265 albertel 4603: $result.='=';
1.800 albertel 4604: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4605: } else {
1.1132 raeburn 4606: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4607: }
4608:
1.800 albertel 4609: if(ref($hashref->{$key}) eq 'ARRAY') {
4610: $result.=&arrayref2str($hashref->{$key}).'&';
4611: } elsif(ref($hashref->{$key}) eq 'HASH') {
4612: $result.=&hashref2str($hashref->{$key}).'&';
4613: } elsif(ref($hashref->{$key})) {
1.265 albertel 4614: $result.='&';
1.800 albertel 4615: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4616: } else {
1.800 albertel 4617: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4618: }
4619: }
1.168 albertel 4620: $result=~s/\&$//;
1.265 albertel 4621: $result .= '__END_HASH_REF__';
1.168 albertel 4622: return $result;
4623: }
4624:
4625: sub str2hash {
1.265 albertel 4626: my ($string)=@_;
4627: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4628: return %$hash;
4629: }
4630:
4631: sub str2hashref {
1.168 albertel 4632: my ($string) = @_;
1.265 albertel 4633:
4634: my %hash;
4635:
4636: if($string !~ /^__HASH_REF__/) {
4637: if (! ($string eq '' || !defined($string))) {
4638: $hash{'error'}='Not hash reference';
4639: }
4640: return (\%hash, $string);
4641: }
4642:
4643: $string =~ s/^__HASH_REF__//;
4644:
4645: while($string !~ /^__END_HASH_REF__/) {
4646: #key
4647: my $key='';
4648: if($string =~ /^__HASH_REF__/) {
4649: ($key, $string)=&str2hashref($string);
4650: if(defined($key->{'error'})) {
4651: $hash{'error'}='Bad data';
4652: return (\%hash, $string);
4653: }
4654: } elsif($string =~ /^__ARRAY_REF__/) {
4655: ($key, $string)=&str2arrayref($string);
4656: if($key->[0] eq 'Array reference error') {
4657: $hash{'error'}='Bad data';
4658: return (\%hash, $string);
4659: }
4660: } else {
4661: $string =~ s/^(.*?)=//;
1.267 albertel 4662: $key=&unescape($1);
1.265 albertel 4663: }
4664: $string =~ s/^=//;
4665:
4666: #value
4667: my $value='';
4668: if($string =~ /^__HASH_REF__/) {
4669: ($value, $string)=&str2hashref($string);
4670: if(defined($value->{'error'})) {
4671: $hash{'error'}='Bad data';
4672: return (\%hash, $string);
4673: }
4674: } elsif($string =~ /^__ARRAY_REF__/) {
4675: ($value, $string)=&str2arrayref($string);
4676: if($value->[0] eq 'Array reference error') {
4677: $hash{'error'}='Bad data';
4678: return (\%hash, $string);
4679: }
4680: } else {
4681: $value=&get_scalar(\$string,'__END_HASH_REF__');
4682: }
4683: $string =~ s/^&//;
4684:
4685: $hash{$key}=$value;
1.204 albertel 4686: }
1.265 albertel 4687:
4688: $string =~ s/^__END_HASH_REF__//;
4689:
4690: return (\%hash, $string);
1.204 albertel 4691: }
4692:
4693: sub str2array {
1.265 albertel 4694: my ($string)=@_;
4695: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4696: return @$array;
4697: }
4698:
4699: sub str2arrayref {
1.204 albertel 4700: my ($string) = @_;
1.265 albertel 4701: my @array;
4702:
4703: if($string !~ /^__ARRAY_REF__/) {
4704: if (! ($string eq '' || !defined($string))) {
4705: $array[0]='Array reference error';
4706: }
4707: return (\@array, $string);
4708: }
4709:
4710: $string =~ s/^__ARRAY_REF__//;
4711:
4712: while($string !~ /^__END_ARRAY_REF__/) {
4713: my $value='';
4714: if($string =~ /^__HASH_REF__/) {
4715: ($value, $string)=&str2hashref($string);
4716: if(defined($value->{'error'})) {
4717: $array[0] ='Array reference error';
4718: return (\@array, $string);
4719: }
4720: } elsif($string =~ /^__ARRAY_REF__/) {
4721: ($value, $string)=&str2arrayref($string);
4722: if($value->[0] eq 'Array reference error') {
4723: $array[0] ='Array reference error';
4724: return (\@array, $string);
4725: }
4726: } else {
4727: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4728: }
4729: $string =~ s/^&//;
4730:
4731: push(@array, $value);
1.191 harris41 4732: }
1.265 albertel 4733:
4734: $string =~ s/^__END_ARRAY_REF__//;
4735:
4736: return (\@array, $string);
1.168 albertel 4737: }
4738:
1.167 albertel 4739: # -------------------------------------------------------------------Temp Store
4740:
1.168 albertel 4741: sub tmpreset {
4742: my ($symb,$namespace,$domain,$stuname) = @_;
4743: if (!$symb) {
4744: $symb=&symbread();
1.620 albertel 4745: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4746: }
4747: $symb=escape($symb);
4748:
1.620 albertel 4749: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4750: $namespace=~s/\//\_/g;
4751: $namespace=~s/\W//g;
4752:
1.620 albertel 4753: if (!$domain) { $domain=$env{'user.domain'}; }
4754: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4755: if ($domain eq 'public' && $stuname eq 'public') {
4756: $stuname=$ENV{'REMOTE_ADDR'};
4757: }
1.1117 foxr 4758: my $path=LONCAPA::tempdir();
1.168 albertel 4759: my %hash;
4760: if (tie(%hash,'GDBM_File',
4761: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4762: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4763: foreach my $key (keys(%hash)) {
1.180 albertel 4764: if ($key=~ /:$symb/) {
1.168 albertel 4765: delete($hash{$key});
4766: }
4767: }
4768: }
4769: }
4770:
1.167 albertel 4771: sub tmpstore {
1.168 albertel 4772: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4773:
4774: if (!$symb) {
4775: $symb=&symbread();
1.620 albertel 4776: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4777: }
4778: $symb=escape($symb);
4779:
4780: if (!$namespace) {
4781: # I don't think we would ever want to store this for a course.
4782: # it seems this will only be used if we don't have a course.
1.620 albertel 4783: #$namespace=$env{'request.course.id'};
1.168 albertel 4784: #if (!$namespace) {
1.620 albertel 4785: $namespace=$env{'request.state'};
1.168 albertel 4786: #}
4787: }
4788: $namespace=~s/\//\_/g;
4789: $namespace=~s/\W//g;
1.620 albertel 4790: if (!$domain) { $domain=$env{'user.domain'}; }
4791: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4792: if ($domain eq 'public' && $stuname eq 'public') {
4793: $stuname=$ENV{'REMOTE_ADDR'};
4794: }
1.168 albertel 4795: my $now=time;
4796: my %hash;
1.1117 foxr 4797: my $path=LONCAPA::tempdir();
1.168 albertel 4798: if (tie(%hash,'GDBM_File',
4799: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4800: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4801: $hash{"version:$symb"}++;
4802: my $version=$hash{"version:$symb"};
4803: my $allkeys='';
4804: foreach my $key (keys(%$storehash)) {
4805: $allkeys.=$key.':';
1.591 albertel 4806: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4807: }
4808: $hash{"$version:$symb:timestamp"}=$now;
4809: $allkeys.='timestamp';
4810: $hash{"$version:keys:$symb"}=$allkeys;
4811: if (untie(%hash)) {
4812: return 'ok';
4813: } else {
4814: return "error:$!";
4815: }
4816: } else {
4817: return "error:$!";
4818: }
4819: }
1.167 albertel 4820:
1.168 albertel 4821: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4822:
1.168 albertel 4823: sub tmprestore {
4824: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4825:
1.168 albertel 4826: if (!$symb) {
4827: $symb=&symbread();
1.620 albertel 4828: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4829: }
4830: $symb=escape($symb);
4831:
1.620 albertel 4832: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4833:
1.620 albertel 4834: if (!$domain) { $domain=$env{'user.domain'}; }
4835: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4836: if ($domain eq 'public' && $stuname eq 'public') {
4837: $stuname=$ENV{'REMOTE_ADDR'};
4838: }
1.168 albertel 4839: my %returnhash;
4840: $namespace=~s/\//\_/g;
4841: $namespace=~s/\W//g;
4842: my %hash;
1.1117 foxr 4843: my $path=LONCAPA::tempdir();
1.168 albertel 4844: if (tie(%hash,'GDBM_File',
4845: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4846: &GDBM_READER(),0640)) {
1.168 albertel 4847: my $version=$hash{"version:$symb"};
4848: $returnhash{'version'}=$version;
4849: my $scope;
4850: for ($scope=1;$scope<=$version;$scope++) {
4851: my $vkeys=$hash{"$scope:keys:$symb"};
4852: my @keys=split(/:/,$vkeys);
4853: my $key;
4854: $returnhash{"$scope:keys"}=$vkeys;
4855: foreach $key (@keys) {
1.591 albertel 4856: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4857: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4858: }
4859: }
1.168 albertel 4860: if (!(untie(%hash))) {
4861: return "error:$!";
4862: }
4863: } else {
4864: return "error:$!";
4865: }
4866: return %returnhash;
1.167 albertel 4867: }
4868:
1.9 www 4869: # ----------------------------------------------------------------------- Store
4870:
4871: sub store {
1.1269 raeburn 4872: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4873: my $home='';
4874:
1.168 albertel 4875: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4876:
1.213 www 4877: $symb=&symbclean($symb);
1.122 albertel 4878: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4879:
1.620 albertel 4880: if (!$domain) { $domain=$env{'user.domain'}; }
4881: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4882:
4883: &devalidate($symb,$stuname,$domain);
1.109 www 4884:
4885: $symb=escape($symb);
1.187 www 4886: if (!$namespace) {
1.620 albertel 4887: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4888: return '';
4889: }
4890: }
1.620 albertel 4891: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4892:
4893: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4894: $$storehash{'host'}=$perlvar{'lonHostID'};
4895:
1.12 www 4896: my $namevalue='';
1.800 albertel 4897: foreach my $key (keys(%$storehash)) {
4898: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4899: }
1.12 www 4900: $namevalue=~s/\&$//;
1.187 www 4901: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 4902: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 4903: }
4904:
1.47 www 4905: # -------------------------------------------------------------- Critical Store
4906:
4907: sub cstore {
1.1269 raeburn 4908: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4909: my $home='';
4910:
1.168 albertel 4911: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4912:
1.213 www 4913: $symb=&symbclean($symb);
1.122 albertel 4914: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4915:
1.620 albertel 4916: if (!$domain) { $domain=$env{'user.domain'}; }
4917: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4918:
4919: &devalidate($symb,$stuname,$domain);
1.109 www 4920:
4921: $symb=escape($symb);
1.187 www 4922: if (!$namespace) {
1.620 albertel 4923: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4924: return '';
4925: }
4926: }
1.620 albertel 4927: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4928:
4929: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4930: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4931:
1.47 www 4932: my $namevalue='';
1.800 albertel 4933: foreach my $key (keys(%$storehash)) {
4934: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4935: }
1.47 www 4936: $namevalue=~s/\&$//;
1.187 www 4937: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4938: return critical
1.1269 raeburn 4939: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 4940: }
4941:
1.9 www 4942: # --------------------------------------------------------------------- Restore
4943:
4944: sub restore {
1.124 www 4945: my ($symb,$namespace,$domain,$stuname) = @_;
4946: my $home='';
4947:
1.168 albertel 4948: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4949:
1.122 albertel 4950: if (!$symb) {
1.1224 raeburn 4951: return if ($namespace eq 'courserequests');
4952: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4953: } else {
1.1224 raeburn 4954: unless ($namespace eq 'courserequests') {
4955: $symb=&escape(&symbclean($symb));
4956: }
1.122 albertel 4957: }
1.188 www 4958: if (!$namespace) {
1.620 albertel 4959: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4960: return '';
4961: }
4962: }
1.620 albertel 4963: if (!$domain) { $domain=$env{'user.domain'}; }
4964: if (!$stuname) { $stuname=$env{'user.name'}; }
4965: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4966: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4967:
1.12 www 4968: my %returnhash=();
1.800 albertel 4969: foreach my $line (split(/\&/,$answer)) {
4970: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4971: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4972: }
1.75 www 4973: my $version;
4974: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4975: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4976: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4977: }
1.75 www 4978: }
1.13 www 4979: return %returnhash;
1.34 www 4980: }
4981:
4982: # ---------------------------------------------------------- Course Description
1.1118 foxr 4983: #
4984: #
1.34 www 4985:
4986: sub coursedescription {
1.731 albertel 4987: my ($courseid,$args)=@_;
1.34 www 4988: $courseid=~s/^\///;
1.49 www 4989: $courseid=~s/\_/\//g;
1.34 www 4990: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4991: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4992: my $normalid=$cdomain.'_'.$cnum;
4993: # need to always cache even if we get errors otherwise we keep
4994: # trying and trying and trying to get the course description.
4995: my %envhash=();
4996: my %returnhash=();
1.731 albertel 4997:
4998: my $expiretime=600;
4999: if ($env{'request.course.id'} eq $normalid) {
5000: $expiretime=120;
5001: }
5002:
5003: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5004: if (!$args->{'freshen_cache'}
5005: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5006: foreach my $key (keys(%env)) {
5007: next if ($key !~ /^\Q$prefix\E(.*)/);
5008: my ($setting) = $1;
5009: $returnhash{$setting} = $env{$key};
5010: }
5011: return %returnhash;
5012: }
5013:
1.1118 foxr 5014: # get the data again
5015:
1.731 albertel 5016: if (!$args->{'one_time'}) {
5017: $envhash{'course.'.$normalid.'.last_cache'}=time;
5018: }
1.811 albertel 5019:
1.34 www 5020: if ($chome ne 'no_host') {
1.302 albertel 5021: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5022: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5023: my $username = $env{'user.name'}; # Defult username
5024: if(defined $args->{'user'}) {
5025: $username = $args->{'user'};
5026: }
1.129 albertel 5027: $returnhash{'home'}= $chome;
5028: $returnhash{'domain'} = $cdomain;
5029: $returnhash{'num'} = $cnum;
1.741 raeburn 5030: if (!defined($returnhash{'type'})) {
5031: $returnhash{'type'} = 'Course';
5032: }
1.130 albertel 5033: while (my ($name,$value) = each %returnhash) {
1.53 www 5034: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5035: }
1.270 www 5036: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5037: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5038: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5039: $envhash{'course.'.$normalid.'.home'}=$chome;
5040: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5041: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5042: }
5043: }
1.731 albertel 5044: if (!$args->{'one_time'}) {
1.949 raeburn 5045: &appenv(\%envhash);
1.731 albertel 5046: }
1.302 albertel 5047: return %returnhash;
1.461 www 5048: }
5049:
1.1080 raeburn 5050: sub update_released_required {
5051: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5052: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5053: $cid = $env{'request.course.id'};
5054: $cdom = $env{'course.'.$cid.'.domain'};
5055: $cnum = $env{'course.'.$cid.'.num'};
5056: $chome = $env{'course.'.$cid.'.home'};
5057: }
5058: if ($needsrelease) {
5059: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5060: my $needsupdate;
5061: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5062: $needsupdate = 1;
5063: } else {
5064: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5065: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5066: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5067: $needsupdate = 1;
5068: }
5069: }
5070: if ($needsupdate) {
5071: my %needshash = (
5072: 'internal.releaserequired' => $needsrelease,
5073: );
5074: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5075: if ($putresult eq 'ok') {
5076: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5077: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5078: if (ref($crsinfo{$cid}) eq 'HASH') {
5079: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5080: &courseidput($cdom,\%crsinfo,$chome,'notime');
5081: }
5082: }
5083: }
5084: }
5085: return;
5086: }
5087:
1.461 www 5088: # -------------------------------------------------See if a user is privileged
5089:
5090: sub privileged {
1.1219 raeburn 5091: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5092: my $now = time;
1.1219 raeburn 5093: my $roles;
5094: if (ref($possroles) eq 'ARRAY') {
5095: $roles = $possroles;
5096: } else {
5097: $roles = ['dc','su'];
5098: }
5099: if (ref($possdomains) eq 'ARRAY') {
5100: my %privileged = &privileged_by_domain($possdomains,$roles);
5101: foreach my $dom (@{$possdomains}) {
5102: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5103: (ref($privileged{$dom}) eq 'HASH')) {
5104: foreach my $role (@{$roles}) {
5105: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5106: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5107: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5108: return 1 unless (($end && $end < $now) ||
5109: ($start && $start > $now));
5110: }
5111: }
5112: }
5113: }
5114: }
5115: } else {
5116: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5117: my $now = time;
1.1170 droeschl 5118:
1.1275 musolffc 5119: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5120: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5121: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5122: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5123: or ($tstart && $tstart > $now);
1.1170 droeschl 5124: }
1.1219 raeburn 5125: }
5126: }
5127: return 0;
5128: }
1.1170 droeschl 5129:
1.1219 raeburn 5130: sub privileged_by_domain {
5131: my ($domains,$roles) = @_;
5132: my %privileged = ();
5133: my $cachetime = 60*60*24;
5134: my $now = time;
5135: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5136: return %privileged;
5137: }
5138: foreach my $dom (@{$domains}) {
5139: next if (ref($privileged{$dom}) eq 'HASH');
5140: my $needroles;
5141: foreach my $role (@{$roles}) {
5142: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5143: if (defined($cached)) {
5144: if (ref($result) eq 'HASH') {
5145: $privileged{$dom}{$role} = $result;
5146: }
5147: } else {
5148: $needroles = 1;
5149: }
5150: }
5151: if ($needroles) {
5152: my %dompersonnel = &get_domain_roles($dom,$roles);
5153: $privileged{$dom} = {};
5154: foreach my $server (keys(%dompersonnel)) {
5155: if (ref($dompersonnel{$server}) eq 'HASH') {
5156: foreach my $item (keys(%{$dompersonnel{$server}})) {
5157: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5158: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5159: next if ($end && $end < $now);
5160: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5161: $dompersonnel{$server}{$item};
5162: }
5163: }
5164: }
5165: if (ref($privileged{$dom}) eq 'HASH') {
5166: foreach my $role (@{$roles}) {
5167: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5168: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5169: } else {
5170: my %hash = ();
5171: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5172: }
5173: }
5174: }
5175: }
5176: }
5177: return %privileged;
1.9 www 5178: }
1.1 albertel 5179:
1.103 harris41 5180: # -------------------------------------------------------- Get user privileges
1.11 www 5181:
5182: sub rolesinit {
1.1169 droeschl 5183: my ($domain, $username) = @_;
5184: my %userroles = ('user.login.time' => time);
5185: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5186:
5187: # firstaccess and timerinterval are related to timed maps/resources.
5188: # also, blocking can be triggered by an activating timer
5189: # it's saved in the user's %env.
5190: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5191: my %timerinterval = &dump('timerinterval', $domain, $username);
5192: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5193: %timerintchk, %timerintenv);
5194:
1.1162 raeburn 5195: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5196: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5197: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5198: }
1.1169 droeschl 5199:
1.1162 raeburn 5200: foreach my $key (keys(%timerinterval)) {
5201: my ($cid,$rest) = split(/\0/,$key);
5202: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5203: }
1.1169 droeschl 5204:
1.11 www 5205: my %allroles=();
1.1162 raeburn 5206: my %allgroups=();
1.11 www 5207:
1.1274 raeburn 5208: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5209: my $role = $rolesdump{$area};
5210: $area =~ s/\_\w\w$//;
5211:
5212: my ($trole, $tend, $tstart, $group_privs);
5213:
5214: if ($role =~ /^cr/) {
5215: # Custom role, defined by a user
5216: # e.g., user.role.cr/msu/smith/mynewrole
5217: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5218: $trole = $1;
5219: ($tend, $tstart) = split('_', $2);
5220: } else {
5221: $trole = $role;
5222: }
5223: } elsif ($role =~ m|^gr/|) {
5224: # Role of member in a group, defined within a course/community
5225: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5226: ($trole, $tend, $tstart) = split(/_/, $role);
5227: next if $tstart eq '-1';
5228: ($trole, $group_privs) = split(/\//, $trole);
5229: $group_privs = &unescape($group_privs);
5230: } else {
5231: # Just a normal role, defined in roles.tab
5232: ($trole, $tend, $tstart) = split(/_/,$role);
5233: }
5234:
5235: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5236: $username);
5237: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5238:
5239: # role expired or not available yet?
5240: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5241: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5242:
5243: next if $area eq '' or $trole eq '';
5244:
5245: my $spec = "$trole.$area";
5246: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5247:
5248: if ($trole =~ /^cr\//) {
5249: # Custom role, defined by a user
5250: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5251: } elsif ($trole eq 'gr') {
5252: # Role of a member in a group, defined within a course/community
5253: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5254: next;
5255: } else {
5256: # Normal role, defined in roles.tab
5257: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5258: }
5259:
5260: my $cid = $tdomain.'_'.$trest;
5261: unless ($firstaccchk{$cid}) {
5262: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5263: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5264: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5265: $coursetimerstarts{$cid}{$item};
5266: }
5267: }
5268: $firstaccchk{$cid} = 1;
5269: }
5270: unless ($timerintchk{$cid}) {
5271: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5272: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5273: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5274: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5275: }
1.12 www 5276: }
1.1169 droeschl 5277: $timerintchk{$cid} = 1;
1.191 harris41 5278: }
1.11 www 5279: }
1.1169 droeschl 5280:
5281: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5282: \%allroles, \%allgroups);
5283: $env{'user.adv'} = $userroles{'user.adv'};
5284:
1.1162 raeburn 5285: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5286: }
5287:
1.567 raeburn 5288: sub set_arearole {
1.1215 raeburn 5289: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5290: unless ($nolog) {
1.567 raeburn 5291: # log the associated role with the area
1.1215 raeburn 5292: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5293: }
1.743 albertel 5294: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5295: }
5296:
5297: sub custom_roleprivs {
5298: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5299: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5300: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5301: if (&hostname($homsvr) ne '') {
1.567 raeburn 5302: my ($rdummy,$roledef)=
5303: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5304: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5305: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5306: if (defined($syspriv)) {
1.1043 raeburn 5307: if ($trest =~ /^$match_community$/) {
5308: $syspriv =~ s/bre\&S//;
5309: }
1.567 raeburn 5310: $$allroles{'cm./'}.=':'.$syspriv;
5311: $$allroles{$spec.'./'}.=':'.$syspriv;
5312: }
5313: if ($tdomain ne '') {
5314: if (defined($dompriv)) {
5315: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5316: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5317: }
5318: if (($trest ne '') && (defined($coursepriv))) {
5319: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5320: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5321: }
5322: }
5323: }
5324: }
5325: }
5326:
1.678 raeburn 5327: sub group_roleprivs {
5328: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5329: my $access = 1;
5330: my $now = time;
5331: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5332: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5333: if ($access) {
1.811 albertel 5334: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5335: $$allgroups{$course}{$group} .=':'.$group_privs;
5336: }
5337: }
1.567 raeburn 5338:
5339: sub standard_roleprivs {
5340: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5341: if (defined($pr{$trole.':s'})) {
5342: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5343: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5344: }
5345: if ($tdomain ne '') {
5346: if (defined($pr{$trole.':d'})) {
5347: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5348: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5349: }
5350: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5351: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5352: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5353: }
5354: }
5355: }
5356:
5357: sub set_userprivs {
1.1064 raeburn 5358: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5359: my $author=0;
5360: my $adv=0;
1.678 raeburn 5361: my %grouproles = ();
5362: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5363: my @groupkeys;
1.1000 raeburn 5364: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5365: push(@groupkeys,$role);
5366: }
5367: if (ref($groups_roles) eq 'HASH') {
5368: foreach my $key (keys(%{$groups_roles})) {
5369: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5370: push(@groupkeys,$key);
5371: }
5372: }
5373: }
5374: if (@groupkeys > 0) {
5375: foreach my $role (@groupkeys) {
5376: my ($trole,$area,$sec,$extendedarea);
5377: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5378: $trole = $1;
5379: $area = $2;
5380: $sec = $3;
5381: $extendedarea = $area.$sec;
5382: if (exists($$allgroups{$area})) {
5383: foreach my $group (keys(%{$$allgroups{$area}})) {
5384: my $spec = $trole.'.'.$extendedarea;
5385: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5386: $$allgroups{$area}{$group};
1.1064 raeburn 5387: }
1.678 raeburn 5388: }
5389: }
5390: }
5391: }
5392: }
1.800 albertel 5393: foreach my $group (keys(%grouproles)) {
5394: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5395: }
1.800 albertel 5396: foreach my $role (keys(%{$allroles})) {
5397: my %thesepriv;
1.941 raeburn 5398: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5399: foreach my $item (split(/:/,$$allroles{$role})) {
5400: if ($item ne '') {
5401: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5402: if ($restrictions eq '') {
5403: $thesepriv{$privilege}='F';
5404: } elsif ($thesepriv{$privilege} ne 'F') {
5405: $thesepriv{$privilege}.=$restrictions;
5406: }
5407: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5408: }
5409: }
5410: my $thesestr='';
1.1104 raeburn 5411: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5412: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5413: }
5414: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5415: }
5416: return ($author,$adv);
5417: }
5418:
1.994 raeburn 5419: sub role_status {
1.1104 raeburn 5420: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5421: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5422: my ($one,$two) = split(m{\./},$rolekey,2);
5423: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5424: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5425: $$where = '/'.$two;
1.994 raeburn 5426: $$trolecode=$$role.'.'.$$where;
5427: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5428: $$tstatus='is';
1.1104 raeburn 5429: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5430: $$tstatus='future';
1.1034 raeburn 5431: if ($$tstart<$now) {
5432: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5433: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5434: my (%allroles,%allgroups,$group_privs,
5435: %groups_roles,@rolecodes);
1.1002 raeburn 5436: my %userroles = (
5437: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5438: );
1.1064 raeburn 5439: @rolecodes = ('cm');
1.1002 raeburn 5440: my $spec=$$role.'.'.$$where;
5441: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5442: if ($$role =~ /^cr\//) {
5443: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5444: push(@rolecodes,'cr');
1.1002 raeburn 5445: } elsif ($$role eq 'gr') {
1.1064 raeburn 5446: push(@rolecodes,$$role);
1.1002 raeburn 5447: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5448: $env{'user.name'});
1.1064 raeburn 5449: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5450: (undef,my $group_privs) = split(/\//,$trole);
5451: $group_privs = &unescape($group_privs);
5452: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5453: 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 5454: &get_groups_roles($tdomain,$trest,
5455: \%course_roles,\@rolecodes,
5456: \%groups_roles);
1.1002 raeburn 5457: } else {
1.1064 raeburn 5458: push(@rolecodes,$$role);
1.1002 raeburn 5459: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5460: }
1.1064 raeburn 5461: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5462: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5463: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5464: }
5465: }
1.1034 raeburn 5466: $$tstatus = 'is';
1.1002 raeburn 5467: }
1.994 raeburn 5468: }
5469: if ($$tend) {
1.1104 raeburn 5470: if ($$tend<$update) {
1.994 raeburn 5471: $$tstatus='expired';
5472: } elsif ($$tend<$now) {
5473: $$tstatus='will_not';
5474: }
5475: }
5476: }
5477: }
5478: }
5479:
1.1104 raeburn 5480: sub get_groups_roles {
5481: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5482: return unless((ref($cdom_courseroles) eq 'HASH') &&
5483: (ref($rolecodes) eq 'ARRAY') &&
5484: (ref($groups_roles) eq 'HASH'));
5485: if (keys(%{$cdom_courseroles}) > 0) {
5486: my ($cnum) = ($rest =~ /^($match_courseid)/);
5487: if ($cdom ne '' && $cnum ne '') {
5488: foreach my $key (keys(%{$cdom_courseroles})) {
5489: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5490: my $crsrole = $1;
5491: my $crssec = $2;
5492: if ($crsrole =~ /^cr/) {
5493: unless (grep(/^cr$/,@{$rolecodes})) {
5494: push(@{$rolecodes},'cr');
5495: }
5496: } else {
5497: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5498: push(@{$rolecodes},$crsrole);
5499: }
5500: }
5501: my $rolekey = "$crsrole./$cdom/$cnum";
5502: if ($crssec ne '') {
5503: $rolekey .= "/$crssec";
5504: }
5505: $rolekey .= './';
5506: $groups_roles->{$rolekey} = $rolecodes;
5507: }
5508: }
5509: }
5510: }
5511: return;
5512: }
5513:
5514: sub delete_env_groupprivs {
5515: my ($where,$courseroles,$possroles) = @_;
5516: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5517: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5518: unless (ref($courseroles->{$udom}) eq 'HASH') {
5519: %{$courseroles->{$udom}} =
5520: &get_my_roles('','','userroles',['active'],
5521: $possroles,[$udom],1);
5522: }
5523: if (ref($courseroles->{$udom}) eq 'HASH') {
5524: foreach my $item (keys(%{$courseroles->{$udom}})) {
5525: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5526: my $area = '/'.$cdom.'/'.$cnum;
5527: my $privkey = "user.priv.$crsrole.$area";
5528: if ($crssec ne '') {
5529: $privkey .= '/'.$crssec;
5530: }
5531: $privkey .= ".$area/$group";
5532: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5533: }
5534: }
5535: return;
5536: }
5537:
1.994 raeburn 5538: sub check_adhoc_privs {
1.1104 raeburn 5539: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5540: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5541: my $setprivs;
1.994 raeburn 5542: if ($env{$cckey}) {
5543: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5544: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5545: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5546: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5547: $setprivs = 1;
1.994 raeburn 5548: }
5549: } else {
1.1088 raeburn 5550: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5551: $setprivs = 1;
1.994 raeburn 5552: }
1.1185 raeburn 5553: return $setprivs;
1.994 raeburn 5554: }
5555:
5556: sub set_adhoc_privileges {
5557: # role can be cc or ca
1.1088 raeburn 5558: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5559: my $area = '/'.$dcdom.'/'.$pickedcourse;
5560: my $spec = $role.'.'.$area;
5561: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5562: $env{'user.name'},1);
1.994 raeburn 5563: my %ccrole = ();
5564: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5565: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5566: &appenv(\%userroles,[$role,'cm']);
5567: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5568: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5569: &appenv( {'request.role' => $spec,
5570: 'request.role.domain' => $dcdom,
5571: 'request.course.sec' => ''
5572: }
5573: );
5574: my $tadv=0;
5575: if (&allowed('adv') eq 'F') { $tadv=1; }
5576: &appenv({'request.role.adv' => $tadv});
5577: }
1.994 raeburn 5578: }
5579:
1.12 www 5580: # --------------------------------------------------------------- get interface
5581:
5582: sub get {
1.131 albertel 5583: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5584: my $items='';
1.800 albertel 5585: foreach my $item (@$storearr) {
5586: $items.=&escape($item).'&';
1.191 harris41 5587: }
1.12 www 5588: $items=~s/\&$//;
1.620 albertel 5589: if (!$udomain) { $udomain=$env{'user.domain'}; }
5590: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5591: my $uhome=&homeserver($uname,$udomain);
5592:
1.133 albertel 5593: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5594: my @pairs=split(/\&/,$rep);
1.273 albertel 5595: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5596: return @pairs;
5597: }
1.15 www 5598: my %returnhash=();
1.42 www 5599: my $i=0;
1.800 albertel 5600: foreach my $item (@$storearr) {
5601: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5602: $i++;
1.191 harris41 5603: }
1.15 www 5604: return %returnhash;
1.27 www 5605: }
5606:
5607: # --------------------------------------------------------------- del interface
5608:
5609: sub del {
1.133 albertel 5610: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5611: my $items='';
1.800 albertel 5612: foreach my $item (@$storearr) {
5613: $items.=&escape($item).'&';
1.191 harris41 5614: }
1.984 neumanie 5615:
1.27 www 5616: $items=~s/\&$//;
1.620 albertel 5617: if (!$udomain) { $udomain=$env{'user.domain'}; }
5618: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5619: my $uhome=&homeserver($uname,$udomain);
5620: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5621: }
5622:
5623: # -------------------------------------------------------------- dump interface
5624:
1.1180 droeschl 5625: sub unserialize {
5626: my ($rep, $escapedkeys) = @_;
5627:
5628: return {} if $rep =~ /^error/;
5629:
5630: my %returnhash=();
1.1252 raeburn 5631: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5632: my ($key, $value) = split(/=/, $item, 2);
5633: $key = unescape($key) unless $escapedkeys;
5634: next if $key =~ /^error: 2 /;
1.1252 raeburn 5635: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5636: }
5637: #return %returnhash;
5638: return \%returnhash;
5639: }
5640:
5641: # see Lond::dump_with_regexp
5642: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5643: sub dump {
1.1180 droeschl 5644: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5645: if (!$udomain) { $udomain=$env{'user.domain'}; }
5646: if (!$uname) { $uname=$env{'user.name'}; }
5647: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5648:
1.1266 raeburn 5649: if ($regexp) {
5650: $regexp=&escape($regexp);
5651: } else {
5652: $regexp='.';
5653: }
1.1180 droeschl 5654: if (grep { $_ eq $uhome } current_machine_ids()) {
5655: # user is hosted on this machine
1.1266 raeburn 5656: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5657: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5658: return %{unserialize($reply, $escapedkeys)};
5659: }
1.1166 raeburn 5660: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5661: my @pairs=split(/\&/,$rep);
5662: my %returnhash=();
1.1098 foxr 5663: if (!($rep =~ /^error/ )) {
5664: foreach my $item (@pairs) {
5665: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5666: $key = unescape($key) unless $escapedkeys;
5667: #$key = &unescape($key);
1.1098 foxr 5668: next if ($key =~ /^error: 2 /);
5669: $returnhash{$key}=&thaw_unescape($value);
5670: }
1.755 albertel 5671: }
5672: return %returnhash;
1.407 www 5673: }
5674:
1.1098 foxr 5675:
1.717 albertel 5676: # --------------------------------------------------------- dumpstore interface
5677:
5678: sub dumpstore {
5679: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5680: # same as dump but keys must be escaped. They may contain colon separated
5681: # lists of values that may themself contain colons (e.g. symbs).
5682: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5683: }
5684:
1.407 www 5685: # -------------------------------------------------------------- keys interface
5686:
5687: sub getkeys {
5688: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5689: if (!$udomain) { $udomain=$env{'user.domain'}; }
5690: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5691: my $uhome=&homeserver($uname,$udomain);
5692: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5693: my @keyarray=();
1.800 albertel 5694: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5695: next if ($key =~ /^error: 2 /);
1.800 albertel 5696: push(@keyarray,&unescape($key));
1.407 www 5697: }
5698: return @keyarray;
1.318 matthew 5699: }
5700:
1.319 matthew 5701: # --------------------------------------------------------------- currentdump
5702: sub currentdump {
1.328 matthew 5703: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5704: $courseid = $env{'request.course.id'} if (! defined($courseid));
5705: $sdom = $env{'user.domain'} if (! defined($sdom));
5706: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5707: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5708: my $rep;
5709:
5710: if (grep { $_ eq $uhome } current_machine_ids()) {
5711: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5712: $courseid)));
5713: } else {
5714: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5715: }
5716:
1.318 matthew 5717: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5718: #
1.318 matthew 5719: my %returnhash=();
1.319 matthew 5720: #
5721: if ($rep eq "unknown_cmd") {
5722: # an old lond will not know currentdump
5723: # Do a dump and make it look like a currentdump
1.822 albertel 5724: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5725: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5726: my %hash = @tmp;
5727: @tmp=();
1.424 matthew 5728: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5729: } else {
5730: my @pairs=split(/\&/,$rep);
1.800 albertel 5731: foreach my $pair (@pairs) {
5732: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5733: my ($symb,$param) = split(/:/,$key);
5734: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5735: &thaw_unescape($value);
1.319 matthew 5736: }
1.191 harris41 5737: }
1.12 www 5738: return %returnhash;
1.424 matthew 5739: }
5740:
5741: sub convert_dump_to_currentdump{
5742: my %hash = %{shift()};
5743: my %returnhash;
5744: # Code ripped from lond, essentially. The only difference
5745: # here is the unescaping done by lonnet::dump(). Conceivably
5746: # we might run in to problems with parameter names =~ /^v\./
5747: while (my ($key,$value) = each(%hash)) {
5748: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5749: $symb = &unescape($symb);
5750: $param = &unescape($param);
1.424 matthew 5751: next if ($v eq 'version' || $symb eq 'keys');
5752: next if (exists($returnhash{$symb}) &&
5753: exists($returnhash{$symb}->{$param}) &&
5754: $returnhash{$symb}->{'v.'.$param} > $v);
5755: $returnhash{$symb}->{$param}=$value;
5756: $returnhash{$symb}->{'v.'.$param}=$v;
5757: }
5758: #
5759: # Remove all of the keys in the hashes which keep track of
5760: # the version of the parameter.
5761: while (my ($symb,$param_hash) = each(%returnhash)) {
5762: # use a foreach because we are going to delete from the hash.
5763: foreach my $key (keys(%$param_hash)) {
5764: delete($param_hash->{$key}) if ($key =~ /^v\./);
5765: }
5766: }
5767: return \%returnhash;
1.12 www 5768: }
5769:
1.627 albertel 5770: # ------------------------------------------------------ critical inc interface
5771:
5772: sub cinc {
5773: return &inc(@_,'critical');
5774: }
5775:
1.449 matthew 5776: # --------------------------------------------------------------- inc interface
5777:
5778: sub inc {
1.627 albertel 5779: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5780: if (!$udomain) { $udomain=$env{'user.domain'}; }
5781: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5782: my $uhome=&homeserver($uname,$udomain);
5783: my $items='';
5784: if (! ref($store)) {
5785: # got a single value, so use that instead
5786: $items = &escape($store).'=&';
5787: } elsif (ref($store) eq 'SCALAR') {
5788: $items = &escape($$store).'=&';
5789: } elsif (ref($store) eq 'ARRAY') {
5790: $items = join('=&',map {&escape($_);} @{$store});
5791: } elsif (ref($store) eq 'HASH') {
5792: while (my($key,$value) = each(%{$store})) {
5793: $items.= &escape($key).'='.&escape($value).'&';
5794: }
5795: }
5796: $items=~s/\&$//;
1.627 albertel 5797: if ($critical) {
5798: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5799: } else {
5800: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5801: }
1.449 matthew 5802: }
5803:
1.12 www 5804: # --------------------------------------------------------------- put interface
5805:
5806: sub put {
1.134 albertel 5807: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5808: if (!$udomain) { $udomain=$env{'user.domain'}; }
5809: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5810: my $uhome=&homeserver($uname,$udomain);
1.12 www 5811: my $items='';
1.800 albertel 5812: foreach my $item (keys(%$storehash)) {
5813: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5814: }
1.12 www 5815: $items=~s/\&$//;
1.134 albertel 5816: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5817: }
5818:
1.631 albertel 5819: # ------------------------------------------------------------ newput interface
5820:
5821: sub newput {
5822: my ($namespace,$storehash,$udomain,$uname)=@_;
5823: if (!$udomain) { $udomain=$env{'user.domain'}; }
5824: if (!$uname) { $uname=$env{'user.name'}; }
5825: my $uhome=&homeserver($uname,$udomain);
5826: my $items='';
5827: foreach my $key (keys(%$storehash)) {
5828: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5829: }
5830: $items=~s/\&$//;
5831: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5832: }
5833:
5834: # --------------------------------------------------------- putstore interface
5835:
1.524 raeburn 5836: sub putstore {
1.1269 raeburn 5837: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 5838: if (!$udomain) { $udomain=$env{'user.domain'}; }
5839: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5840: my $uhome=&homeserver($uname,$udomain);
5841: my $items='';
1.715 albertel 5842: foreach my $key (keys(%$storehash)) {
5843: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5844: }
1.715 albertel 5845: $items=~s/\&$//;
1.716 albertel 5846: my $esc_symb=&escape($symb);
5847: my $esc_v=&escape($version);
1.715 albertel 5848: my $reply =
1.716 albertel 5849: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5850: $uhome);
1.1269 raeburn 5851: if (($tolog) && ($reply eq 'ok')) {
5852: my $namevalue='';
5853: foreach my $key (keys(%{$storehash})) {
5854: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5855: }
5856: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
5857: '&host='.&escape($perlvar{'lonHostID'}).
5858: '&version='.$esc_v.
5859: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
5860: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
5861: }
1.715 albertel 5862: if ($reply eq 'unknown_cmd') {
1.716 albertel 5863: # gfall back to way things use to be done
1.715 albertel 5864: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5865: $uname);
1.524 raeburn 5866: }
1.715 albertel 5867: return $reply;
5868: }
5869:
5870: sub old_putstore {
1.716 albertel 5871: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5872: if (!$udomain) { $udomain=$env{'user.domain'}; }
5873: if (!$uname) { $uname=$env{'user.name'}; }
5874: my $uhome=&homeserver($uname,$udomain);
5875: my %newstorehash;
1.800 albertel 5876: foreach my $item (keys(%$storehash)) {
5877: my $key = $version.':'.&escape($symb).':'.$item;
5878: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5879: }
5880: my $items='';
5881: my %allitems = ();
1.800 albertel 5882: foreach my $item (keys(%newstorehash)) {
5883: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5884: my $key = $1.':keys:'.$2;
5885: $allitems{$key} .= $3.':';
5886: }
1.800 albertel 5887: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5888: }
1.800 albertel 5889: foreach my $item (keys(%allitems)) {
5890: $allitems{$item} =~ s/\:$//;
5891: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5892: }
5893: $items=~s/\&$//;
5894: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5895: }
5896:
1.47 www 5897: # ------------------------------------------------------ critical put interface
5898:
5899: sub cput {
1.134 albertel 5900: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5901: if (!$udomain) { $udomain=$env{'user.domain'}; }
5902: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5903: my $uhome=&homeserver($uname,$udomain);
1.47 www 5904: my $items='';
1.800 albertel 5905: foreach my $item (keys(%$storehash)) {
5906: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5907: }
1.47 www 5908: $items=~s/\&$//;
1.134 albertel 5909: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5910: }
5911:
5912: # -------------------------------------------------------------- eget interface
5913:
5914: sub eget {
1.133 albertel 5915: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5916: my $items='';
1.800 albertel 5917: foreach my $item (@$storearr) {
5918: $items.=&escape($item).'&';
1.191 harris41 5919: }
1.12 www 5920: $items=~s/\&$//;
1.620 albertel 5921: if (!$udomain) { $udomain=$env{'user.domain'}; }
5922: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5923: my $uhome=&homeserver($uname,$udomain);
5924: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5925: my @pairs=split(/\&/,$rep);
5926: my %returnhash=();
1.42 www 5927: my $i=0;
1.800 albertel 5928: foreach my $item (@$storearr) {
5929: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5930: $i++;
1.191 harris41 5931: }
1.12 www 5932: return %returnhash;
5933: }
5934:
1.667 albertel 5935: # ------------------------------------------------------------ tmpput interface
5936: sub tmpput {
1.802 raeburn 5937: my ($storehash,$server,$context)=@_;
1.667 albertel 5938: my $items='';
1.800 albertel 5939: foreach my $item (keys(%$storehash)) {
5940: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5941: }
5942: $items=~s/\&$//;
1.802 raeburn 5943: if (defined($context)) {
5944: $items .= ':'.&escape($context);
5945: }
1.667 albertel 5946: return &reply("tmpput:$items",$server);
5947: }
5948:
5949: # ------------------------------------------------------------ tmpget interface
5950: sub tmpget {
1.688 albertel 5951: my ($token,$server)=@_;
5952: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5953: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5954: my %returnhash;
5955: foreach my $item (split(/\&/,$rep)) {
5956: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5957: next if ($key =~ /^error: 2 /);
1.667 albertel 5958: $returnhash{&unescape($key)}=&thaw_unescape($value);
5959: }
5960: return %returnhash;
5961: }
5962:
1.1113 raeburn 5963: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5964: sub tmpdel {
5965: my ($token,$server)=@_;
5966: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5967: return &reply("tmpdel:$token",$server);
5968: }
5969:
1.1198 raeburn 5970: # ------------------------------------------------------------ get_timebased_id
5971:
5972: sub get_timebased_id {
5973: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5974: $maxtries) = @_;
5975: my ($newid,$error,$dellock);
5976: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5977: return ('','ok','invalid call to get suffix');
5978: }
5979:
5980: # set defaults for any optional args for which values were not supplied
5981: if ($who eq '') {
5982: $who = $env{'user.name'}.':'.$env{'user.domain'};
5983: }
5984: if (!$locktries) {
5985: $locktries = 3;
5986: }
5987: if (!$maxtries) {
5988: $maxtries = 10;
5989: }
5990:
5991: if (($cdom eq '') || ($cnum eq '')) {
5992: if ($env{'request.course.id'}) {
5993: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5994: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5995: }
5996: if (($cdom eq '') || ($cnum eq '')) {
5997: return ('','ok','call to get suffix not in course context');
5998: }
5999: }
6000:
6001: # construct locking item
6002: my $lockhash = {
6003: $prefix."\0".'locked_'.$keyid => $who,
6004: };
6005: my $tries = 0;
6006:
6007: # attempt to get lock on nohist_$namespace file
6008: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6009: while (($gotlock ne 'ok') && $tries <$locktries) {
6010: $tries ++;
6011: sleep 1;
6012: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6013: }
6014:
6015: # attempt to get unique identifier, based on current timestamp
6016: if ($gotlock eq 'ok') {
6017: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6018: my $id = time;
6019: $newid = $id;
1.1268 raeburn 6020: if ($idtype eq 'addcode') {
6021: $newid .= &sixnum_code();
6022: }
1.1198 raeburn 6023: my $idtries = 0;
6024: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6025: if ($idtype eq 'concat') {
6026: $newid = $id.$idtries;
1.1268 raeburn 6027: } elsif ($idtype eq 'addcode') {
6028: $newid = $newid.&sixnum_code();
1.1198 raeburn 6029: } else {
6030: $newid ++;
6031: }
6032: $idtries ++;
6033: }
6034: if (!exists($inuse{$prefix."\0".$newid})) {
6035: my %new_item = (
6036: $prefix."\0".$newid => $who,
6037: );
6038: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6039: $cdom,$cnum);
6040: if ($putresult ne 'ok') {
6041: undef($newid);
6042: $error = 'error saving new item: '.$putresult;
6043: }
6044: } else {
1.1268 raeburn 6045: undef($newid);
1.1198 raeburn 6046: $error = ('error: no unique suffix available for the new item ');
6047: }
6048: # remove lock
6049: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6050: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6051: } else {
6052: $error = "error: could not obtain lockfile\n";
6053: $dellock = 'ok';
1.1276 raeburn 6054: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6055: $dellock = 'nolock';
6056: }
1.1198 raeburn 6057: }
6058: return ($newid,$dellock,$error);
6059: }
6060:
1.1268 raeburn 6061: sub sixnum_code {
6062: my $code;
6063: for (0..6) {
6064: $code .= int( rand(9) );
6065: }
6066: return $code;
6067: }
6068:
1.765 albertel 6069: # -------------------------------------------------- portfolio access checking
6070:
6071: sub portfolio_access {
1.1270 raeburn 6072: my ($requrl,$clientip) = @_;
1.765 albertel 6073: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6074: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6075: if ($result) {
6076: my %setters;
6077: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6078: my ($startblock,$endblock) =
6079: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6080: if ($startblock && $endblock) {
6081: return 'B';
6082: }
6083: } else {
6084: my ($startblock,$endblock) =
6085: &Apache::loncommon::blockcheck(\%setters,'port');
6086: if ($startblock && $endblock) {
6087: return 'B';
6088: }
6089: }
6090: }
1.765 albertel 6091: if ($result eq 'ok') {
1.766 albertel 6092: return 'F';
1.765 albertel 6093: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6094: return 'A';
1.765 albertel 6095: }
1.766 albertel 6096: return '';
1.765 albertel 6097: }
6098:
6099: sub get_portfolio_access {
1.1270 raeburn 6100: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6101:
6102: if (!ref($access_hash)) {
6103: my $current_perms = &get_portfile_permissions($udom,$unum);
6104: my %access_controls = &get_access_controls($current_perms,$group,
6105: $file_name);
6106: $access_hash = $access_controls{$file_name};
6107: }
6108:
1.1270 raeburn 6109: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6110: my $now = time;
6111: if (ref($access_hash) eq 'HASH') {
6112: foreach my $key (keys(%{$access_hash})) {
6113: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6114: if ($start > $now) {
6115: next;
6116: }
6117: if ($end && $end<$now) {
6118: next;
6119: }
6120: if ($scope eq 'public') {
6121: $public = $key;
6122: last;
6123: } elsif ($scope eq 'guest') {
6124: $guest = $key;
6125: } elsif ($scope eq 'domains') {
6126: push(@domains,$key);
6127: } elsif ($scope eq 'users') {
6128: push(@users,$key);
6129: } elsif ($scope eq 'course') {
6130: push(@courses,$key);
6131: } elsif ($scope eq 'group') {
6132: push(@groups,$key);
1.1270 raeburn 6133: } elsif ($scope eq 'ip') {
6134: push(@ips,$key);
1.765 albertel 6135: }
6136: }
6137: if ($public) {
6138: return 'ok';
1.1270 raeburn 6139: } elsif (@ips > 0) {
6140: my $allowed;
6141: foreach my $ipkey (@ips) {
6142: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6143: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6144: $allowed = 1;
6145: last;
6146: }
6147: }
6148: }
6149: if ($allowed) {
6150: return 'ok';
6151: }
1.765 albertel 6152: }
6153: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6154: if ($guest) {
6155: return $guest;
6156: }
6157: } else {
6158: if (@domains > 0) {
6159: foreach my $domkey (@domains) {
6160: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6161: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6162: return 'ok';
6163: }
6164: }
6165: }
6166: }
6167: if (@users > 0) {
6168: foreach my $userkey (@users) {
1.865 raeburn 6169: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6170: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6171: if (ref($item) eq 'HASH') {
6172: if (($item->{'uname'} eq $env{'user.name'}) &&
6173: ($item->{'udom'} eq $env{'user.domain'})) {
6174: return 'ok';
6175: }
6176: }
6177: }
6178: }
1.765 albertel 6179: }
6180: }
6181: my %roleshash;
6182: my @courses_and_groups = @courses;
6183: push(@courses_and_groups,@groups);
6184: if (@courses_and_groups > 0) {
6185: my (%allgroups,%allroles);
6186: my ($start,$end,$role,$sec,$group);
6187: foreach my $envkey (%env) {
1.1060 raeburn 6188: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6189: my $cid = $2.'_'.$3;
6190: if ($1 eq 'gr') {
6191: $group = $4;
6192: $allgroups{$cid}{$group} = $env{$envkey};
6193: } else {
6194: if ($4 eq '') {
6195: $sec = 'none';
6196: } else {
6197: $sec = $4;
6198: }
6199: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6200: }
1.811 albertel 6201: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6202: my $cid = $2.'_'.$3;
6203: if ($4 eq '') {
6204: $sec = 'none';
6205: } else {
6206: $sec = $4;
6207: }
6208: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6209: }
6210: }
6211: if (keys(%allroles) == 0) {
6212: return;
6213: }
6214: foreach my $key (@courses_and_groups) {
6215: my %content = %{$$access_hash{$key}};
6216: my $cnum = $content{'number'};
6217: my $cdom = $content{'domain'};
6218: my $cid = $cdom.'_'.$cnum;
6219: if (!exists($allroles{$cid})) {
6220: next;
6221: }
6222: foreach my $role_id (keys(%{$content{'roles'}})) {
6223: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6224: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6225: my @status = @{$content{'roles'}{$role_id}{'access'}};
6226: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6227: foreach my $role (keys(%{$allroles{$cid}})) {
6228: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6229: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6230: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6231: if (grep/^all$/,@sections) {
6232: return 'ok';
6233: } else {
6234: if (grep/^$sec$/,@sections) {
6235: return 'ok';
6236: }
6237: }
6238: }
6239: }
6240: if (keys(%{$allgroups{$cid}}) == 0) {
6241: if (grep/^none$/,@groups) {
6242: return 'ok';
6243: }
6244: } else {
6245: if (grep/^all$/,@groups) {
6246: return 'ok';
6247: }
6248: foreach my $group (keys(%{$allgroups{$cid}})) {
6249: if (grep/^$group$/,@groups) {
6250: return 'ok';
6251: }
6252: }
6253: }
6254: }
6255: }
6256: }
6257: }
6258: }
6259: if ($guest) {
6260: return $guest;
6261: }
6262: }
6263: }
6264: return;
6265: }
6266:
6267: sub course_group_datechecker {
6268: my ($dates,$now,$status) = @_;
6269: my ($start,$end) = split(/\./,$dates);
6270: if (!$start && !$end) {
6271: return 'ok';
6272: }
6273: if (grep/^active$/,@{$status}) {
6274: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6275: return 'ok';
6276: }
6277: }
6278: if (grep/^previous$/,@{$status}) {
6279: if ($end > $now ) {
6280: return 'ok';
6281: }
6282: }
6283: if (grep/^future$/,@{$status}) {
6284: if ($start > $now) {
6285: return 'ok';
6286: }
6287: }
6288: return;
6289: }
6290:
6291: sub parse_portfolio_url {
6292: my ($url) = @_;
6293:
6294: my ($type,$udom,$unum,$group,$file_name);
6295:
1.823 albertel 6296: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6297: $type = 1;
6298: $udom = $1;
6299: $unum = $2;
6300: $file_name = $3;
1.823 albertel 6301: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6302: $type = 2;
6303: $udom = $1;
6304: $unum = $2;
6305: $group = $3;
6306: $file_name = $3.'/'.$4;
6307: }
6308: if (wantarray) {
6309: return ($type,$udom,$unum,$file_name,$group);
6310: }
6311: return $type;
6312: }
6313:
6314: sub is_portfolio_url {
6315: my ($url) = @_;
6316: return scalar(&parse_portfolio_url($url));
6317: }
6318:
1.798 raeburn 6319: sub is_portfolio_file {
6320: my ($file) = @_;
1.820 raeburn 6321: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6322: return 1;
6323: }
6324: return;
6325: }
6326:
1.976 raeburn 6327: sub usertools_access {
1.1084 raeburn 6328: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6329: my ($access,%tools);
6330: if ($context eq '') {
6331: $context = 'tools';
6332: }
6333: if ($context eq 'requestcourses') {
6334: %tools = (
6335: official => 1,
6336: unofficial => 1,
1.1006 raeburn 6337: community => 1,
1.1246 raeburn 6338: textbook => 1,
1.985 raeburn 6339: );
1.1183 raeburn 6340: } elsif ($context eq 'requestauthor') {
6341: %tools = (
6342: requestauthor => 1,
6343: );
1.985 raeburn 6344: } else {
6345: %tools = (
6346: aboutme => 1,
6347: blog => 1,
1.1177 raeburn 6348: webdav => 1,
1.985 raeburn 6349: portfolio => 1,
6350: );
6351: }
1.976 raeburn 6352: return if (!defined($tools{$tool}));
6353:
1.1242 raeburn 6354: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6355: $udom = $env{'user.domain'};
6356: $uname = $env{'user.name'};
6357: }
6358:
1.978 raeburn 6359: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6360: if ($action ne 'reload') {
1.985 raeburn 6361: if ($context eq 'requestcourses') {
6362: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6363: } elsif ($context eq 'requestauthor') {
6364: return $env{'environment.canrequest.author'};
1.985 raeburn 6365: } else {
6366: return $env{'environment.availabletools.'.$tool};
6367: }
6368: }
1.976 raeburn 6369: }
6370:
1.1183 raeburn 6371: my ($toolstatus,$inststatus,$envkey);
6372: if ($context eq 'requestauthor') {
6373: $envkey = $context;
6374: } else {
6375: $envkey = $context.'.'.$tool;
6376: }
1.976 raeburn 6377:
1.985 raeburn 6378: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6379: ($action ne 'reload')) {
1.1183 raeburn 6380: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6381: $inststatus = $env{'environment.inststatus'};
6382: } else {
1.1084 raeburn 6383: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6384: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6385: $inststatus = $userenvref->{'inststatus'};
6386: } else {
1.1183 raeburn 6387: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6388: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6389: $inststatus = $userenv{'inststatus'};
6390: }
1.976 raeburn 6391: }
6392:
6393: if ($toolstatus ne '') {
6394: if ($toolstatus) {
6395: $access = 1;
6396: } else {
6397: $access = 0;
6398: }
6399: return $access;
6400: }
6401:
1.1084 raeburn 6402: my ($is_adv,%domdef);
6403: if (ref($is_advref) eq 'HASH') {
6404: $is_adv = $is_advref->{'is_adv'};
6405: } else {
6406: $is_adv = &is_advanced_user($udom,$uname);
6407: }
6408: if (ref($domdefref) eq 'HASH') {
6409: %domdef = %{$domdefref};
6410: } else {
6411: %domdef = &get_domain_defaults($udom);
6412: }
1.976 raeburn 6413: if (ref($domdef{$tool}) eq 'HASH') {
6414: if ($is_adv) {
6415: if ($domdef{$tool}{'_LC_adv'} ne '') {
6416: if ($domdef{$tool}{'_LC_adv'}) {
6417: $access = 1;
6418: } else {
6419: $access = 0;
6420: }
6421: return $access;
6422: }
6423: }
6424: if ($inststatus ne '') {
6425: my ($hasaccess,$hasnoaccess);
6426: foreach my $affiliation (split(/:/,$inststatus)) {
6427: if ($domdef{$tool}{$affiliation} ne '') {
6428: if ($domdef{$tool}{$affiliation}) {
6429: $hasaccess = 1;
6430: } else {
6431: $hasnoaccess = 1;
6432: }
6433: }
6434: }
6435: if ($hasaccess || $hasnoaccess) {
6436: if ($hasaccess) {
6437: $access = 1;
6438: } elsif ($hasnoaccess) {
6439: $access = 0;
6440: }
6441: return $access;
6442: }
6443: } else {
6444: if ($domdef{$tool}{'default'} ne '') {
6445: if ($domdef{$tool}{'default'}) {
6446: $access = 1;
6447: } elsif ($domdef{$tool}{'default'} == 0) {
6448: $access = 0;
6449: }
6450: return $access;
6451: }
6452: }
6453: } else {
1.1177 raeburn 6454: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6455: $access = 1;
6456: } else {
6457: $access = 0;
6458: }
1.976 raeburn 6459: return $access;
6460: }
6461: }
6462:
1.1050 raeburn 6463: sub is_course_owner {
6464: my ($cdom,$cnum,$udom,$uname) = @_;
6465: if (($udom eq '') || ($uname eq '')) {
6466: $udom = $env{'user.domain'};
6467: $uname = $env{'user.name'};
6468: }
6469: unless (($udom eq '') || ($uname eq '')) {
6470: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6471: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6472: return 1;
6473: } else {
6474: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6475: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6476: return 1;
6477: }
6478: }
6479: }
6480: }
6481: return;
6482: }
6483:
1.976 raeburn 6484: sub is_advanced_user {
6485: my ($udom,$uname) = @_;
1.1085 raeburn 6486: if ($udom ne '' && $uname ne '') {
6487: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6488: if (wantarray) {
6489: return ($env{'user.adv'},$env{'user.author'});
6490: } else {
6491: return $env{'user.adv'};
6492: }
1.1085 raeburn 6493: }
6494: }
1.976 raeburn 6495: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6496: my %allroles;
1.1128 raeburn 6497: my ($is_adv,$is_author);
1.976 raeburn 6498: foreach my $role (keys(%roleshash)) {
6499: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6500: my $area = '/'.$tdomain.'/'.$trest;
6501: if ($sec ne '') {
6502: $area .= '/'.$sec;
6503: }
6504: if (($area ne '') && ($trole ne '')) {
6505: my $spec=$trole.'.'.$area;
6506: if ($trole =~ /^cr\//) {
6507: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6508: } elsif ($trole ne 'gr') {
6509: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6510: }
1.1128 raeburn 6511: if ($trole eq 'au') {
6512: $is_author = 1;
6513: }
1.976 raeburn 6514: }
6515: }
6516: foreach my $role (keys(%allroles)) {
6517: last if ($is_adv);
6518: foreach my $item (split(/:/,$allroles{$role})) {
6519: if ($item ne '') {
6520: my ($privilege,$restrictions)=split(/&/,$item);
6521: if ($privilege eq 'adv') {
6522: $is_adv = 1;
6523: last;
6524: }
6525: }
6526: }
6527: }
1.1128 raeburn 6528: if (wantarray) {
6529: return ($is_adv,$is_author);
6530: }
1.976 raeburn 6531: return $is_adv;
6532: }
1.798 raeburn 6533:
1.1035 raeburn 6534: sub check_can_request {
1.1036 raeburn 6535: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6536: my $canreq = 0;
6537: my ($types,$typename) = &Apache::loncommon::course_types();
6538: my @options = ('approval','validate','autolimit');
6539: my $optregex = join('|',@options);
6540: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6541: foreach my $type (@{$types}) {
6542: if (&usertools_access($env{'user.name'},
6543: $env{'user.domain'},
6544: $type,undef,'requestcourses')) {
6545: $canreq ++;
1.1036 raeburn 6546: if (ref($request_domains) eq 'HASH') {
6547: push(@{$request_domains->{$type}},$env{'user.domain'});
6548: }
1.1035 raeburn 6549: if ($dom eq $env{'user.domain'}) {
6550: $can_request->{$type} = 1;
6551: }
6552: }
6553: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6554: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6555: if (@curr > 0) {
1.1036 raeburn 6556: foreach my $item (@curr) {
6557: if (ref($request_domains) eq 'HASH') {
6558: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6559: if ($otherdom ne '') {
6560: if (ref($request_domains->{$type}) eq 'ARRAY') {
6561: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6562: push(@{$request_domains->{$type}},$otherdom);
6563: }
6564: } else {
6565: push(@{$request_domains->{$type}},$otherdom);
6566: }
6567: }
6568: }
6569: }
6570: unless($dom eq $env{'user.domain'}) {
6571: $canreq ++;
1.1035 raeburn 6572: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6573: $can_request->{$type} = 1;
6574: }
6575: }
6576: }
6577: }
6578: }
6579: }
6580: return $canreq;
6581: }
6582:
1.341 www 6583: # ---------------------------------------------- Custom access rule evaluation
6584:
6585: sub customaccess {
6586: my ($priv,$uri)=@_;
1.807 albertel 6587: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6588: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6589: $udom = &LONCAPA::clean_domain($udom);
6590: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6591: my $access=0;
1.800 albertel 6592: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6593: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6594: if ($type eq 'user') {
6595: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6596: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6597: if ($tdom) {
6598: if ($tdom ne $env{'user.domain'}) { next; }
6599: }
1.896 albertel 6600: if ($tuname) {
6601: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6602: }
6603: $access=($effect eq 'allow');
6604: last;
6605: }
6606: } else {
6607: if ($role) {
6608: if ($role ne $urole) { next; }
6609: }
6610: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6611: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6612: if ($tdom) {
6613: if ($tdom ne $udom) { next; }
6614: }
6615: if ($tcrs) {
6616: if ($tcrs ne $ucrs) { next; }
6617: }
6618: if ($tsec) {
6619: if ($tsec ne $usec) { next; }
6620: }
6621: $access=($effect eq 'allow');
6622: last;
6623: }
6624: if ($realm eq '' && $role eq '') {
6625: $access=($effect eq 'allow');
6626: }
1.402 bowersj2 6627: }
1.341 www 6628: }
6629: return $access;
6630: }
6631:
1.103 harris41 6632: # ------------------------------------------------- Check for a user privilege
1.12 www 6633:
6634: sub allowed {
1.1270 raeburn 6635: my ($priv,$uri,$symb,$role,$clientip)=@_;
1.705 albertel 6636: my $ver_orguri=$uri;
1.439 www 6637: $uri=&deversion($uri);
1.152 www 6638: my $orguri=$uri;
1.52 www 6639: $uri=&declutter($uri);
1.809 raeburn 6640:
1.810 raeburn 6641: if ($priv eq 'evb') {
6642: # Evade communication block restrictions for specified role in a course
6643: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6644: return $1;
6645: } else {
6646: return;
6647: }
6648: }
6649:
1.620 albertel 6650: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6651: # Free bre access to adm and meta resources
1.775 albertel 6652: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6653: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6654: && ($priv eq 'bre')) {
1.14 www 6655: return 'F';
1.159 www 6656: }
6657:
1.545 banghart 6658: # Free bre access to user's own portfolio contents
1.714 raeburn 6659: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6660: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6661: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6662: my %setters;
6663: my ($startblock,$endblock) =
6664: &Apache::loncommon::blockcheck(\%setters,'port');
6665: if ($startblock && $endblock) {
6666: return 'B';
6667: } else {
6668: return 'F';
6669: }
1.545 banghart 6670: }
6671:
1.762 raeburn 6672: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6673: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6674: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6675: if (exists($env{'request.course.id'})) {
6676: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6677: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6678: if (($domain eq $cdom) && ($name eq $cnum)) {
6679: my $courseprivid=$env{'request.course.id'};
6680: $courseprivid=~s/\_/\//;
6681: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6682: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6683: return $1;
1.762 raeburn 6684: } else {
6685: if ($env{'request.course.sec'}) {
6686: $courseprivid.='/'.$env{'request.course.sec'};
6687: }
6688: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6689: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6690: return $2;
6691: }
1.714 raeburn 6692: }
6693: }
6694: }
6695: }
6696:
1.159 www 6697: # Free bre to public access
6698:
6699: if ($priv eq 'bre') {
1.238 www 6700: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6701: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6702: return 'F';
6703: }
1.238 www 6704: if ($copyright eq 'priv') {
6705: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6706: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6707: return '';
6708: }
6709: }
6710: if ($copyright eq 'domain') {
6711: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6712: unless (($env{'user.domain'} eq $1) ||
6713: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6714: return '';
6715: }
1.262 matthew 6716: }
1.620 albertel 6717: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6718: # Library role, so allow browsing of resources in this domain.
6719: return 'F';
1.238 www 6720: }
1.341 www 6721: if ($copyright eq 'custom') {
6722: unless (&customaccess($priv,$uri)) { return ''; }
6723: }
1.14 www 6724: }
1.264 matthew 6725: # Domain coordinator is trying to create a course
1.620 albertel 6726: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6727: # uri is the requested domain in this case.
6728: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6729: # a role of dc for the domain in question.
1.620 albertel 6730: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6731: }
1.29 www 6732:
1.52 www 6733: my $thisallowed='';
6734: my $statecond=0;
6735: my $courseprivid='';
6736:
1.1039 raeburn 6737: my $ownaccess;
1.1043 raeburn 6738: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6739: if (($priv eq 'bro') && ($env{'user.author'})) {
6740: if ($uri eq '') {
6741: $ownaccess = 1;
6742: } else {
6743: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6744: my $udom = $env{'user.domain'};
6745: my $uname = $env{'user.name'};
6746: if ($uri =~ m{^\Q$udom\E/?$}) {
6747: $ownaccess = 1;
1.1040 raeburn 6748: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6749: unless ($uri =~ m{\.\./}) {
6750: $ownaccess = 1;
6751: }
6752: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6753: my $now = time;
6754: if ($uri =~ m{^([^/]+)/?$}) {
6755: my $adom = $1;
6756: foreach my $key (keys(%env)) {
1.1042 raeburn 6757: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6758: my ($start,$end) = split('.',$env{$key});
6759: if (($now >= $start) && (!$end || $end < $now)) {
6760: $ownaccess = 1;
6761: last;
6762: }
6763: }
6764: }
6765: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6766: my $adom = $1;
6767: my $aname = $2;
1.1042 raeburn 6768: foreach my $role ('ca','aa') {
6769: if ($env{"user.role.$role./$adom/$aname"}) {
6770: my ($start,$end) =
6771: split('.',$env{"user.role.$role./$adom/$aname"});
6772: if (($now >= $start) && (!$end || $end < $now)) {
6773: $ownaccess = 1;
6774: last;
6775: }
1.1039 raeburn 6776: }
6777: }
6778: }
6779: }
6780: }
6781: }
6782: }
6783:
1.52 www 6784: # Course
6785:
1.620 albertel 6786: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6787: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6788: $thisallowed.=$1;
6789: }
1.52 www 6790: }
1.29 www 6791:
1.52 www 6792: # Domain
6793:
1.620 albertel 6794: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6795: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6796: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6797: $thisallowed.=$1;
6798: }
1.12 www 6799: }
1.52 www 6800:
1.1141 raeburn 6801: # User who is not author or co-author might still be able to edit
6802: # resource of an author in the domain (e.g., if Domain Coordinator).
6803: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6804: (&allowed('mdc',$env{'request.course.id'}))) {
6805: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6806: $thisallowed.=$1;
6807: }
6808: }
6809:
1.52 www 6810: # Course: uri itself is a course
1.66 www 6811: my $courseuri=$uri;
6812: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6813: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6814:
1.620 albertel 6815: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6816: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6817: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6818: $thisallowed.=$1;
6819: }
1.12 www 6820: }
1.29 www 6821:
1.665 albertel 6822: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6823: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6824: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6825: $thisallowed='';
1.671 raeburn 6826: my ($match)=&is_on_map($uri);
6827: if ($match) {
6828: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6829: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6830: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6831: if (@blockers > 0) {
6832: $thisallowed = 'B';
6833: } else {
6834: $thisallowed.=$1;
6835: }
1.671 raeburn 6836: }
6837: } else {
1.705 albertel 6838: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6839: if ($refuri) {
6840: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6841: $thisallowed='F';
1.671 raeburn 6842: } else {
6843: $refuri=&declutter($refuri);
6844: my ($match) = &is_on_map($refuri);
6845: if ($match) {
1.1162 raeburn 6846: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6847: if (@blockers > 0) {
6848: $thisallowed = 'B';
6849: } else {
6850: $thisallowed='F';
6851: }
1.671 raeburn 6852: }
1.669 raeburn 6853: }
1.671 raeburn 6854: }
6855: }
1.314 www 6856: }
1.492 albertel 6857:
1.766 albertel 6858: if ($priv eq 'bre'
6859: && $thisallowed ne 'F'
6860: && $thisallowed ne '2'
6861: && &is_portfolio_url($uri)) {
1.1270 raeburn 6862: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 6863: }
1.1250 raeburn 6864:
1.52 www 6865: # Full access at system, domain or course-wide level? Exit.
1.29 www 6866: if ($thisallowed=~/F/) {
6867: return 'F';
6868: }
6869:
1.52 www 6870: # If this is generating or modifying users, exit with special codes
1.29 www 6871:
1.643 www 6872: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6873: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6874: my ($audom,$auname)=split('/',$uri);
1.643 www 6875: # no author name given, so this just checks on the general right to make a co-author in this domain
6876: unless ($auname) { return $thisallowed; }
6877: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6878: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6879: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6880: ($audom ne $env{'request.role.domain'}))) { return ''; }
6881: }
1.52 www 6882: return $thisallowed;
6883: }
6884: #
1.103 harris41 6885: # Gathered so far: system, domain and course wide privileges
1.52 www 6886: #
6887: # Course: See if uri or referer is an individual resource that is part of
6888: # the course
6889:
1.620 albertel 6890: if ($env{'request.course.id'}) {
1.232 www 6891:
1.620 albertel 6892: $courseprivid=$env{'request.course.id'};
6893: if ($env{'request.course.sec'}) {
6894: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6895: }
6896: $courseprivid=~s/\_/\//;
6897: my $checkreferer=1;
1.232 www 6898: my ($match,$cond)=&is_on_map($uri);
6899: if ($match) {
6900: $statecond=$cond;
1.620 albertel 6901: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6902: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6903: my $value = $1;
6904: if ($priv eq 'bre') {
6905: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6906: if (@blockers > 0) {
6907: $thisallowed = 'B';
6908: } else {
6909: $thisallowed.=$value;
6910: }
6911: } else {
6912: $thisallowed.=$value;
6913: }
1.52 www 6914: $checkreferer=0;
6915: }
1.29 www 6916: }
1.83 www 6917:
1.148 www 6918: if ($checkreferer) {
1.620 albertel 6919: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6920: unless ($refuri) {
1.800 albertel 6921: foreach my $key (keys(%env)) {
6922: if ($key=~/^httpref\..*\*/) {
6923: my $pattern=$key;
1.156 www 6924: $pattern=~s/^httpref\.\/res\///;
1.148 www 6925: $pattern=~s/\*/\[\^\/\]\+/g;
6926: $pattern=~s/\//\\\//g;
1.152 www 6927: if ($orguri=~/$pattern/) {
1.800 albertel 6928: $refuri=$env{$key};
1.148 www 6929: }
6930: }
1.191 harris41 6931: }
1.148 www 6932: }
1.232 www 6933:
1.148 www 6934: if ($refuri) {
1.152 www 6935: $refuri=&declutter($refuri);
1.232 www 6936: my ($match,$cond)=&is_on_map($refuri);
6937: if ($match) {
6938: my $refstatecond=$cond;
1.620 albertel 6939: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6940: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6941: my $value = $1;
6942: if ($priv eq 'bre') {
6943: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6944: if (@blockers > 0) {
6945: $thisallowed = 'B';
6946: } else {
6947: $thisallowed.=$value;
6948: }
6949: } else {
6950: $thisallowed.=$value;
6951: }
1.53 www 6952: $uri=$refuri;
6953: $statecond=$refstatecond;
1.52 www 6954: }
6955: }
1.148 www 6956: }
1.29 www 6957: }
1.52 www 6958: }
1.29 www 6959:
1.52 www 6960: #
1.103 harris41 6961: # Gathered now: all privileges that could apply, and condition number
1.52 www 6962: #
6963: #
6964: # Full or no access?
6965: #
1.29 www 6966:
1.52 www 6967: if ($thisallowed=~/F/) {
6968: return 'F';
6969: }
1.29 www 6970:
1.52 www 6971: unless ($thisallowed) {
6972: return '';
6973: }
1.29 www 6974:
1.52 www 6975: # Restrictions exist, deal with them
6976: #
6977: # C:according to course preferences
6978: # R:according to resource settings
6979: # L:unless locked
6980: # X:according to user session state
6981: #
6982:
6983: # Possibly locked functionality, check all courses
1.54 www 6984: # Locks might take effect only after 10 minutes cache expiration for other
6985: # courses, and 2 minutes for current course
1.52 www 6986:
6987: my $envkey;
6988: if ($thisallowed=~/L/) {
1.1000 raeburn 6989: foreach $envkey (keys(%env)) {
1.54 www 6990: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6991: my $courseid=$2;
6992: my $roleid=$1.'.'.$2;
1.92 www 6993: $courseid=~s/^\///;
1.54 www 6994: my $expiretime=600;
1.620 albertel 6995: if ($env{'request.role'} eq $roleid) {
1.54 www 6996: $expiretime=120;
6997: }
6998: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6999: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7000: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7001: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7002: }
1.620 albertel 7003: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7004: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7005: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7006: &log($env{'user.domain'},$env{'user.name'},
7007: $env{'user.home'},
1.57 www 7008: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7009: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7010: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7011: return '';
7012: }
7013: }
1.620 albertel 7014: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7015: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7016: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7017: &log($env{'user.domain'},$env{'user.name'},
7018: $env{'user.home'},
1.57 www 7019: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7020: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7021: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7022: return '';
7023: }
7024: }
7025: }
1.29 www 7026: }
1.52 www 7027: }
7028:
7029: #
7030: # Rest of the restrictions depend on selected course
7031: #
7032:
1.620 albertel 7033: unless ($env{'request.course.id'}) {
1.766 albertel 7034: if ($thisallowed eq 'A') {
7035: return 'A';
1.814 raeburn 7036: } elsif ($thisallowed eq 'B') {
7037: return 'B';
1.766 albertel 7038: } else {
7039: return '1';
7040: }
1.52 www 7041: }
1.29 www 7042:
1.52 www 7043: #
7044: # Now user is definitely in a course
7045: #
1.53 www 7046:
7047:
7048: # Course preferences
7049:
7050: if ($thisallowed=~/C/) {
1.620 albertel 7051: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7052: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7053: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7054: =~/\Q$rolecode\E/) {
1.1103 raeburn 7055: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7056: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7057: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7058: $env{'request.course.id'});
7059: }
1.237 www 7060: return '';
7061: }
7062:
1.620 albertel 7063: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7064: =~/\Q$unamedom\E/) {
1.1103 raeburn 7065: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7066: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7067: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7068: $env{'request.course.id'});
7069: }
1.54 www 7070: return '';
7071: }
1.53 www 7072: }
7073:
7074: # Resource preferences
7075:
7076: if ($thisallowed=~/R/) {
1.620 albertel 7077: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7078: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7079: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7080: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7081: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7082: }
7083: return '';
1.54 www 7084: }
1.53 www 7085: }
1.30 www 7086:
1.246 www 7087: # Restricted by state or randomout?
1.30 www 7088:
1.52 www 7089: if ($thisallowed=~/X/) {
1.620 albertel 7090: if ($env{'acc.randomout'}) {
1.579 albertel 7091: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7092: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7093: return '';
7094: }
1.247 www 7095: }
7096: if (&condval($statecond)) {
1.52 www 7097: return '2';
7098: } else {
7099: return '';
7100: }
7101: }
1.30 www 7102:
1.766 albertel 7103: if ($thisallowed eq 'A') {
7104: return 'A';
1.814 raeburn 7105: } elsif ($thisallowed eq 'B') {
7106: return 'B';
1.766 albertel 7107: }
1.52 www 7108: return 'F';
1.232 www 7109: }
1.1162 raeburn 7110:
1.1192 raeburn 7111: # ------------------------------------------- Check construction space access
7112:
7113: sub constructaccess {
7114: my ($url,$setpriv)=@_;
7115:
7116: # We do not allow editing of previous versions of files
7117: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7118:
7119: # Get username and domain from URL
7120: my ($ownername,$ownerdomain,$ownerhome);
7121:
7122: ($ownerdomain,$ownername) =
7123: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7124:
7125: # The URL does not really point to any authorspace, forget it
7126: unless (($ownername) && ($ownerdomain)) { return ''; }
7127:
7128: # Now we need to see if the user has access to the authorspace of
7129: # $ownername at $ownerdomain
7130:
7131: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7132: # Real author for this?
7133: $ownerhome = $env{'user.home'};
7134: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7135: return ($ownername,$ownerdomain,$ownerhome);
7136: }
7137: } else {
7138: # Co-author for this?
7139: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7140: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7141: $ownerhome = &homeserver($ownername,$ownerdomain);
7142: return ($ownername,$ownerdomain,$ownerhome);
7143: }
7144: }
7145:
7146: # We don't have any access right now. If we are not possibly going to do anything about this,
7147: # we might as well leave
7148: unless ($setpriv) { return ''; }
7149:
7150: # Backdoor access?
7151: my $allowed=&allowed('eco',$ownerdomain);
7152: # Nope
7153: unless ($allowed) { return ''; }
7154: # Looks like we may have access, but could be locked by the owner of the construction space
7155: if ($allowed eq 'U') {
7156: my %blocked=&get('environment',['domcoord.author'],
7157: $ownerdomain,$ownername);
7158: # Is blocked by owner
7159: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7160: }
7161: if (($allowed eq 'F') || ($allowed eq 'U')) {
7162: # Grant temporary access
7163: my $then=$env{'user.login.time'};
1.1209 raeburn 7164: my $update=$env{'user.update.time'};
1.1192 raeburn 7165: if (!$update) { $update = $then; }
7166: my $refresh=$env{'user.refresh.time'};
7167: if (!$refresh) { $refresh = $update; }
7168: my $now = time;
7169: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7170: $now,'ca','constructaccess');
7171: $ownerhome = &homeserver($ownername,$ownerdomain);
7172: return($ownername,$ownerdomain,$ownerhome);
7173: }
7174: # No business here
7175: return '';
7176: }
7177:
1.1162 raeburn 7178: sub get_comm_blocks {
7179: my ($cdom,$cnum) = @_;
7180: if ($cdom eq '' || $cnum eq '') {
7181: return unless ($env{'request.course.id'});
7182: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7183: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7184: }
7185: my %commblocks;
7186: my $hashid=$cdom.'_'.$cnum;
7187: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7188: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7189: %commblocks = %{$blocksref};
7190: } else {
7191: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7192: my $cachetime = 600;
7193: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7194: }
7195: return %commblocks;
7196: }
7197:
7198: sub has_comm_blocking {
7199: my ($priv,$symb,$uri,$blocks) = @_;
7200: return unless ($env{'request.course.id'});
7201: return unless ($priv eq 'bre');
7202: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7203: my %commblocks;
7204: if (ref($blocks) eq 'HASH') {
7205: %commblocks = %{$blocks};
7206: } else {
7207: %commblocks = &get_comm_blocks();
7208: }
7209: return unless (keys(%commblocks) > 0);
7210: if (!$symb) { $symb=&symbread($uri,1); }
7211: my ($map,$resid,undef)=&decode_symb($symb);
7212: my %tocheck = (
7213: maps => $map,
7214: resources => $symb,
7215: );
7216: my @blockers;
7217: my $now = time;
1.1163 raeburn 7218: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7219: foreach my $block (keys(%commblocks)) {
7220: if ($block =~ /^(\d+)____(\d+)$/) {
7221: my ($start,$end) = ($1,$2);
7222: if ($start <= $now && $end >= $now) {
7223: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7224: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7225: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7226: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7227: unless (grep(/^\Q$block\E$/,@blockers)) {
7228: push(@blockers,$block);
7229: }
7230: }
7231: }
7232: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7233: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7234: unless (grep(/^\Q$block\E$/,@blockers)) {
7235: push(@blockers,$block);
7236: }
7237: }
7238: }
7239: }
7240: }
7241: }
7242: } elsif ($block =~ /^firstaccess____(.+)$/) {
7243: my $item = $1;
1.1163 raeburn 7244: my @to_test;
1.1162 raeburn 7245: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7246: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7247: my $check_interval;
7248: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7249: my @interval;
7250: my $type = 'map';
7251: if ($item eq 'course') {
7252: $type = 'course';
7253: @interval=&EXT("resource.0.interval");
7254: } else {
7255: if ($item =~ /___\d+___/) {
7256: $type = 'resource';
7257: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7258: if (ref($navmap)) {
7259: my $res = $navmap->getBySymb($item);
7260: push(@to_test,$res);
7261: }
1.1162 raeburn 7262: } else {
7263: my $mapsymb = &symbread($item,1);
7264: if ($mapsymb) {
7265: if (ref($navmap)) {
7266: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7267: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7268: foreach my $res (@to_test) {
1.1162 raeburn 7269: my $symb = $res->symb();
7270: next if ($symb eq $mapsymb);
7271: if ($symb ne '') {
7272: @interval=&EXT("resource.0.interval",$symb);
7273: last;
7274: }
7275: }
7276: }
7277: }
7278: }
7279: }
7280: if ($interval[0] =~ /\d+/) {
7281: my $first_access;
7282: if ($type eq 'resource') {
7283: $first_access=&get_first_access($interval[1],$item);
7284: } elsif ($type eq 'map') {
7285: $first_access=&get_first_access($interval[1],undef,$item);
7286: } else {
7287: $first_access=&get_first_access($interval[1]);
7288: }
7289: if ($first_access) {
7290: my $timesup = $first_access+$interval[0];
7291: if ($timesup > $now) {
1.1163 raeburn 7292: foreach my $res (@to_test) {
7293: if ($res->is_problem()) {
7294: if ($res->completable()) {
7295: unless (grep(/^\Q$block\E$/,@blockers)) {
7296: push(@blockers,$block);
7297: }
7298: last;
7299: }
7300: }
1.1162 raeburn 7301: }
7302: }
7303: }
7304: }
7305: }
7306: }
7307: }
7308: }
7309: }
7310: return @blockers;
7311: }
7312:
7313: sub check_docs_block {
7314: my ($docsblock,$tocheck) =@_;
7315: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7316: return;
7317: }
7318: if (ref($docsblock->{'maps'}) eq 'HASH') {
7319: if ($tocheck->{'maps'}) {
7320: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7321: return 1;
7322: }
7323: }
7324: }
7325: if (ref($docsblock->{'resources'}) eq 'HASH') {
7326: if ($tocheck->{'resources'}) {
7327: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7328: return 1;
7329: }
7330: }
7331: }
7332: return;
7333: }
7334:
1.1133 foxr 7335: #
7336: # Removes the versino from a URI and
7337: # splits it in to its filename and path to the filename.
7338: # Seems like File::Basename could have done this more clearly.
7339: # Parameters:
7340: # $uri - input URI
7341: # Returns:
7342: # Two element list consisting of
7343: # $pathname - the URI up to and excluding the trailing /
7344: # $filename - The part of the URI following the last /
7345: # NOTE:
7346: # Another realization of this is simply:
7347: # use File::Basename;
7348: # ...
7349: # $uri = shift;
7350: # $filename = basename($uri);
7351: # $path = dirname($uri);
7352: # return ($filename, $path);
7353: #
7354: # The implementation below is probably faster however.
7355: #
1.710 albertel 7356: sub split_uri_for_cond {
7357: my $uri=&deversion(&declutter(shift));
7358: my @uriparts=split(/\//,$uri);
7359: my $filename=pop(@uriparts);
7360: my $pathname=join('/',@uriparts);
7361: return ($pathname,$filename);
7362: }
1.232 www 7363: # --------------------------------------------------- Is a resource on the map?
7364:
7365: sub is_on_map {
1.710 albertel 7366: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7367: #Trying to find the conditional for the file
1.620 albertel 7368: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7369: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7370: if ($match) {
1.289 bowersj2 7371: return (1,$1);
7372: } else {
1.434 www 7373: return (0,0);
1.289 bowersj2 7374: }
1.12 www 7375: }
7376:
1.427 www 7377: # --------------------------------------------------------- Get symb from alias
7378:
7379: sub get_symb_from_alias {
7380: my $symb=shift;
7381: my ($map,$resid,$url)=&decode_symb($symb);
7382: # Already is a symb
7383: if ($url) { return $symb; }
7384: # Must be an alias
7385: my $aliassymb='';
7386: my %bighash;
1.620 albertel 7387: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7388: &GDBM_READER(),0640)) {
7389: my $rid=$bighash{'mapalias_'.$symb};
7390: if ($rid) {
7391: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7392: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7393: $resid,$bighash{'src_'.$rid});
1.427 www 7394: }
7395: untie %bighash;
7396: }
7397: return $aliassymb;
7398: }
7399:
1.12 www 7400: # ----------------------------------------------------------------- Define Role
7401:
7402: sub definerole {
7403: if (allowed('mcr','/')) {
7404: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7405: foreach my $role (split(':',$sysrole)) {
7406: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7407: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7408: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7409: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7410: return "refused:s:$crole&$cqual";
7411: }
7412: }
1.191 harris41 7413: }
1.800 albertel 7414: foreach my $role (split(':',$domrole)) {
7415: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7416: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7417: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7418: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7419: return "refused:d:$crole&$cqual";
7420: }
7421: }
1.191 harris41 7422: }
1.800 albertel 7423: foreach my $role (split(':',$courole)) {
7424: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7425: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7426: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7427: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7428: return "refused:c:$crole&$cqual";
7429: }
7430: }
1.191 harris41 7431: }
1.620 albertel 7432: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7433: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7434: "rolesdef_$rolename=".
7435: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7436: return reply($command,$env{'user.home'});
1.12 www 7437: } else {
7438: return 'refused';
7439: }
1.105 harris41 7440: }
7441:
7442: # ---------------- Make a metadata query against the network of library servers
7443:
7444: sub metadata_query {
1.1237 raeburn 7445: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7446: my %rhash;
1.845 albertel 7447: my %libserv = &all_library();
1.244 matthew 7448: my @server_list = (defined($server_array) ? @$server_array
7449: : keys(%libserv) );
7450: for my $server (@server_list) {
1.1237 raeburn 7451: my $domains = '';
7452: if (ref($domains_hash) eq 'HASH') {
7453: $domains = $domains_hash->{$server};
7454: }
1.118 harris41 7455: unless ($custom or $customshow) {
1.1237 raeburn 7456: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7457: $rhash{$server}=$reply;
7458: }
7459: else {
7460: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7461: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7462: $server);
7463: $rhash{$server}=$reply;
7464: }
1.112 harris41 7465: }
1.118 harris41 7466: return \%rhash;
1.240 www 7467: }
7468:
7469: # ----------------------------------------- Send log queries and wait for reply
7470:
7471: sub log_query {
7472: my ($uname,$udom,$query,%filters)=@_;
7473: my $uhome=&homeserver($uname,$udom);
7474: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7475: my $uhost=&hostname($uhome);
1.800 albertel 7476: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7477: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7478: $uhome);
1.479 albertel 7479: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7480: return get_query_reply($queryid);
7481: }
7482:
1.818 raeburn 7483: # -------------------------- Update MySQL table for portfolio file
7484:
7485: sub update_portfolio_table {
1.821 raeburn 7486: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7487: if ($group ne '') {
7488: $file_name =~s /^\Q$group\E//;
7489: }
1.818 raeburn 7490: my $homeserver = &homeserver($uname,$udom);
7491: my $queryid=
1.821 raeburn 7492: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7493: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7494: my $reply = &get_query_reply($queryid);
7495: return $reply;
7496: }
7497:
1.899 raeburn 7498: # -------------------------- Update MySQL allusers table
7499:
7500: sub update_allusers_table {
7501: my ($uname,$udom,$names) = @_;
7502: my $homeserver = &homeserver($uname,$udom);
7503: my $queryid=
7504: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7505: 'lastname='.&escape($names->{'lastname'}).'%%'.
7506: 'firstname='.&escape($names->{'firstname'}).'%%'.
7507: 'middlename='.&escape($names->{'middlename'}).'%%'.
7508: 'generation='.&escape($names->{'generation'}).'%%'.
7509: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7510: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7511: return;
1.899 raeburn 7512: }
7513:
1.508 raeburn 7514: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7515:
7516: sub fetch_enrollment_query {
1.511 raeburn 7517: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7518: my $homeserver;
1.547 raeburn 7519: my $maxtries = 1;
1.508 raeburn 7520: if ($context eq 'automated') {
7521: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7522: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7523: } else {
7524: $homeserver = &homeserver($cnum,$dom);
7525: }
1.838 albertel 7526: my $host=&hostname($homeserver);
1.506 raeburn 7527: my $cmd = '';
1.1000 raeburn 7528: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7529: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7530: }
7531: $cmd =~ s/%%$//;
7532: $cmd = &escape($cmd);
7533: my $query = 'fetchenrollment';
1.620 albertel 7534: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7535: unless ($queryid=~/^\Q$host\E\_/) {
7536: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7537: return 'error: '.$queryid;
7538: }
1.506 raeburn 7539: my $reply = &get_query_reply($queryid);
1.547 raeburn 7540: my $tries = 1;
7541: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7542: $reply = &get_query_reply($queryid);
7543: $tries ++;
7544: }
1.526 raeburn 7545: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7546: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7547: } else {
1.901 albertel 7548: my @responses = split(/:/,$reply);
1.515 raeburn 7549: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7550: foreach my $line (@responses) {
7551: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7552: $$replyref{$key} = $value;
7553: }
7554: } else {
1.1117 foxr 7555: my $pathname = LONCAPA::tempdir();
1.800 albertel 7556: foreach my $line (@responses) {
7557: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7558: $$replyref{$key} = $value;
7559: if ($value > 0) {
1.800 albertel 7560: foreach my $item (@{$$affiliatesref{$key}}) {
7561: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7562: my $destname = $pathname.'/'.$filename;
7563: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7564: if ($xml_classlist =~ /^error/) {
7565: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7566: } else {
1.506 raeburn 7567: if ( open(FILE,">$destname") ) {
7568: print FILE &unescape($xml_classlist);
7569: close(FILE);
1.526 raeburn 7570: } else {
7571: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7572: }
7573: }
7574: }
7575: }
7576: }
7577: }
7578: return 'ok';
7579: }
7580: return 'error';
7581: }
7582:
1.242 www 7583: sub get_query_reply {
7584: my $queryid=shift;
1.1117 foxr 7585: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7586: my $reply='';
7587: for (1..100) {
7588: sleep 2;
7589: if (-e $replyfile.'.end') {
1.448 albertel 7590: if (open(my $fh,$replyfile)) {
1.904 albertel 7591: $reply = join('',<$fh>);
7592: close($fh);
1.240 www 7593: } else { return 'error: reply_file_error'; }
1.242 www 7594: return &unescape($reply);
7595: }
1.240 www 7596: }
1.242 www 7597: return 'timeout:'.$queryid;
1.240 www 7598: }
7599:
7600: sub courselog_query {
1.241 www 7601: #
7602: # possible filters:
7603: # url: url or symb
7604: # username
7605: # domain
7606: # action: view, submit, grade
7607: # start: timestamp
7608: # end: timestamp
7609: #
1.240 www 7610: my (%filters)=@_;
1.620 albertel 7611: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7612: if ($filters{'url'}) {
7613: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7614: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7615: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7616: }
1.620 albertel 7617: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7618: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7619: return &log_query($cname,$cdom,'courselog',%filters);
7620: }
7621:
7622: sub userlog_query {
1.858 raeburn 7623: #
7624: # possible filters:
7625: # action: log check role
7626: # start: timestamp
7627: # end: timestamp
7628: #
1.240 www 7629: my ($uname,$udom,%filters)=@_;
7630: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7631: }
7632:
1.506 raeburn 7633: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7634:
7635: sub auto_run {
1.508 raeburn 7636: my ($cnum,$cdom) = @_;
1.876 raeburn 7637: my $response = 0;
7638: my $settings;
7639: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7640: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7641: $settings = $domconfig{'autoenroll'};
7642: if ($settings->{'run'} eq '1') {
7643: $response = 1;
7644: }
7645: } else {
1.934 raeburn 7646: my $homeserver;
7647: if (&is_course($cdom,$cnum)) {
7648: $homeserver = &homeserver($cnum,$cdom);
7649: } else {
7650: $homeserver = &domain($cdom,'primary');
7651: }
7652: if ($homeserver ne 'no_host') {
7653: $response = &reply('autorun:'.$cdom,$homeserver);
7654: }
1.876 raeburn 7655: }
1.506 raeburn 7656: return $response;
7657: }
1.776 albertel 7658:
1.506 raeburn 7659: sub auto_get_sections {
1.508 raeburn 7660: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7661: my $homeserver;
7662: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7663: $homeserver = &homeserver($cnum,$cdom);
7664: }
7665: if (!defined($homeserver)) {
7666: if ($cdom =~ /^$match_domain$/) {
7667: $homeserver = &domain($cdom,'primary');
7668: }
7669: }
7670: my @secs;
7671: if (defined($homeserver)) {
7672: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7673: unless ($response eq 'refused') {
7674: @secs = split(/:/,$response);
7675: }
1.506 raeburn 7676: }
7677: return @secs;
7678: }
1.776 albertel 7679:
1.506 raeburn 7680: sub auto_new_course {
1.1099 raeburn 7681: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7682: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7683: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7684: return $response;
7685: }
1.776 albertel 7686:
1.506 raeburn 7687: sub auto_validate_courseID {
1.508 raeburn 7688: my ($cnum,$cdom,$inst_course_id) = @_;
7689: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7690: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7691: return $response;
7692: }
1.776 albertel 7693:
1.1007 raeburn 7694: sub auto_validate_instcode {
1.1020 raeburn 7695: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7696: my ($homeserver,$response);
7697: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7698: $homeserver = &homeserver($cnum,$cdom);
7699: }
7700: if (!defined($homeserver)) {
7701: if ($cdom =~ /^$match_domain$/) {
7702: $homeserver = &domain($cdom,'primary');
7703: }
7704: }
1.1065 raeburn 7705: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7706: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7707: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7708: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7709: }
7710:
1.506 raeburn 7711: sub auto_create_password {
1.873 raeburn 7712: my ($cnum,$cdom,$authparam,$udom) = @_;
7713: my ($homeserver,$response);
1.506 raeburn 7714: my $create_passwd = 0;
7715: my $authchk = '';
1.873 raeburn 7716: if ($udom =~ /^$match_domain$/) {
7717: $homeserver = &domain($udom,'primary');
7718: }
7719: if ($homeserver eq '') {
7720: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7721: $homeserver = &homeserver($cnum,$cdom);
7722: }
7723: }
7724: if ($homeserver eq '') {
7725: $authchk = 'nodomain';
1.506 raeburn 7726: } else {
1.873 raeburn 7727: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7728: if ($response eq 'refused') {
7729: $authchk = 'refused';
7730: } else {
1.901 albertel 7731: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7732: }
1.506 raeburn 7733: }
7734: return ($authparam,$create_passwd,$authchk);
7735: }
7736:
1.706 raeburn 7737: sub auto_photo_permission {
7738: my ($cnum,$cdom,$students) = @_;
7739: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7740: my ($outcome,$perm_reqd,$conditions) =
7741: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7742: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7743: return (undef,undef);
7744: }
1.706 raeburn 7745: return ($outcome,$perm_reqd,$conditions);
7746: }
7747:
7748: sub auto_checkphotos {
7749: my ($uname,$udom,$pid) = @_;
7750: my $homeserver = &homeserver($uname,$udom);
7751: my ($result,$resulttype);
7752: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7753: &escape($uname).':'.&escape($pid),
7754: $homeserver));
1.709 albertel 7755: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7756: return (undef,undef);
7757: }
1.706 raeburn 7758: if ($outcome) {
7759: ($result,$resulttype) = split(/:/,$outcome);
7760: }
7761: return ($result,$resulttype);
7762: }
7763:
7764: sub auto_photochoice {
7765: my ($cnum,$cdom) = @_;
7766: my $homeserver = &homeserver($cnum,$cdom);
7767: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7768: &escape($cdom),
7769: $homeserver)));
1.709 albertel 7770: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7771: return (undef,undef);
7772: }
1.706 raeburn 7773: return ($update,$comment);
7774: }
7775:
7776: sub auto_photoupdate {
7777: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7778: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7779: my $host=&hostname($homeserver);
1.706 raeburn 7780: my $cmd = '';
7781: my $maxtries = 1;
1.800 albertel 7782: foreach my $affiliate (keys(%{$affiliatesref})) {
7783: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7784: }
7785: $cmd =~ s/%%$//;
7786: $cmd = &escape($cmd);
7787: my $query = 'institutionalphotos';
7788: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7789: unless ($queryid=~/^\Q$host\E\_/) {
7790: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7791: return 'error: '.$queryid;
7792: }
7793: my $reply = &get_query_reply($queryid);
7794: my $tries = 1;
7795: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7796: $reply = &get_query_reply($queryid);
7797: $tries ++;
7798: }
7799: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7800: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7801: } else {
7802: my @responses = split(/:/,$reply);
7803: my $outcome = shift(@responses);
7804: foreach my $item (@responses) {
7805: my ($key,$value) = split(/=/,$item);
7806: $$photo{$key} = $value;
7807: }
7808: return $outcome;
7809: }
7810: return 'error';
7811: }
7812:
1.521 raeburn 7813: sub auto_instcode_format {
1.793 albertel 7814: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7815: $cat_order) = @_;
1.521 raeburn 7816: my $courses = '';
1.772 raeburn 7817: my @homeservers;
1.521 raeburn 7818: if ($caller eq 'global') {
1.841 albertel 7819: my %servers = &get_servers($codedom,'library');
7820: foreach my $tryserver (keys(%servers)) {
7821: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7822: push(@homeservers,$tryserver);
7823: }
1.584 raeburn 7824: }
1.1022 raeburn 7825: } elsif ($caller eq 'requests') {
7826: if ($codedom =~ /^$match_domain$/) {
7827: my $chome = &domain($codedom,'primary');
7828: unless ($chome eq 'no_host') {
7829: push(@homeservers,$chome);
7830: }
7831: }
1.521 raeburn 7832: } else {
1.772 raeburn 7833: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7834: }
1.793 albertel 7835: foreach my $code (keys(%{$instcodes})) {
7836: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7837: }
7838: chop($courses);
1.772 raeburn 7839: my $ok_response = 0;
7840: my $response;
7841: while (@homeservers > 0 && $ok_response == 0) {
7842: my $server = shift(@homeservers);
7843: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7844: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7845: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7846: split(/:/,$response);
1.772 raeburn 7847: %{$codes} = (%{$codes},&str2hash($codes_str));
7848: push(@{$codetitles},&str2array($codetitles_str));
7849: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7850: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7851: $ok_response = 1;
7852: }
7853: }
7854: if ($ok_response) {
1.521 raeburn 7855: return 'ok';
1.772 raeburn 7856: } else {
7857: return $response;
1.521 raeburn 7858: }
7859: }
7860:
1.792 raeburn 7861: sub auto_instcode_defaults {
7862: my ($domain,$returnhash,$code_order) = @_;
7863: my @homeservers;
1.841 albertel 7864:
7865: my %servers = &get_servers($domain,'library');
7866: foreach my $tryserver (keys(%servers)) {
7867: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7868: push(@homeservers,$tryserver);
7869: }
1.792 raeburn 7870: }
1.841 albertel 7871:
1.792 raeburn 7872: my $response;
1.841 albertel 7873: foreach my $server (@homeservers) {
1.792 raeburn 7874: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7875: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7876:
7877: foreach my $pair (split(/\&/,$response)) {
7878: my ($name,$value)=split(/\=/,$pair);
7879: if ($name eq 'code_order') {
7880: @{$code_order} = split(/\&/,&unescape($value));
7881: } else {
7882: $returnhash->{&unescape($name)}=&unescape($value);
7883: }
7884: }
7885: return 'ok';
1.792 raeburn 7886: }
1.841 albertel 7887:
7888: return $response;
1.1003 raeburn 7889: }
7890:
7891: sub auto_possible_instcodes {
1.1007 raeburn 7892: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7893: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7894: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7895: return;
7896: }
1.1003 raeburn 7897: my (@homeservers,$uhome);
7898: if (defined(&domain($domain,'primary'))) {
7899: $uhome=&domain($domain,'primary');
7900: push(@homeservers,&domain($domain,'primary'));
7901: } else {
7902: my %servers = &get_servers($domain,'library');
7903: foreach my $tryserver (keys(%servers)) {
7904: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7905: push(@homeservers,$tryserver);
7906: }
7907: }
7908: }
7909: my $response;
7910: foreach my $server (@homeservers) {
7911: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7912: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7913: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7914: split(':',$response);
7915: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7916: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7917: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7918: my ($name,$value)=split('=',$item);
7919: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7920: }
7921: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7922: my ($name,$value)=split('=',$item);
7923: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7924: }
7925: return 'ok';
7926: }
7927: return $response;
7928: }
1.792 raeburn 7929:
1.1010 raeburn 7930: sub auto_courserequest_checks {
7931: my ($dom) = @_;
1.1020 raeburn 7932: my ($homeserver,%validations);
7933: if ($dom =~ /^$match_domain$/) {
7934: $homeserver = &domain($dom,'primary');
7935: }
7936: unless ($homeserver eq 'no_host') {
7937: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7938: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7939: my @items = split(/&/,$response);
7940: foreach my $item (@items) {
7941: my ($key,$value) = split('=',$item);
7942: $validations{&unescape($key)} = &thaw_unescape($value);
7943: }
7944: }
7945: }
1.1010 raeburn 7946: return %validations;
7947: }
7948:
1.1020 raeburn 7949: sub auto_courserequest_validation {
1.1255 raeburn 7950: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 7951: my ($homeserver,$response);
7952: if ($dom =~ /^$match_domain$/) {
7953: $homeserver = &domain($dom,'primary');
7954: }
1.1255 raeburn 7955: unless ($homeserver eq 'no_host') {
7956: my $customdata;
7957: if (ref($custominfo) eq 'HASH') {
7958: $customdata = &freeze_escape($custominfo);
7959: }
1.1020 raeburn 7960: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7961: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 7962: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7963: $customdata,$homeserver));
1.1020 raeburn 7964: }
7965: return $response;
7966: }
7967:
1.777 albertel 7968: sub auto_validate_class_sec {
1.918 raeburn 7969: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7970: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7971: my $ownerlist;
7972: if (ref($owners) eq 'ARRAY') {
7973: $ownerlist = join(',',@{$owners});
7974: } else {
7975: $ownerlist = $owners;
7976: }
1.773 raeburn 7977: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7978: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7979: return $response;
7980: }
7981:
1.1248 raeburn 7982: sub auto_crsreq_update {
7983: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 7984: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 7985: my ($homeserver,%crsreqresponse);
7986: if ($cdom =~ /^$match_domain$/) {
7987: $homeserver = &domain($cdom,'primary');
7988: }
7989: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7990: my $info;
7991: if (ref($inbound) eq 'HASH') {
7992: $info = &freeze_escape($inbound);
7993: }
7994: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7995: ':'.&escape($action).':'.&escape($ownername).':'.
7996: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 7997: &escape($title).':'.&escape($code).':'.
7998: &escape($accessstart).':'.&escape($accessend).':'.$info,
7999: $homeserver);
1.1248 raeburn 8000: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8001: my @items = split(/&/,$response);
8002: foreach my $item (@items) {
8003: my ($key,$value) = split('=',$item);
8004: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8005: }
8006: }
8007: }
8008: return \%crsreqresponse;
8009: }
8010:
1.679 raeburn 8011: # ------------------------------------------------------- Course Group routines
8012:
8013: sub get_coursegroups {
1.809 raeburn 8014: my ($cdom,$cnum,$group,$namespace) = @_;
8015: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8016: }
8017:
1.679 raeburn 8018: sub modify_coursegroup {
8019: my ($cdom,$cnum,$groupsettings) = @_;
8020: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8021: }
8022:
1.809 raeburn 8023: sub toggle_coursegroup_status {
8024: my ($cdom,$cnum,$group,$action) = @_;
8025: my ($from_namespace,$to_namespace);
8026: if ($action eq 'delete') {
8027: $from_namespace = 'coursegroups';
8028: $to_namespace = 'deleted_groups';
8029: } else {
8030: $from_namespace = 'deleted_groups';
8031: $to_namespace = 'coursegroups';
8032: }
8033: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8034: if (my $tmp = &error(%curr_group)) {
8035: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8036: return ('read error',$tmp);
8037: } else {
8038: my %savedsettings = %curr_group;
1.809 raeburn 8039: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8040: my $deloutcome;
8041: if ($result eq 'ok') {
1.809 raeburn 8042: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8043: } else {
8044: return ('write error',$result);
8045: }
8046: if ($deloutcome eq 'ok') {
8047: return 'ok';
8048: } else {
8049: return ('delete error',$deloutcome);
8050: }
8051: }
8052: }
8053:
1.679 raeburn 8054: sub modify_group_roles {
1.957 raeburn 8055: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8056: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8057: my $role = 'gr/'.&escape($userprivs);
8058: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8059: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8060: if ($result eq 'ok') {
8061: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8062: }
1.679 raeburn 8063: return $result;
8064: }
8065:
8066: sub modify_coursegroup_membership {
8067: my ($cdom,$cnum,$membership) = @_;
8068: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8069: return $result;
8070: }
8071:
1.682 raeburn 8072: sub get_active_groups {
8073: my ($udom,$uname,$cdom,$cnum) = @_;
8074: my $now = time;
8075: my %groups = ();
8076: foreach my $key (keys(%env)) {
1.811 albertel 8077: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8078: my ($start,$end) = split(/\./,$env{$key});
8079: if (($end!=0) && ($end<$now)) { next; }
8080: if (($start!=0) && ($start>$now)) { next; }
8081: if ($1 eq $cdom && $2 eq $cnum) {
8082: $groups{$3} = $env{$key} ;
8083: }
8084: }
8085: }
8086: return %groups;
8087: }
8088:
1.683 raeburn 8089: sub get_group_membership {
8090: my ($cdom,$cnum,$group) = @_;
8091: return(&dump('groupmembership',$cdom,$cnum,$group));
8092: }
8093:
8094: sub get_users_groups {
8095: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8096: my @usersgroups;
1.683 raeburn 8097: my $cachetime=1800;
8098:
8099: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8100: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8101: if (defined($cached)) {
1.734 albertel 8102: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8103: } else {
8104: $grouplist = '';
1.816 raeburn 8105: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8106: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8107: my $access_end = $env{'course.'.$courseid.
8108: '.default_enrollment_end_date'};
8109: my $now = time;
8110: foreach my $key (keys(%roleshash)) {
8111: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8112: my $group = $1;
8113: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8114: my $start = $2;
8115: my $end = $1;
8116: if ($start == -1) { next; } # deleted from group
8117: if (($start!=0) && ($start>$now)) { next; }
8118: if (($end!=0) && ($end<$now)) {
8119: if ($access_end && $access_end < $now) {
8120: if ($access_end - $end < 86400) {
8121: push(@usersgroups,$group);
1.733 raeburn 8122: }
8123: }
1.817 raeburn 8124: next;
1.733 raeburn 8125: }
1.817 raeburn 8126: push(@usersgroups,$group);
1.683 raeburn 8127: }
8128: }
8129: }
1.817 raeburn 8130: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8131: $grouplist = join(':',@usersgroups);
8132: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8133: }
1.733 raeburn 8134: return @usersgroups;
1.683 raeburn 8135: }
8136:
8137: sub devalidate_getgroups_cache {
8138: my ($udom,$uname,$cdom,$cnum)=@_;
8139: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8140:
1.683 raeburn 8141: my $hashid="$udom:$uname:$courseid";
8142: &devalidate_cache_new('getgroups',$hashid);
8143: }
8144:
1.12 www 8145: # ------------------------------------------------------------------ Plain Text
8146:
8147: sub plaintext {
1.988 raeburn 8148: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8149: if ($short =~ m{^cr/}) {
1.758 albertel 8150: return (split('/',$short))[-1];
8151: }
1.742 raeburn 8152: if (!defined($cid)) {
8153: $cid = $env{'request.course.id'};
8154: }
8155: my %rolenames = (
1.1008 raeburn 8156: Course => 'std',
8157: Community => 'alt1',
1.742 raeburn 8158: );
1.1037 raeburn 8159: if ($cid ne '') {
8160: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8161: unless ($forcedefault) {
8162: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8163: &Apache::lonlocal::mt_escape(\$roletext);
8164: return &Apache::lonlocal::mt($roletext);
8165: }
8166: }
8167: }
8168: if ((defined($type)) && (defined($rolenames{$type})) &&
8169: (defined($rolenames{$type})) &&
8170: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8171: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8172: } elsif ($cid ne '') {
8173: my $crstype = $env{'course.'.$cid.'.type'};
8174: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8175: (defined($prp{$short}{$rolenames{$crstype}}))) {
8176: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8177: }
1.742 raeburn 8178: }
1.1037 raeburn 8179: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8180: }
8181:
8182: # ----------------------------------------------------------------- Assign Role
8183:
8184: sub assignrole {
1.957 raeburn 8185: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8186: $context)=@_;
1.21 www 8187: my $mrole;
8188: if ($role =~ /^cr\//) {
1.393 www 8189: my $cwosec=$url;
1.811 albertel 8190: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8191: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8192: my $refused = 1;
8193: if ($context eq 'requestcourses') {
8194: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8195: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8196: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8197: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8198: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8199: if ($crsenv{'internal.courseowner'} eq
8200: $env{'user.name'}.':'.$env{'user.domain'}) {
8201: $refused = '';
8202: }
8203: }
8204: }
8205: }
8206: }
8207: if ($refused) {
8208: &logthis('Refused custom assignrole: '.
8209: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8210: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8211: return 'refused';
8212: }
1.104 www 8213: }
1.21 www 8214: $mrole='cr';
1.678 raeburn 8215: } elsif ($role =~ /^gr\//) {
8216: my $cwogrp=$url;
1.811 albertel 8217: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8218: unless (&allowed('mdg',$cwogrp)) {
8219: &logthis('Refused group assignrole: '.
8220: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8221: $env{'user.name'}.' at '.$env{'user.domain'});
8222: return 'refused';
8223: }
8224: $mrole='gr';
1.21 www 8225: } else {
1.82 www 8226: my $cwosec=$url;
1.811 albertel 8227: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8228: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8229: my $refused;
8230: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8231: if (!(&allowed('c'.$role,$url))) {
8232: $refused = 1;
8233: }
8234: } else {
8235: $refused = 1;
8236: }
1.947 raeburn 8237: if ($refused) {
1.1045 raeburn 8238: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8239: if (!$selfenroll && $context eq 'course') {
8240: my %crsenv;
8241: if ($role eq 'cc' || $role eq 'co') {
8242: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8243: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8244: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8245: if ($crsenv{'internal.courseowner'} eq
8246: $env{'user.name'}.':'.$env{'user.domain'}) {
8247: $refused = '';
8248: }
8249: }
8250: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8251: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8252: if ($crsenv{'internal.courseowner'} eq
8253: $env{'user.name'}.':'.$env{'user.domain'}) {
8254: $refused = '';
8255: }
8256: }
8257: }
8258: }
8259: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8260: $refused = '';
1.1017 raeburn 8261: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8262: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8263: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8264: my $wrongcc;
8265: if ($cnum =~ /^$match_community$/) {
8266: $wrongcc = 1 if ($role eq 'cc');
8267: } else {
8268: $wrongcc = 1 if ($role eq 'co');
8269: }
8270: unless ($wrongcc) {
8271: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8272: if ($crsenv{'internal.courseowner'} eq
8273: $env{'user.name'}.':'.$env{'user.domain'}) {
8274: $refused = '';
8275: }
1.1017 raeburn 8276: }
8277: }
1.1183 raeburn 8278: } elsif ($context eq 'requestauthor') {
8279: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8280: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8281: if ($env{'environment.requestauthor'} eq 'automatic') {
8282: $refused = '';
8283: } else {
8284: my %domdefaults = &get_domain_defaults($udom);
8285: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8286: my $checkbystatus;
8287: if ($env{'user.adv'}) {
8288: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8289: if ($disposition eq 'automatic') {
8290: $refused = '';
8291: } elsif ($disposition eq '') {
8292: $checkbystatus = 1;
8293: }
8294: } else {
8295: $checkbystatus = 1;
8296: }
8297: if ($checkbystatus) {
8298: if ($env{'environment.inststatus'}) {
8299: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8300: foreach my $type (@inststatuses) {
8301: if (($type ne '') &&
8302: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8303: $refused = '';
8304: }
8305: }
8306: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8307: $refused = '';
8308: }
8309: }
8310: }
8311: }
8312: }
1.1017 raeburn 8313: }
8314: if ($refused) {
1.947 raeburn 8315: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8316: ' '.$role.' '.$end.' '.$start.' by '.
8317: $env{'user.name'}.' at '.$env{'user.domain'});
8318: return 'refused';
8319: }
1.932 raeburn 8320: }
1.1131 raeburn 8321: } elsif ($role eq 'au') {
8322: if ($url ne '/'.$udom.'/') {
8323: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8324: ' to assign author role for '.$uname.':'.$udom.
8325: ' in domain: '.$url.' refused (wrong domain).');
8326: return 'refused';
8327: }
1.104 www 8328: }
1.21 www 8329: $mrole=$role;
8330: }
1.620 albertel 8331: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8332: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8333: if ($end) { $command.='_'.$end; }
1.21 www 8334: if ($start) {
8335: if ($end) {
1.81 www 8336: $command.='_'.$start;
1.21 www 8337: } else {
1.81 www 8338: $command.='_0_'.$start;
1.21 www 8339: }
8340: }
1.739 raeburn 8341: my $origstart = $start;
8342: my $origend = $end;
1.957 raeburn 8343: my $delflag;
1.357 www 8344: # actually delete
8345: if ($deleteflag) {
1.373 www 8346: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8347: # modify command to delete the role
1.620 albertel 8348: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8349: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8350: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8351: # set start and finish to negative values for userrolelog
8352: $start=-1;
8353: $end=-1;
1.957 raeburn 8354: $delflag = 1;
1.357 www 8355: }
8356: }
8357: # send command
1.349 www 8358: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8359: # log new user role if status is ok
1.349 www 8360: if ($answer eq 'ok') {
1.663 raeburn 8361: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8362: if (($role eq 'cc') || ($role eq 'in') ||
8363: ($role eq 'ep') || ($role eq 'ad') ||
8364: ($role eq 'ta') || ($role eq 'st') ||
8365: ($role=~/^cr/) || ($role eq 'gr') ||
8366: ($role eq 'co')) {
1.1200 raeburn 8367: # for course roles, perform group memberships changes triggered by role change.
8368: unless ($role =~ /^gr/) {
8369: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8370: $origstart,$selfenroll,$context);
8371: }
1.1184 raeburn 8372: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8373: $selfenroll,$context);
8374: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8375: ($role eq 'au') || ($role eq 'dc')) {
8376: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8377: $context);
8378: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8379: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8380: $context);
8381: }
1.1053 raeburn 8382: if ($role eq 'cc') {
8383: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8384: }
1.349 www 8385: }
8386: return $answer;
1.169 harris41 8387: }
8388:
1.1053 raeburn 8389: sub autoupdate_coowners {
8390: my ($url,$end,$start,$uname,$udom) = @_;
8391: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8392: if (($cdom ne '') && ($cnum ne '')) {
8393: my $now = time;
8394: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8395: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8396: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8397: my $instcode = $coursehash{'internal.coursecode'};
8398: if ($instcode ne '') {
1.1056 raeburn 8399: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8400: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8401: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8402: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8403: if ($result eq 'valid') {
8404: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8405: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8406: push(@newcoowners,$coowner);
8407: }
8408: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8409: push(@newcoowners,$uname.':'.$udom);
8410: }
8411: @newcoowners = sort(@newcoowners);
8412: } else {
8413: push(@newcoowners,$uname.':'.$udom);
8414: }
8415: } else {
8416: if ($coursehash{'internal.co-owners'}) {
8417: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8418: unless ($coowner eq $uname.':'.$udom) {
8419: push(@newcoowners,$coowner);
8420: }
8421: }
8422: unless (@newcoowners > 0) {
8423: $delcoowners = 1;
8424: $coowners = '';
8425: }
8426: }
8427: }
8428: if (@newcoowners || $delcoowners) {
8429: &store_coowners($cdom,$cnum,$coursehash{'home'},
8430: $delcoowners,@newcoowners);
8431: }
8432: }
8433: }
8434: }
8435: }
8436: }
8437: }
8438:
8439: sub store_coowners {
8440: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8441: my $cid = $cdom.'_'.$cnum;
8442: my ($coowners,$delresult,$putresult);
8443: if (@newcoowners) {
8444: $coowners = join(',',@newcoowners);
8445: my %coownershash = (
8446: 'internal.co-owners' => $coowners,
8447: );
8448: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8449: if ($putresult eq 'ok') {
8450: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8451: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8452: }
8453: }
8454: }
8455: if ($delcoowners) {
8456: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8457: if ($delresult eq 'ok') {
8458: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8459: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8460: }
8461: }
8462: }
8463: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8464: my %crsinfo =
8465: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8466: if (ref($crsinfo{$cid}) eq 'HASH') {
8467: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8468: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8469: }
8470: }
8471: }
8472:
1.169 harris41 8473: # -------------------------------------------------- Modify user authentication
1.197 www 8474: # Overrides without validation
8475:
1.169 harris41 8476: sub modifyuserauth {
8477: my ($udom,$uname,$umode,$upass)=@_;
8478: my $uhome=&homeserver($uname,$udom);
1.197 www 8479: unless (&allowed('mau',$udom)) { return 'refused'; }
8480: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8481: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8482: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8483: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8484: &escape($upass),$uhome);
1.620 albertel 8485: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8486: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8487: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8488: &log($udom,,$uname,$uhome,
1.620 albertel 8489: 'Authentication changed by '.$env{'user.domain'}.', '.
8490: $env{'user.name'}.', '.$umode.
1.197 www 8491: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8492: unless ($reply eq 'ok') {
1.197 www 8493: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8494: return 'error: '.$reply;
8495: }
1.170 harris41 8496: return 'ok';
1.80 www 8497: }
8498:
1.81 www 8499: # --------------------------------------------------------------- Modify a user
1.80 www 8500:
1.81 www 8501: sub modifyuser {
1.206 matthew 8502: my ($udom, $uname, $uid,
8503: $umode, $upass, $first,
8504: $middle, $last, $gene,
1.1058 raeburn 8505: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8506: $udom= &LONCAPA::clean_domain($udom);
8507: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8508: my $showcandelete = 'none';
8509: if (ref($candelete) eq 'ARRAY') {
8510: if (@{$candelete} > 0) {
8511: $showcandelete = join(', ',@{$candelete});
8512: }
8513: }
1.81 www 8514: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8515: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8516: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8517: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8518: ' desiredhome not specified').
1.620 albertel 8519: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8520: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8521: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8522: my $newuser;
8523: if ($uhome eq 'no_host') {
8524: $newuser = 1;
8525: }
1.80 www 8526: # ----------------------------------------------------------------- Create User
1.406 albertel 8527: if (($uhome eq 'no_host') &&
8528: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8529: my $unhome='';
1.844 albertel 8530: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8531: $unhome = $desiredhome;
1.620 albertel 8532: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8533: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8534: } else { # load balancing routine for determining $unhome
1.81 www 8535: my $loadm=10000000;
1.841 albertel 8536: my %servers = &get_servers($udom,'library');
8537: foreach my $tryserver (keys(%servers)) {
8538: my $answer=reply('load',$tryserver);
8539: if (($answer=~/\d+/) && ($answer<$loadm)) {
8540: $loadm=$answer;
8541: $unhome=$tryserver;
8542: }
1.80 www 8543: }
8544: }
8545: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8546: return 'error: unable to find a home server for '.$uname.
8547: ' in domain '.$udom;
1.80 www 8548: }
8549: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8550: &escape($upass),$unhome);
8551: unless ($reply eq 'ok') {
8552: return 'error: '.$reply;
8553: }
1.230 stredwic 8554: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8555: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8556: return 'error: unable verify users home machine.';
1.80 www 8557: }
1.209 matthew 8558: } # End of creation of new user
1.80 www 8559: # ---------------------------------------------------------------------- Add ID
8560: if ($uid) {
8561: $uid=~tr/A-Z/a-z/;
8562: my %uidhash=&idrget($udom,$uname);
1.196 www 8563: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8564: && (!$forceid)) {
1.80 www 8565: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8566: return 'error: user id "'.$uid.'" does not match '.
8567: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8568: }
8569: } else {
8570: &idput($udom,($uname => $uid));
8571: }
8572: }
8573: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8574: my @tmp=&get('environment',
1.899 raeburn 8575: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8576: 'permanentemail','inststatus'],
1.134 albertel 8577: $udom,$uname);
1.1075 raeburn 8578: my (%names,%oldnames);
1.313 matthew 8579: if ($tmp[0] =~ m/^error:.*/) {
8580: %names=();
8581: } else {
8582: %names = @tmp;
1.1075 raeburn 8583: %oldnames = %names;
1.313 matthew 8584: }
1.388 www 8585: #
1.1058 raeburn 8586: # If name, email and/or uid are blank (e.g., because an uploaded file
8587: # of users did not contain them), do not overwrite existing values
8588: # unless field is in $candelete array ref.
8589: #
8590:
8591: my @fields = ('firstname','middlename','lastname','generation',
8592: 'permanentemail','id');
8593: my %newvalues;
8594: if (ref($candelete) eq 'ARRAY') {
8595: foreach my $field (@fields) {
8596: if (grep(/^\Q$field\E$/,@{$candelete})) {
8597: if ($field eq 'firstname') {
8598: $names{$field} = $first;
8599: } elsif ($field eq 'middlename') {
8600: $names{$field} = $middle;
8601: } elsif ($field eq 'lastname') {
8602: $names{$field} = $last;
8603: } elsif ($field eq 'generation') {
8604: $names{$field} = $gene;
8605: } elsif ($field eq 'permanentemail') {
8606: $names{$field} = $email;
8607: } elsif ($field eq 'id') {
8608: $names{$field} = $uid;
8609: }
8610: }
8611: }
8612: }
1.388 www 8613: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8614: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8615: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8616: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8617: if ($email) {
8618: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8619: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8620: }
1.899 raeburn 8621: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8622: if (defined($inststatus)) {
8623: $names{'inststatus'} = '';
8624: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8625: if (ref($usertypes) eq 'HASH') {
8626: my @okstatuses;
8627: foreach my $item (split(/:/,$inststatus)) {
8628: if (defined($usertypes->{$item})) {
8629: push(@okstatuses,$item);
8630: }
8631: }
8632: if (@okstatuses) {
8633: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8634: }
8635: }
8636: }
1.1075 raeburn 8637: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8638: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8639: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8640: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8641: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8642: } else {
8643: $logmsg .= ' during self creation';
8644: }
1.1075 raeburn 8645: my $changed;
8646: if ($newuser) {
8647: $changed = 1;
8648: } else {
8649: foreach my $field (@fields) {
8650: if ($names{$field} ne $oldnames{$field}) {
8651: $changed = 1;
8652: last;
8653: }
8654: }
8655: }
8656: unless ($changed) {
8657: $logmsg = 'No changes in user information needed for: '.$logmsg;
8658: &logthis($logmsg);
8659: return 'ok';
8660: }
8661: my $reply = &put('environment', \%names, $udom,$uname);
8662: if ($reply ne 'ok') {
8663: return 'error: '.$reply;
8664: }
1.1087 raeburn 8665: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8666: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8667: }
1.1075 raeburn 8668: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8669: &devalidate_cache_new('namescache',$uname.':'.$udom);
8670: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8671: &logthis($logmsg);
1.134 albertel 8672: return 'ok';
1.80 www 8673: }
8674:
1.81 www 8675: # -------------------------------------------------------------- Modify student
1.80 www 8676:
1.81 www 8677: sub modifystudent {
8678: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8679: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8680: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8681: if (!$cid) {
1.620 albertel 8682: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8683: return 'not_in_class';
8684: }
1.80 www 8685: }
8686: # --------------------------------------------------------------- Make the user
1.81 www 8687: my $reply=&modifyuser
1.209 matthew 8688: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8689: $desiredhome,$email,$inststatus);
1.80 www 8690: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8691: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8692: # student's environment
1.297 matthew 8693: $uid = undef if (!$forceid);
1.455 albertel 8694: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8695: $gene,$usec,$end,$start,$type,$locktype,
8696: $cid,$selfenroll,$context,$credits);
1.297 matthew 8697: return $reply;
8698: }
8699:
8700: sub modify_student_enrollment {
1.1216 raeburn 8701: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8702: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8703: my ($cdom,$cnum,$chome);
8704: if (!$cid) {
1.620 albertel 8705: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8706: return 'not_in_class';
8707: }
1.620 albertel 8708: $cdom=$env{'course.'.$cid.'.domain'};
8709: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8710: } else {
8711: ($cdom,$cnum)=split(/_/,$cid);
8712: }
1.620 albertel 8713: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8714: if (!$chome) {
1.457 raeburn 8715: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8716: }
1.455 albertel 8717: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8718: # Make sure the user exists
1.81 www 8719: my $uhome=&homeserver($uname,$udom);
8720: if (($uhome eq '') || ($uhome eq 'no_host')) {
8721: return 'error: no such user';
8722: }
1.297 matthew 8723: # Get student data if we were not given enough information
8724: if (!defined($first) || $first eq '' ||
8725: !defined($last) || $last eq '' ||
8726: !defined($uid) || $uid eq '' ||
8727: !defined($middle) || $middle eq '' ||
8728: !defined($gene) || $gene eq '') {
1.294 matthew 8729: # They did not supply us with enough data to enroll the student, so
8730: # we need to pick up more information.
1.297 matthew 8731: my %tmp = &get('environment',
1.294 matthew 8732: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8733: ,$udom,$uname);
8734:
1.800 albertel 8735: #foreach my $key (keys(%tmp)) {
8736: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8737: #}
1.294 matthew 8738: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8739: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8740: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8741: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8742: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8743: }
1.556 albertel 8744: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8745: my $user = "$uname:$udom";
8746: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8747: my $reply=cput('classlist',
1.1148 raeburn 8748: {$user =>
1.1216 raeburn 8749: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8750: $cdom,$cnum);
1.1148 raeburn 8751: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8752: &devalidate_getsection_cache($udom,$uname,$cid);
8753: } else {
1.81 www 8754: return 'error: '.$reply;
8755: }
1.297 matthew 8756: # Add student role to user
1.83 www 8757: my $uurl='/'.$cid;
1.81 www 8758: $uurl=~s/\_/\//g;
8759: if ($usec) {
8760: $uurl.='/'.$usec;
8761: }
1.1148 raeburn 8762: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8763: $selfenroll,$context);
8764: if ($result ne 'ok') {
8765: if ($old_entry{$user} ne '') {
8766: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8767: } else {
8768: $reply = &del('classlist',[$user],$cdom,$cnum);
8769: }
8770: }
8771: return $result;
1.21 www 8772: }
8773:
1.556 albertel 8774: sub format_name {
8775: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8776: my $name;
8777: if ($first ne 'lastname') {
8778: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8779: } else {
8780: if ($lastname=~/\S/) {
8781: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8782: $name=~s/\s+,/,/;
8783: } else {
8784: $name.= $firstname.' '.$middlename.' '.$generation;
8785: }
8786: }
8787: $name=~s/^\s+//;
8788: $name=~s/\s+$//;
8789: $name=~s/\s+/ /g;
8790: return $name;
8791: }
8792:
1.84 www 8793: # ------------------------------------------------- Write to course preferences
8794:
8795: sub writecoursepref {
8796: my ($courseid,%prefs)=@_;
8797: $courseid=~s/^\///;
8798: $courseid=~s/\_/\//g;
8799: my ($cdomain,$cnum)=split(/\//,$courseid);
8800: my $chome=homeserver($cnum,$cdomain);
8801: if (($chome eq '') || ($chome eq 'no_host')) {
8802: return 'error: no such course';
8803: }
8804: my $cstring='';
1.800 albertel 8805: foreach my $pref (keys(%prefs)) {
8806: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8807: }
1.84 www 8808: $cstring=~s/\&$//;
8809: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8810: }
8811:
8812: # ---------------------------------------------------------- Make/modify course
8813:
8814: sub createcourse {
1.741 raeburn 8815: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8816: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8817: $url=&declutter($url);
8818: my $cid='';
1.1028 raeburn 8819: if ($context eq 'requestcourses') {
8820: my $can_create = 0;
8821: my ($ownername,$ownerdom) = split(':',$course_owner);
8822: if ($udom eq $ownerdom) {
8823: if (&usertools_access($ownername,$ownerdom,$category,undef,
8824: $context)) {
8825: $can_create = 1;
8826: }
8827: } else {
8828: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8829: $category);
8830: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8831: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8832: if (@curr > 0) {
8833: my @options = qw(approval validate autolimit);
8834: my $optregex = join('|',@options);
8835: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8836: $can_create = 1;
8837: }
8838: }
8839: }
8840: }
8841: if ($can_create) {
8842: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8843: unless (&allowed('ccc',$udom)) {
8844: return 'refused';
8845: }
1.1017 raeburn 8846: }
8847: } else {
8848: return 'refused';
8849: }
1.1028 raeburn 8850: } elsif (!&allowed('ccc',$udom)) {
8851: return 'refused';
1.84 www 8852: }
1.1011 raeburn 8853: # --------------------------------------------------------------- Get Unique ID
8854: my $uname;
8855: if ($cnum =~ /^$match_courseid$/) {
8856: my $chome=&homeserver($cnum,$udom,'true');
8857: if (($chome eq '') || ($chome eq 'no_host')) {
8858: $uname = $cnum;
8859: } else {
1.1038 raeburn 8860: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8861: }
8862: } else {
1.1038 raeburn 8863: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8864: }
8865: return $uname if ($uname =~ /^error/);
8866: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8867: if (!defined($course_server)) {
8868: if (defined(&domain($udom,'primary'))) {
8869: $course_server = &domain($udom,'primary');
8870: } else {
8871: $course_server = $env{'user.home'};
8872: }
8873: }
8874: my %host_servers =
8875: &Apache::lonnet::get_servers($udom,'library');
8876: unless ($host_servers{$course_server}) {
8877: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8878: }
1.84 www 8879: # ------------------------------------------------------------- Make the course
8880: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8881: $course_server);
1.84 www 8882: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8883: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8884: if (($uhome eq '') || ($uhome eq 'no_host')) {
8885: return 'error: no such course';
8886: }
1.271 www 8887: # ----------------------------------------------------------------- Course made
1.516 raeburn 8888: # log existence
1.1029 raeburn 8889: my $now = time;
1.918 raeburn 8890: my $newcourse = {
8891: $udom.'_'.$uname => {
1.921 raeburn 8892: description => $description,
8893: inst_code => $inst_code,
8894: owner => $course_owner,
8895: type => $crstype,
1.1029 raeburn 8896: creator => $env{'user.name'}.':'.
8897: $env{'user.domain'},
8898: created => $now,
8899: context => $context,
1.918 raeburn 8900: },
8901: };
1.921 raeburn 8902: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8903: # set toplevel url
1.271 www 8904: my $topurl=$url;
8905: unless ($nonstandard) {
8906: # ------------------------------------------ For standard courses, make top url
8907: my $mapurl=&clutter($url);
1.278 www 8908: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8909: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8910: <map>
8911: <resource id="1" type="start"></resource>
8912: <resource id="2" src="$mapurl"></resource>
8913: <resource id="3" type="finish"></resource>
8914: <link index="1" from="1" to="2"></link>
8915: <link index="2" from="2" to="3"></link>
8916: </map>
8917: ENDINITMAP
8918: $topurl=&declutter(
1.638 albertel 8919: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8920: );
8921: }
8922: # ----------------------------------------------------------- Write preferences
1.84 www 8923: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8924: ('description' => $description,
8925: 'url' => $topurl,
8926: 'internal.creator' => $env{'user.name'}.':'.
8927: $env{'user.domain'},
8928: 'internal.created' => $now,
8929: 'internal.creationcontext' => $context)
8930: );
1.84 www 8931: return '/'.$udom.'/'.$uname;
8932: }
8933:
1.1011 raeburn 8934: # ------------------------------------------------------------------- Create ID
8935: sub generate_coursenum {
1.1038 raeburn 8936: my ($udom,$crstype) = @_;
1.1011 raeburn 8937: my $domdesc = &domain($udom);
8938: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8939: my $first;
8940: if ($crstype eq 'Community') {
8941: $first = '0';
8942: } else {
8943: $first = int(1+rand(9));
8944: }
8945: my $uname=$first.
1.1011 raeburn 8946: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8947: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8948: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8949: # ----------------------------------------------- Make sure that does not exist
8950: my $uhome=&homeserver($uname,$udom,'true');
8951: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8952: if ($crstype eq 'Community') {
8953: $first = '0';
8954: } else {
8955: $first = int(1+rand(9));
8956: }
8957: $uname=$first.
1.1011 raeburn 8958: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8959: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8960: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8961: $uhome=&homeserver($uname,$udom,'true');
8962: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8963: return 'error: unable to generate unique course-ID';
8964: }
8965: }
8966: return $uname;
8967: }
8968:
1.813 albertel 8969: sub is_course {
1.1167 droeschl 8970: my ($cdom, $cnum) = scalar(@_) == 1 ?
8971: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8972:
8973: return unless $cdom and $cnum;
8974:
8975: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8976: '.');
8977:
1.1219 raeburn 8978: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8979: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8980: }
8981:
1.1015 raeburn 8982: sub store_userdata {
8983: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8984: my $result;
1.1016 raeburn 8985: if ($datakey ne '') {
1.1013 raeburn 8986: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8987: if ($udom eq '' || $uname eq '') {
8988: $udom = $env{'user.domain'};
8989: $uname = $env{'user.name'};
8990: }
8991: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8992: if (($uhome eq '') || ($uhome eq 'no_host')) {
8993: $result = 'error: no_host';
8994: } else {
8995: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8996: $storehash->{'host'} = $perlvar{'lonHostID'};
8997:
8998: my $namevalue='';
8999: foreach my $key (keys(%{$storehash})) {
9000: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9001: }
9002: $namevalue=~s/\&$//;
1.1224 raeburn 9003: unless ($namespace eq 'courserequests') {
9004: $datakey = &escape($datakey);
9005: }
1.1105 raeburn 9006: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9007: $namevalue,$uhome);
1.1013 raeburn 9008: }
9009: } else {
9010: $result = 'error: data to store was not a hash reference';
9011: }
9012: } else {
9013: $result= 'error: invalid requestkey';
9014: }
9015: return $result;
9016: }
9017:
1.21 www 9018: # ---------------------------------------------------------- Assign Custom Role
9019:
9020: sub assigncustomrole {
1.957 raeburn 9021: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9022: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9023: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9024: }
9025:
9026: # ----------------------------------------------------------------- Revoke Role
9027:
9028: sub revokerole {
1.957 raeburn 9029: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9030: my $now=time;
1.965 raeburn 9031: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9032: }
9033:
9034: # ---------------------------------------------------------- Revoke Custom Role
9035:
9036: sub revokecustomrole {
1.957 raeburn 9037: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9038: my $now=time;
1.357 www 9039: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9040: $deleteflag,$selfenroll,$context);
1.17 www 9041: }
9042:
1.533 banghart 9043: # ------------------------------------------------------------ Disk usage
1.535 albertel 9044: sub diskusage {
1.955 raeburn 9045: my ($udom,$uname,$directorypath,$getpropath)=@_;
9046: $directorypath =~ s/\/$//;
9047: my $listing=&reply('du2:'.&escape($directorypath).':'
9048: .&escape($getpropath).':'.&escape($uname).':'
9049: .&escape($udom),homeserver($uname,$udom));
9050: if ($listing eq 'unknown_cmd') {
9051: if ($getpropath) {
9052: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9053: }
9054: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9055: }
1.514 albertel 9056: return $listing;
1.512 banghart 9057: }
9058:
1.566 banghart 9059: sub is_locked {
1.1096 raeburn 9060: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9061: my @check;
9062: my $is_locked;
1.1093 raeburn 9063: push (@check,$file_name);
1.613 albertel 9064: my %locked = &get('file_permissions',\@check,
1.620 albertel 9065: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9066: my ($tmp)=keys(%locked);
9067: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9068:
1.566 banghart 9069: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9070: $is_locked = 'false';
9071: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9072: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9073: $is_locked = 'true';
1.1096 raeburn 9074: if (ref($which) eq 'ARRAY') {
9075: push(@{$which},$entry);
9076: } else {
9077: last;
9078: }
1.745 raeburn 9079: }
9080: }
1.566 banghart 9081: } else {
9082: $is_locked = 'false';
9083: }
1.1093 raeburn 9084: return $is_locked;
1.566 banghart 9085: }
9086:
1.759 albertel 9087: sub declutter_portfile {
9088: my ($file) = @_;
1.833 albertel 9089: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9090: return $file;
9091: }
9092:
1.559 banghart 9093: # ------------------------------------------------------------- Mark as Read Only
9094:
9095: sub mark_as_readonly {
9096: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9097: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9098: my ($tmp)=keys(%current_permissions);
9099: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9100: foreach my $file (@{$files}) {
1.759 albertel 9101: $file = &declutter_portfile($file);
1.561 banghart 9102: push(@{$current_permissions{$file}},$what);
1.559 banghart 9103: }
1.613 albertel 9104: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9105: return;
9106: }
9107:
1.572 banghart 9108: # ------------------------------------------------------------Save Selected Files
9109:
9110: sub save_selected_files {
9111: my ($user, $path, @files) = @_;
9112: my $filename = $user."savedfiles";
1.573 banghart 9113: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9114: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9115: foreach my $file (@files) {
1.620 albertel 9116: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9117: }
9118: foreach my $file (@other_files) {
1.574 banghart 9119: print (OUT $file."\n");
1.572 banghart 9120: }
1.574 banghart 9121: close (OUT);
1.572 banghart 9122: return 'ok';
9123: }
9124:
1.574 banghart 9125: sub clear_selected_files {
9126: my ($user) = @_;
9127: my $filename = $user."savedfiles";
1.1117 foxr 9128: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9129: print (OUT undef);
9130: close (OUT);
9131: return ("ok");
9132: }
9133:
1.572 banghart 9134: sub files_in_path {
9135: my ($user, $path) = @_;
9136: my $filename = $user."savedfiles";
9137: my %return_files;
1.1117 foxr 9138: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9139: while (my $line_in = <IN>) {
1.574 banghart 9140: chomp ($line_in);
9141: my @paths_and_file = split (m!/!, $line_in);
9142: my $file_part = pop (@paths_and_file);
9143: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9144: $path_part.='/';
9145: my $path_and_file = $path_part.$file_part;
9146: if ($path_part eq $path) {
9147: $return_files{$file_part}= 'selected';
9148: }
9149: }
1.574 banghart 9150: close (IN);
9151: return (\%return_files);
1.572 banghart 9152: }
9153:
9154: # called in portfolio select mode, to show files selected NOT in current directory
9155: sub files_not_in_path {
9156: my ($user, $path) = @_;
9157: my $filename = $user."savedfiles";
9158: my @return_files;
9159: my $path_part;
1.1117 foxr 9160: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9161: while (my $line = <IN>) {
1.572 banghart 9162: #ok, I know it's clunky, but I want it to work
1.800 albertel 9163: my @paths_and_file = split(m|/|, $line);
9164: my $file_part = pop(@paths_and_file);
9165: chomp($file_part);
9166: my $path_part = join('/', @paths_and_file);
1.572 banghart 9167: $path_part .= '/';
9168: my $path_and_file = $path_part.$file_part;
9169: if ($path_part ne $path) {
1.800 albertel 9170: push(@return_files, ($path_and_file));
1.572 banghart 9171: }
9172: }
1.800 albertel 9173: close(OUT);
1.574 banghart 9174: return (@return_files);
1.572 banghart 9175: }
9176:
1.1273 raeburn 9177: #------------------------------Submitted/Handedback Portfolio Files Versioning
9178:
9179: sub portfiles_versioning {
9180: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9181: my $portfolio_root = '/userfiles/portfolio';
9182: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9183: foreach my $file (@{$portfiles}) {
9184: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9185: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9186: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9187: my $getpropath = 1;
9188: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9189: $stu_name,$getpropath);
9190: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9191: my $new_answer =
9192: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9193: if ($new_answer ne 'problem getting file') {
9194: push(@{$versioned_portfiles}, $directory.$new_answer);
9195: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9196: [$symb,$env{'request.course.id'},'graded']);
9197: }
9198: }
9199: }
9200:
9201: sub get_next_version {
9202: my ($answer_name, $answer_ext, $dir_list) = @_;
9203: my $version;
9204: if (ref($dir_list) eq 'ARRAY') {
9205: foreach my $row (@{$dir_list}) {
9206: my ($file) = split(/\&/,$row,2);
9207: my ($file_name,$file_version,$file_ext) =
9208: &file_name_version_ext($file);
9209: if (($file_name eq $answer_name) &&
9210: ($file_ext eq $answer_ext)) {
9211: # gets here if filename and extension match,
9212: # regardless of version
9213: if ($file_version ne '') {
9214: # a versioned file is found so save it for later
9215: if ($file_version > $version) {
9216: $version = $file_version;
9217: }
9218: }
9219: }
9220: }
9221: }
9222: $version ++;
9223: return($version);
9224: }
9225:
9226: sub version_selected_portfile {
9227: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9228: my ($answer_name,$answer_ver,$answer_ext) =
9229: &file_name_version_ext($file_name);
9230: my $new_answer;
9231: $env{'form.copy'} =
9232: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9233: if($env{'form.copy'} eq '-1') {
9234: $new_answer = 'problem getting file';
9235: } else {
9236: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9237: my $copy_result =
9238: &finishuserfileupload($stu_name,$domain,'copy',
9239: '/portfolio'.$directory.$new_answer);
9240: }
9241: undef($env{'form.copy'});
9242: return ($new_answer);
9243: }
9244:
9245: sub file_name_version_ext {
9246: my ($file)=@_;
9247: my @file_parts = split(/\./, $file);
9248: my ($name,$version,$ext);
9249: if (@file_parts > 1) {
9250: $ext=pop(@file_parts);
9251: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9252: $version=pop(@file_parts);
9253: }
9254: $name=join('.',@file_parts);
9255: } else {
9256: $name=join('.',@file_parts);
9257: }
9258: return($name,$version,$ext);
9259: }
9260:
1.745 raeburn 9261: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9262:
1.745 raeburn 9263: sub get_portfile_permissions {
9264: my ($domain,$user) = @_;
1.613 albertel 9265: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9266: my ($tmp)=keys(%current_permissions);
9267: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9268: return \%current_permissions;
9269: }
9270:
9271: #---------------------------------------------Get portfolio file access controls
9272:
1.749 raeburn 9273: sub get_access_controls {
1.745 raeburn 9274: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9275: my %access;
9276: my $real_file = $file;
9277: $file =~ s/\.meta$//;
1.745 raeburn 9278: if (defined($file)) {
1.749 raeburn 9279: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9280: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9281: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9282: }
9283: }
1.745 raeburn 9284: } else {
1.749 raeburn 9285: foreach my $key (keys(%{$current_permissions})) {
9286: if ($key =~ /\0accesscontrol$/) {
9287: if (defined($group)) {
9288: if ($key !~ m-^\Q$group\E/-) {
9289: next;
9290: }
9291: }
9292: my ($fullpath) = split(/\0/,$key);
9293: if (ref($$current_permissions{$key}) eq 'HASH') {
9294: foreach my $control (keys(%{$$current_permissions{$key}})) {
9295: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9296: }
9297: }
9298: }
9299: }
9300: }
9301: return %access;
9302: }
9303:
9304: sub modify_access_controls {
9305: my ($file_name,$changes,$domain,$user)=@_;
9306: my ($outcome,$deloutcome);
9307: my %store_permissions;
9308: my %new_values;
9309: my %new_control;
9310: my %translation;
9311: my @deletions = ();
9312: my $now = time;
9313: if (exists($$changes{'activate'})) {
9314: if (ref($$changes{'activate'}) eq 'HASH') {
9315: my @newitems = sort(keys(%{$$changes{'activate'}}));
9316: my $numnew = scalar(@newitems);
9317: for (my $i=0; $i<$numnew; $i++) {
9318: my $newkey = $newitems[$i];
9319: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9320: if ($newkey =~ /^\d+:/) {
9321: $newkey =~ s/^(\d+)/$newid/;
9322: $translation{$1} = $newid;
9323: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9324: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9325: $translation{$1} = $newid;
9326: }
1.749 raeburn 9327: $new_values{$file_name."\0".$newkey} =
9328: $$changes{'activate'}{$newitems[$i]};
9329: $new_control{$newkey} = $now;
9330: }
9331: }
9332: }
9333: my %todelete;
9334: my %changed_items;
9335: foreach my $action ('delete','update') {
9336: if (exists($$changes{$action})) {
9337: if (ref($$changes{$action}) eq 'HASH') {
9338: foreach my $key (keys(%{$$changes{$action}})) {
9339: my ($itemnum) = ($key =~ /^([^:]+):/);
9340: if ($action eq 'delete') {
9341: $todelete{$itemnum} = 1;
9342: } else {
9343: $changed_items{$itemnum} = $key;
9344: }
9345: }
1.745 raeburn 9346: }
9347: }
1.749 raeburn 9348: }
9349: # get lock on access controls for file.
9350: my $lockhash = {
9351: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9352: ':'.$env{'user.domain'},
9353: };
9354: my $tries = 0;
9355: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9356:
9357: while (($gotlock ne 'ok') && $tries <3) {
9358: $tries ++;
9359: sleep 1;
9360: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9361: }
9362: if ($gotlock eq 'ok') {
9363: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9364: my ($tmp)=keys(%curr_permissions);
9365: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9366: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9367: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9368: if (ref($curr_controls) eq 'HASH') {
9369: foreach my $control_item (keys(%{$curr_controls})) {
9370: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9371: if (defined($todelete{$itemnum})) {
9372: push(@deletions,$file_name."\0".$control_item);
9373: } else {
9374: if (defined($changed_items{$itemnum})) {
9375: $new_control{$changed_items{$itemnum}} = $now;
9376: push(@deletions,$file_name."\0".$control_item);
9377: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9378: } else {
9379: $new_control{$control_item} = $$curr_controls{$control_item};
9380: }
9381: }
1.745 raeburn 9382: }
9383: }
9384: }
1.970 raeburn 9385: my ($group);
9386: if (&is_course($domain,$user)) {
9387: ($group,my $file) = split(/\//,$file_name,2);
9388: }
1.749 raeburn 9389: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9390: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9391: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9392: # remove lock
9393: my @del_lock = ($file_name."\0".'locked_access_records');
9394: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9395: my $sqlresult =
1.970 raeburn 9396: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9397: $group);
1.749 raeburn 9398: } else {
9399: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9400: }
1.749 raeburn 9401: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9402: }
9403:
1.827 raeburn 9404: sub make_public_indefinitely {
1.1271 raeburn 9405: my (@requrl) = @_;
9406: return &automated_portfile_access('public',\@requrl);
9407: }
9408:
9409: sub automated_portfile_access {
9410: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9411: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9412: return 'invalid';
9413: }
1.1271 raeburn 9414: my %urls;
9415: if (ref($addsref) eq 'ARRAY') {
9416: foreach my $requrl (@{$addsref}) {
9417: if (&is_portfolio_url($requrl)) {
9418: unless (exists($urls{$requrl})) {
9419: $urls{$requrl} = 'add';
9420: }
9421: }
9422: }
9423: }
9424: if (ref($delsref) eq 'ARRAY') {
9425: foreach my $requrl (@{$delsref}) {
9426: if (&is_portfolio_url($requrl)) {
9427: unless (exists($urls{$requrl})) {
9428: $urls{$requrl} = 'delete';
9429: }
9430: }
9431: }
9432: }
9433: unless (keys(%urls)) {
9434: return 'invalid';
9435: }
9436: my $ip;
9437: if ($accesstype eq 'ip') {
9438: if (ref($info) eq 'HASH') {
9439: if ($info->{'ip'} ne '') {
9440: $ip = $info->{'ip'};
9441: }
9442: }
9443: if ($ip eq '') {
9444: return 'invalid';
9445: }
9446: }
9447: my $errors;
1.827 raeburn 9448: my $now = time;
1.1271 raeburn 9449: my %current_perms;
9450: foreach my $requrl (sort(keys(%urls))) {
9451: my $action;
9452: if ($urls{$requrl} eq 'add') {
9453: $action = 'activate';
9454: } else {
9455: $action = 'none';
9456: }
9457: my $aclnum = 0;
1.827 raeburn 9458: my (undef,$udom,$unum,$file_name,$group) =
9459: &parse_portfolio_url($requrl);
1.1271 raeburn 9460: unless (exists($current_perms{$unum.':'.$udom})) {
9461: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9462: }
9463: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9464: $group,$file_name);
9465: foreach my $key (keys(%{$access_controls{$file_name}})) {
9466: my ($num,$scope,$end,$start) =
9467: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9468: if ($scope eq $accesstype) {
9469: if (($start <= $now) && ($end == 0)) {
9470: if ($accesstype eq 'ip') {
9471: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9472: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9473: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9474: if ($urls{$requrl} eq 'add') {
9475: $action = 'none';
9476: last;
9477: } else {
9478: $action = 'delete';
9479: $aclnum = $num;
9480: last;
9481: }
9482: }
9483: }
9484: }
9485: } elsif ($accesstype eq 'public') {
9486: if ($urls{$requrl} eq 'add') {
9487: $action = 'none';
9488: last;
9489: } else {
9490: $action = 'delete';
9491: $aclnum = $num;
9492: last;
9493: }
9494: }
9495: } elsif ($accesstype eq 'public') {
1.827 raeburn 9496: $action = 'update';
9497: $aclnum = $num;
1.1271 raeburn 9498: last;
1.827 raeburn 9499: }
9500: }
9501: }
9502: if ($action eq 'none') {
1.1271 raeburn 9503: next;
1.827 raeburn 9504: } else {
9505: my %changes;
9506: my $newend = 0;
9507: my $newstart = $now;
1.1271 raeburn 9508: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 9509: $changes{$action}{$newkey} = {
1.1271 raeburn 9510: type => $accesstype,
1.827 raeburn 9511: time => {
9512: start => $newstart,
9513: end => $newend,
9514: },
9515: };
1.1271 raeburn 9516: if ($accesstype eq 'ip') {
9517: $changes{$action}{$newkey}{'ip'} = [$ip];
9518: }
1.827 raeburn 9519: my ($outcome,$deloutcome,$new_values,$translation) =
9520: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 9521: unless ($outcome eq 'ok') {
9522: $errors .= $outcome.' ';
9523: }
1.827 raeburn 9524: }
1.1271 raeburn 9525: }
9526: if ($errors) {
9527: $errors =~ s/\s$//;
9528: return $errors;
1.827 raeburn 9529: } else {
1.1271 raeburn 9530: return 'ok';
1.827 raeburn 9531: }
9532: }
9533:
1.745 raeburn 9534: #------------------------------------------------------Get Marked as Read Only
9535:
9536: sub get_marked_as_readonly {
9537: my ($domain,$user,$what,$group) = @_;
9538: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9539: my @readonly_files;
1.629 banghart 9540: my $cmp1=$what;
9541: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9542: while (my ($file_name,$value) = each(%{$current_permissions})) {
9543: if (defined($group)) {
9544: if ($file_name !~ m-^\Q$group\E/-) {
9545: next;
9546: }
9547: }
1.561 banghart 9548: if (ref($value) eq "ARRAY"){
9549: foreach my $stored_what (@{$value}) {
1.629 banghart 9550: my $cmp2=$stored_what;
1.759 albertel 9551: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9552: $cmp2=join('',@{$stored_what});
1.745 raeburn 9553: }
1.629 banghart 9554: if ($cmp1 eq $cmp2) {
1.561 banghart 9555: push(@readonly_files, $file_name);
1.745 raeburn 9556: last;
1.563 banghart 9557: } elsif (!defined($what)) {
9558: push(@readonly_files, $file_name);
1.745 raeburn 9559: last;
1.561 banghart 9560: }
9561: }
1.745 raeburn 9562: }
1.561 banghart 9563: }
9564: return @readonly_files;
9565: }
1.577 banghart 9566: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9567:
1.577 banghart 9568: sub get_marked_as_readonly_hash {
1.745 raeburn 9569: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9570: my %readonly_files;
1.745 raeburn 9571: while (my ($file_name,$value) = each(%{$current_permissions})) {
9572: if (defined($group)) {
9573: if ($file_name !~ m-^\Q$group\E/-) {
9574: next;
9575: }
9576: }
1.577 banghart 9577: if (ref($value) eq "ARRAY"){
9578: foreach my $stored_what (@{$value}) {
1.745 raeburn 9579: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9580: foreach my $lock_descriptor(@{$stored_what}) {
9581: if ($lock_descriptor eq 'graded') {
9582: $readonly_files{$file_name} = 'graded';
9583: } elsif ($lock_descriptor eq 'handback') {
9584: $readonly_files{$file_name} = 'handback';
9585: } else {
9586: if (!exists($readonly_files{$file_name})) {
9587: $readonly_files{$file_name} = 'locked';
9588: }
9589: }
1.745 raeburn 9590: }
1.750 banghart 9591: }
1.577 banghart 9592: }
9593: }
9594: }
9595: return %readonly_files;
9596: }
1.559 banghart 9597: # ------------------------------------------------------------ Unmark as Read Only
9598:
9599: sub unmark_as_readonly {
1.629 banghart 9600: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9601: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9602: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9603: $file_name = &declutter_portfile($file_name);
1.634 albertel 9604: my $symb_crs = $what;
9605: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9606: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9607: my ($tmp)=keys(%current_permissions);
9608: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9609: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9610: foreach my $file (@readonly_files) {
1.759 albertel 9611: my $clean_file = &declutter_portfile($file);
9612: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9613: my $current_locks = $current_permissions{$file};
1.563 banghart 9614: my @new_locks;
9615: my @del_keys;
9616: if (ref($current_locks) eq "ARRAY"){
9617: foreach my $locker (@{$current_locks}) {
1.632 albertel 9618: my $compare=$locker;
1.749 raeburn 9619: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9620: $compare=join('',@{$locker});
1.746 raeburn 9621: if ($compare ne $symb_crs) {
9622: push(@new_locks, $locker);
9623: }
1.563 banghart 9624: }
9625: }
1.650 albertel 9626: if (scalar(@new_locks) > 0) {
1.563 banghart 9627: $current_permissions{$file} = \@new_locks;
9628: } else {
9629: push(@del_keys, $file);
1.613 albertel 9630: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9631: delete($current_permissions{$file});
1.563 banghart 9632: }
9633: }
1.561 banghart 9634: }
1.613 albertel 9635: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9636: return;
9637: }
1.512 banghart 9638:
1.17 www 9639: # ------------------------------------------------------------ Directory lister
9640:
9641: sub dirlist {
1.955 raeburn 9642: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9643: $uri=~s/^\///;
9644: $uri=~s/\/$//;
1.253 stredwic 9645: my ($udom, $uname);
1.955 raeburn 9646: if ($getuserdir) {
1.253 stredwic 9647: $udom = $userdomain;
9648: $uname = $username;
1.955 raeburn 9649: } else {
9650: (undef,$udom,$uname)=split(/\//,$uri);
9651: if(defined($userdomain)) {
9652: $udom = $userdomain;
9653: }
9654: if(defined($username)) {
9655: $uname = $username;
9656: }
1.253 stredwic 9657: }
1.955 raeburn 9658: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9659:
1.955 raeburn 9660: $dirRoot = $perlvar{'lonDocRoot'};
9661: if (defined($getpropath)) {
9662: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9663: $dirRoot =~ s/\/$//;
1.955 raeburn 9664: } elsif (defined($getuserdir)) {
9665: my $subdir=$uname.'__';
9666: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9667: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9668: ."/$udom/$subdir/$uname";
9669: } elsif (defined($alternateRoot)) {
9670: $dirRoot = $alternateRoot;
1.751 banghart 9671: }
1.253 stredwic 9672:
9673: if($udom) {
9674: if($uname) {
1.1135 raeburn 9675: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9676: if ($uhome eq 'no_host') {
9677: return ([],'no_host');
9678: }
1.955 raeburn 9679: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9680: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9681: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9682: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9683: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9684: } else {
9685: @listing_results = map { &unescape($_); } split(/:/,$listing);
9686: }
1.605 matthew 9687: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9688: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9689: @listing_results = split(/:/,$listing);
9690: } else {
9691: @listing_results = map { &unescape($_); } split(/:/,$listing);
9692: }
1.1135 raeburn 9693: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9694: ($listing eq 'rejected') || ($listing eq 'refused') ||
9695: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9696: return ([],$listing);
9697: } else {
9698: return (\@listing_results);
1.1135 raeburn 9699: }
1.955 raeburn 9700: } elsif(!$alternateRoot) {
1.1136 raeburn 9701: my (%allusers,%listerror);
1.841 albertel 9702: my %servers = &get_servers($udom,'library');
1.955 raeburn 9703: foreach my $tryserver (keys(%servers)) {
9704: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9705: &escape($udom),$tryserver);
9706: if ($listing eq 'unknown_cmd') {
9707: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9708: $udom, $tryserver);
9709: } else {
9710: @listing_results = map { &unescape($_); } split(/:/,$listing);
9711: }
1.841 albertel 9712: if ($listing eq 'unknown_cmd') {
9713: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9714: $udom, $tryserver);
9715: @listing_results = split(/:/,$listing);
9716: } else {
9717: @listing_results =
9718: map { &unescape($_); } split(/:/,$listing);
9719: }
1.1136 raeburn 9720: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9721: ($listing eq 'rejected') || ($listing eq 'refused') ||
9722: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9723: $listerror{$tryserver} = $listing;
9724: } else {
1.841 albertel 9725: foreach my $line (@listing_results) {
9726: my ($entry) = split(/&/,$line,2);
9727: $allusers{$entry} = 1;
9728: }
9729: }
1.253 stredwic 9730: }
1.1136 raeburn 9731: my @alluserslist=();
1.800 albertel 9732: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9733: push(@alluserslist,$user.'&user');
1.253 stredwic 9734: }
1.1136 raeburn 9735: return (\@alluserslist);
1.253 stredwic 9736: } else {
1.1136 raeburn 9737: return ([],'missing username');
1.253 stredwic 9738: }
1.955 raeburn 9739: } elsif(!defined($getpropath)) {
1.1136 raeburn 9740: my $path = $perlvar{'lonDocRoot'}.'/res/';
9741: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9742: return (\@all_domains);
1.955 raeburn 9743: } else {
1.1136 raeburn 9744: return ([],'missing domain');
1.275 stredwic 9745: }
9746: }
9747:
9748: # --------------------------------------------- GetFileTimestamp
9749: # This function utilizes dirlist and returns the date stamp for
9750: # when it was last modified. It will also return an error of -1
9751: # if an error occurs
9752:
9753: sub GetFileTimestamp {
1.955 raeburn 9754: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9755: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9756: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9757: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9758: undef,$getuserdir);
9759: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9760: return -1;
9761: }
9762: if (ref($fileref) eq 'ARRAY') {
9763: my @stats = split('&',$fileref->[0]);
1.375 matthew 9764: # @stats contains first the filename, then the stat output
9765: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9766: } else {
9767: return -1;
1.253 stredwic 9768: }
1.26 www 9769: }
9770:
1.712 albertel 9771: sub stat_file {
9772: my ($uri) = @_;
1.787 albertel 9773: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9774:
1.955 raeburn 9775: my ($udom,$uname,$file);
1.712 albertel 9776: if ($uri =~ m-^/(uploaded|editupload)/-) {
9777: ($udom,$uname,$file) =
1.811 albertel 9778: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9779: $file = 'userfiles/'.$file;
9780: }
9781: if ($uri =~ m-^/res/-) {
9782: ($udom,$uname) =
1.807 albertel 9783: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9784: $file = $uri;
9785: }
9786:
9787: if (!$udom || !$uname || !$file) {
9788: # unable to handle the uri
9789: return ();
9790: }
1.956 raeburn 9791: my $getpropath;
9792: if ($file =~ /^userfiles\//) {
9793: $getpropath = 1;
9794: }
1.1136 raeburn 9795: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9796: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9797: return ();
9798: } else {
9799: if (ref($listref) eq 'ARRAY') {
9800: my @stats = split('&',$listref->[0]);
9801: shift(@stats); #filename is first
9802: return @stats;
9803: }
1.712 albertel 9804: }
9805: return ();
9806: }
9807:
1.26 www 9808: # -------------------------------------------------------- Value of a Condition
9809:
1.713 albertel 9810: # gets the value of a specific preevaluated condition
9811: # stored in the string $env{user.state.<cid>}
9812: # or looks up a condition reference in the bighash and if if hasn't
9813: # already been evaluated recurses into docondval to get the value of
9814: # the condition, then memoizing it to
9815: # $env{user.state.<cid>.<condition>}
1.40 www 9816: sub directcondval {
9817: my $number=shift;
1.620 albertel 9818: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9819: &Apache::lonuserstate::evalstate();
9820: }
1.713 albertel 9821: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9822: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9823: } elsif ($number =~ /^_/) {
9824: my $sub_condition;
9825: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9826: &GDBM_READER(),0640)) {
9827: $sub_condition=$bighash{'conditions'.$number};
9828: untie(%bighash);
9829: }
9830: my $value = &docondval($sub_condition);
1.949 raeburn 9831: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9832: return $value;
9833: }
1.620 albertel 9834: if ($env{'user.state.'.$env{'request.course.id'}}) {
9835: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9836: } else {
9837: return 2;
9838: }
9839: }
9840:
1.713 albertel 9841: # get the collection of conditions for this resource
1.26 www 9842: sub condval {
9843: my $condidx=shift;
1.54 www 9844: my $allpathcond='';
1.713 albertel 9845: foreach my $cond (split(/\|/,$condidx)) {
9846: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9847: $allpathcond.=
9848: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9849: }
1.191 harris41 9850: }
1.54 www 9851: $allpathcond=~s/\|$//;
1.713 albertel 9852: return &docondval($allpathcond);
9853: }
9854:
9855: #evaluates an expression of conditions
9856: sub docondval {
9857: my ($allpathcond) = @_;
9858: my $result=0;
9859: if ($env{'request.course.id'}
9860: && defined($allpathcond)) {
9861: my $operand='|';
9862: my @stack;
9863: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9864: if ($chunk eq '(') {
9865: push @stack,($operand,$result);
9866: } elsif ($chunk eq ')') {
9867: my $before=pop @stack;
9868: if (pop @stack eq '&') {
9869: $result=$result>$before?$before:$result;
9870: } else {
9871: $result=$result>$before?$result:$before;
9872: }
9873: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9874: $operand=$chunk;
9875: } else {
9876: my $new=directcondval($chunk);
9877: if ($operand eq '&') {
9878: $result=$result>$new?$new:$result;
9879: } else {
9880: $result=$result>$new?$result:$new;
9881: }
9882: }
9883: }
1.26 www 9884: }
9885: return $result;
1.421 albertel 9886: }
9887:
9888: # ---------------------------------------------------- Devalidate courseresdata
9889:
9890: sub devalidatecourseresdata {
9891: my ($coursenum,$coursedomain)=@_;
9892: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9893: &devalidate_cache_new('courseres',$hashid);
1.28 www 9894: }
9895:
1.763 www 9896:
1.200 www 9897: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9898: #
9899: # Parameters:
9900: # $coursenum - Number of the course.
9901: # $coursedomain - Domain at which the course was created.
9902: # Returns:
9903: # A hash of the course parameters along (I think) with timestamps
9904: # and version info.
1.877 foxr 9905:
1.624 albertel 9906: sub get_courseresdata {
9907: my ($coursenum,$coursedomain)=@_;
1.200 www 9908: my $coursehom=&homeserver($coursenum,$coursedomain);
9909: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9910: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9911: my %dumpreply;
1.417 albertel 9912: unless (defined($cached)) {
1.624 albertel 9913: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9914: $result=\%dumpreply;
1.251 albertel 9915: my ($tmp) = keys(%dumpreply);
9916: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9917: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9918: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9919: return $tmp;
1.416 albertel 9920: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9921: $result=undef;
1.599 albertel 9922: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9923: }
9924: }
1.624 albertel 9925: return $result;
9926: }
9927:
1.633 albertel 9928: sub devalidateuserresdata {
9929: my ($uname,$udom)=@_;
9930: my $hashid="$udom:$uname";
9931: &devalidate_cache_new('userres',$hashid);
9932: }
9933:
1.624 albertel 9934: sub get_userresdata {
9935: my ($uname,$udom)=@_;
9936: #most student don\'t have any data set, check if there is some data
9937: if (&EXT_cache_status($udom,$uname)) { return undef; }
9938:
9939: my $hashid="$udom:$uname";
9940: my ($result,$cached)=&is_cached_new('userres',$hashid);
9941: if (!defined($cached)) {
9942: my %resourcedata=&dump('resourcedata',$udom,$uname);
9943: $result=\%resourcedata;
9944: &do_cache_new('userres',$hashid,$result,600);
9945: }
9946: my ($tmp)=keys(%$result);
9947: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9948: return $result;
9949: }
9950: #error 2 occurs when the .db doesn't exist
9951: if ($tmp!~/error: 2 /) {
1.672 albertel 9952: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9953: " Trying to get resource data for ".
9954: $uname." at ".$udom.": ".
9955: $tmp."</font>");
9956: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9957: #&EXT_cache_set($udom,$uname);
9958: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9959: undef($tmp); # not really an error so don't send it back
1.624 albertel 9960: }
9961: return $tmp;
9962: }
1.879 foxr 9963: #----------------------------------------------- resdata - return resource data
9964: # Purpose:
9965: # Return resource data for either users or for a course.
9966: # Parameters:
9967: # $name - Course/user name.
9968: # $domain - Name of the domain the user/course is registered on.
9969: # $type - Type of thing $name is (must be 'course' or 'user'
9970: # @which - Array of names of resources desired.
9971: # Returns:
9972: # The value of the first reasource in @which that is found in the
9973: # resource hash.
9974: # Exceptional Conditions:
9975: # If the $type passed in is not valid (not the string 'course' or
9976: # 'user', an undefined reference is returned.
9977: # If none of the resources are found, an undef is returned
1.624 albertel 9978: sub resdata {
9979: my ($name,$domain,$type,@which)=@_;
9980: my $result;
9981: if ($type eq 'course') {
9982: $result=&get_courseresdata($name,$domain);
9983: } elsif ($type eq 'user') {
9984: $result=&get_userresdata($name,$domain);
9985: }
9986: if (!ref($result)) { return $result; }
1.251 albertel 9987: foreach my $item (@which) {
1.927 albertel 9988: if (defined($result->{$item->[0]})) {
9989: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9990: }
1.250 albertel 9991: }
1.291 albertel 9992: return undef;
1.200 www 9993: }
9994:
1.1236 raeburn 9995: sub get_numsuppfiles {
9996: my ($cnum,$cdom,$ignorecache)=@_;
9997: my $hashid=$cnum.':'.$cdom;
9998: my ($suppcount,$cached);
9999: unless ($ignorecache) {
10000: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10001: }
10002: unless (defined($cached)) {
10003: my $chome=&homeserver($cnum,$cdom);
10004: unless ($chome eq 'no_host') {
10005: ($suppcount,my $errors) = (0,0);
10006: my $suppmap = 'supplemental.sequence';
10007: ($suppcount,$errors) =
10008: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10009: }
10010: &do_cache_new('suppcount',$hashid,$suppcount,600);
10011: }
10012: return $suppcount;
10013: }
10014:
1.379 matthew 10015: #
10016: # EXT resource caching routines
10017: #
10018:
10019: sub clear_EXT_cache_status {
1.383 albertel 10020: &delenv('cache.EXT.');
1.379 matthew 10021: }
10022:
10023: sub EXT_cache_status {
10024: my ($target_domain,$target_user) = @_;
1.383 albertel 10025: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10026: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10027: # We know already the user has no data
10028: return 1;
10029: } else {
10030: return 0;
10031: }
10032: }
10033:
10034: sub EXT_cache_set {
10035: my ($target_domain,$target_user) = @_;
1.383 albertel 10036: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10037: #&appenv({$cachename => time});
1.379 matthew 10038: }
10039:
1.28 www 10040: # --------------------------------------------------------- Value of a Variable
1.58 www 10041: sub EXT {
1.715 albertel 10042:
1.1228 raeburn 10043: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10044: unless ($varname) { return ''; }
1.218 albertel 10045: #get real user name/domain, courseid and symb
10046: my $courseid;
1.359 albertel 10047: my $publicuser;
1.427 www 10048: if ($symbparm) {
10049: $symbparm=&get_symb_from_alias($symbparm);
10050: }
1.218 albertel 10051: if (!($uname && $udom)) {
1.790 albertel 10052: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10053: if (!$symbparm) { $symbparm=$cursymb; }
10054: } else {
1.620 albertel 10055: $courseid=$env{'request.course.id'};
1.218 albertel 10056: }
1.48 www 10057: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10058: my $rest;
1.320 albertel 10059: if (defined($therest[0])) {
1.48 www 10060: $rest=join('.',@therest);
10061: } else {
10062: $rest='';
10063: }
1.320 albertel 10064:
1.57 www 10065: my $qualifierrest=$qualifier;
10066: if ($rest) { $qualifierrest.='.'.$rest; }
10067: my $spacequalifierrest=$space;
10068: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10069: if ($realm eq 'user') {
1.48 www 10070: # --------------------------------------------------------------- user.resource
10071: if ($space eq 'resource') {
1.651 albertel 10072: if ( (defined($Apache::lonhomework::parsing_a_problem)
10073: || defined($Apache::lonhomework::parsing_a_task))
10074: &&
1.744 albertel 10075: ($symbparm eq &symbread()) ) {
10076: # if we are in the middle of processing the resource the
10077: # get the value we are planning on committing
10078: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10079: return $Apache::lonhomework::results{$qualifierrest};
10080: } else {
10081: return $Apache::lonhomework::history{$qualifierrest};
10082: }
1.335 albertel 10083: } else {
1.359 albertel 10084: my %restored;
1.620 albertel 10085: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10086: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10087: } else {
10088: %restored=&restore($symbparm,$courseid,$udom,$uname);
10089: }
1.335 albertel 10090: return $restored{$qualifierrest};
10091: }
1.48 www 10092: # ----------------------------------------------------------------- user.access
10093: } elsif ($space eq 'access') {
1.218 albertel 10094: # FIXME - not supporting calls for a specific user
1.48 www 10095: return &allowed($qualifier,$rest);
10096: # ------------------------------------------ user.preferences, user.environment
10097: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10098: if (($uname eq $env{'user.name'}) &&
10099: ($udom eq $env{'user.domain'})) {
10100: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10101: } else {
1.359 albertel 10102: my %returnhash;
10103: if (!$publicuser) {
10104: %returnhash=&userenvironment($udom,$uname,
10105: $qualifierrest);
10106: }
1.218 albertel 10107: return $returnhash{$qualifierrest};
10108: }
1.48 www 10109: # ----------------------------------------------------------------- user.course
10110: } elsif ($space eq 'course') {
1.218 albertel 10111: # FIXME - not supporting calls for a specific user
1.620 albertel 10112: return $env{join('.',('request.course',$qualifier))};
1.48 www 10113: # ------------------------------------------------------------------- user.role
10114: } elsif ($space eq 'role') {
1.218 albertel 10115: # FIXME - not supporting calls for a specific user
1.620 albertel 10116: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10117: if ($qualifier eq 'value') {
10118: return $role;
10119: } elsif ($qualifier eq 'extent') {
10120: return $where;
10121: }
10122: # ----------------------------------------------------------------- user.domain
10123: } elsif ($space eq 'domain') {
1.218 albertel 10124: return $udom;
1.48 www 10125: # ------------------------------------------------------------------- user.name
10126: } elsif ($space eq 'name') {
1.218 albertel 10127: return $uname;
1.48 www 10128: # ---------------------------------------------------- Any other user namespace
1.29 www 10129: } else {
1.359 albertel 10130: my %reply;
10131: if (!$publicuser) {
10132: %reply=&get($space,[$qualifierrest],$udom,$uname);
10133: }
10134: return $reply{$qualifierrest};
1.48 www 10135: }
1.236 www 10136: } elsif ($realm eq 'query') {
10137: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10138: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10139: [$spacequalifierrest]);
1.620 albertel 10140: return $env{'form.'.$spacequalifierrest};
1.236 www 10141: } elsif ($realm eq 'request') {
1.48 www 10142: # ------------------------------------------------------------- request.browser
10143: if ($space eq 'browser') {
1.1145 bisitz 10144: return $env{'browser.'.$qualifier};
1.57 www 10145: # ------------------------------------------------------------ request.filename
10146: } else {
1.620 albertel 10147: return $env{'request.'.$spacequalifierrest};
1.29 www 10148: }
1.28 www 10149: } elsif ($realm eq 'course') {
1.48 www 10150: # ---------------------------------------------------------- course.description
1.620 albertel 10151: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10152: } elsif ($realm eq 'resource') {
1.165 www 10153:
1.620 albertel 10154: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10155: if (!$symbparm) { $symbparm=&symbread(); }
10156: }
1.693 albertel 10157:
1.1232 raeburn 10158: if ($qualifier eq '') {
10159: if ($space eq 'title') {
10160: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10161: return &gettitle($symbparm);
10162: }
1.693 albertel 10163:
1.1232 raeburn 10164: if ($space eq 'map') {
10165: my ($map) = &decode_symb($symbparm);
10166: return &symbread($map);
10167: }
10168: if ($space eq 'maptitle') {
10169: my ($map) = &decode_symb($symbparm);
10170: return &gettitle($map);
10171: }
10172: if ($space eq 'filename') {
10173: if ($symbparm) {
10174: return &clutter((&decode_symb($symbparm))[2]);
10175: }
10176: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10177: }
1.1232 raeburn 10178:
1.1233 raeburn 10179: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10180: if ($space eq 'visibleparts') {
10181: my $navmap = Apache::lonnavmaps::navmap->new();
10182: my $item;
10183: if (ref($navmap)) {
10184: my $res = $navmap->getBySymb($symbparm);
10185: my $parts = $res->parts();
10186: if (ref($parts) eq 'ARRAY') {
10187: $item = join(',',@{$parts});
10188: }
10189: undef($navmap);
1.1232 raeburn 10190: }
1.1233 raeburn 10191: return $item;
1.1232 raeburn 10192: }
10193: }
10194: }
1.693 albertel 10195:
10196: my ($section, $group, @groups);
1.593 albertel 10197: my ($courselevelm,$courselevel);
1.1228 raeburn 10198: if (($courseid eq '') && ($cid)) {
10199: $courseid = $cid;
10200: }
10201: if (($symbparm && $courseid) &&
10202: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10203:
1.218 albertel 10204: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10205:
1.60 www 10206: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10207: my $symbp=$symbparm;
1.735 albertel 10208: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10209:
10210: my $symbparm=$symbp.'.'.$spacequalifierrest;
10211: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10212:
1.620 albertel 10213: if (($env{'user.name'} eq $uname) &&
10214: ($env{'user.domain'} eq $udom)) {
10215: $section=$env{'request.course.sec'};
1.733 raeburn 10216: @groups = split(/:/,$env{'request.course.groups'});
10217: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10218: } else {
1.539 albertel 10219: if (! defined($usection)) {
1.551 albertel 10220: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10221: } else {
10222: $section = $usection;
10223: }
1.733 raeburn 10224: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10225: }
10226:
10227: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10228: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10229: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10230:
1.593 albertel 10231: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10232: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10233: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10234:
1.60 www 10235: # ----------------------------------------------------------- first, check user
1.624 albertel 10236:
10237: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10238: ([$courselevelr,'resource'],
10239: [$courselevelm,'map' ],
10240: [$courselevel, 'course' ]));
1.931 albertel 10241: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10242:
1.594 albertel 10243: # ------------------------------------------------ second, check some of course
1.684 raeburn 10244: my $coursereply;
1.691 raeburn 10245: if (@groups > 0) {
10246: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10247: $mapparm,$spacequalifierrest);
1.927 albertel 10248: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10249: }
1.96 www 10250:
1.684 raeburn 10251: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10252: $env{'course.'.$courseid.'.domain'},
10253: 'course',
10254: ([$seclevelr, 'resource'],
10255: [$seclevelm, 'map' ],
10256: [$seclevel, 'course' ],
10257: [$courselevelr,'resource']));
10258: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10259:
1.60 www 10260: # ------------------------------------------------------ third, check map parms
1.218 albertel 10261: my %parmhash=();
10262: my $thisparm='';
10263: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10264: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10265: &GDBM_READER(),0640)) {
1.218 albertel 10266: $thisparm=$parmhash{$symbparm};
10267: untie(%parmhash);
10268: }
1.927 albertel 10269: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10270: }
1.594 albertel 10271: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10272:
1.218 albertel 10273: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10274: my $filename;
10275: if (!$symbparm) { $symbparm=&symbread(); }
10276: if ($symbparm) {
1.409 www 10277: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10278: } else {
1.620 albertel 10279: $filename=$env{'request.filename'};
1.282 albertel 10280: }
10281: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10282: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10283: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10284: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10285:
1.927 albertel 10286: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10287: if ($symbparm && defined($courseid) &&
1.620 albertel 10288: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10289: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10290: $env{'course.'.$courseid.'.domain'},
10291: 'course',
1.927 albertel 10292: ([$courselevelm,'map' ],
10293: [$courselevel, 'course']));
10294: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10295: }
1.145 www 10296: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10297: unless ($space eq '0') {
1.336 albertel 10298: my @parts=split(/_/,$space);
10299: my $id=pop(@parts);
10300: my $part=join('_',@parts);
10301: if ($part eq '') { $part='0'; }
1.927 albertel 10302: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10303: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10304: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10305: }
1.395 albertel 10306: if ($recurse) { return undef; }
10307: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10308: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10309: # ---------------------------------------------------- Any other user namespace
10310: } elsif ($realm eq 'environment') {
10311: # ----------------------------------------------------------------- environment
1.620 albertel 10312: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10313: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10314: } else {
1.770 albertel 10315: if ($uname eq 'anonymous' && $udom eq '') {
10316: return '';
10317: }
1.219 albertel 10318: my %returnhash=&userenvironment($udom,$uname,
10319: $spacequalifierrest);
10320: return $returnhash{$spacequalifierrest};
10321: }
1.28 www 10322: } elsif ($realm eq 'system') {
1.48 www 10323: # ----------------------------------------------------------------- system.time
10324: if ($space eq 'time') {
10325: return time;
10326: }
1.696 albertel 10327: } elsif ($realm eq 'server') {
10328: # ----------------------------------------------------------------- system.time
10329: if ($space eq 'name') {
10330: return $ENV{'SERVER_NAME'};
10331: }
1.28 www 10332: }
1.48 www 10333: return '';
1.61 www 10334: }
10335:
1.927 albertel 10336: sub get_reply {
10337: my ($reply_value) = @_;
1.940 raeburn 10338: if (ref($reply_value) eq 'ARRAY') {
10339: if (wantarray) {
10340: return @$reply_value;
10341: }
10342: return $reply_value->[0];
10343: } else {
10344: return $reply_value;
1.927 albertel 10345: }
10346: }
10347:
1.691 raeburn 10348: sub check_group_parms {
10349: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10350: my @groupitems = ();
10351: my $resultitem;
1.927 albertel 10352: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10353: foreach my $group (@{$groups}) {
10354: foreach my $level (@levels) {
1.927 albertel 10355: my $item = $courseid.'.['.$group.'].'.$level->[0];
10356: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10357: }
10358: }
10359: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10360: $env{'course.'.$courseid.'.domain'},
10361: 'course',@groupitems);
10362: return $coursereply;
10363: }
10364:
10365: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10366: my ($courseid,@groups) = @_;
10367: @groups = sort(@groups);
1.691 raeburn 10368: return @groups;
10369: }
10370:
1.395 albertel 10371: sub packages_tab_default {
10372: my ($uri,$varname)=@_;
10373: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10374:
10375: my (@extension,@specifics,$do_default);
10376: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10377: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10378: if ($pack_type eq 'default') {
10379: $do_default=1;
10380: } elsif ($pack_type eq 'extension') {
10381: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10382: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10383: # only look at packages defaults for packages that this id is
1.738 albertel 10384: push(@specifics,[$package,$pack_type,$pack_part]);
10385: }
10386: }
10387: # first look for a package that matches the requested part id
10388: foreach my $package (@specifics) {
10389: my (undef,$pack_type,$pack_part)=@{$package};
10390: next if ($pack_part ne $part);
10391: if (defined($packagetab{"$pack_type&$name&default"})) {
10392: return $packagetab{"$pack_type&$name&default"};
10393: }
10394: }
10395: # look for any possible matching non extension_ package
10396: foreach my $package (@specifics) {
10397: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10398: if (defined($packagetab{"$pack_type&$name&default"})) {
10399: return $packagetab{"$pack_type&$name&default"};
10400: }
1.585 albertel 10401: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10402: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10403: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10404: }
10405: }
1.738 albertel 10406: # look for any posible extension_ match
10407: foreach my $package (@extension) {
10408: my ($package,$pack_type)=@{$package};
10409: if (defined($packagetab{"$pack_type&$name&default"})) {
10410: return $packagetab{"$pack_type&$name&default"};
10411: }
10412: if (defined($packagetab{$package."&$name&default"})) {
10413: return $packagetab{$package."&$name&default"};
10414: }
10415: }
10416: # look for a global default setting
10417: if ($do_default && defined($packagetab{"default&$name&default"})) {
10418: return $packagetab{"default&$name&default"};
10419: }
1.395 albertel 10420: return undef;
10421: }
10422:
1.334 albertel 10423: sub add_prefix_and_part {
10424: my ($prefix,$part)=@_;
10425: my $keyroot;
10426: if (defined($prefix) && $prefix !~ /^__/) {
10427: # prefix that has a part already
10428: $keyroot=$prefix;
10429: } elsif (defined($prefix)) {
10430: # prefix that is missing a part
10431: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10432: } else {
10433: # no prefix at all
10434: if (defined($part)) { $keyroot='_'.$part; }
10435: }
10436: return $keyroot;
10437: }
10438:
1.71 www 10439: # ---------------------------------------------------------------- Get metadata
10440:
1.599 albertel 10441: my %metaentry;
1.1070 www 10442: my %importedpartids;
1.71 www 10443: sub metadata {
1.176 www 10444: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10445: $uri=&declutter($uri);
1.288 albertel 10446: # if it is a non metadata possible uri return quickly
1.529 albertel 10447: if (($uri eq '') ||
10448: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10449: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10450: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10451: return undef;
10452: }
1.1261 raeburn 10453: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10454: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10455: return undef;
1.288 albertel 10456: }
1.73 www 10457: my $filename=$uri;
10458: $uri=~s/\.meta$//;
1.172 www 10459: #
10460: # Is the metadata already cached?
1.177 www 10461: # Look at timestamp of caching
1.172 www 10462: # Everything is cached by the main uri, libraries are never directly cached
10463: #
1.428 albertel 10464: if (!defined($liburi)) {
1.599 albertel 10465: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10466: if (defined($cached)) { return $result->{':'.$what}; }
10467: }
10468: {
1.1069 www 10469: # Imported parts would go here
1.1070 www 10470: my %importedids=();
10471: my @origfileimportpartids=();
1.1069 www 10472: my $importedparts=0;
1.172 www 10473: #
10474: # Is this a recursive call for a library?
10475: #
1.599 albertel 10476: # if (! exists($metacache{$uri})) {
10477: # $metacache{$uri}={};
10478: # }
1.924 albertel 10479: my $cachetime = 60*60;
1.171 www 10480: if ($liburi) {
10481: $liburi=&declutter($liburi);
10482: $filename=$liburi;
1.401 bowersj2 10483: } else {
1.599 albertel 10484: &devalidate_cache_new('meta',$uri);
10485: undef(%metaentry);
1.401 bowersj2 10486: }
1.140 www 10487: my %metathesekeys=();
1.73 www 10488: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10489: my $metastring;
1.1140 www 10490: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10491: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10492: $metastring =
1.929 albertel 10493: &Apache::lonnet::ssi_body($which,
1.924 albertel 10494: ('grade_target' => 'meta'));
10495: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10496: } elsif (($uri !~ m -^(editupload)/-) &&
10497: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10498: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10499: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10500: $metastring=&getfile($file);
1.489 albertel 10501: }
1.208 albertel 10502: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10503: my $token;
1.140 www 10504: undef %metathesekeys;
1.71 www 10505: while ($token=$parser->get_token) {
1.339 albertel 10506: if ($token->[0] eq 'S') {
10507: if (defined($token->[2]->{'package'})) {
1.172 www 10508: #
10509: # This is a package - get package info
10510: #
1.339 albertel 10511: my $package=$token->[2]->{'package'};
10512: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10513: if (defined($token->[2]->{'id'})) {
10514: $keyroot.='_'.$token->[2]->{'id'};
10515: }
1.599 albertel 10516: if ($metaentry{':packages'}) {
10517: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10518: } else {
1.599 albertel 10519: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10520: }
1.736 albertel 10521: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10522: my $part=$keyroot;
10523: $part=~s/^\_//;
1.736 albertel 10524: if ($pack_entry=~/^\Q$package\E\&/ ||
10525: $pack_entry=~/^\Q$package\E_0\&/) {
10526: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10527: # ignore package.tab specified default values
10528: # here &package_tab_default() will fetch those
10529: if ($subp eq 'default') { next; }
1.736 albertel 10530: my $value=$packagetab{$pack_entry};
1.432 albertel 10531: my $unikey;
10532: if ($pack =~ /_0$/) {
10533: $unikey='parameter_0_'.$name;
10534: $part=0;
10535: } else {
10536: $unikey='parameter'.$keyroot.'_'.$name;
10537: }
1.339 albertel 10538: if ($subp eq 'display') {
10539: $value.=' [Part: '.$part.']';
10540: }
1.599 albertel 10541: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10542: $metathesekeys{$unikey}=1;
1.599 albertel 10543: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10544: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10545: }
1.599 albertel 10546: if (defined($metaentry{':'.$unikey.'.default'})) {
10547: $metaentry{':'.$unikey}=
10548: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10549: }
1.339 albertel 10550: }
10551: }
10552: } else {
1.172 www 10553: #
10554: # This is not a package - some other kind of start tag
1.339 albertel 10555: #
10556: my $entry=$token->[1];
1.1068 www 10557: my $unikey='';
1.175 www 10558:
1.339 albertel 10559: if ($entry eq 'import') {
1.175 www 10560: #
10561: # Importing a library here
1.339 albertel 10562: #
1.1067 www 10563: my $location=$parser->get_text('/import');
10564: my $dir=$filename;
10565: $dir=~s|[^/]*$||;
10566: $location=&filelocation($dir,$location);
1.1069 www 10567:
1.1068 www 10568: my $importmode=$token->[2]->{'importmode'};
10569: if ($importmode eq 'problem') {
1.1069 www 10570: # Import as problem/response
1.1068 www 10571: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10572: } elsif ($importmode eq 'part') {
10573: # Import as part(s)
1.1069 www 10574: $importedparts=1;
10575: # We need to get the original file and the imported file to get the part order correct
10576: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10577: # Load and inspect original file
1.1070 www 10578: if ($#origfileimportpartids<0) {
10579: undef(%importedpartids);
10580: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10581: my $origfile=&getfile($origfilelocation);
10582: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10583: }
10584:
1.1069 www 10585: # Load and inspect imported file
10586: my $impfile=&getfile($location);
10587: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10588: if ($#impfilepartids>=0) {
10589: # This problem had parts
1.1070 www 10590: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10591: } else {
10592: # Importing by turning a single problem into a problem part
10593: # It gets the import-tags ID as part-ID
10594: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10595: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10596: }
1.1068 www 10597: } else {
10598: # Normal import
10599: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10600: if (defined($token->[2]->{'id'})) {
10601: $unikey.='_'.$token->[2]->{'id'};
10602: }
1.1067 www 10603: }
10604:
1.339 albertel 10605: if ($depthcount<20) {
1.736 albertel 10606: my $metadata =
10607: &metadata($uri,'keys', $location,$unikey,
10608: $depthcount+1);
10609: foreach my $meta (split(',',$metadata)) {
10610: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10611: $metathesekeys{$meta}=1;
1.339 albertel 10612: }
1.1068 www 10613:
10614: }
1.1067 www 10615: } else {
10616: #
10617: # Not importing, some other kind of non-package, non-library start tag
10618: #
10619: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10620: if (defined($token->[2]->{'id'})) {
10621: $unikey.='_'.$token->[2]->{'id'};
10622: }
1.339 albertel 10623: if (defined($token->[2]->{'name'})) {
10624: $unikey.='_'.$token->[2]->{'name'};
10625: }
10626: $metathesekeys{$unikey}=1;
1.736 albertel 10627: foreach my $param (@{$token->[3]}) {
10628: $metaentry{':'.$unikey.'.'.$param} =
10629: $token->[2]->{$param};
1.339 albertel 10630: }
10631: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10632: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10633: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10634: # only ws inside the tag, and not in default, so use default
10635: # as value
1.599 albertel 10636: $metaentry{':'.$unikey}=$default;
1.908 albertel 10637: } elsif ( $internaltext =~ /\S/ ) {
10638: # something interesting inside the tag
10639: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10640: } else {
1.908 albertel 10641: # no interesting values, don't set a default
1.339 albertel 10642: }
1.172 www 10643: # end of not-a-package not-a-library import
1.339 albertel 10644: }
1.172 www 10645: # end of not-a-package start tag
1.339 albertel 10646: }
1.172 www 10647: # the next is the end of "start tag"
1.339 albertel 10648: }
10649: }
1.483 albertel 10650: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10651: $extension = lc($extension);
10652: if ($extension eq 'htm') { $extension='html'; }
10653:
1.737 albertel 10654: foreach my $key (keys(%packagetab)) {
1.483 albertel 10655: #no specific packages #how's our extension
10656: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10657: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10658: \%metathesekeys);
10659: }
1.883 albertel 10660:
10661: if (!exists($metaentry{':packages'})
10662: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10663: foreach my $key (keys(%packagetab)) {
1.483 albertel 10664: #no specific packages well let's get default then
10665: if ($key!~/^default&/) { next; }
1.488 albertel 10666: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10667: \%metathesekeys);
10668: }
10669: }
1.338 www 10670: # are there custom rights to evaluate
1.599 albertel 10671: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10672:
1.338 www 10673: #
10674: # Importing a rights file here
1.339 albertel 10675: #
10676: unless ($depthcount) {
1.599 albertel 10677: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10678: my $dir=$filename;
10679: $dir=~s|[^/]*$||;
10680: $location=&filelocation($dir,$location);
1.736 albertel 10681: my $rights_metadata =
10682: &metadata($uri,'keys',$location,'_rights',
10683: $depthcount+1);
10684: foreach my $rights (split(',',$rights_metadata)) {
10685: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10686: $metathesekeys{$rights}=1;
1.339 albertel 10687: }
10688: }
10689: }
1.737 albertel 10690: # uniqifiy package listing
10691: my %seen;
10692: my @uniq_packages =
10693: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10694: $metaentry{':packages'} = join(',',@uniq_packages);
10695:
1.1070 www 10696: if ($importedparts) {
10697: # We had imported parts and need to rebuild partorder
10698: $metaentry{':partorder'}='';
10699: $metathesekeys{'partorder'}=1;
10700: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10701: if ($origfileimportpartids[$index] eq 'part') {
10702: # original part, part of the problem
10703: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10704: } else {
10705: # we have imported parts at this position
10706: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10707: }
10708: }
10709: $metaentry{':partorder'}=~s/^\,//;
10710: }
10711:
1.737 albertel 10712: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10713: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 10714: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10715: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10716: # this is the end of "was not already recently cached
1.71 www 10717: }
1.599 albertel 10718: return $metaentry{':'.$what};
1.261 albertel 10719: }
10720:
1.488 albertel 10721: sub metadata_create_package_def {
1.483 albertel 10722: my ($uri,$key,$package,$metathesekeys)=@_;
10723: my ($pack,$name,$subp)=split(/\&/,$key);
10724: if ($subp eq 'default') { next; }
10725:
1.599 albertel 10726: if (defined($metaentry{':packages'})) {
10727: $metaentry{':packages'}.=','.$package;
1.483 albertel 10728: } else {
1.599 albertel 10729: $metaentry{':packages'}=$package;
1.483 albertel 10730: }
10731: my $value=$packagetab{$key};
10732: my $unikey;
10733: $unikey='parameter_0_'.$name;
1.599 albertel 10734: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10735: $$metathesekeys{$unikey}=1;
1.599 albertel 10736: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10737: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10738: }
1.599 albertel 10739: if (defined($metaentry{':'.$unikey.'.default'})) {
10740: $metaentry{':'.$unikey}=
10741: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10742: }
10743: }
10744:
1.261 albertel 10745: sub metadata_generate_part0 {
10746: my ($metadata,$metacache,$uri) = @_;
10747: my %allnames;
1.737 albertel 10748: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10749: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10750: my $part=$$metacache{':'.$metakey.'.part'};
10751: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10752: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10753: $allnames{$name}=$part;
10754: }
10755: }
10756: }
10757: foreach my $name (keys(%allnames)) {
10758: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10759: my $key=":parameter_0_$name";
1.261 albertel 10760: $$metacache{"$key.part"}='0';
10761: $$metacache{"$key.name"}=$name;
1.428 albertel 10762: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10763: $allnames{$name}.'_'.$name.
10764: '.type'};
1.428 albertel 10765: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10766: '.display'};
1.644 www 10767: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10768: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10769: $$metacache{"$key.display"}=$olddis;
10770: }
1.71 www 10771: }
10772:
1.764 albertel 10773: # ------------------------------------------------------ Devalidate title cache
10774:
10775: sub devalidate_title_cache {
10776: my ($url)=@_;
10777: if (!$env{'request.course.id'}) { return; }
10778: my $symb=&symbread($url);
10779: if (!$symb) { return; }
10780: my $key=$env{'request.course.id'}."\0".$symb;
10781: &devalidate_cache_new('title',$key);
10782: }
10783:
1.1014 droeschl 10784: # ------------------------------------------------- Get the title of a course
10785:
10786: sub current_course_title {
10787: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10788: }
1.301 www 10789: # ------------------------------------------------- Get the title of a resource
10790:
10791: sub gettitle {
10792: my $urlsymb=shift;
10793: my $symb=&symbread($urlsymb);
1.534 albertel 10794: if ($symb) {
1.620 albertel 10795: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10796: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10797: if (defined($cached)) {
10798: return $result;
10799: }
1.534 albertel 10800: my ($map,$resid,$url)=&decode_symb($symb);
10801: my $title='';
1.907 albertel 10802: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10803: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10804: } else {
10805: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10806: &GDBM_READER(),0640)) {
10807: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10808: $title=$bighash{'title_'.$mapid.'.'.$resid};
10809: untie(%bighash);
10810: }
1.534 albertel 10811: }
10812: $title=~s/\&colon\;/\:/gs;
10813: if ($title) {
1.1159 www 10814: # Remember both $symb and $title for dynamic metadata
10815: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10816: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10817: # Cache this title and then return it
1.599 albertel 10818: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10819: }
10820: $urlsymb=$url;
10821: }
10822: my $title=&metadata($urlsymb,'title');
10823: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10824: return $title;
1.301 www 10825: }
1.613 albertel 10826:
1.614 albertel 10827: sub get_slot {
10828: my ($which,$cnum,$cdom)=@_;
10829: if (!$cnum || !$cdom) {
1.790 albertel 10830: (undef,my $courseid)=&whichuser();
1.620 albertel 10831: $cdom=$env{'course.'.$courseid.'.domain'};
10832: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10833: }
1.703 albertel 10834: my $key=join("\0",'slots',$cdom,$cnum,$which);
10835: my %slotinfo;
10836: if (exists($remembered{$key})) {
10837: $slotinfo{$which} = $remembered{$key};
10838: } else {
10839: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10840: &Apache::lonhomework::showhash(%slotinfo);
10841: my ($tmp)=keys(%slotinfo);
10842: if ($tmp=~/^error:/) { return (); }
10843: $remembered{$key} = $slotinfo{$which};
10844: }
1.616 albertel 10845: if (ref($slotinfo{$which}) eq 'HASH') {
10846: return %{$slotinfo{$which}};
10847: }
10848: return $slotinfo{$which};
1.614 albertel 10849: }
1.1150 raeburn 10850:
10851: sub get_reservable_slots {
10852: my ($cnum,$cdom,$uname,$udom) = @_;
10853: my $now = time;
10854: my $reservable_info;
10855: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10856: if (exists($remembered{$key})) {
10857: $reservable_info = $remembered{$key};
10858: } else {
10859: my %resv;
10860: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10861: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10862: $reservable_info = \%resv;
10863: $remembered{$key} = $reservable_info;
10864: }
10865: return $reservable_info;
10866: }
10867:
10868: sub get_course_slots {
10869: my ($cnum,$cdom) = @_;
10870: my $hashid=$cnum.':'.$cdom;
10871: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10872: if (defined($cached)) {
10873: if (ref($result) eq 'HASH') {
10874: return %{$result};
10875: }
10876: } else {
10877: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10878: my ($tmp) = keys(%slots);
10879: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10880: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10881: return %slots;
10882: }
10883: }
10884: return;
10885: }
10886:
10887: sub devalidate_slots_cache {
10888: my ($cnum,$cdom)=@_;
10889: my $hashid=$cnum.':'.$cdom;
10890: &devalidate_cache_new('allslots',$hashid);
10891: }
10892:
1.1181 raeburn 10893: sub get_coursechange {
10894: my ($cdom,$cnum) = @_;
10895: if ($cdom eq '' || $cnum eq '') {
10896: return unless ($env{'request.course.id'});
10897: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10898: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10899: }
10900: my $hashid=$cdom.'_'.$cnum;
10901: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10902: if ((defined($cached)) && ($change ne '')) {
10903: return $change;
10904: } else {
10905: my %crshash;
10906: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10907: if ($crshash{'internal.contentchange'} eq '') {
10908: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10909: if ($change eq '') {
10910: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10911: $change = $crshash{'internal.created'};
10912: }
10913: } else {
10914: $change = $crshash{'internal.contentchange'};
10915: }
10916: my $cachetime = 600;
10917: &do_cache_new('crschange',$hashid,$change,$cachetime);
10918: }
10919: return $change;
10920: }
10921:
10922: sub devalidate_coursechange_cache {
10923: my ($cnum,$cdom)=@_;
10924: my $hashid=$cnum.':'.$cdom;
10925: &devalidate_cache_new('crschange',$hashid);
10926: }
10927:
1.31 www 10928: # ------------------------------------------------- Update symbolic store links
10929:
10930: sub symblist {
10931: my ($mapname,%newhash)=@_;
1.438 www 10932: $mapname=&deversion(&declutter($mapname));
1.31 www 10933: my %hash;
1.620 albertel 10934: if (($env{'request.course.fn'}) && (%newhash)) {
10935: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10936: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10937: foreach my $url (keys(%newhash)) {
1.711 albertel 10938: next if ($url eq 'last_known'
10939: && $env{'form.no_update_last_known'});
10940: $hash{declutter($url)}=&encode_symb($mapname,
10941: $newhash{$url}->[1],
10942: $newhash{$url}->[0]);
1.191 harris41 10943: }
1.31 www 10944: if (untie(%hash)) {
10945: return 'ok';
10946: }
10947: }
10948: }
10949: return 'error';
1.212 www 10950: }
10951:
10952: # --------------------------------------------------------------- Verify a symb
10953:
10954: sub symbverify {
1.1190 raeburn 10955: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10956: my $thisfn=$thisurl;
1.439 www 10957: $thisfn=&declutter($thisfn);
1.215 www 10958: # direct jump to resource in page or to a sequence - will construct own symbs
10959: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10960: # check URL part
1.409 www 10961: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10962:
1.431 www 10963: unless ($url eq $thisfn) { return 0; }
1.213 www 10964:
1.216 www 10965: $symb=&symbclean($symb);
1.510 www 10966: $thisurl=&deversion($thisurl);
1.439 www 10967: $thisfn=&deversion($thisfn);
1.213 www 10968:
10969: my %bighash;
10970: my $okay=0;
1.431 www 10971:
1.620 albertel 10972: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10973: &GDBM_READER(),0640)) {
1.1204 raeburn 10974: my $noclutter;
1.1032 raeburn 10975: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10976: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10977: if ($map =~ m{^uploaded/.+\.page$}) {
10978: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10979: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10980: $noclutter = 1;
10981: }
10982: }
10983: my $ids;
10984: if ($noclutter) {
10985: $ids=$bighash{'ids_'.$thisurl};
10986: } else {
10987: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10988: }
1.1102 raeburn 10989: unless ($ids) {
10990: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10991: $ids=$bighash{$idkey};
1.216 www 10992: }
10993: if ($ids) {
10994: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10995: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10996: $symb =~ s/\?.+$//;
1.1202 raeburn 10997: }
1.800 albertel 10998: foreach my $id (split(/\,/,$ids)) {
10999: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11000: if (
11001: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11002: eq $symb) {
11003: if (ref($encstate)) {
11004: $$encstate = $bighash{'encrypted_'.$id};
11005: }
1.620 albertel 11006: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11007: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11008: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11009: $okay=1;
1.1202 raeburn 11010: last;
1.582 albertel 11011: }
11012: }
1.216 www 11013: }
11014: }
1.213 www 11015: untie(%bighash);
11016: }
11017: return $okay;
1.31 www 11018: }
11019:
1.210 www 11020: # --------------------------------------------------------------- Clean-up symb
11021:
11022: sub symbclean {
11023: my $symb=shift;
1.568 albertel 11024: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11025: # remove version from map
11026: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11027:
1.210 www 11028: # remove version from URL
11029: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11030:
1.507 www 11031: # remove wrapper
11032:
1.510 www 11033: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11034: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11035: return $symb;
1.409 www 11036: }
11037:
11038: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11039:
11040: sub encode_symb {
11041: my ($map,$resid,$url)=@_;
11042: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11043: }
1.409 www 11044:
11045: sub decode_symb {
1.568 albertel 11046: my $symb=shift;
11047: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11048: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11049: return (&fixversion($map),$resid,&fixversion($url));
11050: }
11051:
11052: sub fixversion {
11053: my $fn=shift;
1.609 banghart 11054: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11055: my %bighash;
11056: my $uri=&clutter($fn);
1.620 albertel 11057: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11058: # is this cached?
1.599 albertel 11059: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11060: if (defined($cached)) { return $result; }
11061: # unfortunately not cached, or expired
1.620 albertel 11062: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11063: &GDBM_READER(),0640)) {
11064: if ($bighash{'version_'.$uri}) {
11065: my $version=$bighash{'version_'.$uri};
1.444 www 11066: unless (($version eq 'mostrecent') ||
11067: ($version==&getversion($uri))) {
1.440 www 11068: $uri=~s/\.(\w+)$/\.$version\.$1/;
11069: }
11070: }
11071: untie %bighash;
1.413 www 11072: }
1.599 albertel 11073: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11074: }
11075:
11076: sub deversion {
11077: my $url=shift;
11078: $url=~s/\.\d+\.(\w+)$/\.$1/;
11079: return $url;
1.210 www 11080: }
11081:
1.31 www 11082: # ------------------------------------------------------ Return symb list entry
11083:
11084: sub symbread {
1.249 www 11085: my ($thisfn,$donotrecurse)=@_;
1.1265 raeburn 11086: my $cache_str='request.symbread.cached.'.$thisfn;
11087: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 11088: # no filename provided? try from environment
1.1265 raeburn 11089: unless ($thisfn) {
1.620 albertel 11090: if ($env{'request.symb'}) {
11091: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11092: }
1.620 albertel 11093: $thisfn=$env{'request.filename'};
1.44 www 11094: }
1.569 albertel 11095: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11096: # is that filename actually a symb? Verify, clean, and return
11097: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11098: if (&symbverify($thisfn,$1)) {
1.620 albertel 11099: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11100: }
1.242 www 11101: }
1.44 www 11102: $thisfn=declutter($thisfn);
1.31 www 11103: my %hash;
1.37 www 11104: my %bighash;
11105: my $syval='';
1.620 albertel 11106: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11107: my $targetfn = $thisfn;
1.609 banghart 11108: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11109: $targetfn = 'adm/wrapper/'.$thisfn;
11110: }
1.687 albertel 11111: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11112: $targetfn=$1;
11113: }
1.620 albertel 11114: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11115: &GDBM_READER(),0640)) {
1.481 raeburn 11116: $syval=$hash{$targetfn};
1.37 www 11117: untie(%hash);
11118: }
11119: # ---------------------------------------------------------- There was an entry
11120: if ($syval) {
1.601 albertel 11121: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11122: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11123: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11124: #return $env{$cache_str}='';
1.601 albertel 11125: #}
11126: #$syval.=$1;
11127: #}
1.37 www 11128: } else {
11129: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11130: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11131: &GDBM_READER(),0640)) {
1.37 www 11132: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11133: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11134: unless ($ids) {
11135: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11136: }
11137: unless ($ids) {
11138: # alias?
11139: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11140: }
1.37 www 11141: if ($ids) {
11142: # ------------------------------------------------------------------- Has ID(s)
11143: my @possibilities=split(/\,/,$ids);
1.39 www 11144: if ($#possibilities==0) {
11145: # ----------------------------------------------- There is only one possibility
1.37 www 11146: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11147: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11148: $resid,$thisfn);
1.249 www 11149: } elsif (!$donotrecurse) {
1.39 www 11150: # ------------------------------------------ There is more than one possibility
11151: my $realpossible=0;
1.800 albertel 11152: foreach my $id (@possibilities) {
11153: my $file=$bighash{'src_'.$id};
1.39 www 11154: if (&allowed('bre',$file)) {
1.800 albertel 11155: my ($mapid,$resid)=split(/\./,$id);
1.39 www 11156: if ($bighash{'map_type_'.$mapid} ne 'page') {
11157: $realpossible++;
1.626 albertel 11158: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11159: $resid,$thisfn);
1.39 www 11160: }
11161: }
1.191 harris41 11162: }
1.39 www 11163: if ($realpossible!=1) { $syval=''; }
1.249 www 11164: } else {
11165: $syval='';
1.37 www 11166: }
11167: }
11168: untie(%bighash)
1.481 raeburn 11169: }
1.31 www 11170: }
1.62 www 11171: if ($syval) {
1.620 albertel 11172: return $env{$cache_str}=$syval;
1.62 www 11173: }
1.31 www 11174: }
1.949 raeburn 11175: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11176: return $env{$cache_str}='';
1.31 www 11177: }
11178:
11179: # ---------------------------------------------------------- Return random seed
11180:
1.32 www 11181: sub numval {
11182: my $txt=shift;
11183: $txt=~tr/A-J/0-9/;
11184: $txt=~tr/a-j/0-9/;
11185: $txt=~tr/K-T/0-9/;
11186: $txt=~tr/k-t/0-9/;
11187: $txt=~tr/U-Z/0-5/;
11188: $txt=~tr/u-z/0-5/;
11189: $txt=~s/\D//g;
1.564 albertel 11190: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11191: return int($txt);
1.368 albertel 11192: }
11193:
1.484 albertel 11194: sub numval2 {
11195: my $txt=shift;
11196: $txt=~tr/A-J/0-9/;
11197: $txt=~tr/a-j/0-9/;
11198: $txt=~tr/K-T/0-9/;
11199: $txt=~tr/k-t/0-9/;
11200: $txt=~tr/U-Z/0-5/;
11201: $txt=~tr/u-z/0-5/;
11202: $txt=~s/\D//g;
11203: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11204: my $total;
11205: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11206: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11207: return int($total);
11208: }
11209:
1.575 albertel 11210: sub numval3 {
11211: use integer;
11212: my $txt=shift;
11213: $txt=~tr/A-J/0-9/;
11214: $txt=~tr/a-j/0-9/;
11215: $txt=~tr/K-T/0-9/;
11216: $txt=~tr/k-t/0-9/;
11217: $txt=~tr/U-Z/0-5/;
11218: $txt=~tr/u-z/0-5/;
11219: $txt=~s/\D//g;
11220: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11221: my $total;
11222: foreach my $val (@txts) { $total+=$val; }
11223: if ($_64bit) { $total=(($total<<32)>>32); }
11224: return $total;
11225: }
11226:
1.675 albertel 11227: sub digest {
11228: my ($data)=@_;
11229: my $digest=&Digest::MD5::md5($data);
11230: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11231: my ($e,$f);
11232: {
11233: use integer;
11234: $e=($a+$b);
11235: $f=($c+$d);
11236: if ($_64bit) {
11237: $e=(($e<<32)>>32);
11238: $f=(($f<<32)>>32);
11239: }
11240: }
11241: if (wantarray) {
11242: return ($e,$f);
11243: } else {
11244: my $g;
11245: {
11246: use integer;
11247: $g=($e+$f);
11248: if ($_64bit) {
11249: $g=(($g<<32)>>32);
11250: }
11251: }
11252: return $g;
11253: }
11254: }
11255:
1.368 albertel 11256: sub latest_rnd_algorithm_id {
1.675 albertel 11257: return '64bit5';
1.366 albertel 11258: }
1.32 www 11259:
1.503 albertel 11260: sub get_rand_alg {
11261: my ($courseid)=@_;
1.790 albertel 11262: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11263: if ($courseid) {
1.620 albertel 11264: return $env{"course.$courseid.rndseed"};
1.503 albertel 11265: }
11266: return &latest_rnd_algorithm_id();
11267: }
11268:
1.562 albertel 11269: sub validCODE {
11270: my ($CODE)=@_;
11271: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11272: return 0;
11273: }
11274:
1.491 albertel 11275: sub getCODE {
1.620 albertel 11276: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11277: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11278: defined($Apache::lonhomework::parsing_a_task) ) &&
11279: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11280: return $Apache::lonhomework::history{'resource.CODE'};
11281: }
11282: return undef;
11283: }
1.1133 foxr 11284: #
11285: # Determines the random seed for a specific context:
11286: #
11287: # parameters:
11288: # symb - in course context the symb for the seed.
11289: # course_id - The course id of the form domain_coursenum.
11290: # domain - Domain for the user.
11291: # course - Course for the user.
11292: # cenv - environment of the course.
11293: #
11294: # NOTE:
11295: # All parameters are picked out of the environment if missing
11296: # or not defined.
11297: # If a symb cannot be determined the current time is used instead.
11298: #
11299: # For a given well defined symb, courside, domain, username,
11300: # and course environment, the seed is reproducible.
11301: #
1.31 www 11302: sub rndseed {
1.1133 foxr 11303: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11304: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11305: if (!defined($symb)) {
1.366 albertel 11306: unless ($symb=$wsymb) { return time; }
11307: }
1.1146 foxr 11308: if (!defined $courseid) {
11309: $courseid=$wcourseid;
11310: }
11311: if (!defined $domain) { $domain=$wdomain; }
11312: if (!defined $username) { $username=$wusername }
1.1133 foxr 11313:
11314: my $which;
11315: if (defined($cenv->{'rndseed'})) {
11316: $which = $cenv->{'rndseed'};
11317: } else {
11318: $which =&get_rand_alg($courseid);
11319: }
1.491 albertel 11320: if (defined(&getCODE())) {
1.1133 foxr 11321:
1.675 albertel 11322: if ($which eq '64bit5') {
11323: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11324: } elsif ($which eq '64bit4') {
1.575 albertel 11325: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11326: } else {
11327: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11328: }
1.675 albertel 11329: } elsif ($which eq '64bit5') {
11330: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11331: } elsif ($which eq '64bit4') {
11332: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11333: } elsif ($which eq '64bit3') {
11334: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11335: } elsif ($which eq '64bit2') {
11336: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11337: } elsif ($which eq '64bit') {
11338: return &rndseed_64bit($symb,$courseid,$domain,$username);
11339: }
11340: return &rndseed_32bit($symb,$courseid,$domain,$username);
11341: }
11342:
11343: sub rndseed_32bit {
11344: my ($symb,$courseid,$domain,$username)=@_;
11345: {
11346: use integer;
11347: my $symbchck=unpack("%32C*",$symb) << 27;
11348: my $symbseed=numval($symb) << 22;
11349: my $namechck=unpack("%32C*",$username) << 17;
11350: my $nameseed=numval($username) << 12;
11351: my $domainseed=unpack("%32C*",$domain) << 7;
11352: my $courseseed=unpack("%32C*",$courseid);
11353: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11354: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11355: #&logthis("rndseed :$num:$symb");
1.564 albertel 11356: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11357: return $num;
11358: }
11359: }
11360:
11361: sub rndseed_64bit {
11362: my ($symb,$courseid,$domain,$username)=@_;
11363: {
11364: use integer;
11365: my $symbchck=unpack("%32S*",$symb) << 21;
11366: my $symbseed=numval($symb) << 10;
11367: my $namechck=unpack("%32S*",$username);
11368:
11369: my $nameseed=numval($username) << 21;
11370: my $domainseed=unpack("%32S*",$domain) << 10;
11371: my $courseseed=unpack("%32S*",$courseid);
11372:
11373: my $num1=$symbchck+$symbseed+$namechck;
11374: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11375: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11376: #&logthis("rndseed :$num:$symb");
1.564 albertel 11377: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11378: return "$num1,$num2";
1.155 albertel 11379: }
1.366 albertel 11380: }
11381:
1.443 albertel 11382: sub rndseed_64bit2 {
11383: my ($symb,$courseid,$domain,$username)=@_;
11384: {
11385: use integer;
11386: # strings need to be an even # of cahracters long, it it is odd the
11387: # last characters gets thrown away
11388: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11389: my $symbseed=numval($symb) << 10;
11390: my $namechck=unpack("%32S*",$username.' ');
11391:
11392: my $nameseed=numval($username) << 21;
1.501 albertel 11393: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11394: my $courseseed=unpack("%32S*",$courseid.' ');
11395:
11396: my $num1=$symbchck+$symbseed+$namechck;
11397: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11398: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11399: #&logthis("rndseed :$num:$symb");
1.803 albertel 11400: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11401: return "$num1,$num2";
11402: }
11403: }
11404:
11405: sub rndseed_64bit3 {
11406: my ($symb,$courseid,$domain,$username)=@_;
11407: {
11408: use integer;
11409: # strings need to be an even # of cahracters long, it it is odd the
11410: # last characters gets thrown away
11411: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11412: my $symbseed=numval2($symb) << 10;
11413: my $namechck=unpack("%32S*",$username.' ');
11414:
11415: my $nameseed=numval2($username) << 21;
1.443 albertel 11416: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11417: my $courseseed=unpack("%32S*",$courseid.' ');
11418:
11419: my $num1=$symbchck+$symbseed+$namechck;
11420: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11421: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11422: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11423: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11424:
1.503 albertel 11425: return "$num1:$num2";
1.443 albertel 11426: }
11427: }
11428:
1.575 albertel 11429: sub rndseed_64bit4 {
11430: my ($symb,$courseid,$domain,$username)=@_;
11431: {
11432: use integer;
11433: # strings need to be an even # of cahracters long, it it is odd the
11434: # last characters gets thrown away
11435: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11436: my $symbseed=numval3($symb) << 10;
11437: my $namechck=unpack("%32S*",$username.' ');
11438:
11439: my $nameseed=numval3($username) << 21;
11440: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11441: my $courseseed=unpack("%32S*",$courseid.' ');
11442:
11443: my $num1=$symbchck+$symbseed+$namechck;
11444: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11445: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11446: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11447: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11448:
1.575 albertel 11449: return "$num1:$num2";
11450: }
11451: }
11452:
1.675 albertel 11453: sub rndseed_64bit5 {
11454: my ($symb,$courseid,$domain,$username)=@_;
11455: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11456: return "$num1:$num2";
11457: }
11458:
1.366 albertel 11459: sub rndseed_CODE_64bit {
11460: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11461: {
1.366 albertel 11462: use integer;
1.443 albertel 11463: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11464: my $symbseed=numval2($symb);
1.491 albertel 11465: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11466: my $CODEseed=numval(&getCODE());
1.443 albertel 11467: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11468: my $num1=$symbseed+$CODEchck;
11469: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11470: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11471: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11472: if ($_64bit) { $num1=(($num1<<32)>>32); }
11473: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11474: return "$num1:$num2";
1.366 albertel 11475: }
11476: }
11477:
1.575 albertel 11478: sub rndseed_CODE_64bit4 {
11479: my ($symb,$courseid,$domain,$username)=@_;
11480: {
11481: use integer;
11482: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11483: my $symbseed=numval3($symb);
11484: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11485: my $CODEseed=numval3(&getCODE());
11486: my $courseseed=unpack("%32S*",$courseid.' ');
11487: my $num1=$symbseed+$CODEchck;
11488: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11489: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11490: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11491: if ($_64bit) { $num1=(($num1<<32)>>32); }
11492: if ($_64bit) { $num2=(($num2<<32)>>32); }
11493: return "$num1:$num2";
11494: }
11495: }
11496:
1.675 albertel 11497: sub rndseed_CODE_64bit5 {
11498: my ($symb,$courseid,$domain,$username)=@_;
11499: my $code = &getCODE();
11500: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11501: return "$num1:$num2";
11502: }
11503:
1.366 albertel 11504: sub setup_random_from_rndseed {
11505: my ($rndseed)=@_;
1.503 albertel 11506: if ($rndseed =~/([,:])/) {
1.1262 raeburn 11507: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11508: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11509: &Math::Random::random_set_seed_from_phrase($rndseed);
11510: } else {
11511: &Math::Random::random_set_seed($num1,$num2);
11512: }
1.366 albertel 11513: } else {
11514: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11515: }
1.36 albertel 11516: }
11517:
1.474 albertel 11518: sub latest_receipt_algorithm_id {
1.835 albertel 11519: return 'receipt3';
1.474 albertel 11520: }
11521:
1.480 www 11522: sub recunique {
11523: my $fucourseid=shift;
11524: my $unique;
1.835 albertel 11525: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11526: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11527: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11528: } else {
11529: $unique=$perlvar{'lonReceipt'};
11530: }
11531: return unpack("%32C*",$unique);
11532: }
11533:
11534: sub recprefix {
11535: my $fucourseid=shift;
11536: my $prefix;
1.835 albertel 11537: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11538: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11539: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11540: } else {
11541: $prefix=$perlvar{'lonHostID'};
11542: }
11543: return unpack("%32C*",$prefix);
11544: }
11545:
1.76 www 11546: sub ireceipt {
1.474 albertel 11547: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11548:
11549: my $return =&recprefix($fucourseid).'-';
11550:
11551: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11552: $env{'request.state'} eq 'construct') {
11553: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11554: return $return;
11555: }
11556:
1.76 www 11557: my $cuname=unpack("%32C*",$funame);
11558: my $cudom=unpack("%32C*",$fudom);
11559: my $cucourseid=unpack("%32C*",$fucourseid);
11560: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11561: my $cunique=&recunique($fucourseid);
1.474 albertel 11562: my $cpart=unpack("%32S*",$part);
1.835 albertel 11563: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11564:
1.790 albertel 11565: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11566:
11567: $return.= ($cunique%$cuname+
11568: $cunique%$cudom+
11569: $cusymb%$cuname+
11570: $cusymb%$cudom+
11571: $cucourseid%$cuname+
11572: $cucourseid%$cudom+
11573: $cpart%$cuname+
11574: $cpart%$cudom);
11575: } else {
11576: $return.= ($cunique%$cuname+
11577: $cunique%$cudom+
11578: $cusymb%$cuname+
11579: $cusymb%$cudom+
11580: $cucourseid%$cuname+
11581: $cucourseid%$cudom);
11582: }
11583: return $return;
1.76 www 11584: }
11585:
11586: sub receipt {
1.474 albertel 11587: my ($part)=@_;
1.790 albertel 11588: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11589: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11590: }
1.260 ng 11591:
1.790 albertel 11592: sub whichuser {
11593: my ($passedsymb)=@_;
11594: my ($symb,$courseid,$domain,$name,$publicuser);
11595: if (defined($env{'form.grade_symb'})) {
11596: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11597: my $allowed=&allowed('vgr',$tmp_courseid);
11598: if (!$allowed &&
11599: exists($env{'request.course.sec'}) &&
11600: $env{'request.course.sec'} !~ /^\s*$/) {
11601: $allowed=&allowed('vgr',$tmp_courseid.
11602: '/'.$env{'request.course.sec'});
11603: }
11604: if ($allowed) {
11605: ($symb)=&get_env_multiple('form.grade_symb');
11606: $courseid=$tmp_courseid;
11607: ($domain)=&get_env_multiple('form.grade_domain');
11608: ($name)=&get_env_multiple('form.grade_username');
11609: return ($symb,$courseid,$domain,$name,$publicuser);
11610: }
11611: }
11612: if (!$passedsymb) {
11613: $symb=&symbread();
11614: } else {
11615: $symb=$passedsymb;
11616: }
11617: $courseid=$env{'request.course.id'};
11618: $domain=$env{'user.domain'};
11619: $name=$env{'user.name'};
11620: if ($name eq 'public' && $domain eq 'public') {
11621: if (!defined($env{'form.username'})) {
11622: $env{'form.username'}.=time.rand(10000000);
11623: }
11624: $name.=$env{'form.username'};
11625: }
11626: return ($symb,$courseid,$domain,$name,$publicuser);
11627:
11628: }
11629:
1.36 albertel 11630: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11631: # returns either the contents of the file or
11632: # -1 if the file doesn't exist
1.481 raeburn 11633: #
11634: # if the target is a file that was uploaded via DOCS,
11635: # a check will be made to see if a current copy exists on the local server,
11636: # if it does this will be served, otherwise a copy will be retrieved from
11637: # the home server for the course and stored in /home/httpd/html/userfiles on
11638: # the local server.
1.472 albertel 11639:
1.36 albertel 11640: sub getfile {
1.538 albertel 11641: my ($file) = @_;
1.609 banghart 11642: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11643: &repcopy($file);
11644: return &readfile($file);
11645: }
11646:
11647: sub repcopy_userfile {
11648: my ($file)=@_;
1.1142 raeburn 11649: my $londocroot = $perlvar{'lonDocRoot'};
11650: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11651: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11652: my ($cdom,$cnum,$filename) =
1.811 albertel 11653: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11654: my $uri="/uploaded/$cdom/$cnum/$filename";
11655: if (-e "$file") {
1.828 www 11656: # we already have a local copy, check it out
1.538 albertel 11657: my @fileinfo = stat($file);
1.828 www 11658: my $rtncode;
11659: my $info;
1.538 albertel 11660: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11661: if ($lwpresp ne 'ok') {
1.828 www 11662: # there is no such file anymore, even though we had a local copy
1.482 albertel 11663: if ($rtncode eq '404') {
1.538 albertel 11664: unlink($file);
1.482 albertel 11665: }
11666: return -1;
11667: }
11668: if ($info < $fileinfo[9]) {
1.828 www 11669: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11670: return 'ok';
1.828 www 11671: } else {
11672: # the file is outdated, get rid of it
11673: unlink($file);
1.482 albertel 11674: }
1.828 www 11675: }
11676: # one way or the other, at this point, we don't have the file
11677: # construct the correct path for the file
11678: my @parts = ($cdom,$cnum);
11679: if ($filename =~ m|^(.+)/[^/]+$|) {
11680: push @parts, split(/\//,$1);
11681: }
11682: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11683: foreach my $part (@parts) {
11684: $path .= '/'.$part;
11685: if (!-e $path) {
11686: mkdir($path,0770);
1.482 albertel 11687: }
11688: }
1.828 www 11689: # now the path exists for sure
11690: # get a user agent
11691: my $ua=new LWP::UserAgent;
11692: my $transferfile=$file.'.in.transfer';
11693: # FIXME: this should flock
11694: if (-e $transferfile) { return 'ok'; }
11695: my $request;
11696: $uri=~s/^\///;
1.980 raeburn 11697: my $homeserver = &homeserver($cnum,$cdom);
11698: my $protocol = $protocol{$homeserver};
11699: $protocol = 'http' if ($protocol ne 'https');
11700: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11701: my $response=$ua->request($request,$transferfile);
11702: # did it work?
11703: if ($response->is_error()) {
11704: unlink($transferfile);
11705: &logthis("Userfile repcopy failed for $uri");
11706: return -1;
11707: }
11708: # worked, rename the transfer file
11709: rename($transferfile,$file);
1.607 raeburn 11710: return 'ok';
1.481 raeburn 11711: }
11712:
1.517 albertel 11713: sub tokenwrapper {
11714: my $uri=shift;
1.980 raeburn 11715: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11716: $uri=~s|^/||;
1.620 albertel 11717: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11718: my $token=$1;
1.552 albertel 11719: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11720: if ($udom && $uname && $file) {
11721: $file=~s|(\?\.*)*$||;
1.949 raeburn 11722: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11723: my $homeserver = &homeserver($uname,$udom);
11724: my $protocol = $protocol{$homeserver};
11725: $protocol = 'http' if ($protocol ne 'https');
11726: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11727: (($uri=~/\?/)?'&':'?').'token='.$token.
11728: '&tokenissued='.$perlvar{'lonHostID'};
11729: } else {
11730: return '/adm/notfound.html';
11731: }
11732: }
11733:
1.828 www 11734: # call with reqtype HEAD: get last modification time
11735: # call with reqtype GET: get the file contents
11736: # Do not call this with reqtype GET for large files! It loads everything into memory
11737: #
1.481 raeburn 11738: sub getuploaded {
11739: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11740: $uri=~s/^\///;
1.980 raeburn 11741: my $homeserver = &homeserver($cnum,$cdom);
11742: my $protocol = $protocol{$homeserver};
11743: $protocol = 'http' if ($protocol ne 'https');
11744: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11745: my $ua=new LWP::UserAgent;
11746: my $request=new HTTP::Request($reqtype,$uri);
11747: my $response=$ua->request($request);
11748: $$rtncode = $response->code;
1.482 albertel 11749: if (! $response->is_success()) {
11750: return 'failed';
11751: }
11752: if ($reqtype eq 'HEAD') {
1.486 www 11753: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11754: } elsif ($reqtype eq 'GET') {
11755: $$info = $response->content;
1.472 albertel 11756: }
1.482 albertel 11757: return 'ok';
1.36 albertel 11758: }
11759:
1.481 raeburn 11760: sub readfile {
11761: my $file = shift;
11762: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11763: my $fh;
11764: open($fh,"<$file");
11765: my $a='';
1.800 albertel 11766: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11767: return $a;
11768: }
11769:
1.36 albertel 11770: sub filelocation {
1.590 banghart 11771: my ($dir,$file) = @_;
11772: my $location;
11773: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11774:
11775: if ($file =~ m-^/adm/-) {
11776: $file=~s-^/adm/wrapper/-/-;
11777: $file=~s-^/adm/coursedocs/showdoc/-/-;
11778: }
1.882 albertel 11779:
1.1139 www 11780: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11781: $location = $file;
1.609 banghart 11782: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11783: my ($udom,$uname,$filename)=
1.811 albertel 11784: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11785: my $home=&homeserver($uname,$udom);
11786: my $is_me=0;
11787: my @ids=¤t_machine_ids();
11788: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11789: if ($is_me) {
1.1117 foxr 11790: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11791: } else {
11792: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11793: $udom.'/'.$uname.'/'.$filename;
11794: }
1.882 albertel 11795: } elsif ($file =~ m-^/adm/-) {
11796: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11797: } else {
11798: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11799: $file=~s:^/(res|priv)/:/:;
11800: my $space=$1;
1.590 banghart 11801: if ( !( $file =~ m:^/:) ) {
11802: $location = $dir. '/'.$file;
11803: } else {
1.1142 raeburn 11804: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11805: }
1.59 albertel 11806: }
1.590 banghart 11807: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11808: while ($location=~m{/\.\./}) {
11809: if ($location =~ m{/[^/]+/\.\./}) {
11810: $location=~ s{/[^/]+/\.\./}{/}g;
11811: } else {
11812: $location=~ s{/\.\./}{/}g;
11813: }
11814: } #remove dir/..
1.590 banghart 11815: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11816: return $location;
1.46 www 11817: }
1.36 albertel 11818:
1.46 www 11819: sub hreflocation {
11820: my ($dir,$file)=@_;
1.980 raeburn 11821: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11822: $file=filelocation($dir,$file);
1.700 albertel 11823: } elsif ($file=~m-^/adm/-) {
11824: $file=~s-^/adm/wrapper/-/-;
11825: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11826: }
11827: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11828: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11829: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11830: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11831: {/uploaded/$1/$2/}x;
1.46 www 11832: }
1.913 albertel 11833: if ($file=~ m{^/userfiles/}) {
11834: $file =~ s{^/userfiles/}{/uploaded/};
11835: }
1.462 albertel 11836: return $file;
1.465 albertel 11837: }
11838:
1.1139 www 11839:
11840:
11841:
11842:
1.465 albertel 11843: sub current_machine_domains {
1.853 albertel 11844: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11845: }
11846:
11847: sub machine_domains {
11848: my ($hostname) = @_;
1.465 albertel 11849: my @domains;
1.838 albertel 11850: my %hostname = &all_hostnames();
1.465 albertel 11851: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11852: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11853: if ($hostname eq $name) {
1.844 albertel 11854: push(@domains,&host_domain($id));
1.465 albertel 11855: }
11856: }
11857: return @domains;
11858: }
11859:
11860: sub current_machine_ids {
1.853 albertel 11861: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11862: }
11863:
11864: sub machine_ids {
11865: my ($hostname) = @_;
11866: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11867: my @ids;
1.888 albertel 11868: my %name_to_host = &all_names();
1.889 albertel 11869: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11870: return @{ $name_to_host{$hostname} };
11871: }
11872: return;
1.31 www 11873: }
11874:
1.824 raeburn 11875: sub additional_machine_domains {
11876: my @domains;
11877: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11878: while( my $line = <$fh>) {
11879: $line =~ s/\s//g;
11880: push(@domains,$line);
11881: }
11882: return @domains;
11883: }
11884:
11885: sub default_login_domain {
11886: my $domain = $perlvar{'lonDefDomain'};
11887: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11888: foreach my $posdom (¤t_machine_domains(),
11889: &additional_machine_domains()) {
11890: if (lc($posdom) eq lc($testdomain)) {
11891: $domain=$posdom;
11892: last;
11893: }
11894: }
11895: return $domain;
11896: }
11897:
1.31 www 11898: # ------------------------------------------------------------- Declutters URLs
11899:
11900: sub declutter {
11901: my $thisfn=shift;
1.569 albertel 11902: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 11903: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11904: $thisfn=~s{^/home/httpd/html}{};
11905: }
1.31 www 11906: $thisfn=~s/^\///;
1.697 albertel 11907: $thisfn=~s|^adm/wrapper/||;
11908: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11909: $thisfn=~s/^res\///;
1.1172 bisitz 11910: $thisfn=~s/^priv\///;
1.1032 raeburn 11911: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11912: $thisfn=~s/\?.+$//;
11913: }
1.268 www 11914: return $thisfn;
11915: }
11916:
11917: # ------------------------------------------------------------- Clutter up URLs
11918:
11919: sub clutter {
11920: my $thisfn='/'.&declutter(shift);
1.887 albertel 11921: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11922: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11923: $thisfn='/res'.$thisfn;
11924: }
1.1031 raeburn 11925: if ($thisfn !~m|^/adm|) {
11926: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11927: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11928: } else {
11929: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11930: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11931: if ($embstyle eq 'ssi'
11932: || ($embstyle eq 'hdn')
11933: || ($embstyle eq 'rat')
11934: || ($embstyle eq 'prv')
11935: || ($embstyle eq 'ign')) {
11936: #do nothing with these
11937: } elsif (($embstyle eq 'img')
1.695 albertel 11938: || ($embstyle eq 'emb')
11939: || ($embstyle eq 'wrp')) {
11940: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11941: } elsif ($embstyle eq 'unk'
11942: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11943: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11944: } else {
1.718 www 11945: # &logthis("Got a blank emb style");
1.695 albertel 11946: }
1.694 albertel 11947: }
11948: }
1.31 www 11949: return $thisfn;
1.12 www 11950: }
11951:
1.787 albertel 11952: sub clutter_with_no_wrapper {
11953: my $uri = &clutter(shift);
11954: if ($uri =~ m-^/adm/-) {
11955: $uri =~ s-^/adm/wrapper/-/-;
11956: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11957: }
11958: return $uri;
11959: }
11960:
1.557 albertel 11961: sub freeze_escape {
11962: my ($value)=@_;
11963: if (ref($value)) {
11964: $value=&nfreeze($value);
11965: return '__FROZEN__'.&escape($value);
11966: }
11967: return &escape($value);
11968: }
11969:
1.11 www 11970:
1.557 albertel 11971: sub thaw_unescape {
11972: my ($value)=@_;
11973: if ($value =~ /^__FROZEN__/) {
11974: substr($value,0,10,undef);
11975: $value=&unescape($value);
11976: return &thaw($value);
11977: }
11978: return &unescape($value);
11979: }
11980:
1.436 albertel 11981: sub correct_line_ends {
11982: my ($result)=@_;
11983: $$result =~s/\r\n/\n/mg;
11984: $$result =~s/\r/\n/mg;
1.415 albertel 11985: }
1.1 albertel 11986: # ================================================================ Main Program
11987:
1.184 www 11988: sub goodbye {
1.204 albertel 11989: &logthis("Starting Shut down");
1.443 albertel 11990: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11991: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11992: #converted
1.599 albertel 11993: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11994: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11995: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11996: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11997: #1.1 only
1.870 albertel 11998: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11999: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12000: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12001: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12002: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12003: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12004: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12005: &flushcourselogs();
12006: &logthis("Shutting down");
12007: }
12008:
1.852 albertel 12009: sub get_dns {
1.1210 raeburn 12010: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12011: if (!$ignore_cache) {
12012: my ($content,$cached)=
12013: &Apache::lonnet::is_cached_new('dns',$url);
12014: if ($cached) {
1.1210 raeburn 12015: &$func($content,$hashref);
1.869 albertel 12016: return;
12017: }
12018: }
12019:
12020: my %alldns;
1.852 albertel 12021: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12022: foreach my $dns (<$config>) {
12023: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12024: my $line = $1;
12025: my ($host,$protocol) = split(/:/,$line);
12026: if ($protocol ne 'https') {
12027: $protocol = 'http';
12028: }
12029: $alldns{$host} = $protocol;
1.869 albertel 12030: }
12031: while (%alldns) {
1.1263 raeburn 12032: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12033: my $ua=new LWP::UserAgent;
1.1134 raeburn 12034: $ua->timeout(30);
1.979 raeburn 12035: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12036: my $response=$ua->request($request);
1.979 raeburn 12037: delete($alldns{$dns});
1.852 albertel 12038: next if ($response->is_error());
12039: my @content = split("\n",$response->content);
1.1210 raeburn 12040: unless ($nocache) {
1.1219 raeburn 12041: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12042: }
12043: &$func(\@content,$hashref);
1.869 albertel 12044: return;
1.852 albertel 12045: }
12046: close($config);
1.871 albertel 12047: my $which = (split('/',$url))[3];
12048: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12049: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12050: my @content = <$config>;
1.1210 raeburn 12051: &$func(\@content,$hashref);
12052: return;
12053: }
12054:
12055: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12056: sub parse_dns_checksums_tab {
1.1210 raeburn 12057: my ($lines,$hashref) = @_;
1.1264 raeburn 12058: my $lonhost = $perlvar{'lonHostID'};
12059: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12060: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12061: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12062: my $webconfdir = '/etc/httpd/conf';
12063: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12064: $webconfdir = '/etc/apache2';
12065: } elsif ($distro =~ /^sles(\d+)$/) {
12066: if ($1 >= 10) {
12067: $webconfdir = '/etc/apache2';
12068: }
12069: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12070: if ($1 >= 10.0) {
12071: $webconfdir = '/etc/apache2';
12072: }
12073: }
1.1210 raeburn 12074: my ($release,$timestamp) = split(/\-/,$loncaparev);
12075: my (%chksum,%revnum);
12076: if (ref($lines) eq 'ARRAY') {
12077: chomp(@{$lines});
1.1238 raeburn 12078: my $version = shift(@{$lines});
12079: if ($version eq $release) {
1.1210 raeburn 12080: foreach my $line (@{$lines}) {
1.1238 raeburn 12081: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12082: if ($file =~ m{^/etc/httpd/conf}) {
12083: if ($webconfdir eq '/etc/apache2') {
12084: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12085: }
12086: }
1.1238 raeburn 12087: $chksum{$file} = $shasum;
12088: $revnum{$file} = $version;
1.1210 raeburn 12089: }
12090: if (ref($hashref) eq 'HASH') {
12091: %{$hashref} = (
12092: sums => \%chksum,
12093: versions => \%revnum,
12094: );
12095: }
12096: }
12097: }
1.869 albertel 12098: return;
1.852 albertel 12099: }
1.1210 raeburn 12100:
12101: sub fetch_dns_checksums {
1.1238 raeburn 12102: my %checksums;
12103: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12104: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12105: my ($release,$timestamp) = split(/\-/,$loncaparev);
12106: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12107: \%checksums);
1.1210 raeburn 12108: return \%checksums;
12109: }
12110:
1.327 albertel 12111: # ------------------------------------------------------------ Read domain file
12112: {
1.852 albertel 12113: my $loaded;
1.846 albertel 12114: my %domain;
12115:
1.852 albertel 12116: sub parse_domain_tab {
12117: my ($lines) = @_;
12118: foreach my $line (@$lines) {
12119: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12120:
1.846 albertel 12121: chomp($line);
1.852 albertel 12122: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12123: my %this_domain;
12124: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12125: 'lang_def', 'city', 'longi', 'lati',
12126: 'primary') {
12127: $this_domain{$field} = shift(@elements);
12128: }
12129: $domain{$name} = \%this_domain;
1.852 albertel 12130: }
12131: }
1.864 albertel 12132:
12133: sub reset_domain_info {
12134: undef($loaded);
12135: undef(%domain);
12136: }
12137:
1.852 albertel 12138: sub load_domain_tab {
1.869 albertel 12139: my ($ignore_cache) = @_;
12140: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 12141: my $fh;
12142: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12143: my @lines = <$fh>;
12144: &parse_domain_tab(\@lines);
1.448 albertel 12145: }
1.852 albertel 12146: close($fh);
12147: $loaded = 1;
1.327 albertel 12148: }
1.846 albertel 12149:
12150: sub domain {
1.852 albertel 12151: &load_domain_tab() if (!$loaded);
12152:
1.846 albertel 12153: my ($name,$what) = @_;
12154: return if ( !exists($domain{$name}) );
12155:
12156: if (!$what) {
12157: return $domain{$name}{'description'};
12158: }
12159: return $domain{$name}{$what};
12160: }
1.974 raeburn 12161:
12162: sub domain_info {
12163: &load_domain_tab() if (!$loaded);
12164: return %domain;
12165: }
12166:
1.327 albertel 12167: }
12168:
12169:
1.1 albertel 12170: # ------------------------------------------------------------- Read hosts file
12171: {
1.838 albertel 12172: my %hostname;
1.844 albertel 12173: my %hostdom;
1.845 albertel 12174: my %libserv;
1.852 albertel 12175: my $loaded;
1.888 albertel 12176: my %name_to_host;
1.1074 raeburn 12177: my %internetdom;
1.1107 raeburn 12178: my %LC_dns_serv;
1.852 albertel 12179:
12180: sub parse_hosts_tab {
12181: my ($file) = @_;
12182: foreach my $configline (@$file) {
12183: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12184: chomp($configline);
12185: if ($configline =~ /^\^/) {
12186: if ($configline =~ /^\^([\w.\-]+)/) {
12187: $LC_dns_serv{$1} = 1;
12188: }
12189: next;
12190: }
1.1074 raeburn 12191: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12192: $name=~s/\s//g;
12193: if ($id && $domain && $role && $name) {
12194: $hostname{$id}=$name;
1.888 albertel 12195: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12196: $hostdom{$id}=$domain;
12197: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12198: if (defined($protocol)) {
12199: if ($protocol eq 'https') {
12200: $protocol{$id} = $protocol;
12201: } else {
12202: $protocol{$id} = 'http';
12203: }
1.968 raeburn 12204: } else {
1.969 raeburn 12205: $protocol{$id} = 'http';
1.968 raeburn 12206: }
1.1074 raeburn 12207: if (defined($intdom)) {
12208: $internetdom{$id} = $intdom;
12209: }
1.852 albertel 12210: }
12211: }
12212: }
1.864 albertel 12213:
12214: sub reset_hosts_info {
1.897 albertel 12215: &purge_remembered();
1.864 albertel 12216: &reset_domain_info();
12217: &reset_hosts_ip_info();
1.892 albertel 12218: undef(%name_to_host);
1.864 albertel 12219: undef(%hostname);
12220: undef(%hostdom);
12221: undef(%libserv);
12222: undef($loaded);
12223: }
1.1 albertel 12224:
1.852 albertel 12225: sub load_hosts_tab {
1.869 albertel 12226: my ($ignore_cache) = @_;
12227: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12228: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12229: my @config = <$config>;
12230: &parse_hosts_tab(\@config);
12231: close($config);
12232: $loaded=1;
1.1 albertel 12233: }
1.852 albertel 12234:
1.838 albertel 12235: sub hostname {
1.852 albertel 12236: &load_hosts_tab() if (!$loaded);
12237:
1.838 albertel 12238: my ($lonid) = @_;
12239: return $hostname{$lonid};
12240: }
1.845 albertel 12241:
1.838 albertel 12242: sub all_hostnames {
1.852 albertel 12243: &load_hosts_tab() if (!$loaded);
12244:
1.838 albertel 12245: return %hostname;
12246: }
1.845 albertel 12247:
1.888 albertel 12248: sub all_names {
12249: &load_hosts_tab() if (!$loaded);
12250:
12251: return %name_to_host;
12252: }
12253:
1.974 raeburn 12254: sub all_host_domain {
12255: &load_hosts_tab() if (!$loaded);
12256: return %hostdom;
12257: }
12258:
1.845 albertel 12259: sub is_library {
1.852 albertel 12260: &load_hosts_tab() if (!$loaded);
12261:
1.845 albertel 12262: return exists($libserv{$_[0]});
12263: }
12264:
12265: sub all_library {
1.852 albertel 12266: &load_hosts_tab() if (!$loaded);
12267:
1.845 albertel 12268: return %libserv;
12269: }
12270:
1.1062 droeschl 12271: sub unique_library {
12272: #2x reverse removes all hostnames that appear more than once
12273: my %unique = reverse &all_library();
12274: return reverse %unique;
12275: }
12276:
1.841 albertel 12277: sub get_servers {
1.852 albertel 12278: &load_hosts_tab() if (!$loaded);
12279:
1.841 albertel 12280: my ($domain,$type) = @_;
12281: my %possible_hosts = ($type eq 'library') ? %libserv
12282: : %hostname;
12283: my %result;
1.842 albertel 12284: if (ref($domain) eq 'ARRAY') {
12285: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12286: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12287: $result{$host} = $hostname;
12288: }
12289: }
12290: } else {
12291: while ( my ($host,$hostname) = each(%possible_hosts)) {
12292: if ($hostdom{$host} eq $domain) {
12293: $result{$host} = $hostname;
12294: }
1.841 albertel 12295: }
12296: }
12297: return %result;
12298: }
1.845 albertel 12299:
1.1062 droeschl 12300: sub get_unique_servers {
12301: my %unique = reverse &get_servers(@_);
12302: return reverse %unique;
12303: }
12304:
1.844 albertel 12305: sub host_domain {
1.852 albertel 12306: &load_hosts_tab() if (!$loaded);
12307:
1.844 albertel 12308: my ($lonid) = @_;
12309: return $hostdom{$lonid};
12310: }
12311:
1.841 albertel 12312: sub all_domains {
1.852 albertel 12313: &load_hosts_tab() if (!$loaded);
12314:
1.841 albertel 12315: my %seen;
12316: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12317: return @uniq;
12318: }
1.1074 raeburn 12319:
12320: sub internet_dom {
12321: &load_hosts_tab() if (!$loaded);
12322:
12323: my ($lonid) = @_;
12324: return $internetdom{$lonid};
12325: }
1.1107 raeburn 12326:
12327: sub is_LC_dns {
12328: &load_hosts_tab() if (!$loaded);
12329:
12330: my ($hostname) = @_;
12331: return exists($LC_dns_serv{$hostname});
12332: }
12333:
1.1 albertel 12334: }
12335:
1.847 albertel 12336: {
12337: my %iphost;
1.856 albertel 12338: my %name_to_ip;
12339: my %lonid_to_ip;
1.869 albertel 12340:
1.847 albertel 12341: sub get_hosts_from_ip {
12342: my ($ip) = @_;
12343: my %iphosts = &get_iphost();
12344: if (ref($iphosts{$ip})) {
12345: return @{$iphosts{$ip}};
12346: }
12347: return;
1.839 albertel 12348: }
1.864 albertel 12349:
12350: sub reset_hosts_ip_info {
12351: undef(%iphost);
12352: undef(%name_to_ip);
12353: undef(%lonid_to_ip);
12354: }
1.856 albertel 12355:
12356: sub get_host_ip {
12357: my ($lonid) = @_;
12358: if (exists($lonid_to_ip{$lonid})) {
12359: return $lonid_to_ip{$lonid};
12360: }
12361: my $name=&hostname($lonid);
12362: my $ip = gethostbyname($name);
12363: return if (!$ip || length($ip) ne 4);
12364: $ip=inet_ntoa($ip);
12365: $name_to_ip{$name} = $ip;
12366: $lonid_to_ip{$lonid} = $ip;
12367: return $ip;
12368: }
1.847 albertel 12369:
12370: sub get_iphost {
1.869 albertel 12371: my ($ignore_cache) = @_;
1.894 albertel 12372:
1.869 albertel 12373: if (!$ignore_cache) {
12374: if (%iphost) {
12375: return %iphost;
12376: }
12377: my ($ip_info,$cached)=
12378: &Apache::lonnet::is_cached_new('iphost','iphost');
12379: if ($cached) {
12380: %iphost = %{$ip_info->[0]};
12381: %name_to_ip = %{$ip_info->[1]};
12382: %lonid_to_ip = %{$ip_info->[2]};
12383: return %iphost;
12384: }
12385: }
1.894 albertel 12386:
12387: # get yesterday's info for fallback
12388: my %old_name_to_ip;
12389: my ($ip_info,$cached)=
12390: &Apache::lonnet::is_cached_new('iphost','iphost');
12391: if ($cached) {
12392: %old_name_to_ip = %{$ip_info->[1]};
12393: }
12394:
1.888 albertel 12395: my %name_to_host = &all_names();
12396: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12397: my $ip;
12398: if (!exists($name_to_ip{$name})) {
12399: $ip = gethostbyname($name);
12400: if (!$ip || length($ip) ne 4) {
1.894 albertel 12401: if (defined($old_name_to_ip{$name})) {
12402: $ip = $old_name_to_ip{$name};
12403: &logthis("Can't find $name defaulting to old $ip");
12404: } else {
12405: &logthis("Name $name no IP found");
12406: next;
12407: }
12408: } else {
12409: $ip=inet_ntoa($ip);
1.847 albertel 12410: }
12411: $name_to_ip{$name} = $ip;
12412: } else {
12413: $ip = $name_to_ip{$name};
1.653 albertel 12414: }
1.888 albertel 12415: foreach my $id (@{ $name_to_host{$name} }) {
12416: $lonid_to_ip{$id} = $ip;
12417: }
12418: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12419: }
1.1219 raeburn 12420: &do_cache_new('iphost','iphost',
12421: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12422: 48*60*60);
1.869 albertel 12423:
1.847 albertel 12424: return %iphost;
1.598 albertel 12425: }
12426:
1.992 raeburn 12427: #
12428: # Given a DNS returns the loncapa host name for that DNS
12429: #
12430: sub host_from_dns {
12431: my ($dns) = @_;
12432: my @hosts;
12433: my $ip;
12434:
1.993 raeburn 12435: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12436: $ip = $name_to_ip{$dns};
12437: }
12438: if (!$ip) {
12439: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12440: if (length($ip) == 4) {
12441: $ip = &IO::Socket::inet_ntoa($ip);
12442: }
12443: }
12444: if ($ip) {
12445: @hosts = get_hosts_from_ip($ip);
12446: return $hosts[0];
12447: }
12448: return undef;
1.986 foxr 12449: }
1.992 raeburn 12450:
1.1074 raeburn 12451: sub get_internet_names {
12452: my ($lonid) = @_;
12453: return if ($lonid eq '');
12454: my ($idnref,$cached)=
12455: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12456: if ($cached) {
12457: return $idnref;
12458: }
12459: my $ip = &get_host_ip($lonid);
12460: my @hosts = &get_hosts_from_ip($ip);
12461: my %iphost = &get_iphost();
12462: my (@idns,%seen);
12463: foreach my $id (@hosts) {
12464: my $dom = &host_domain($id);
12465: my $prim_id = &domain($dom,'primary');
12466: my $prim_ip = &get_host_ip($prim_id);
12467: next if ($seen{$prim_ip});
12468: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12469: foreach my $id (@{$iphost{$prim_ip}}) {
12470: my $intdom = &internet_dom($id);
12471: unless (grep(/^\Q$intdom\E$/,@idns)) {
12472: push(@idns,$intdom);
12473: }
12474: }
12475: }
12476: $seen{$prim_ip} = 1;
12477: }
1.1219 raeburn 12478: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12479: }
12480:
1.986 foxr 12481: }
12482:
1.1079 raeburn 12483: sub all_loncaparevs {
1.1249 raeburn 12484: 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 12485: }
12486:
1.1227 raeburn 12487: # ---------------------------------------------------------- Read loncaparev table
12488: {
12489: sub load_loncaparevs {
12490: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12491: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12492: while (my $configline=<$config>) {
12493: chomp($configline);
12494: my ($hostid,$loncaparev)=split(/:/,$configline);
12495: $loncaparevs{$hostid}=$loncaparev;
12496: }
12497: close($config);
12498: }
12499: }
12500: }
12501: }
12502:
12503: # ---------------------------------------------------------- Read serverhostID table
12504: {
12505: sub load_serverhomeIDs {
12506: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12507: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12508: while (my $configline=<$config>) {
12509: chomp($configline);
12510: my ($name,$id)=split(/:/,$configline);
12511: $serverhomeIDs{$name}=$id;
12512: }
12513: close($config);
12514: }
12515: }
12516: }
12517: }
12518:
12519:
1.862 albertel 12520: BEGIN {
12521:
12522: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12523: unless ($readit) {
12524: {
12525: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12526: %perlvar = (%perlvar,%{$configvars});
12527: }
12528:
12529:
1.1 albertel 12530: # ------------------------------------------------------ Read spare server file
12531: {
1.448 albertel 12532: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12533:
12534: while (my $configline=<$config>) {
12535: chomp($configline);
1.284 matthew 12536: if ($configline) {
1.784 albertel 12537: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12538: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12539: push(@{ $spareid{$type} }, $host);
1.1 albertel 12540: }
12541: }
1.448 albertel 12542: close($config);
1.1 albertel 12543: }
1.11 www 12544: # ------------------------------------------------------------ Read permissions
12545: {
1.448 albertel 12546: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12547:
12548: while (my $configline=<$config>) {
1.448 albertel 12549: chomp($configline);
12550: if ($configline) {
12551: my ($role,$perm)=split(/ /,$configline);
12552: if ($perm ne '') { $pr{$role}=$perm; }
12553: }
1.11 www 12554: }
1.448 albertel 12555: close($config);
1.11 www 12556: }
12557:
12558: # -------------------------------------------- Read plain texts for permissions
12559: {
1.448 albertel 12560: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12561:
12562: while (my $configline=<$config>) {
1.448 albertel 12563: chomp($configline);
12564: if ($configline) {
1.742 raeburn 12565: my ($short,@plain)=split(/:/,$configline);
12566: %{$prp{$short}} = ();
12567: if (@plain > 0) {
12568: $prp{$short}{'std'} = $plain[0];
12569: for (my $i=1; $i<@plain; $i++) {
12570: $prp{$short}{'alt'.$i} = $plain[$i];
12571: }
12572: }
1.448 albertel 12573: }
1.135 www 12574: }
1.448 albertel 12575: close($config);
1.135 www 12576: }
12577:
12578: # ---------------------------------------------------------- Read package table
12579: {
1.448 albertel 12580: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12581:
12582: while (my $configline=<$config>) {
1.483 albertel 12583: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12584: chomp($configline);
12585: my ($short,$plain)=split(/:/,$configline);
12586: my ($pack,$name)=split(/\&/,$short);
12587: if ($plain ne '') {
12588: $packagetab{$pack.'&'.$name.'&name'}=$name;
12589: $packagetab{$short}=$plain;
12590: }
1.11 www 12591: }
1.448 albertel 12592: close($config);
1.329 matthew 12593: }
12594:
1.1073 raeburn 12595: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12596:
12597: &load_loncaparevs();
1.1073 raeburn 12598:
1.1074 raeburn 12599: # ---------------------------------------------------------- Read serverhostID table
12600:
1.1227 raeburn 12601: &load_serverhomeIDs();
12602:
12603: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12604: {
12605: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12606: if (-e $file) {
12607: my $parser = HTML::LCParser->new($file);
12608: while (my $token = $parser->get_token()) {
12609: if ($token->[0] eq 'S') {
12610: my $item = $token->[1];
12611: my $name = $token->[2]{'name'};
12612: my $value = $token->[2]{'value'};
12613: if ($item ne '' && $name ne '' && $value ne '') {
12614: my $release = $parser->get_text();
12615: $release =~ s/(^\s*|\s*$ )//gx;
12616: $needsrelease{$item.':'.$name.':'.$value} = $release;
12617: }
12618: }
12619: }
12620: }
1.1073 raeburn 12621: }
12622:
1.1138 raeburn 12623: # ---------------------------------------------------------- Read managers table
12624: {
12625: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12626: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12627: while (my $configline=<$config>) {
12628: chomp($configline);
12629: next if ($configline =~ /^\#/);
12630: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12631: $managerstab{$configline} = 1;
12632: }
12633: }
12634: close($config);
12635: }
12636: }
12637: }
12638:
1.329 matthew 12639: # ------------- set up temporary directory
12640: {
1.1117 foxr 12641: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12642:
1.11 www 12643: }
12644:
1.794 albertel 12645: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12646: 'compress_threshold'=> 20_000,
12647: });
1.185 www 12648:
1.281 www 12649: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12650: $dumpcount=0;
1.958 www 12651: $locknum=0;
1.22 www 12652:
1.163 harris41 12653: &logtouch();
1.672 albertel 12654: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12655: $readit=1;
1.564 albertel 12656: {
12657: use integer;
12658: my $test=(2**32)+1;
1.568 albertel 12659: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12660: &logthis(" Detected 64bit platform ($_64bit)");
12661: }
1.195 www 12662: }
1.1 albertel 12663: }
1.179 www 12664:
1.1 albertel 12665: 1;
1.191 harris41 12666: __END__
12667:
1.243 albertel 12668: =pod
12669:
1.191 harris41 12670: =head1 NAME
12671:
1.243 albertel 12672: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12673:
12674: =head1 SYNOPSIS
12675:
1.243 albertel 12676: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12677:
12678: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12679:
1.243 albertel 12680: Common parameters:
12681:
12682: =over 4
12683:
12684: =item *
12685:
12686: $uname : an internal username (if $cname expecting a course Id specifically)
12687:
12688: =item *
12689:
12690: $udom : a domain (if $cdom expecting a course's domain specifically)
12691:
12692: =item *
12693:
12694: $symb : a resource instance identifier
12695:
12696: =item *
12697:
12698: $namespace : the name of a .db file that contains the data needed or
12699: being set.
12700:
12701: =back
12702:
1.394 bowersj2 12703: =head1 OVERVIEW
1.191 harris41 12704:
1.394 bowersj2 12705: lonnet provides subroutines which interact with the
12706: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12707: about classes, users, and resources.
1.243 albertel 12708:
12709: For many of these objects you can also use this to store data about
12710: them or modify them in various ways.
1.191 harris41 12711:
1.394 bowersj2 12712: =head2 Symbs
1.191 harris41 12713:
1.394 bowersj2 12714: To identify a specific instance of a resource, LON-CAPA uses symbols
12715: or "symbs"X<symb>. These identifiers are built from the URL of the
12716: map, the resource number of the resource in the map, and the URL of
12717: the resource itself. The latter is somewhat redundant, but might help
12718: if maps change.
12719:
12720: An example is
12721:
12722: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12723:
12724: The respective map entry is
12725:
12726: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12727: title="Problem 2">
12728: </resource>
12729:
12730: Symbs are used by the random number generator, as well as to store and
12731: restore data specific to a certain instance of for example a problem.
12732:
12733: =head2 Storing And Retrieving Data
12734:
12735: X<store()>X<cstore()>X<restore()>Three of the most important functions
12736: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12737: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12738: is is the non-critical message twin of cstore. These functions are for
12739: handlers to store a perl hash to a user's permanent data space in an
12740: easy manner, and to retrieve it again on another call. It is expected
12741: that a handler would use this once at the beginning to retrieve data,
12742: and then again once at the end to send only the new data back.
12743:
12744: The data is stored in the user's data directory on the user's
12745: homeserver under the ID of the course.
12746:
12747: The hash that is returned by restore will have all of the previous
12748: value for all of the elements of the hash.
12749:
12750: Example:
12751:
12752: #creating a hash
12753: my %hash;
12754: $hash{'foo'}='bar';
12755:
12756: #storing it
12757: &Apache::lonnet::cstore(\%hash);
12758:
12759: #changing a value
12760: $hash{'foo'}='notbar';
12761:
12762: #adding a new value
12763: $hash{'bar'}='foo';
12764: &Apache::lonnet::cstore(\%hash);
12765:
12766: #retrieving the hash
12767: my %history=&Apache::lonnet::restore();
12768:
12769: #print the hash
12770: foreach my $key (sort(keys(%history))) {
12771: print("\%history{$key} = $history{$key}");
12772: }
12773:
12774: Will print out:
1.191 harris41 12775:
1.394 bowersj2 12776: %history{1:foo} = bar
12777: %history{1:keys} = foo:timestamp
12778: %history{1:timestamp} = 990455579
12779: %history{2:bar} = foo
12780: %history{2:foo} = notbar
12781: %history{2:keys} = foo:bar:timestamp
12782: %history{2:timestamp} = 990455580
12783: %history{bar} = foo
12784: %history{foo} = notbar
12785: %history{timestamp} = 990455580
12786: %history{version} = 2
12787:
12788: Note that the special hash entries C<keys>, C<version> and
12789: C<timestamp> were added to the hash. C<version> will be equal to the
12790: total number of versions of the data that have been stored. The
12791: C<timestamp> attribute will be the UNIX time the hash was
12792: stored. C<keys> is available in every historical section to list which
12793: keys were added or changed at a specific historical revision of a
12794: hash.
12795:
12796: B<Warning>: do not store the hash that restore returns directly. This
12797: will cause a mess since it will restore the historical keys as if the
12798: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12799:
1.394 bowersj2 12800: Calling convention:
1.191 harris41 12801:
1.1225 raeburn 12802: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 12803: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 12804:
1.394 bowersj2 12805: For more detailed information, see lonnet specific documentation.
1.191 harris41 12806:
1.394 bowersj2 12807: =head1 RETURN MESSAGES
1.191 harris41 12808:
1.394 bowersj2 12809: =over 4
1.191 harris41 12810:
1.394 bowersj2 12811: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12812:
1.394 bowersj2 12813: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12814: when the connection is brought back up
1.191 harris41 12815:
1.394 bowersj2 12816: =item * B<con_failed>: unable to contact remote host and unable to save message
12817: for later delivery
1.191 harris41 12818:
1.967 bisitz 12819: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12820:
1.394 bowersj2 12821: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12822: that was requested
1.191 harris41 12823:
1.243 albertel 12824: =back
1.191 harris41 12825:
1.243 albertel 12826: =head1 PUBLIC SUBROUTINES
1.191 harris41 12827:
1.243 albertel 12828: =head2 Session Environment Functions
1.191 harris41 12829:
1.243 albertel 12830: =over 4
1.191 harris41 12831:
1.394 bowersj2 12832: =item *
12833: X<appenv()>
1.949 raeburn 12834: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12835: the user envirnoment file, and will be restored for each access this
1.620 albertel 12836: user makes during this session, also modifies the %env for the current
1.949 raeburn 12837: process. Optional rolesarrayref - if defined contains a reference to an array
12838: of roles which are exempt from the restriction on modifying user.role entries
12839: in the user's environment.db and in %env.
1.191 harris41 12840:
12841: =item *
1.394 bowersj2 12842: X<delenv()>
1.987 raeburn 12843: B<delenv($delthis,$regexp)>: removes all items from the session
12844: environment file that begin with $delthis. If the
12845: optional second arg - $regexp - is true, $delthis is treated as a
12846: regular expression, otherwise \Q$delthis\E is used.
12847: The values are also deleted from the current processes %env.
1.191 harris41 12848:
1.795 albertel 12849: =item * get_env_multiple($name)
12850:
12851: gets $name from the %env hash, it seemlessly handles the cases where multiple
12852: values may be defined and end up as an array ref.
12853:
12854: returns an array of values
12855:
1.243 albertel 12856: =back
12857:
12858: =head2 User Information
1.191 harris41 12859:
1.243 albertel 12860: =over 4
1.191 harris41 12861:
12862: =item *
1.394 bowersj2 12863: X<queryauthenticate()>
12864: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12865: authentication scheme
12866:
12867: =item *
1.394 bowersj2 12868: X<authenticate()>
1.1073 raeburn 12869: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12870: authenticate user from domain's lib servers (first use the current
12871: one). C<$upass> should be the users password.
1.1073 raeburn 12872: $checkdefauth is optional (value is 1 if a check should be made to
12873: authenticate user using default authentication method, and allow
12874: account creation if username does not have account in the domain).
12875: $clientcancheckhost is optional (value is 1 if checking whether the
12876: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12877:
12878: =item *
1.394 bowersj2 12879: X<homeserver()>
12880: B<homeserver($uname,$udom)>: find the server which has
12881: the user's directory and files (there must be only one), this caches
12882: the answer, and also caches if there is a borken connection.
1.191 harris41 12883:
12884: =item *
1.394 bowersj2 12885: X<idget()>
12886: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12887: (IDs are a unique resource in a domain, there must be only 1 ID per
12888: username, and only 1 username per ID in a specific domain) (returns
12889: hash: id=>name,id=>name)
1.191 harris41 12890:
12891: =item *
1.394 bowersj2 12892: X<idrget()>
12893: B<idrget($udom,@unames)>: find the IDs behind a list of
12894: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12895:
12896: =item *
1.394 bowersj2 12897: X<idput()>
12898: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12899:
12900: =item *
1.394 bowersj2 12901: X<rolesinit()>
1.1169 droeschl 12902: B<rolesinit($udom,$username)>: get user privileges.
12903: returns user role, first access and timer interval hashes
1.243 albertel 12904:
12905: =item *
1.1171 droeschl 12906: X<privileged()>
12907: B<privileged($username,$domain)>: returns a true if user has a
12908: privileged and active role (i.e. su or dc), false otherwise.
12909:
12910: =item *
1.551 albertel 12911: X<getsection()>
12912: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12913: course $cname, return section name/number or '' for "not in course"
12914: and '-1' for "no section"
12915:
12916: =item *
1.394 bowersj2 12917: X<userenvironment()>
12918: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12919: passed in @what from the requested user's environment, returns a hash
12920:
1.858 raeburn 12921: =item *
12922: X<userlog_query()>
1.859 albertel 12923: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12924: activity.log file. %filters defines filters applied when parsing the
12925: log file. These can be start or end timestamps, or the type of action
12926: - log to look for Login or Logout events, check for Checkin or
12927: Checkout, role for role selection. The response is in the form
12928: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12929: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12930:
1.243 albertel 12931: =back
12932:
12933: =head2 User Roles
12934:
12935: =over 4
12936:
12937: =item *
12938:
1.810 raeburn 12939: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12940: F: full access
12941: U,I,K: authentication modes (cxx only)
12942: '': forbidden
12943: 1: user needs to choose course
12944: 2: browse allowed
1.766 albertel 12945: A: passphrase authentication needed
1.243 albertel 12946:
12947: =item *
12948:
1.1192 raeburn 12949: constructaccess($url,$setpriv) : check for access to construction space URL
12950:
12951: See if the owner domain and name in the URL match those in the
12952: expected environment. If so, return three element list
12953: ($ownername,$ownerdomain,$ownerhome).
12954:
12955: Otherwise return the null string.
12956:
12957: If second argument 'setpriv' is true, it assigns the privileges,
12958: and returns the same three element list, unless the owner has
12959: blocked "ad hoc" Domain Coordinator access to the Author Space,
12960: in which case the null string is returned.
12961:
12962: =item *
12963:
1.243 albertel 12964: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12965: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12966: and course level
12967:
12968: =item *
12969:
1.988 raeburn 12970: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12971: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12972: $type is Course (default) or Community.
1.988 raeburn 12973: If $forcedefault evaluates to true, text returned will be default
12974: text for $type. Otherwise, if this is a course, the text returned
12975: will be a custom name for the role (if defined in the course's
12976: environment). If no custom name is defined the default is returned.
12977:
1.832 raeburn 12978: =item *
12979:
1.1219 raeburn 12980: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12981: All arguments are optional. Returns a hash of a roles, either for
12982: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12983: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12984: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12985: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12986: For each key, value is set to colon-separated start and end times for
12987: the role. If no username and domain are specified, will default to
1.934 raeburn 12988: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12989: of role statuses (active, future or previous), roles
12990: (e.g., cc,in, st etc.) and domains of the roles which can be used
12991: to restrict the list of roles reported. If no array ref is
12992: provided for types, will default to return only active roles.
1.834 albertel 12993:
1.1195 raeburn 12994: =item *
12995:
12996: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12997: user: $uname:$udom has a role in the course: $cdom_$cnum.
12998:
12999: Additional optional arguments are: $type (if role checking is to be restricted
13000: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13001: available roles) or future (roles available in the future), and
13002: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13003: have active Domain Coordinator role in course's domain or in additional
13004: domains (specified in 'Domains to check for privileged users' in course
13005: environment -- set via: Course Settings -> Classlists and staff listing).
13006:
13007: =item *
13008:
13009: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13010: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13011: $possdomains and $possroles are optional array refs -- to domains to check and
13012: roles to check. If $possdomains is not specified, a dump will be done of the
13013: users' roles.db to check for a dc or su role in any domain. This can be
13014: time consuming if &privileged is called repeatedly (e.g., when displaying a
13015: classlist), so in such cases, supplying a $possdomains array is preferred, as
13016: this then allows &privileged_by_domain() to be used, which caches the identity
13017: of privileged users, eliminating the need for repeated calls to &dump().
13018:
13019: =item *
13020:
13021: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13022: where the outer hash keys are domains specified in the $possdomains array ref,
13023: next inner hash keys are privileged roles specified in the $roles array ref,
13024: and the innermost hash contains key = value pairs for username:domain = end:start
13025: for active or future "privileged" users with that role in that domain. To avoid
13026: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13027: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13028:
1.243 albertel 13029: =back
13030:
13031: =head2 User Modification
13032:
13033: =over 4
13034:
13035: =item *
13036:
1.957 raeburn 13037: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13038: user for the level given by URL. Optional start and end dates (leave empty
13039: string or zero for "no date")
1.191 harris41 13040:
13041: =item *
13042:
1.243 albertel 13043: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13044: change a users, password, possible return values are: ok,
13045: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13046: refused
1.191 harris41 13047:
13048: =item *
13049:
1.243 albertel 13050: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13051:
13052: =item *
13053:
1.1058 raeburn 13054: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13055: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13056:
13057: will update user information (firstname,middlename,lastname,generation,
13058: permanentemail), and if forceid is true, student/employee ID also.
13059: A user's institutional affiliation(s) can also be updated.
13060: User information fields will not be overwritten with empty entries
13061: unless the field is included in the $candelete array reference.
13062: This array is included when a single user is modified via "Manage Users",
13063: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13064:
13065: =item *
13066:
1.286 matthew 13067: modifystudent
13068:
1.957 raeburn 13069: modify a student's enrollment and identification information.
1.1235 raeburn 13070: The course id is resolved based on the current user's environment.
13071: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13072: associated with a course.
13073:
1.297 matthew 13074: This call is essentially a wrapper for lonnet::modifyuser and
13075: lonnet::modify_student_enrollment
1.286 matthew 13076:
13077: Inputs:
13078:
13079: =over 4
13080:
1.957 raeburn 13081: =item B<$udom> Student's loncapa domain
1.286 matthew 13082:
1.957 raeburn 13083: =item B<$uname> Student's loncapa login name
1.286 matthew 13084:
1.964 bisitz 13085: =item B<$uid> Student/Employee ID
1.286 matthew 13086:
1.957 raeburn 13087: =item B<$umode> Student's authentication mode
1.286 matthew 13088:
1.957 raeburn 13089: =item B<$upass> Student's password
1.286 matthew 13090:
1.957 raeburn 13091: =item B<$first> Student's first name
1.286 matthew 13092:
1.957 raeburn 13093: =item B<$middle> Student's middle name
1.286 matthew 13094:
1.957 raeburn 13095: =item B<$last> Student's last name
1.286 matthew 13096:
1.957 raeburn 13097: =item B<$gene> Student's generation
1.286 matthew 13098:
1.957 raeburn 13099: =item B<$usec> Student's section in course
1.286 matthew 13100:
13101: =item B<$end> Unix time of the roles expiration
13102:
13103: =item B<$start> Unix time of the roles start date
13104:
13105: =item B<$forceid> If defined, allow $uid to be changed
13106:
13107: =item B<$desiredhome> server to use as home server for student
13108:
1.957 raeburn 13109: =item B<$email> Student's permanent e-mail address
13110:
13111: =item B<$type> Type of enrollment (auto or manual)
13112:
1.963 raeburn 13113: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13114:
13115: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13116:
1.963 raeburn 13117: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13118:
1.963 raeburn 13119: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13120:
1.1216 raeburn 13121: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13122:
13123: =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 13124:
1.286 matthew 13125: =back
1.297 matthew 13126:
13127: =item *
13128:
13129: modify_student_enrollment
13130:
1.1235 raeburn 13131: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13132: 'role.request.course' must be defined for this function to proceed.
13133:
13134: Inputs:
13135:
13136: =over 4
13137:
1.1235 raeburn 13138: =item $udom, student's domain
1.297 matthew 13139:
1.1235 raeburn 13140: =item $uname, student's name
1.297 matthew 13141:
1.1235 raeburn 13142: =item $uid, student's user id
1.297 matthew 13143:
1.1235 raeburn 13144: =item $first, student's first name
1.297 matthew 13145:
13146: =item $middle
13147:
13148: =item $last
13149:
13150: =item $gene
13151:
13152: =item $usec
13153:
13154: =item $end
13155:
13156: =item $start
13157:
1.957 raeburn 13158: =item $type
13159:
13160: =item $locktype
13161:
13162: =item $cid
13163:
13164: =item $selfenroll
13165:
13166: =item $context
13167:
1.1216 raeburn 13168: =item $credits, number of credits student will earn from this class
13169:
1.297 matthew 13170: =back
13171:
1.191 harris41 13172:
13173: =item *
13174:
1.243 albertel 13175: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13176: custom role; give a custom role to a user for the level given by URL. Specify
13177: name and domain of role author, and role name
1.191 harris41 13178:
13179: =item *
13180:
1.243 albertel 13181: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13182:
13183: =item *
13184:
1.243 albertel 13185: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13186:
13187: =back
13188:
13189: =head2 Course Infomation
13190:
13191: =over 4
1.191 harris41 13192:
13193: =item *
13194:
1.1118 foxr 13195: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13196: specified course id, including all environment settings for the
13197: course, the description of the course will be in the hash under the
13198: key 'description'
1.191 harris41 13199:
1.1118 foxr 13200: $options is an optional parameter that if supplied is a hash reference that controls
13201: what how this function works. It has the following key/values:
13202:
13203: =over 4
13204:
13205: =item freshen_cache
13206:
13207: If defined, and the environment cache for the course is valid, it is
13208: returned in the returned hash.
13209:
13210: =item one_time
13211:
13212: If defined, the last cache time is set to _now_
13213:
13214: =item user
13215:
13216: If defined, the supplied username is used instead of the current user.
13217:
13218:
13219: =back
13220:
1.191 harris41 13221: =item *
13222:
1.624 albertel 13223: resdata($name,$domain,$type,@which) : request for current parameter
13224: setting for a specific $type, where $type is either 'course' or 'user',
13225: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 13226: answers for 10 minutes.
1.243 albertel 13227:
1.877 foxr 13228: =item *
13229:
13230: get_courseresdata($courseid, $domain) : dump the entire course resource
13231: data base, returning a hash that is keyed by the resource name and has
13232: values that are the resource value. I believe that the timestamps and
13233: versions are also returned.
13234:
1.1236 raeburn 13235: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13236: supplemental content area. This routine caches the number of files for
13237: 10 minutes.
13238:
1.243 albertel 13239: =back
13240:
13241: =head2 Course Modification
13242:
13243: =over 4
1.191 harris41 13244:
13245: =item *
13246:
1.243 albertel 13247: writecoursepref($courseid,%prefs) : write preferences (environment
13248: database) for a course
1.191 harris41 13249:
13250: =item *
13251:
1.1011 raeburn 13252: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13253:
13254: =item *
13255:
1.1038 raeburn 13256: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13257:
1.1167 droeschl 13258: =item *
13259:
13260: is_course($courseid), is_course($cdom, $cnum)
13261:
13262: Accepts either a combined $courseid (in the form of domain_courseid) or the
13263: two component version $cdom, $cnum. It checks if the specified course exists.
13264:
13265: Returns:
13266: undef if the course doesn't exist, otherwise
13267: in scalar context the combined courseid.
13268: in list context the two components of the course identifier, domain and
13269: courseid.
13270:
1.243 albertel 13271: =back
13272:
13273: =head2 Resource Subroutines
13274:
13275: =over 4
1.191 harris41 13276:
13277: =item *
13278:
1.243 albertel 13279: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13280:
13281: =item *
13282:
1.243 albertel 13283: repcopy($filename) : subscribes to the requested file, and attempts to
13284: replicate from the owning library server, Might return
1.607 raeburn 13285: 'unavailable', 'not_found', 'forbidden', 'ok', or
13286: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13287: resource. Expects the local filesystem pathname
13288: (/home/httpd/html/res/....)
13289:
13290: =back
13291:
13292: =head2 Resource Information
13293:
13294: =over 4
1.191 harris41 13295:
13296: =item *
13297:
1.1228 raeburn 13298: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13299: and returns the value of a variety of different possible values,
13300: $varname should be a request string, and the other parameters can be
13301: used to specify who and what one is asking about. Ordinarily, $cid
13302: does not need to be specified, as it is retrived from
13303: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13304: within lonuserstate::loadmap() when initializing a course, before
13305: $env{'request.course.id'} has been set, so it needs to be provided
13306: in that one case.
1.243 albertel 13307:
13308: Possible values for $varname are environment.lastname (or other item
13309: from the envirnment hash), user.name (or someother aspect about the
13310: user), resource.0.maxtries (or some other part and parameter of a
13311: resource)
1.204 albertel 13312:
13313: =item *
13314:
1.243 albertel 13315: directcondval($number) : get current value of a condition; reads from a state
13316: string
1.204 albertel 13317:
13318: =item *
13319:
1.243 albertel 13320: condval($condidx) : value of condition index based on state
1.204 albertel 13321:
13322: =item *
13323:
1.243 albertel 13324: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13325: resource's metadata, $what should be either a specific key, or either
13326: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13327: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13328:
13329: this function automatically caches all requests
1.191 harris41 13330:
13331: =item *
13332:
1.243 albertel 13333: metadata_query($query,$custom,$customshow) : make a metadata query against the
13334: network of library servers; returns file handle of where SQL and regex results
13335: will be stored for query
1.191 harris41 13336:
13337: =item *
13338:
1.243 albertel 13339: symbread($filename) : return symbolic list entry (filename argument optional);
13340: returns the data handle
1.191 harris41 13341:
13342: =item *
13343:
1.1190 raeburn 13344: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13345: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13346: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13347: on failure, user must be in a course, as it assumes the existence of
13348: the course initial hash, and uses $env('request.course.id'}. The third
13349: arg is an optional reference to a scalar. If this arg is passed in the
13350: call to symbverify, it will be set to 1 if the symb has been set to be
13351: encrypted; otherwise it will be null.
1.191 harris41 13352:
13353: =item *
13354:
1.243 albertel 13355: symbclean($symb) : removes versions numbers from a symb, returns the
13356: cleaned symb
1.191 harris41 13357:
13358: =item *
13359:
1.243 albertel 13360: is_on_map($uri) : checks if the $uri is somewhere on the current
13361: course map, user must be in a course for it to work.
1.191 harris41 13362:
13363: =item *
13364:
1.243 albertel 13365: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13366:
13367: =item *
13368:
1.243 albertel 13369: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13370: a random seed, all arguments are optional, if they aren't sent it uses the
13371: environment to derive them. Note: if symb isn't sent and it can't get one
13372: from &symbread it will use the current time as its return value
1.191 harris41 13373:
13374: =item *
13375:
1.243 albertel 13376: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13377: unfakeable, receipt
1.191 harris41 13378:
13379: =item *
13380:
1.620 albertel 13381: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13382:
13383: =item *
13384:
1.243 albertel 13385: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13386:
13387: =item *
13388:
1.243 albertel 13389: 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 13390:
13391: =item *
13392:
1.243 albertel 13393: 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 13394:
13395: =item *
13396:
1.243 albertel 13397: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13398:
13399: =item *
13400:
1.243 albertel 13401: devalidate($symb) : devalidate temporary spreadsheet calculations,
13402: forcing spreadsheet to reevaluate the resource scores next time.
13403:
1.1195 raeburn 13404: =item *
13405:
1.1196 raeburn 13406: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13407: when viewing in course context.
1.1195 raeburn 13408:
1.1196 raeburn 13409: input: six args -- filename (decluttered), course number, course domain,
13410: url, symb (if registered) and group (if this is a
13411: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13412:
1.1196 raeburn 13413: output: array of five scalars --
1.1195 raeburn 13414: $cfile -- url for file editing if editable on current server
13415: $home -- homeserver of resource (i.e., for author if published,
13416: or course if uploaded.).
13417: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13418: $forceedit -- 1 if icon/link should be to go to edit mode
13419: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13420:
13421: =item *
13422:
13423: is_course_upload($file,$cnum,$cdom)
13424:
13425: Used in course context to determine if current file was uploaded to
13426: the course (i.e., would be found in /userfiles/docs on the course's
13427: homeserver.
13428:
13429: input: 3 args -- filename (decluttered), course number and course domain.
13430: output: boolean -- 1 if file was uploaded.
13431:
1.243 albertel 13432: =back
13433:
13434: =head2 Storing/Retreiving Data
13435:
13436: =over 4
1.191 harris41 13437:
13438: =item *
13439:
1.1269 raeburn 13440: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13441: permanently for this url; hashref needs to be given and should be a \%hashname;
13442: the remaining args aren't required and if they aren't passed or are '' they will
13443: be derived from the env (with the exception of $laststore, which is an
13444: optional arg used when a user's submission is stored in grading).
13445: $laststore is $version=$timestamp, where $version is the most recent version
13446: number retrieved for the corresponding $symb in the $namespace db file, and
13447: $timestamp is the timestamp for that transaction (UNIX time).
13448: $laststore is currently only passed when cstore() is called by
13449: structuretags::finalize_storage().
1.191 harris41 13450:
13451: =item *
13452:
1.1269 raeburn 13453: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13454: but uses critical subroutine
1.191 harris41 13455:
13456: =item *
13457:
1.243 albertel 13458: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13459: all args are optional
1.191 harris41 13460:
13461: =item *
13462:
1.717 albertel 13463: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13464: dumps the complete (or key matching regexp) namespace into a hash
13465: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13466: normally &store()ed into
13467:
13468: $range should be either an integer '100' (give me the first 100
13469: matching records)
13470: or be two integers sperated by a - with no spaces
13471: '30-50' (give me the 30th through the 50th matching
13472: records)
13473:
13474:
13475: =item *
13476:
1.1269 raeburn 13477: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13478: replaces a &store() version of data with a replacement set of data
13479: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 13480: reference. If $tolog is true, the transaction is logged in the courselog
13481: with an action=PUTSTORE.
1.717 albertel 13482:
13483: =item *
13484:
1.243 albertel 13485: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13486: works very similar to store/cstore, but all data is stored in a
13487: temporary location and can be reset using tmpreset, $storehash should
13488: be a hash reference, returns nothing on success
1.191 harris41 13489:
13490: =item *
13491:
1.243 albertel 13492: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13493: similar to restore, but all data is stored in a temporary location and
13494: can be reset using tmpreset. Returns a hash of values on success,
13495: error string otherwise.
1.191 harris41 13496:
13497: =item *
13498:
1.243 albertel 13499: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13500: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13501:
13502: =item *
13503:
1.243 albertel 13504: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13505: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13506:
13507: =item *
13508:
1.243 albertel 13509: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13510: namesp ($udom and $uname are optional)
1.191 harris41 13511:
13512: =item *
13513:
1.702 albertel 13514: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13515: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13516: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13517:
1.702 albertel 13518: $range should be either an integer '100' (give me the first 100
13519: matching records)
13520: or be two integers sperated by a - with no spaces
13521: '30-50' (give me the 30th through the 50th matching
13522: records)
1.449 matthew 13523: =item *
13524:
13525: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13526: $store can be a scalar, an array reference, or if the amount to be
13527: incremented is > 1, a hash reference.
13528:
13529: ($udom and $uname are optional)
1.191 harris41 13530:
13531: =item *
13532:
1.243 albertel 13533: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13534: ($udom and $uname are optional)
1.191 harris41 13535:
13536: =item *
13537:
1.243 albertel 13538: cput($namespace,$storehash,$udom,$uname) : critical put
13539: ($udom and $uname are optional)
1.191 harris41 13540:
13541: =item *
13542:
1.748 albertel 13543: newput($namespace,$storehash,$udom,$uname) :
13544:
13545: Attempts to store the items in the $storehash, but only if they don't
13546: currently exist, if this succeeds you can be certain that you have
13547: successfully created a new key value pair in the $namespace db.
13548:
13549:
13550: Args:
13551: $namespace: name of database to store values to
13552: $storehash: hashref to store to the db
13553: $udom: (optional) domain of user containing the db
13554: $uname: (optional) name of user caontaining the db
13555:
13556: Returns:
13557: 'ok' -> succeeded in storing all keys of $storehash
13558: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13559: least <key> already existed in the db (other
13560: requested keys may also already exist)
1.967 bisitz 13561: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13562: 'con_lost' -> unable to contact request server
13563: 'refused' -> action was not allowed by remote machine
13564:
13565:
13566: =item *
13567:
1.243 albertel 13568: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13569: reference filled in from namesp (encrypts the return communication)
13570: ($udom and $uname are optional)
1.191 harris41 13571:
13572: =item *
13573:
1.243 albertel 13574: log($udom,$name,$home,$message) : write to permanent log for user; use
13575: critical subroutine
13576:
1.806 raeburn 13577: =item *
13578:
1.860 raeburn 13579: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13580: array reference filled in from namespace found in domain level on either
13581: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13582:
13583: =item *
13584:
1.860 raeburn 13585: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13586: domain level either on specified domain server ($uhome) or primary domain
13587: server ($udom and $uhome are optional)
1.806 raeburn 13588:
1.943 raeburn 13589: =item *
13590:
1.1240 raeburn 13591: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13592: for: authentication, language, quotas, timezone, date locale, and portal URL in
13593: the target domain.
13594:
13595: May also include additional key => value pairs for the following groups:
13596:
13597: =over
13598:
13599: =item
13600: disk quotas (MB allocated by default to portfolios and authoring spaces).
13601:
13602: =over
13603:
13604: =item defaultquota, authorquota
13605:
13606: =back
13607:
13608: =item
13609: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13610: portfolio for users).
13611:
13612: =over
13613:
13614: =item
13615: aboutme, blog, webdav, portfolio
13616:
13617: =back
13618:
13619: =item
13620: requestcourses: ability to request courses, and how requests are processed.
13621:
13622: =over
13623:
13624: =item
1.1246 raeburn 13625: official, unofficial, community, textbook
1.1240 raeburn 13626:
13627: =back
13628:
13629: =item
13630: inststatus: types of institutional affiliation, and order in which they are displayed.
13631:
13632: =over
13633:
13634: =item
1.1256 raeburn 13635: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 13636:
13637: =back
13638:
13639: =item
13640: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13641: for course's uploaded content.
13642:
13643: =over
13644:
13645: =item
1.1246 raeburn 13646: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13647: communityquota, textbookquota
1.1240 raeburn 13648:
13649: =back
13650:
13651: =item
13652: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13653: on your servers.
13654:
13655: =over
13656:
13657: =item
13658: remotesessions, hostedsessions
13659:
13660: =back
13661:
13662: =back
13663:
13664: In cases where a domain coordinator has never used the "Set Domain Configuration"
13665: utility to create a configuration.db file on a domain's primary library server
13666: only the following domain defaults: auth_def, auth_arg_def, lang_def
13667: -- corresponding values are authentication type (internal, krb4, krb5,
13668: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13669: will be available. Values are retrieved from cache (if current), unless the
13670: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13671: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13672:
13673: Typical usage:
1.943 raeburn 13674:
1.1240 raeburn 13675: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13676:
1.243 albertel 13677: =back
13678:
13679: =head2 Network Status Functions
13680:
13681: =over 4
1.191 harris41 13682:
13683: =item *
13684:
1.1137 raeburn 13685: dirlist() : return directory list based on URI (first arg).
13686:
13687: Inputs: 1 required, 5 optional.
13688:
13689: =over
13690:
13691: =item
13692: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13693:
13694: =item
13695: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13696:
13697: =item
13698: $username - username of user/course to be listed. Extracted from $uri if absent.
13699:
13700: =item
13701: $getpropath - boolean: 1 if prepend path using &propath().
13702:
13703: =item
13704: $getuserdir - boolean: 1 if prepend path for "userfiles".
13705:
13706: =item
13707: $alternateRoot - path to prepend in place of path from $uri.
13708:
13709: =back
13710:
13711: Returns: Array of up to two items.
13712:
13713: =over
13714:
13715: a reference to an array of files/subdirectories
13716:
13717: =over
13718:
13719: Each element in the array of files/subdirectories is a & separated list of
13720: item name and the result of running stat on the item. If dirlist was requested
13721: for a file instead of a directory, the item name will be ''. For a directory
13722: listing, if the item is a metadata file, the element will end &N&M
13723: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13724: default copyright set (1).
13725:
13726: =back
13727:
13728: a scalar containing error condition (if encountered).
13729:
13730: =over
13731:
13732: =item
13733: no_host (no homeserver identified for $username:$domain).
13734:
13735: =item
13736: no_such_host (server contacted for listing not identified as valid host).
13737:
13738: =item
13739: con_lost (connection to remote server failed).
13740:
13741: =item
13742: refused (invalid $username:$domain received on lond side).
13743:
13744: =item
13745: no_such_dir (directory at specified path on lond side does not exist).
13746:
13747: =item
13748: empty (directory at specified path on lond side is empty).
13749:
13750: =over
13751:
13752: This is currently not encountered because the &ls3, &ls2,
13753: &ls (_handler) routines on the lond side do not filter out
13754: . and .. from a directory listing.
13755:
13756: =back
13757:
13758: =back
13759:
13760: =back
1.191 harris41 13761:
13762: =item *
13763:
1.243 albertel 13764: spareserver() : find server with least workload from spare.tab
13765:
1.986 foxr 13766:
13767: =item *
13768:
13769: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13770: if there is no corresponding loncapa host.
13771:
1.243 albertel 13772: =back
13773:
1.986 foxr 13774:
1.243 albertel 13775: =head2 Apache Request
13776:
13777: =over 4
1.191 harris41 13778:
13779: =item *
13780:
1.243 albertel 13781: ssi($url,%hash) : server side include, does a complete request cycle on url to
13782: localhost, posts hash
13783:
13784: =back
13785:
13786: =head2 Data to String to Data
13787:
13788: =over 4
1.191 harris41 13789:
13790: =item *
13791:
1.243 albertel 13792: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13793: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13794:
13795: =item *
13796:
1.243 albertel 13797: hashref2str($hashref) : convert a hashref into a string complete with
13798: escaping and '=' and '&' separators, supports elements that are
13799: arrayrefs and hashrefs
1.191 harris41 13800:
13801: =item *
13802:
1.243 albertel 13803: arrayref2str($arrayref) : convert an arrayref into a string complete
13804: with escaping and '&' separators, supports elements that are arrayrefs
13805: and hashrefs
1.191 harris41 13806:
13807: =item *
13808:
1.243 albertel 13809: str2hash($string) : convert string to hash using unescaping and
13810: splitting on '=' and '&', supports elements that are arrayrefs and
13811: hashrefs
1.191 harris41 13812:
13813: =item *
13814:
1.243 albertel 13815: str2array($string) : convert string to hash using unescaping and
13816: splitting on '&', supports elements that are arrayrefs and hashrefs
13817:
13818: =back
13819:
13820: =head2 Logging Routines
13821:
13822:
13823: These routines allow one to make log messages in the lonnet.log and
13824: lonnet.perm logfiles.
1.191 harris41 13825:
1.1119 foxr 13826: =over 4
13827:
1.191 harris41 13828: =item *
13829:
1.243 albertel 13830: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13831:
13832: =item *
13833:
1.243 albertel 13834: logthis() : append message to the normal lonnet.log file, it gets
13835: preiodically rolled over and deleted.
1.191 harris41 13836:
13837: =item *
13838:
1.243 albertel 13839: logperm() : append a permanent message to lonnet.perm.log, this log
13840: file never gets deleted by any automated portion of the system, only
13841: messages of critical importance should go in here.
13842:
1.1119 foxr 13843:
1.243 albertel 13844: =back
13845:
13846: =head2 General File Helper Routines
13847:
13848: =over 4
1.191 harris41 13849:
13850: =item *
13851:
1.481 raeburn 13852: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13853: (a) files in /uploaded
13854: (i) If a local copy of the file exists -
13855: compares modification date of local copy with last-modified date for
13856: definitive version stored on home server for course. If local copy is
13857: stale, requests a new version from the home server and stores it.
13858: If the original has been removed from the home server, then local copy
13859: is unlinked.
13860: (ii) If local copy does not exist -
13861: requests the file from the home server and stores it.
13862:
13863: If $caller is 'uploadrep':
13864: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13865: for request for files originally uploaded via DOCS.
13866: - returns 'ok' if fresh local copy now available, -1 otherwise.
13867:
13868: Otherwise:
13869: This indicates a call from the content generation phase of the request.
13870: - returns the entire contents of the file or -1.
13871:
13872: (b) files in /res
13873: - returns the entire contents of a file or -1;
13874: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13875:
1.712 albertel 13876:
13877: =item *
13878:
13879: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13880: reference
13881:
13882: returns either a stat() list of data about the file or an empty list
13883: if the file doesn't exist or couldn't find out about it (connection
13884: problems or user unknown)
13885:
1.191 harris41 13886: =item *
13887:
1.243 albertel 13888: filelocation($dir,$file) : returns file system location of a file
13889: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13890: directory that relative $file lookups are to looked in ($dir of /a/dir
13891: and a file of ../bob will become /a/bob)
1.191 harris41 13892:
13893: =item *
13894:
13895: hreflocation($dir,$file) : returns file system location or a URL; same as
13896: filelocation except for hrefs
13897:
13898: =item *
13899:
1.1261 raeburn 13900: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13901: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 13902:
1.243 albertel 13903: =back
13904:
1.608 albertel 13905: =head2 Usererfile file routines (/uploaded*)
13906:
13907: =over 4
13908:
13909: =item *
13910:
13911: userfileupload(): main rotine for putting a file in a user or course's
13912: filespace, arguments are,
13913:
1.620 albertel 13914: formname - required - this is the name of the element in $env where the
1.608 albertel 13915: filename, and the contents of the file to create/modifed exist
1.620 albertel 13916: the filename is in $env{'form.'.$formname.'.filename'} and the
13917: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13918: context - if coursedoc, store the file in the course of the active role
13919: of the current user;
13920: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13921: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13922: subdir - required - subdirectory to put the file in under ../userfiles/
13923: if undefined, it will be placed in "unknown"
13924:
13925: (This routine calls clean_filename() to remove any dangerous
13926: characters from the filename, and then calls finuserfileupload() to
13927: complete the transaction)
13928:
13929: returns either the url of the uploaded file (/uploaded/....) if successful
13930: and /adm/notfound.html if unsuccessful
13931:
13932: =item *
13933:
13934: clean_filename(): routine for cleaing a filename up for storage in
13935: userfile space, argument is:
13936:
13937: filename - proposed filename
13938:
13939: returns: the new clean filename
13940:
13941: =item *
13942:
1.1090 raeburn 13943: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13944: userspace, probably shouldn't be called directly
13945:
13946: docuname: username or courseid of destination for the file
13947: docudom: domain of user/course of destination for the file
13948: formname: same as for userfileupload()
1.1090 raeburn 13949: fname: filename (including subdirectories) for the file
13950: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13951: allfiles: reference to hash used to store objects found by parser
13952: codebase: reference to hash used for codebases of java objects found by parser
13953: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13954: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13955: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13956: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13957: context: if 'overwrite', will move the uploaded file from its temporary location to
13958: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13959: mimetype: reference to scalar to accommodate mime type determined
13960: from File::MMagic if $parser = parse.
1.608 albertel 13961:
13962: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13963: and /adm/notfound.html if unsuccessful (or an error message if context
13964: was 'overwrite').
13965:
1.608 albertel 13966:
13967: =item *
13968:
13969: renameuserfile(): renames an existing userfile to a new name
13970:
13971: Args:
13972: docuname: username or courseid of destination for the file
13973: docudom: domain of user/course of destination for the file
13974: old: current file name (including any subdirs under userfiles)
13975: new: desired file name (including any subdirs under userfiles)
13976:
13977: =item *
13978:
13979: mkdiruserfile(): creates a directory is a userfiles dir
13980:
13981: Args:
13982: docuname: username or courseid of destination for the file
13983: docudom: domain of user/course of destination for the file
13984: dir: dir to create (including any subdirs under userfiles)
13985:
13986: =item *
13987:
13988: removeuserfile(): removes a file that exists in userfiles
13989:
13990: Args:
13991: docuname: username or courseid of destination for the file
13992: docudom: domain of user/course of destination for the file
13993: fname: filname to delete (including any subdirs under userfiles)
13994:
13995: =item *
13996:
13997: removeuploadedurl(): convience function for removeuserfile()
13998:
13999: Args:
14000: url: a full /uploaded/... url to delete
14001:
1.747 albertel 14002: =item *
14003:
14004: get_portfile_permissions():
14005: Args:
14006: domain: domain of user or course contain the portfolio files
14007: user: name of user or num of course contain the portfolio files
14008: Returns:
14009: hashref of a dump of the proper file_permissions.db
14010:
14011:
14012: =item *
14013:
14014: get_access_controls():
14015:
14016: Args:
14017: current_permissions: the hash ref returned from get_portfile_permissions()
14018: group: (optional) the group you want the files associated with
14019: file: (optional) the file you want access info on
14020:
14021: Returns:
1.749 raeburn 14022: a hash (keys are file names) of hashes containing
14023: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14024: values are XML containing access control settings (see below)
1.747 albertel 14025:
14026: Internal notes:
14027:
1.749 raeburn 14028: access controls are stored in file_permissions.db as key=value pairs.
14029: key -> path to file/file_name\0uniqueID:scope_end_start
14030: where scope -> public,guest,course,group,domains or users.
14031: end -> UNIX time for end of access (0 -> no end date)
14032: start -> UNIX time for start of access
14033:
14034: value -> XML description of access control
14035: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14036: <start></start>
14037: <end></end>
14038:
14039: <password></password> for scope type = guest
14040:
14041: <domain></domain> for scope type = course or group
14042: <number></number>
14043: <roles id="">
14044: <role></role>
14045: <access></access>
14046: <section></section>
14047: <group></group>
14048: </roles>
14049:
14050: <dom></dom> for scope type = domains
14051:
14052: <users> for scope type = users
14053: <user>
14054: <uname></uname>
14055: <udom></udom>
14056: </user>
14057: </users>
14058: </scope>
14059:
14060: Access data is also aggregated for each file in an additional key=value pair:
14061: key -> path to file/file_name\0accesscontrol
14062: value -> reference to hash
14063: hash contains key = value pairs
14064: where key = uniqueID:scope_end_start
14065: value = UNIX time record was last updated
14066:
14067: Used to improve speed of look-ups of access controls for each file.
14068:
14069: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14070:
1.1198 raeburn 14071: =item *
14072:
1.749 raeburn 14073: modify_access_controls():
14074:
14075: Modifies access controls for a portfolio file
14076: Args
14077: 1. file name
14078: 2. reference to hash of required changes,
14079: 3. domain
14080: 4. username
14081: where domain,username are the domain of the portfolio owner
14082: (either a user or a course)
14083:
14084: Returns:
14085: 1. result of additions or updates ('ok' or 'error', with error message).
14086: 2. result of deletions ('ok' or 'error', with error message).
14087: 3. reference to hash of any new or updated access controls.
14088: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14089: key = integer (inbound ID)
1.1198 raeburn 14090: value = uniqueID
14091:
14092: =item *
14093:
14094: get_timebased_id():
14095:
14096: Attempts to get a unique timestamp-based suffix for use with items added to a
14097: course via the Course Editor (e.g., folders, composite pages,
14098: group bulletin boards).
14099:
14100: Args: (first three required; six others optional)
14101:
14102: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14103: docssequence, or name of group
14104:
14105: 2. keyid (alphanumeric): name of temporary locking key in hash,
14106: e.g., num, boardids
14107:
14108: 3. namespace: name of gdbm file used to store suffixes already assigned;
14109: file will be named nohist_namespace.db
14110:
14111: 4. cdom: domain of course; default is current course domain from %env
14112:
14113: 5. cnum: course number; default is current course number from %env
14114:
14115: 6. idtype: set to concat if an additional digit is to be appended to the
14116: unix timestamp to form the suffix, if the plain timestamp is already
14117: in use. Default is to not do this, but simply increment the unix
14118: timestamp by 1 until a unique key is obtained.
14119:
14120: 7. who: holder of locking key; defaults to user:domain for user.
14121:
14122: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14123: retrying); default is 3.
14124:
14125: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14126:
14127: Returns:
14128:
14129: 1. suffix obtained (numeric)
14130:
14131: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14132:
14133: 3. error: contains (localized) error message if an error occurred.
14134:
1.747 albertel 14135:
1.608 albertel 14136: =back
14137:
1.243 albertel 14138: =head2 HTTP Helper Routines
14139:
14140: =over 4
14141:
1.191 harris41 14142: =item *
14143:
14144: escape() : unpack non-word characters into CGI-compatible hex codes
14145:
14146: =item *
14147:
14148: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14149:
1.243 albertel 14150: =back
14151:
14152: =head1 PRIVATE SUBROUTINES
14153:
14154: =head2 Underlying communication routines (Shouldn't call)
14155:
14156: =over 4
14157:
14158: =item *
14159:
14160: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14161:
14162: =item *
14163:
14164: reply() : uses subreply to send a message to remote machine, logs all failures
14165:
14166: =item *
14167:
14168: critical() : passes a critical message to another server; if cannot
14169: get through then place message in connection buffer directory and
14170: returns con_delayed, if incapable of saving message, returns
14171: con_failed
14172:
14173: =item *
14174:
14175: reconlonc() : tries to reconnect lonc client processes.
14176:
14177: =back
14178:
14179: =head2 Resource Access Logging
14180:
14181: =over 4
14182:
14183: =item *
14184:
14185: flushcourselogs() : flush (save) buffer logs and access logs
14186:
14187: =item *
14188:
14189: courselog($what) : save message for course in hash
14190:
14191: =item *
14192:
14193: courseacclog($what) : save message for course using &courselog(). Perform
14194: special processing for specific resource types (problems, exams, quizzes, etc).
14195:
1.191 harris41 14196: =item *
14197:
14198: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14199: as a PerlChildExitHandler
1.243 albertel 14200:
14201: =back
14202:
14203: =head2 Other
14204:
14205: =over 4
14206:
14207: =item *
14208:
14209: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14210:
14211: =back
14212:
14213: =cut
1.877 foxr 14214:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>