Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.122
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.122! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.121 2020/01/21 19:03:08 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;
1.1172.2.107 raeburn 77: use CGI::Cookie;
1.977 amueller 78:
1.1172.2.104 raeburn 79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138 raeburn 80: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114 raeburn 81: %managerstab $passwdmin);
1.871 albertel 82:
83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
84: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
85: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 86: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 87:
1.1 albertel 88: use IO::Socket;
1.31 www 89: use GDBM_File;
1.208 albertel 90: use HTML::LCParser;
1.88 www 91: use Fcntl qw(:flock);
1.870 albertel 92: use Storable qw(thaw nfreeze);
1.1172.2.79 raeburn 93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 94: use Cache::Memcached;
1.676 albertel 95: use Digest::MD5;
1.790 albertel 96: use Math::Random;
1.1024 raeburn 97: use File::MMagic;
1.807 albertel 98: use LONCAPA qw(:DEFAULT :match);
1.740 www 99: use LONCAPA::Configuration;
1.1160 www 100: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 101: use LONCAPA::Lond;
1.1172.2.110 raeburn 102: use LONCAPA::transliterate;
1.1117 foxr 103:
1.1090 raeburn 104: use File::Copy;
1.676 albertel 105:
1.195 www 106: my $readit;
1.1172.2.79 raeburn 107: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 108:
1.619 albertel 109: require Exporter;
110:
111: our @ISA = qw (Exporter);
112: our @EXPORT = qw(%env);
113:
1.1172.2.9 raeburn 114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 115: {
116: my $logid;
1.1172.2.9 raeburn 117: sub write_log {
118: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
119: if ($context eq 'course') {
120: if (($cnum eq '') || ($cdom eq '')) {
121: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
122: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
123: }
1.957 raeburn 124: }
1.1172.2.13 raeburn 125: $logid ++;
1.957 raeburn 126: my $now = time();
127: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 128: my $logentry = {
129: $id => {
130: 'exe_uname' => $env{'user.name'},
131: 'exe_udom' => $env{'user.domain'},
132: 'exe_time' => $now,
133: 'exe_ip' => $ENV{'REMOTE_ADDR'},
134: 'delflag' => $delflag,
135: 'logentry' => $storehash,
136: 'uname' => $uname,
137: 'udom' => $udom,
138: }
139: };
140: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 141: }
142: }
1.1 albertel 143:
1.163 harris41 144: sub logtouch {
145: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 146: unless (-e "$execdir/logs/lonnet.log") {
1.1172.2.96 raeburn 147: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 148: close $fh;
149: }
150: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
151: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
152: }
153:
1.1 albertel 154: sub logthis {
155: my $message=shift;
156: my $execdir=$perlvar{'lonDaemons'};
157: my $now=time;
158: my $local=localtime($now);
1.1172.2.96 raeburn 159: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 160: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
161: print $fh $logstring;
1.448 albertel 162: close($fh);
163: }
1.1 albertel 164: return 1;
165: }
166:
167: sub logperm {
168: my $message=shift;
169: my $execdir=$perlvar{'lonDaemons'};
170: my $now=time;
171: my $local=localtime($now);
1.1172.2.96 raeburn 172: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 173: print $fh "$now:$message:$local\n";
174: close($fh);
175: }
1.1 albertel 176: return 1;
177: }
178:
1.850 albertel 179: sub create_connection {
1.853 albertel 180: my ($hostname,$lonid) = @_;
1.851 albertel 181: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 182: Type => SOCK_STREAM,
183: Timeout => 10);
184: return 0 if (!$client);
1.890 albertel 185: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 186: my $result = <$client>;
187: chomp($result);
188: return 1 if ($result eq 'done');
189: return 0;
190: }
191:
1.983 raeburn 192: sub get_server_timezone {
193: my ($cnum,$cdom) = @_;
194: my $home=&homeserver($cnum,$cdom);
195: if ($home ne 'no_host') {
196: my $cachetime = 24*3600;
197: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
198: if (defined($cached)) {
199: return $timezone;
200: } else {
201: my $timezone = &reply('servertimezone',$home);
202: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
203: }
204: }
205: }
1.850 albertel 206:
1.1106 raeburn 207: sub get_server_distarch {
208: my ($lonhost,$ignore_cache) = @_;
209: if (defined($lonhost)) {
210: if (!defined(&hostname($lonhost))) {
211: return;
212: }
213: my $cachetime = 12*3600;
214: if (!$ignore_cache) {
215: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
216: if (defined($cached)) {
217: return $distarch;
218: }
219: }
220: my $rep = &reply('serverdistarch',$lonhost);
221: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
222: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
223: $rep eq '') {
224: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
225: }
226: }
227: return;
228: }
229:
1.993 raeburn 230: sub get_server_loncaparev {
1.1073 raeburn 231: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 232: if (defined($lonhost)) {
233: if (!defined(&hostname($lonhost))) {
234: undef($lonhost);
235: }
236: }
237: if (!defined($lonhost)) {
238: if (defined(&domain($dom,'primary'))) {
239: $lonhost=&domain($dom,'primary');
240: if ($lonhost eq 'no_host') {
241: undef($lonhost);
242: }
243: }
244: }
245: if (defined($lonhost)) {
1.1073 raeburn 246: my $cachetime = 12*3600;
247: if (!$ignore_cache) {
248: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
249: if (defined($cached)) {
250: return $loncaparev;
251: }
252: }
253: my ($answer,$loncaparev);
254: my @ids=¤t_machine_ids();
255: if (grep(/^\Q$lonhost\E$/,@ids)) {
256: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 257: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 258: $loncaparev = $1;
259: }
260: } else {
261: $answer = &reply('serverloncaparev',$lonhost);
262: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
263: if ($caller eq 'loncron') {
264: my $ua=new LWP::UserAgent;
1.1082 raeburn 265: $ua->timeout(4);
1.1172.2.120 raeburn 266: my $hostname = &hostname($lonhost);
1.1073 raeburn 267: my $protocol = $protocol{$lonhost};
268: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 269: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 270: my $request=new HTTP::Request('GET',$url);
271: my $response=$ua->request($request);
272: unless ($response->is_error()) {
273: my $content = $response->content;
1.1081 raeburn 274: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 275: $loncaparev = $1;
276: }
277: }
278: } else {
279: $loncaparev = $loncaparevs{$lonhost};
280: }
1.1081 raeburn 281: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 282: $loncaparev = $1;
283: }
1.993 raeburn 284: }
1.1073 raeburn 285: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 286: }
287: }
288:
1.1074 raeburn 289: sub get_server_homeID {
290: my ($hostname,$ignore_cache,$caller) = @_;
291: unless ($ignore_cache) {
292: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
293: if (defined($cached)) {
294: return $serverhomeID;
295: }
296: }
297: my $cachetime = 12*3600;
298: my $serverhomeID;
299: if ($caller eq 'loncron') {
300: my @machine_ids = &machine_ids($hostname);
301: foreach my $id (@machine_ids) {
302: my $response = &reply('serverhomeID',$id);
303: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
304: $serverhomeID = $response;
305: last;
306: }
307: }
308: if ($serverhomeID eq '') {
309: $serverhomeID = $machine_ids[-1];
310: }
311: } else {
312: $serverhomeID = $serverhomeIDs{$hostname};
313: }
314: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
315: }
316:
1.1121 raeburn 317: sub get_remote_globals {
318: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 319: my ($result,%returnhash,%whatneeded);
320: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 321: foreach my $what (sort(keys(%{$whathash}))) {
322: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 323: my ($response,$cached);
1.1121 raeburn 324: unless ($ignore_cache) {
1.1125 raeburn 325: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 326: }
327: if (defined($cached)) {
1.1125 raeburn 328: $returnhash{$what} = $response;
1.1121 raeburn 329: } else {
1.1125 raeburn 330: $whatneeded{$what} = 1;
1.1121 raeburn 331: }
332: }
1.1125 raeburn 333: if (keys(%whatneeded) == 0) {
334: $result = 'ok';
335: } else {
1.1121 raeburn 336: my $requested = &freeze_escape(\%whatneeded);
337: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 338: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
339: ($rep eq 'unknown_cmd')) {
340: $result = $rep;
341: } else {
342: $result = 'ok';
1.1121 raeburn 343: my @pairs=split(/\&/,$rep);
1.1125 raeburn 344: foreach my $item (@pairs) {
345: my ($key,$value)=split(/=/,$item,2);
346: my $what = &unescape($key);
347: my $hashid = $lonhost.'-'.$what;
348: $returnhash{$what}=&thaw_unescape($value);
349: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 350: }
351: }
352: }
353: }
1.1125 raeburn 354: return ($result,\%returnhash);
1.1121 raeburn 355: }
356:
1.1124 raeburn 357: sub remote_devalidate_cache {
1.1172.2.35 raeburn 358: my ($lonhost,$cachekeys) = @_;
359: my $items;
360: return unless (ref($cachekeys) eq 'ARRAY');
361: my $cachestr = join('&',@{$cachekeys});
362: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 363: }
364:
1.1 albertel 365: # -------------------------------------------------- Non-critical communication
366: sub subreply {
367: my ($cmd,$server)=@_;
1.838 albertel 368: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 369: #
370: # With loncnew process trimming, there's a timing hole between lonc server
371: # process exit and the master server picking up the listen on the AF_UNIX
372: # socket. In that time interval, a lock file will exist:
373:
374: my $lockfile=$peerfile.".lock";
375: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 376: sleep(0.1);
1.549 foxr 377: }
378: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 379: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 380: #
1.550 foxr 381: # We'll give the connection a few tries before abandoning it. If
382: # connection is not possible, we'll con_lost back to the client.
383: #
384: my $client;
385: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
386: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
387: Type => SOCK_STREAM,
388: Timeout => 10);
1.869 albertel 389: if ($client) {
1.550 foxr 390: last; # Connected!
1.850 albertel 391: } else {
1.853 albertel 392: &create_connection(&hostname($server),$server);
1.550 foxr 393: }
1.1172.2.79 raeburn 394: sleep(0.1); # Try again later if failed connection.
1.550 foxr 395: }
396: my $answer;
397: if ($client) {
1.704 albertel 398: print $client "sethost:$server:$cmd\n";
1.550 foxr 399: $answer=<$client>;
400: if (!$answer) { $answer="con_lost"; }
401: chomp($answer);
402: } else {
403: $answer = 'con_lost'; # Failed connection.
404: }
1.1 albertel 405: return $answer;
406: }
407:
408: sub reply {
409: my ($cmd,$server)=@_;
1.838 albertel 410: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 411: my $answer=subreply($cmd,$server);
1.65 www 412: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111 raeburn 413: my $logged = $cmd;
414: if ($cmd =~ /^encrypt:([^:]+):/) {
415: my $subcmd = $1;
416: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
417: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
418: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
419: (undef,undef,my @rest) = split(/:/,$cmd);
420: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
421: splice(@rest,2,1,'Hidden');
422: } elsif ($subcmd eq 'passwd') {
423: splice(@rest,2,2,('Hidden','Hidden'));
424: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
425: ($subcmd eq 'autoexportgrades')) {
426: splice(@rest,3,1,'Hidden');
427: }
428: $logged = join(':',('encrypt:'.$subcmd,@rest));
429: }
430: }
431: &logthis("<font color=\"blue\">WARNING:".
432: " $logged to $server returned $answer</font>");
1.12 www 433: }
1.1 albertel 434: return $answer;
435: }
436:
437: # ----------------------------------------------------------- Send USR1 to lonc
438:
439: sub reconlonc {
1.891 albertel 440: my ($lonid) = @_;
441: if ($lonid) {
1.1172.2.72 raeburn 442: my $hostname = &hostname($lonid);
1.891 albertel 443: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
444: if ($hostname && -e $peerfile) {
445: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
446: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
447: Type => SOCK_STREAM,
448: Timeout => 10);
449: if ($client) {
450: print $client ("reset_retries\n");
451: my $answer=<$client>;
452: #reset just this one.
453: }
454: }
455: return;
456: }
457:
1.836 www 458: &logthis("Trying to reconnect lonc");
1.1 albertel 459: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96 raeburn 460: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 461: my $loncpid=<$fh>;
462: chomp($loncpid);
463: if (kill 0 => $loncpid) {
464: &logthis("lonc at pid $loncpid responding, sending USR1");
465: kill USR1 => $loncpid;
466: sleep 1;
1.836 www 467: } else {
1.12 www 468: &logthis(
1.672 albertel 469: "<font color=\"blue\">WARNING:".
1.12 www 470: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 471: }
472: } else {
1.836 www 473: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 474: }
475: }
476:
477: # ------------------------------------------------------ Critical communication
1.12 www 478:
1.1 albertel 479: sub critical {
480: my ($cmd,$server)=@_;
1.838 albertel 481: unless (&hostname($server)) {
1.672 albertel 482: &logthis("<font color=\"blue\">WARNING:".
1.89 www 483: " Critical message to unknown server ($server)</font>");
484: return 'no_such_host';
485: }
1.1 albertel 486: my $answer=reply($cmd,$server);
487: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 488: &reconlonc($server);
1.589 albertel 489: my $answer=reply($cmd,$server);
1.1 albertel 490: if ($answer eq 'con_lost') {
491: my $now=time;
492: my $middlename=$cmd;
1.5 www 493: $middlename=substr($middlename,0,16);
1.1 albertel 494: $middlename=~s/\W//g;
495: my $dfilename=
1.305 www 496: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
497: $dumpcount++;
1.1 albertel 498: {
1.448 albertel 499: my $dfh;
1.1172.2.96 raeburn 500: if (open($dfh,">",$dfilename)) {
1.448 albertel 501: print $dfh "$cmd\n";
502: close($dfh);
503: }
1.1 albertel 504: }
1.1172.2.79 raeburn 505: sleep 1;
1.1 albertel 506: my $wcmd='';
507: {
1.448 albertel 508: my $dfh;
1.1172.2.96 raeburn 509: if (open($dfh,"<",$dfilename)) {
1.448 albertel 510: $wcmd=<$dfh>;
511: close($dfh);
512: }
1.1 albertel 513: }
514: chomp($wcmd);
1.7 www 515: if ($wcmd eq $cmd) {
1.672 albertel 516: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 517: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 518: &logperm("D:$server:$cmd");
519: return 'con_delayed';
520: } else {
1.672 albertel 521: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 522: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 523: &logperm("F:$server:$cmd");
524: return 'con_failed';
525: }
526: }
527: }
528: return $answer;
1.405 albertel 529: }
530:
1.755 albertel 531: # ------------------------------------------- check if return value is an error
532:
533: sub error {
534: my ($result) = @_;
1.756 albertel 535: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 536: if ($2 == 2) { return undef; }
537: return $1;
538: }
539: return undef;
540: }
541:
1.783 albertel 542: sub convert_and_load_session_env {
543: my ($lonidsdir,$handle)=@_;
544: my @profile;
545: {
1.917 albertel 546: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
547: if (!$opened) {
1.915 albertel 548: return 0;
549: }
1.783 albertel 550: flock($idf,LOCK_SH);
551: @profile=<$idf>;
552: close($idf);
553: }
554: my %temp_env;
555: foreach my $line (@profile) {
1.786 albertel 556: if ($line !~ m/=/) {
557: return 0;
558: }
1.783 albertel 559: chomp($line);
560: my ($envname,$envvalue)=split(/=/,$line,2);
561: $temp_env{&unescape($envname)} = &unescape($envvalue);
562: }
563: unlink("$lonidsdir/$handle.id");
564: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
565: 0640)) {
566: %disk_env = %temp_env;
567: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
568: untie(%disk_env);
569: }
1.786 albertel 570: return 1;
1.783 albertel 571: }
572:
1.374 www 573: # ------------------------------------------- Transfer profile into environment
1.780 albertel 574: my $env_loaded;
575: sub transfer_profile_to_env {
1.788 albertel 576: my ($lonidsdir,$handle,$force_transfer) = @_;
577: if (!$force_transfer && $env_loaded) { return; }
1.374 www 578:
1.720 albertel 579: if (!defined($lonidsdir)) {
580: $lonidsdir = $perlvar{'lonIDsDir'};
581: }
582: if (!defined($handle)) {
583: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
584: }
585:
1.786 albertel 586: my $convert;
587: {
1.917 albertel 588: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
589: if (!$opened) {
1.915 albertel 590: return;
591: }
1.786 albertel 592: flock($idf,LOCK_SH);
593: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
594: &GDBM_READER(),0640)) {
595: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
596: untie(%disk_env);
597: } else {
598: $convert = 1;
599: }
600: }
601: if ($convert) {
602: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
603: &logthis("Failed to load session, or convert session.");
604: }
1.374 www 605: }
1.783 albertel 606:
1.786 albertel 607: my %remove;
1.783 albertel 608: while ( my $envname = each(%env) ) {
1.433 matthew 609: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
610: if ($time < time-300) {
1.783 albertel 611: $remove{$key}++;
1.433 matthew 612: }
613: }
614: }
1.783 albertel 615:
1.619 albertel 616: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 617: $env_loaded=1;
1.783 albertel 618: foreach my $expired_key (keys(%remove)) {
1.433 matthew 619: &delenv($expired_key);
1.374 www 620: }
1.1 albertel 621: }
622:
1.916 albertel 623: # ---------------------------------------------------- Check for valid session
624: sub check_for_valid_session {
1.1172.2.96 raeburn 625: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 626: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108 raeburn 627: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155 raeburn 628: if ($name eq 'lonDAV') {
629: $lonidsdir=$r->dir_config('lonDAVsessDir');
630: } else {
631: $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108 raeburn 632: if ($name eq '') {
633: $name = 'lonID';
634: }
635: }
636: if ($name eq 'lonID') {
637: $secure = 'lonSID';
638: $linkname = 'lonLinkID';
639: $pubname = 'lonPubID';
640: if (exists($cookies{$secure})) {
641: $lonid=$cookies{$secure};
642: } elsif (exists($cookies{$name})) {
643: $lonid=$cookies{$name};
644: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
645: $lonid=$cookies{$linkname};
646: } elsif (exists($cookies{$pubname})) {
647: $lonid=$cookies{$pubname};
648: }
649: } else {
650: $lonid=$cookies{$name};
651: }
652: return undef if (!$lonid);
653:
654: my $handle=&LONCAPA::clean_handle($lonid->value);
655: if (-l "$lonidsdir/$handle.id") {
656: my $link = readlink("$lonidsdir/$handle.id");
657: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
658: $handle = $1;
659: }
1.1155 raeburn 660: }
1.1172.2.96 raeburn 661: if (!-e "$lonidsdir/$handle.id") {
662: if ((ref($domref)) && ($name eq 'lonID') &&
663: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
664: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
665: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
666: $$domref = $possudom;
667: }
668: }
669: return undef;
670: }
1.916 albertel 671:
1.917 albertel 672: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
673: return undef if (!$opened);
1.916 albertel 674:
675: flock($idf,LOCK_SH);
676: my %disk_env;
677: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
678: &GDBM_READER(),0640)) {
679: return undef;
680: }
681:
682: if (!defined($disk_env{'user.name'})
683: || !defined($disk_env{'user.domain'})) {
1.1172.2.107 raeburn 684: untie(%disk_env);
1.916 albertel 685: return undef;
686: }
1.1172.2.18 raeburn 687:
1.1172.2.36 raeburn 688: if (ref($userhashref) eq 'HASH') {
689: $userhashref->{'name'} = $disk_env{'user.name'};
690: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 691: }
1.1172.2.107 raeburn 692: untie(%disk_env);
1.1172.2.18 raeburn 693:
1.916 albertel 694: return $handle;
695: }
696:
1.830 albertel 697: sub timed_flock {
698: my ($file,$lock_type) = @_;
699: my $failed=0;
700: eval {
701: local $SIG{__DIE__}='DEFAULT';
702: local $SIG{ALRM}=sub {
703: $failed=1;
704: die("failed lock");
705: };
706: alarm(13);
707: flock($file,$lock_type);
708: alarm(0);
709: };
710: if ($failed) {
711: return undef;
712: } else {
713: return 1;
714: }
715: }
716:
1.1172.2.107 raeburn 717: sub get_sessionfile_vars {
718: my ($handle,$lonidsdir,$storearr) = @_;
719: my %returnhash;
720: unless (ref($storearr) eq 'ARRAY') {
721: return %returnhash;
722: }
723: if (-l "$lonidsdir/$handle.id") {
724: my $link = readlink("$lonidsdir/$handle.id");
725: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
726: $handle = $1;
727: }
728: }
729: if ((-e "$lonidsdir/$handle.id") &&
730: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
731: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
732: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
733: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
734: flock($idf,LOCK_SH);
735: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
736: &GDBM_READER(),0640)) {
737: foreach my $item (@{$storearr}) {
738: $returnhash{$item} = $disk_env{$item};
739: }
740: untie(%disk_env);
741: }
742: }
743: }
744: }
745: return %returnhash;
746: }
747:
1.5 www 748: # ---------------------------------------------------------- Append Environment
749:
750: sub appenv {
1.949 raeburn 751: my ($newenv,$roles) = @_;
752: if (ref($newenv) eq 'HASH') {
753: foreach my $key (keys(%{$newenv})) {
754: my $refused = 0;
755: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
756: $refused = 1;
757: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 758: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 759: if (grep(/^\Q$role\E$/,@{$roles})) {
760: $refused = 0;
761: }
762: }
763: }
764: if ($refused) {
765: &logthis("<font color=\"blue\">WARNING: ".
766: "Attempt to modify environment ".$key." to ".$newenv->{$key}
767: .'</font>');
768: delete($newenv->{$key});
769: } else {
770: $env{$key}=$newenv->{$key};
771: }
772: }
1.1172.2.96 raeburn 773: my $lonids = $perlvar{'lonIDsDir'};
774: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
775: my $opened = open(my $env_file,'+<',$env{'user.environment'});
776: if ($opened
777: && &timed_flock($env_file,LOCK_EX)
778: &&
779: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
780: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
781: while (my ($key,$value) = each(%{$newenv})) {
782: $disk_env{$key} = $value;
783: }
784: untie(%disk_env);
785: }
1.35 www 786: }
1.191 harris41 787: }
1.56 www 788: return 'ok';
789: }
790: # ----------------------------------------------------- Delete from Environment
791:
792: sub delenv {
1.1104 raeburn 793: my ($delthis,$regexp,$roles) = @_;
794: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
795: my $refused = 1;
796: if (ref($roles) eq 'ARRAY') {
797: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
798: if (grep(/^\Q$role\E$/,@{$roles})) {
799: $refused = 0;
800: }
801: }
802: if ($refused) {
803: &logthis("<font color=\"blue\">WARNING: ".
804: "Attempt to delete from environment ".$delthis);
805: return 'error';
806: }
1.56 www 807: }
1.917 albertel 808: my $opened = open(my $env_file,'+<',$env{'user.environment'});
809: if ($opened
1.915 albertel 810: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 811: &&
812: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
813: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 814: foreach my $key (keys(%disk_env)) {
1.987 raeburn 815: if ($regexp) {
816: if ($key=~/^$delthis/) {
817: delete($env{$key});
818: delete($disk_env{$key});
819: }
820: } else {
821: if ($key=~/^\Q$delthis\E/) {
822: delete($env{$key});
823: delete($disk_env{$key});
824: }
825: }
1.448 albertel 826: }
1.783 albertel 827: untie(%disk_env);
1.5 www 828: }
829: return 'ok';
1.369 albertel 830: }
831:
1.790 albertel 832: sub get_env_multiple {
833: my ($name) = @_;
834: my @values;
835: if (defined($env{$name})) {
836: # exists is it an array
837: if (ref($env{$name})) {
838: @values=@{ $env{$name} };
839: } else {
840: $values[0]=$env{$name};
841: }
842: }
843: return(@values);
844: }
845:
1.958 www 846: # ------------------------------------------------------------------- Locking
847:
848: sub set_lock {
849: my ($text)=@_;
850: $locknum++;
851: my $id=$$.'-'.$locknum;
852: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
853: 'session.lock.'.$id => $text});
854: return $id;
855: }
856:
857: sub get_locks {
858: my $num=0;
859: my %texts=();
860: foreach my $lock (split(/\,/,$env{'session.locks'})) {
861: if ($lock=~/\w/) {
862: $num++;
863: $texts{$lock}=$env{'session.lock.'.$lock};
864: }
865: }
866: return ($num,%texts);
867: }
868:
869: sub remove_lock {
870: my ($id)=@_;
871: my $newlocks='';
872: foreach my $lock (split(/\,/,$env{'session.locks'})) {
873: if (($lock=~/\w/) && ($lock ne $id)) {
874: $newlocks.=','.$lock;
875: }
876: }
877: &appenv({'session.locks' => $newlocks});
878: &delenv('session.lock.'.$id);
879: }
880:
881: sub remove_all_locks {
882: my $activelocks=$env{'session.locks'};
883: foreach my $lock (split(/\,/,$env{'session.locks'})) {
884: if ($lock=~/\w/) {
885: &remove_lock($lock);
886: }
887: }
888: }
889:
890:
1.369 albertel 891: # ------------------------------------------ Find out current server userload
892: sub userload {
893: my $numusers=0;
894: {
895: opendir(LONIDS,$perlvar{'lonIDsDir'});
896: my $filename;
897: my $curtime=time;
898: while ($filename=readdir(LONIDS)) {
1.925 albertel 899: next if ($filename eq '.' || $filename eq '..');
900: next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112 raeburn 901: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 902: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 903: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 904: }
905: closedir(LONIDS);
906: }
907: my $userloadpercent=0;
908: my $maxuserload=$perlvar{'lonUserLoadLim'};
909: if ($maxuserload) {
1.371 albertel 910: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 911: }
1.372 albertel 912: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 913: return $userloadpercent;
1.283 www 914: }
915:
1.1 albertel 916: # ------------------------------ Find server with least workload from spare.tab
1.11 www 917:
1.1 albertel 918: sub spareserver {
1.1083 raeburn 919: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 920: my $spare_server;
1.370 albertel 921: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 922: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
923: : $userloadpercent;
1.1083 raeburn 924: my ($uint_dom,$remotesessions);
925: if (($udom ne '') && (&domain($udom) ne '')) {
926: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
927: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
928: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
929: $remotesessions = $udomdefaults{'remotesessions'};
930: }
1.1123 raeburn 931: my $spareshash = &this_host_spares($udom);
932: if (ref($spareshash) eq 'HASH') {
933: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 935: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
936: $try_server));
1.1123 raeburn 937: ($spare_server, $lowest_load) =
938: &compare_server_load($try_server, $spare_server, $lowest_load);
939: }
1.1083 raeburn 940: }
1.784 albertel 941:
1.1123 raeburn 942: my $found_server = ($spare_server ne '' && $lowest_load < 100);
943:
944: if (!$found_server) {
945: if (ref($spareshash->{'default'}) eq 'ARRAY') {
946: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 947: next unless (&spare_can_host($udom,$uint_dom,
948: $remotesessions,$try_server));
1.1123 raeburn 949: ($spare_server, $lowest_load) =
950: &compare_server_load($try_server, $spare_server, $lowest_load);
951: }
952: }
953: }
1.784 albertel 954: }
955:
956: if (!$want_server_name) {
1.1001 raeburn 957: if (defined($spare_server)) {
958: my $hostname = &hostname($spare_server);
1.1083 raeburn 959: if (defined($hostname)) {
1.1172.2.120 raeburn 960: my $protocol = 'http';
961: if ($protocol{$spare_server} eq 'https') {
962: $protocol = $protocol{$spare_server};
963: }
1.1001 raeburn 964: $spare_server = $protocol.'://'.$hostname;
965: }
966: }
1.784 albertel 967: }
968: return $spare_server;
969: }
970:
971: sub compare_server_load {
1.1172.2.41 raeburn 972: my ($try_server, $spare_server, $lowest_load, $required) = @_;
973:
974: if ($required) {
975: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
976: my $remoterev = &get_server_loncaparev(undef,$try_server);
977: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
978: if (($major eq '' && $minor eq '') ||
979: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
980: return ($spare_server,$lowest_load);
981: }
982: }
1.784 albertel 983:
984: my $loadans = &reply('load', $try_server);
985: my $userloadans = &reply('userload',$try_server);
986:
987: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 988: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 989: }
990:
991: my $load;
992: if ($loadans =~ /\d/) {
993: if ($userloadans =~ /\d/) {
994: #both are numbers, pick the bigger one
995: $load = ($loadans > $userloadans) ? $loadans
996: : $userloadans;
1.411 albertel 997: } else {
1.784 albertel 998: $load = $loadans;
1.411 albertel 999: }
1.784 albertel 1000: } else {
1001: $load = $userloadans;
1002: }
1003:
1004: if (($load =~ /\d/) && ($load < $lowest_load)) {
1005: $spare_server = $try_server;
1006: $lowest_load = $load;
1.370 albertel 1007: }
1.784 albertel 1008: return ($spare_server,$lowest_load);
1.202 matthew 1009: }
1.914 albertel 1010:
1011: # --------------------------- ask offload servers if user already has a session
1012: sub find_existing_session {
1013: my ($udom,$uname) = @_;
1.1123 raeburn 1014: my $spareshash = &this_host_spares($udom);
1015: if (ref($spareshash) eq 'HASH') {
1016: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1017: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1018: return $try_server if (&has_user_session($try_server, $udom, $uname));
1019: }
1020: }
1021: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1022: foreach my $try_server (@{ $spareshash->{'default'} }) {
1023: return $try_server if (&has_user_session($try_server, $udom, $uname));
1024: }
1025: }
1.914 albertel 1026: }
1027: return;
1028: }
1029:
1.1172.2.107 raeburn 1030: # check if user's browser sent load balancer cookie and server still has session
1031: # and is not overloaded.
1032: sub check_for_balancer_cookie {
1033: my ($r,$update_mtime) = @_;
1034: my ($otherserver,$cookie);
1035: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1036: if (exists($cookies{'balanceID'})) {
1037: my $balid = $cookies{'balanceID'};
1038: $cookie=&LONCAPA::clean_handle($balid->value);
1039: my $balancedir=$r->dir_config('lonBalanceDir');
1040: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1041: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1042: my ($possudom,$possuname) = ($1,$2);
1043: my $has_session = 0;
1044: if ((&domain($possudom) ne '') &&
1045: (&homeserver($possuname,$possudom) ne 'no_host')) {
1046: my $try_server;
1047: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1048: if ($opened) {
1049: flock($idf,LOCK_SH);
1050: while (my $line = <$idf>) {
1051: chomp($line);
1052: if (&hostname($line) ne '') {
1053: $try_server = $line;
1054: last;
1055: }
1056: }
1057: close($idf);
1058: if (($try_server) &&
1059: (&has_user_session($try_server,$possudom,$possuname))) {
1060: my $lowest_load = 30000;
1061: ($otherserver,$lowest_load) =
1062: &compare_server_load($try_server,undef,$lowest_load);
1063: if ($otherserver ne '' && $lowest_load < 100) {
1064: $has_session = 1;
1065: } else {
1066: undef($otherserver);
1067: }
1068: }
1069: }
1070: }
1071: if ($has_session) {
1072: if ($update_mtime) {
1073: my $atime = my $mtime = time;
1074: utime($atime,$mtime,"$balancedir/$cookie.id");
1075: }
1076: } else {
1077: unlink("$balancedir/$cookie.id");
1078: }
1079: }
1080: }
1081: }
1082: return ($otherserver,$cookie);
1083: }
1084:
1085: sub delbalcookie {
1086: my ($cookie,$balancer) =@_;
1087: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1088: my ($udom,$uname) = ($1,$2);
1089: my $uprimary_id = &domain($udom,'primary');
1090: my $uintdom = &internet_dom($uprimary_id);
1091: my $intdom = &internet_dom($balancer);
1092: my $serverhomedom = &host_domain($balancer);
1093: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1094: return &reply("delbalcookie:$cookie",$balancer);
1095: }
1096: }
1097: }
1098:
1.914 albertel 1099: # -------------------------------- ask if server already has a session for user
1100: sub has_user_session {
1101: my ($lonid,$udom,$uname) = @_;
1102: my $result = &reply(join(':','userhassession',
1103: map {&escape($_)} ($udom,$uname)),$lonid);
1104: return 1 if ($result eq 'ok');
1105:
1106: return 0;
1107: }
1108:
1.1076 raeburn 1109: # --------- determine least loaded server in a user's domain which allows login
1110:
1111: sub choose_server {
1.1172.2.47 raeburn 1112: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1113: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1114: my %servers = &get_servers($udom);
1.1076 raeburn 1115: my $lowest_load = 30000;
1.1172.2.47 raeburn 1116: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1117: if ($skiploadbal) {
1118: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1119: unless (defined($cached)) {
1120: my $cachetime = 60*60*24;
1121: my %domconfig =
1122: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1123: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1124: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1125: $cachetime);
1126: }
1127: }
1128: }
1.1076 raeburn 1129: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 1130: my $loginvia;
1.1172.2.47 raeburn 1131: if ($skiploadbal) {
1132: if (ref($balancers) eq 'HASH') {
1133: next if (exists($balancers->{$lonhost}));
1134: }
1135: }
1.1115 raeburn 1136: if ($checkloginvia) {
1137: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1138: if ($loginvia) {
1139: my ($server,$path) = split(/:/,$loginvia);
1140: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1141: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1142: if ($login_host eq $server) {
1143: $portal_path = $path;
1.1151 raeburn 1144: $isredirect = 1;
1.1116 raeburn 1145: }
1146: } else {
1147: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1148: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1149: if ($login_host eq $lonhost) {
1150: $portal_path = '';
1.1151 raeburn 1151: $isredirect = '';
1.1116 raeburn 1152: }
1153: }
1154: } else {
1.1076 raeburn 1155: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1156: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1157: }
1158: }
1159: if ($login_host ne '') {
1.1116 raeburn 1160: $hostname = &hostname($login_host);
1.1076 raeburn 1161: }
1.1172.2.88 raeburn 1162: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1163: }
1164:
1.202 matthew 1165: # --------------------------------------------- Try to change a user's password
1166:
1167: sub changepass {
1.799 raeburn 1168: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1169: $currentpass = &escape($currentpass);
1170: $newpass = &escape($newpass);
1.1030 raeburn 1171: my $lonhost = $perlvar{'lonHostID'};
1172: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1173: $server);
1174: if (! $answer) {
1175: &logthis("No reply on password change request to $server ".
1176: "by $uname in domain $udom.");
1177: } elsif ($answer =~ "^ok") {
1178: &logthis("$uname in $udom successfully changed their password ".
1179: "on $server.");
1180: } elsif ($answer =~ "^pwchange_failure") {
1181: &logthis("$uname in $udom was unable to change their password ".
1182: "on $server. The action was blocked by either lcpasswd ".
1183: "or pwchange");
1184: } elsif ($answer =~ "^non_authorized") {
1185: &logthis("$uname in $udom did not get their password correct when ".
1186: "attempting to change it on $server.");
1187: } elsif ($answer =~ "^auth_mode_error") {
1188: &logthis("$uname in $udom attempted to change their password despite ".
1189: "not being locally or internally authenticated on $server.");
1190: } elsif ($answer =~ "^unknown_user") {
1191: &logthis("$uname in $udom attempted to change their password ".
1192: "on $server but were unable to because $server is not ".
1193: "their home server.");
1194: } elsif ($answer =~ "^refused") {
1195: &logthis("$server refused to change $uname in $udom password because ".
1196: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1197: } elsif ($answer =~ "invalid_client") {
1198: &logthis("$server refused to change $uname in $udom password because ".
1199: "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113 raeburn 1200: } elsif ($answer =~ "^prioruse") {
1201: &logthis("$server refused to change $uname in $udom password because ".
1202: "the password had been used before");
1.202 matthew 1203: }
1204: return $answer;
1.1 albertel 1205: }
1206:
1.169 harris41 1207: # ----------------------- Try to determine user's current authentication scheme
1208:
1209: sub queryauthenticate {
1210: my ($uname,$udom)=@_;
1.456 albertel 1211: my $uhome=&homeserver($uname,$udom);
1212: if (!$uhome) {
1213: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1214: return 'no_host';
1215: }
1216: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1217: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1218: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1219: }
1.456 albertel 1220: return $answer;
1.169 harris41 1221: }
1222:
1.1 albertel 1223: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1224:
1.1 albertel 1225: sub authenticate {
1.1073 raeburn 1226: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1227: $upass=&escape($upass);
1228: $uname= &LONCAPA::clean_username($uname);
1.836 www 1229: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1230: my $newhome;
1.836 www 1231: if ((!$uhome) || ($uhome eq 'no_host')) {
1232: # Maybe the machine was offline and only re-appeared again recently?
1233: &reconlonc();
1234: # One more
1.952 raeburn 1235: $uhome=&homeserver($uname,$udom,1);
1236: if (($uhome eq 'no_host') && $checkdefauth) {
1237: if (defined(&domain($udom,'primary'))) {
1238: $newhome=&domain($udom,'primary');
1239: }
1240: if ($newhome ne '') {
1241: $uhome = $newhome;
1242: }
1243: }
1.836 www 1244: if ((!$uhome) || ($uhome eq 'no_host')) {
1245: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1246: return 'no_host';
1247: }
1.1 albertel 1248: }
1.1073 raeburn 1249: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1250: if ($answer eq 'authorized') {
1.952 raeburn 1251: if ($newhome) {
1252: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1253: return 'no_account_on_host';
1254: } else {
1255: &logthis("User $uname at $udom authorized by $uhome");
1256: return $uhome;
1257: }
1.471 albertel 1258: }
1259: if ($answer eq 'non_authorized') {
1260: &logthis("User $uname at $udom rejected by $uhome");
1261: return 'no_host';
1.9 www 1262: }
1.471 albertel 1263: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1264: return 'no_host';
1265: }
1266:
1.1073 raeburn 1267: sub can_host_session {
1.1074 raeburn 1268: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1269: my $canhost = 1;
1.1074 raeburn 1270: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1271: if (ref($remotesessions) eq 'HASH') {
1272: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1273: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1274: $canhost = 0;
1275: } else {
1276: $canhost = 1;
1277: }
1278: }
1279: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1280: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1281: $canhost = 1;
1282: } else {
1283: $canhost = 0;
1284: }
1285: }
1286: if ($canhost) {
1287: if ($remotesessions->{'version'} ne '') {
1288: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1289: if ($reqmajor ne '' && $reqminor ne '') {
1290: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1291: my $major = $1;
1292: my $minor = $2;
1293: if (($major < $reqmajor ) ||
1294: (($major == $reqmajor) && ($minor < $reqminor))) {
1295: $canhost = 0;
1296: }
1297: } else {
1298: $canhost = 0;
1299: }
1300: }
1301: }
1302: }
1303: }
1304: if ($canhost) {
1305: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1306: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1307: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1308: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1309: if (($uint_dom ne '') &&
1310: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1311: $canhost = 0;
1312: } else {
1313: $canhost = 1;
1314: }
1315: }
1316: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1317: if (($uint_dom ne '') &&
1318: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1319: $canhost = 1;
1320: } else {
1321: $canhost = 0;
1322: }
1323: }
1324: }
1325: }
1326: return $canhost;
1327: }
1328:
1.1083 raeburn 1329: sub spare_can_host {
1330: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1331: my $canhost=1;
1.1172.2.62 raeburn 1332: my $try_server_hostname = &hostname($try_server);
1333: my $serverhomeID = &get_server_homeID($try_server_hostname);
1334: my $serverhomedom = &host_domain($serverhomeID);
1335: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1336: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1337: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1338: $canhost = 0;
1339: }
1340: }
1341: if (($canhost) && ($uint_dom)) {
1342: my @intdoms;
1343: my $internet_names = &get_internet_names($try_server);
1344: if (ref($internet_names) eq 'ARRAY') {
1345: @intdoms = @{$internet_names};
1346: }
1347: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1348: my $remoterev = &get_server_loncaparev(undef,$try_server);
1349: $canhost = &can_host_session($udom,$try_server,$remoterev,
1350: $remotesessions,
1351: $defdomdefaults{'hostedsessions'});
1352: }
1.1083 raeburn 1353: }
1354: return $canhost;
1355: }
1356:
1.1123 raeburn 1357: sub this_host_spares {
1358: my ($dom) = @_;
1.1126 raeburn 1359: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1360: my @hosts = ¤t_machine_ids();
1361: foreach my $lonhost (@hosts) {
1362: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1363: $dom_in_use = $dom;
1364: $lonhost_in_use = $lonhost;
1.1123 raeburn 1365: last;
1366: }
1367: }
1.1126 raeburn 1368: if ($dom_in_use ne '') {
1369: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1370: }
1371: if (ref($result) ne 'HASH') {
1372: $lonhost_in_use = $perlvar{'lonHostID'};
1373: $dom_in_use = &host_domain($lonhost_in_use);
1374: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1375: if (ref($result) ne 'HASH') {
1376: $result = \%spareid;
1377: }
1378: }
1379: return $result;
1380: }
1381:
1382: sub spares_for_offload {
1383: my ($dom_in_use,$lonhost_in_use) = @_;
1384: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1385: if (defined($cached)) {
1386: return $result;
1387: } else {
1.1126 raeburn 1388: my $cachetime = 60*60*24;
1389: my %domconfig =
1390: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1391: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1392: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1393: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1394: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1395: }
1396: }
1397: }
1398: }
1.1126 raeburn 1399: return;
1.1123 raeburn 1400: }
1401:
1.1129 raeburn 1402: sub get_lonbalancer_config {
1403: my ($servers) = @_;
1404: my ($currbalancer,$currtargets);
1405: if (ref($servers) eq 'HASH') {
1406: foreach my $server (keys(%{$servers})) {
1407: my %what = (
1408: spareid => 1,
1409: perlvar => 1,
1410: );
1411: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1412: if ($result eq 'ok') {
1413: if (ref($returnhash) eq 'HASH') {
1414: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1415: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1416: $currbalancer = $server;
1417: $currtargets = {};
1418: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1419: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1420: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1421: }
1422: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1423: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1424: }
1425: }
1426: last;
1427: }
1428: }
1429: }
1430: }
1431: }
1432: }
1433: return ($currbalancer,$currtargets);
1434: }
1435:
1436: sub check_loadbalancing {
1.1172.2.88 raeburn 1437: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1438: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107 raeburn 1439: $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129 raeburn 1440: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1441: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1442: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1443: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1444: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1445: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1446: my $domneedscache;
1.1129 raeburn 1447: my $cachetime = 60*60*24;
1448:
1449: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1450: $dom_in_use = $udom;
1451: $homeintdom = 1;
1452: } else {
1453: $dom_in_use = $serverhomedom;
1454: }
1455: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1456: unless (defined($cached)) {
1457: my %domconfig =
1458: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1459: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1460: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1461: } else {
1462: $domneedscache = $dom_in_use;
1.1129 raeburn 1463: }
1464: }
1465: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1466: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1467: &check_balancer_result($result,@hosts);
1.1129 raeburn 1468: if ($is_balancer) {
1469: if (ref($currrules) eq 'HASH') {
1470: if ($homeintdom) {
1471: if ($uname ne '') {
1472: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1473: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1474: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1475: $rule_in_effect = $currrules->{'_LC_author'};
1476: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1477: $rule_in_effect = $currrules->{'_LC_adv'}
1478: }
1479: }
1480: if ($rule_in_effect eq '') {
1481: my %userenv = &userenvironment($udom,$uname,'inststatus');
1482: if ($userenv{'inststatus'} ne '') {
1483: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1484: my ($othertitle,$usertypes,$types) =
1485: &Apache::loncommon::sorted_inst_types($udom);
1486: if (ref($types) eq 'ARRAY') {
1487: foreach my $type (@{$types}) {
1488: if (grep(/^\Q$type\E$/,@statuses)) {
1489: if (exists($currrules->{$type})) {
1490: $rule_in_effect = $currrules->{$type};
1491: }
1492: }
1493: }
1494: }
1495: } else {
1496: if (exists($currrules->{'default'})) {
1497: $rule_in_effect = $currrules->{'default'};
1498: }
1499: }
1500: }
1501: } else {
1502: if (exists($currrules->{'default'})) {
1503: $rule_in_effect = $currrules->{'default'};
1504: }
1505: }
1506: } else {
1507: if ($currrules->{'_LC_external'} ne '') {
1508: $rule_in_effect = $currrules->{'_LC_external'};
1509: }
1510: }
1511: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1512: $uname,$udom);
1513: }
1514: }
1515: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1516: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1517: unless (defined($cached)) {
1518: my %domconfig =
1519: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1520: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1521: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1522: } else {
1523: $domneedscache = $serverhomedom;
1.1129 raeburn 1524: }
1525: }
1526: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1527: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1528: &check_balancer_result($result,@hosts);
1529: if ($is_balancer) {
1.1129 raeburn 1530: if (ref($currrules) eq 'HASH') {
1531: if ($currrules->{'_LC_internetdom'} ne '') {
1532: $rule_in_effect = $currrules->{'_LC_internetdom'};
1533: }
1534: }
1535: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1536: $uname,$udom);
1537: }
1538: } else {
1539: if ($perlvar{'lonBalancer'} eq 'yes') {
1540: $is_balancer = 1;
1541: $offloadto = &this_host_spares($dom_in_use);
1542: }
1.1172.2.75 raeburn 1543: unless (defined($cached)) {
1544: $domneedscache = $serverhomedom;
1545: }
1.1129 raeburn 1546: }
1547: } else {
1548: if ($perlvar{'lonBalancer'} eq 'yes') {
1549: $is_balancer = 1;
1550: $offloadto = &this_host_spares($dom_in_use);
1551: }
1.1172.2.75 raeburn 1552: unless (defined($cached)) {
1553: $domneedscache = $serverhomedom;
1554: }
1555: }
1556: if ($domneedscache) {
1557: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1558: }
1.1172.2.5 raeburn 1559: if ($is_balancer) {
1560: my $lowest_load = 30000;
1561: if (ref($offloadto) eq 'HASH') {
1562: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1563: foreach my $try_server (@{$offloadto->{'primary'}}) {
1564: ($otherserver,$lowest_load) =
1565: &compare_server_load($try_server,$otherserver,$lowest_load);
1566: }
1.1129 raeburn 1567: }
1.1172.2.5 raeburn 1568: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1569:
1.1172.2.5 raeburn 1570: if (!$found_server) {
1571: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1572: foreach my $try_server (@{$offloadto->{'default'}}) {
1573: ($otherserver,$lowest_load) =
1574: &compare_server_load($try_server,$otherserver,$lowest_load);
1575: }
1576: }
1577: }
1578: } elsif (ref($offloadto) eq 'ARRAY') {
1579: if (@{$offloadto} == 1) {
1580: $otherserver = $offloadto->[0];
1581: } elsif (@{$offloadto} > 1) {
1582: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1583: ($otherserver,$lowest_load) =
1584: &compare_server_load($try_server,$otherserver,$lowest_load);
1585: }
1586: }
1587: }
1.1172.2.88 raeburn 1588: unless ($caller eq 'login') {
1589: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1590: $is_balancer = 0;
1591: if ($uname ne '' && $udom ne '') {
1592: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1593: &appenv({'user.loadbalexempt' => $lonhost,
1594: 'user.loadbalcheck.time' => time});
1595: }
1.1172.2.5 raeburn 1596: }
1.1129 raeburn 1597: }
1598: }
1.1172.2.107 raeburn 1599: unless ($homeintdom) {
1600: undef($setcookie);
1601: }
1.1129 raeburn 1602: }
1.1172.2.107 raeburn 1603: return ($is_balancer,$otherserver,$setcookie);
1.1129 raeburn 1604: }
1605:
1.1172.2.12 raeburn 1606: sub check_balancer_result {
1607: my ($result,@hosts) = @_;
1.1172.2.107 raeburn 1608: my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1609: if (ref($result) eq 'HASH') {
1610: if ($result->{'lonhost'} ne '') {
1611: my $currbalancer = $result->{'lonhost'};
1612: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1613: $is_balancer = 1;
1614: $currtargets = $result->{'targets'};
1615: $currrules = $result->{'rules'};
1616: }
1617: } else {
1618: foreach my $key (keys(%{$result})) {
1619: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1620: (ref($result->{$key}) eq 'HASH')) {
1621: $is_balancer = 1;
1622: $currrules = $result->{$key}{'rules'};
1623: $currtargets = $result->{$key}{'targets'};
1.1172.2.107 raeburn 1624: $setcookie = $result->{$key}{'cookie'};
1.1172.2.12 raeburn 1625: last;
1626: }
1627: }
1628: }
1629: }
1.1172.2.107 raeburn 1630: return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1631: }
1632:
1.1129 raeburn 1633: sub get_loadbalancer_targets {
1634: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1635: my $offloadto;
1.1172.2.4 raeburn 1636: if ($rule_in_effect eq 'none') {
1637: return [$perlvar{'lonHostID'}];
1638: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1639: $offloadto = $currtargets;
1640: } else {
1641: if ($rule_in_effect eq 'homeserver') {
1642: my $homeserver = &homeserver($uname,$udom);
1643: if ($homeserver ne 'no_host') {
1644: $offloadto = [$homeserver];
1645: }
1646: } elsif ($rule_in_effect eq 'externalbalancer') {
1647: my %domconfig =
1648: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1649: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1650: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1651: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1652: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1653: }
1654: }
1655: } else {
1.1172.2.7 raeburn 1656: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1657: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1658: if (&hostname($remotebalancer) ne '') {
1659: $offloadto = [$remotebalancer];
1660: }
1661: }
1662: } elsif (&hostname($rule_in_effect) ne '') {
1663: $offloadto = [$rule_in_effect];
1664: }
1665: }
1666: return $offloadto;
1667: }
1668:
1.1127 raeburn 1669: sub internet_dom_servers {
1670: my ($dom) = @_;
1671: my (%uniqservers,%servers);
1672: my $primaryserver = &hostname(&domain($dom,'primary'));
1673: my @machinedoms = &machine_domains($primaryserver);
1674: foreach my $mdom (@machinedoms) {
1675: my %currservers = %servers;
1676: my %server = &get_servers($mdom);
1677: %servers = (%currservers,%server);
1678: }
1679: my %by_hostname;
1680: foreach my $id (keys(%servers)) {
1681: push(@{$by_hostname{$servers{$id}}},$id);
1682: }
1683: foreach my $hostname (sort(keys(%by_hostname))) {
1684: if (@{$by_hostname{$hostname}} > 1) {
1685: my $match = 0;
1686: foreach my $id (@{$by_hostname{$hostname}}) {
1687: if (&host_domain($id) eq $dom) {
1688: $uniqservers{$id} = $hostname;
1689: $match = 1;
1690: }
1691: }
1692: unless ($match) {
1693: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1694: }
1695: } else {
1696: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1697: }
1698: }
1699: return %uniqservers;
1700: }
1701:
1.1 albertel 1702: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1703:
1.599 albertel 1704: my %homecache;
1.1 albertel 1705: sub homeserver {
1.230 stredwic 1706: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1707: my $index="$uname:$udom";
1.426 albertel 1708:
1.599 albertel 1709: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1710:
1711: my %servers = &get_servers($udom,'library');
1712: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1713: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1714: exists($badServerCache{$tryserver}));
1.841 albertel 1715:
1716: my $answer=reply("home:$udom:$uname",$tryserver);
1717: if ($answer eq 'found') {
1718: delete($badServerCache{$tryserver});
1719: return $homecache{$index}=$tryserver;
1720: } elsif ($answer eq 'no_host') {
1721: $badServerCache{$tryserver}=1;
1722: }
1.1 albertel 1723: }
1724: return 'no_host';
1.70 www 1725: }
1726:
1727: # ------------------------------------- Find the usernames behind a list of IDs
1728:
1729: sub idget {
1730: my ($udom,@ids)=@_;
1731: my %returnhash=();
1732:
1.841 albertel 1733: my %servers = &get_servers($udom,'library');
1734: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1735: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1736: $idlist=~tr/A-Z/a-z/;
1737: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1738: my @answer=();
1739: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1740: @answer=split(/\&/,$reply);
1741: } ;
1742: my $i;
1743: for ($i=0;$i<=$#ids;$i++) {
1744: if ($answer[$i]) {
1.1172.2.73 raeburn 1745: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1746: }
1747: }
1748: }
1.70 www 1749: return %returnhash;
1750: }
1751:
1752: # ------------------------------------- Find the IDs behind a list of usernames
1753:
1754: sub idrget {
1755: my ($udom,@unames)=@_;
1756: my %returnhash=();
1.800 albertel 1757: foreach my $uname (@unames) {
1758: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1759: }
1.70 www 1760: return %returnhash;
1761: }
1762:
1763: # ------------------------------- Store away a list of names and associated IDs
1764:
1765: sub idput {
1766: my ($udom,%ids)=@_;
1767: my %servers=();
1.800 albertel 1768: foreach my $uname (keys(%ids)) {
1769: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1770: my $uhom=&homeserver($uname,$udom);
1.70 www 1771: if ($uhom ne 'no_host') {
1.800 albertel 1772: my $id=&escape($ids{$uname});
1.70 www 1773: $id=~tr/A-Z/a-z/;
1.800 albertel 1774: my $esc_unam=&escape($uname);
1.70 www 1775: if ($servers{$uhom}) {
1.800 albertel 1776: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1777: } else {
1.800 albertel 1778: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1779: }
1780: }
1.191 harris41 1781: }
1.800 albertel 1782: foreach my $server (keys(%servers)) {
1783: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1784: }
1.344 www 1785: }
1786:
1.1172.2.30 raeburn 1787: # ---------------------------------------- Delete unwanted IDs from ids.db file
1788:
1789: sub iddel {
1790: my ($udom,$idshashref,$uhome)=@_;
1791: my %result=();
1792: unless (ref($idshashref) eq 'HASH') {
1793: return %result;
1794: }
1795: my %servers=();
1796: while (my ($id,$uname) = each(%{$idshashref})) {
1797: my $uhom;
1798: if ($uhome) {
1799: $uhom = $uhome;
1800: } else {
1801: $uhom=&homeserver($uname,$udom);
1802: }
1803: if ($uhom ne 'no_host') {
1804: if ($servers{$uhom}) {
1805: $servers{$uhom}.='&'.&escape($id);
1806: } else {
1807: $servers{$uhom}=&escape($id);
1808: }
1809: }
1810: }
1811: foreach my $server (keys(%servers)) {
1812: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1813: }
1814: return %result;
1815: }
1816:
1.1023 raeburn 1817: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1818: sub dump_dom {
1.1165 droeschl 1819: my ($namespace, $udom, $regexp) = @_;
1820:
1821: $udom ||= $env{'user.domain'};
1822:
1823: return () unless $udom;
1824:
1825: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1826: }
1827:
1.1023 raeburn 1828: # ------------------------------------------ get items from domain db files
1.806 raeburn 1829:
1830: sub get_dom {
1.860 raeburn 1831: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1832: return if ($udom eq 'public');
1.806 raeburn 1833: my $items='';
1834: foreach my $item (@$storearr) {
1835: $items.=&escape($item).'&';
1836: }
1837: $items=~s/\&$//;
1.860 raeburn 1838: if (!$udom) {
1839: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1840: return if ($udom eq 'public');
1.860 raeburn 1841: if (defined(&domain($udom,'primary'))) {
1842: $uhome=&domain($udom,'primary');
1843: } else {
1.874 albertel 1844: undef($uhome);
1.860 raeburn 1845: }
1846: } else {
1847: if (!$uhome) {
1848: if (defined(&domain($udom,'primary'))) {
1849: $uhome=&domain($udom,'primary');
1850: }
1851: }
1852: }
1853: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1854: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1855: my %returnhash;
1.875 albertel 1856: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1857: return %returnhash;
1858: }
1.806 raeburn 1859: my @pairs=split(/\&/,$rep);
1860: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1861: return @pairs;
1862: }
1863: my $i=0;
1864: foreach my $item (@$storearr) {
1865: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1866: $i++;
1867: }
1868: return %returnhash;
1869: } else {
1.880 banghart 1870: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1871: }
1872: }
1873:
1874: # -------------------------------------------- put items in domain db files
1875:
1876: sub put_dom {
1.860 raeburn 1877: my ($namespace,$storehash,$udom,$uhome)=@_;
1878: if (!$udom) {
1879: $udom=$env{'user.domain'};
1880: if (defined(&domain($udom,'primary'))) {
1881: $uhome=&domain($udom,'primary');
1882: } else {
1.874 albertel 1883: undef($uhome);
1.860 raeburn 1884: }
1885: } else {
1886: if (!$uhome) {
1887: if (defined(&domain($udom,'primary'))) {
1888: $uhome=&domain($udom,'primary');
1889: }
1890: }
1891: }
1892: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1893: my $items='';
1894: foreach my $item (keys(%$storehash)) {
1895: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1896: }
1897: $items=~s/\&$//;
1898: return &reply("putdom:$udom:$namespace:$items",$uhome);
1899: } else {
1.860 raeburn 1900: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1901: }
1902: }
1903:
1.1023 raeburn 1904: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1905: sub newput_dom {
1.1023 raeburn 1906: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1907: my $result;
1908: if (!$udom) {
1909: $udom=$env{'user.domain'};
1910: }
1.1023 raeburn 1911: if ($udom) {
1912: my $uname = &get_domainconfiguser($udom);
1913: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1914: }
1915: return $result;
1916: }
1917:
1.1023 raeburn 1918: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1919: sub del_dom {
1.1023 raeburn 1920: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1921: if (ref($storearr) eq 'ARRAY') {
1922: if (!$udom) {
1923: $udom=$env{'user.domain'};
1924: }
1.1023 raeburn 1925: if ($udom) {
1926: my $uname = &get_domainconfiguser($udom);
1927: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1928: }
1929: }
1930: }
1931:
1.1023 raeburn 1932: # ----------------------------------construct domainconfig user for a domain
1933: sub get_domainconfiguser {
1934: my ($udom) = @_;
1935: return $udom.'-domainconfig';
1936: }
1937:
1.837 raeburn 1938: sub retrieve_inst_usertypes {
1939: my ($udom) = @_;
1940: my (%returnhash,@order);
1.989 raeburn 1941: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1942: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1943: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1944: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1945: } else {
1946: if (defined(&domain($udom,'primary'))) {
1947: my $uhome=&domain($udom,'primary');
1948: my $rep=&reply("inst_usertypes:$udom",$uhome);
1949: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1950: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1951: return (\%returnhash,\@order);
1952: }
1953: my ($hashitems,$orderitems) = split(/:/,$rep);
1954: my @pairs=split(/\&/,$hashitems);
1955: foreach my $item (@pairs) {
1956: my ($key,$value)=split(/=/,$item,2);
1957: $key = &unescape($key);
1958: next if ($key =~ /^error: 2 /);
1959: $returnhash{$key}=&thaw_unescape($value);
1960: }
1961: my @esc_order = split(/\&/,$orderitems);
1962: foreach my $item (@esc_order) {
1963: push(@order,&unescape($item));
1964: }
1965: } else {
1.1172.2.44 raeburn 1966: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1967: }
1.1172.2.44 raeburn 1968: return (\%returnhash,\@order);
1.837 raeburn 1969: }
1970: }
1971:
1.868 raeburn 1972: sub is_domainimage {
1973: my ($url) = @_;
1.1172.2.74 raeburn 1974: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1975: if (&domain($1) ne '') {
1976: return '1';
1977: }
1978: }
1979: return;
1980: }
1981:
1.899 raeburn 1982: sub inst_directory_query {
1983: my ($srch) = @_;
1984: my $udom = $srch->{'srchdomain'};
1985: my %results;
1986: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1987: my $outcome;
1.899 raeburn 1988: if ($homeserver ne '') {
1.1172.2.116 raeburn 1989: unless ($homeserver eq $perlvar{'lonHostID'}) {
1990: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 1991: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116 raeburn 1992: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1993: if (($major eq '' && $minor eq '') || ($major < 2) ||
1994: (($major == 2) && ($minor < 11)) ||
1995: (($major == 2) && ($minor == 11) && ($subver < 3))) {
1996: return;
1997: }
1998: }
1999: }
1.904 albertel 2000: my $queryid=&reply("querysend:instdirsearch:".
2001: &escape($srch->{'srchby'}).':'.
2002: &escape($srch->{'srchterm'}).':'.
2003: &escape($srch->{'srchtype'}),$homeserver);
2004: my $host=&hostname($homeserver);
2005: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96 raeburn 2006: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2007: return;
2008: }
2009: my $response = &get_query_reply($queryid);
2010: my $maxtries = 5;
2011: my $tries = 1;
2012: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2013: $response = &get_query_reply($queryid);
2014: $tries ++;
2015: }
2016:
2017: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2018: if ($response eq 'unavailable') {
2019: $outcome = $response;
2020: } else {
2021: $outcome = 'ok';
2022: my @matches = split(/\n/,$response);
2023: foreach my $match (@matches) {
2024: my ($key,$value) = split(/=/,$match);
2025: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2026: }
1.899 raeburn 2027: }
2028: }
2029: }
1.909 raeburn 2030: return ($outcome,%results);
1.899 raeburn 2031: }
2032:
2033: sub usersearch {
2034: my ($srch) = @_;
2035: my $dom = $srch->{'srchdomain'};
2036: my %results;
2037: my %libserv = &all_library();
2038: my $query = 'usersearch';
2039: foreach my $tryserver (keys(%libserv)) {
2040: if (&host_domain($tryserver) eq $dom) {
1.1172.2.116 raeburn 2041: unless ($tryserver eq $perlvar{'lonHostID'}) {
2042: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2043: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119 raeburn 2044: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116 raeburn 2045: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2046: (($major == 2) && ($minor < 11)) ||
2047: (($major == 2) && ($minor == 11) && ($subver < 3)));
2048: }
2049: }
1.899 raeburn 2050: my $host=&hostname($tryserver);
2051: my $queryid=
1.911 raeburn 2052: &reply("querysend:".&escape($query).':'.
2053: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2054: &escape($srch->{'srchtype'}).':'.
2055: &escape($srch->{'srchterm'}),$tryserver);
2056: if ($queryid !~/^\Q$host\E\_/) {
2057: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2058: next;
1.899 raeburn 2059: }
2060: my $reply = &get_query_reply($queryid);
2061: my $maxtries = 1;
2062: my $tries = 1;
2063: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2064: $reply = &get_query_reply($queryid);
2065: $tries ++;
2066: }
2067: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2068: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2069: } else {
1.911 raeburn 2070: my @matches;
2071: if ($reply =~ /\n/) {
2072: @matches = split(/\n/,$reply);
2073: } else {
2074: @matches = split(/\&/,$reply);
2075: }
1.899 raeburn 2076: foreach my $match (@matches) {
2077: my ($uname,$udom,%userhash);
1.911 raeburn 2078: foreach my $entry (split(/:/,$match)) {
2079: my ($key,$value) =
2080: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2081: $userhash{$key} = $value;
2082: if ($key eq 'username') {
2083: $uname = $value;
2084: } elsif ($key eq 'domain') {
2085: $udom = $value;
1.911 raeburn 2086: }
1.899 raeburn 2087: }
2088: $results{$uname.':'.$udom} = \%userhash;
2089: }
2090: }
2091: }
2092: }
2093: return %results;
2094: }
2095:
1.912 raeburn 2096: sub get_instuser {
2097: my ($udom,$uname,$id) = @_;
2098: my $homeserver = &domain($udom,'primary');
2099: my ($outcome,%results);
2100: if ($homeserver ne '') {
2101: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2102: &escape($id).':'.&escape($udom),$homeserver);
2103: my $host=&hostname($homeserver);
2104: if ($queryid !~/^\Q$host\E\_/) {
2105: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2106: return;
2107: }
2108: my $response = &get_query_reply($queryid);
2109: my $maxtries = 5;
2110: my $tries = 1;
2111: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2112: $response = &get_query_reply($queryid);
2113: $tries ++;
2114: }
2115: if (!&error($response) && $response ne 'refused') {
2116: if ($response eq 'unavailable') {
2117: $outcome = $response;
2118: } else {
2119: $outcome = 'ok';
2120: my @matches = split(/\n/,$response);
2121: foreach my $match (@matches) {
2122: my ($key,$value) = split(/=/,$match);
2123: $results{&unescape($key)} = &thaw_unescape($value);
2124: }
2125: }
2126: }
2127: }
2128: my %userinfo;
2129: if (ref($results{$uname}) eq 'HASH') {
2130: %userinfo = %{$results{$uname}};
2131: }
2132: return ($outcome,%userinfo);
2133: }
2134:
1.1172.2.69 raeburn 2135: sub get_multiple_instusers {
2136: my ($udom,$users,$caller) = @_;
2137: my ($outcome,$results);
2138: if (ref($users) eq 'HASH') {
2139: my $count = keys(%{$users});
2140: my $requested = &freeze_escape($users);
2141: my $homeserver = &domain($udom,'primary');
2142: if ($homeserver ne '') {
2143: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2144: my $host=&hostname($homeserver);
2145: if ($queryid !~/^\Q$host\E\_/) {
2146: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2147: ' for host: '.$homeserver.'in domain '.$udom);
2148: return ($outcome,$results);
2149: }
2150: my $response = &get_query_reply($queryid);
2151: my $maxtries = 5;
2152: if ($count > 100) {
2153: $maxtries = 1+int($count/20);
2154: }
2155: my $tries = 1;
2156: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2157: $response = &get_query_reply($queryid);
2158: $tries ++;
2159: }
2160: if ($response eq '') {
2161: $results = {};
2162: foreach my $key (keys(%{$users})) {
2163: my ($uname,$id);
2164: if ($caller eq 'id') {
2165: $id = $key;
2166: } else {
2167: $uname = $key;
2168: }
2169: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2170: $outcome = $resp;
2171: if ($resp eq 'ok') {
2172: %{$results} = (%{$results}, %info);
2173: } else {
2174: last;
2175: }
2176: }
2177: } elsif(!&error($response) && ($response ne 'refused')) {
2178: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2179: $outcome = $response;
2180: } else {
2181: ($outcome,my $userdata) = split(/=/,$response,2);
2182: if ($outcome eq 'ok') {
2183: $results = &thaw_unescape($userdata);
2184: }
2185: }
2186: }
2187: }
2188: }
2189: return ($outcome,$results);
2190: }
2191:
1.912 raeburn 2192: sub inst_rulecheck {
1.923 raeburn 2193: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2194: my %returnhash;
2195: if ($udom ne '') {
2196: if (ref($rules) eq 'ARRAY') {
2197: @{$rules} = map {&escape($_);} (@{$rules});
2198: my $rulestr = join(':',@{$rules});
2199: my $homeserver=&domain($udom,'primary');
2200: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2201: my $response;
2202: if ($item eq 'username') {
2203: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2204: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2205: $homeserver));
1.923 raeburn 2206: } elsif ($item eq 'id') {
2207: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2208: ':'.&escape($id).':'.$rulestr,
2209: $homeserver));
1.945 raeburn 2210: } elsif ($item eq 'selfcreate') {
2211: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2212: &escape($udom).':'.&escape($uname).
2213: ':'.$rulestr,$homeserver));
1.923 raeburn 2214: }
1.912 raeburn 2215: if ($response ne 'refused') {
2216: my @pairs=split(/\&/,$response);
2217: foreach my $item (@pairs) {
2218: my ($key,$value)=split(/=/,$item,2);
2219: $key = &unescape($key);
2220: next if ($key =~ /^error: 2 /);
2221: $returnhash{$key}=&thaw_unescape($value);
2222: }
2223: }
2224: }
2225: }
2226: }
2227: return %returnhash;
2228: }
2229:
2230: sub inst_userrules {
1.923 raeburn 2231: my ($udom,$check) = @_;
1.912 raeburn 2232: my (%ruleshash,@ruleorder);
2233: if ($udom ne '') {
2234: my $homeserver=&domain($udom,'primary');
2235: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2236: my $response;
2237: if ($check eq 'id') {
2238: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2239: $homeserver);
1.943 raeburn 2240: } elsif ($check eq 'email') {
2241: $response=&reply('instemailrules:'.&escape($udom),
2242: $homeserver);
1.923 raeburn 2243: } else {
2244: $response=&reply('instuserrules:'.&escape($udom),
2245: $homeserver);
2246: }
1.912 raeburn 2247: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2248: ($response ne 'unknown_cmd') &&
1.912 raeburn 2249: ($response ne 'no_such_host')) {
2250: my ($hashitems,$orderitems) = split(/:/,$response);
2251: my @pairs=split(/\&/,$hashitems);
2252: foreach my $item (@pairs) {
2253: my ($key,$value)=split(/=/,$item,2);
2254: $key = &unescape($key);
2255: next if ($key =~ /^error: 2 /);
2256: $ruleshash{$key}=&thaw_unescape($value);
2257: }
2258: my @esc_order = split(/\&/,$orderitems);
2259: foreach my $item (@esc_order) {
2260: push(@ruleorder,&unescape($item));
2261: }
2262: }
2263: }
2264: }
2265: return (\%ruleshash,\@ruleorder);
2266: }
2267:
1.976 raeburn 2268: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2269:
2270: sub get_domain_defaults {
1.1172.2.35 raeburn 2271: my ($domain,$ignore_cache) = @_;
2272: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2273: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2274: unless ($ignore_cache) {
2275: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2276: if (defined($cached)) {
2277: if (ref($result) eq 'HASH') {
2278: return %{$result};
2279: }
1.943 raeburn 2280: }
2281: }
2282: my %domdefaults;
2283: my %domconfig =
1.989 raeburn 2284: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2285: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2286: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2287: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2288: 'coursecategories','autoenroll',
2289: 'helpsettings'],$domain);
1.1172.2.41 raeburn 2290: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2291: if (ref($domconfig{'defaults'}) eq 'HASH') {
2292: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2293: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2294: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2295: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2296: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2297: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2298: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2299: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2300: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2301: } else {
2302: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2303: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2304: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2305: }
1.976 raeburn 2306: if (ref($domconfig{'quotas'}) eq 'HASH') {
2307: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2308: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2309: } else {
2310: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2311: }
1.1172.2.6 raeburn 2312: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2313: foreach my $item (@usertools) {
2314: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2315: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2316: }
2317: }
1.1172.2.29 raeburn 2318: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2319: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2320: }
1.976 raeburn 2321: }
1.985 raeburn 2322: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2323: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2324: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2325: }
2326: }
1.1172.2.9 raeburn 2327: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2328: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2329: }
1.989 raeburn 2330: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2331: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2332: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2333: }
2334: }
1.1047 raeburn 2335: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2336: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2337: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2338: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2339: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2340: }
1.1172.2.41 raeburn 2341: foreach my $type (@coursetypes) {
2342: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2343: unless ($type eq 'community') {
2344: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2345: }
2346: }
2347: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2348: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2349: }
1.1172.2.60 raeburn 2350: if ($domdefaults{'postsubmit'} eq 'on') {
2351: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2352: $domdefaults{$type.'postsubtimeout'} =
2353: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2354: }
2355: }
1.1172.2.30 raeburn 2356: }
1.1172.2.67 raeburn 2357: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2358: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2359: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2360: if (@clonecodes) {
2361: $domdefaults{'canclone'} = join('+',@clonecodes);
2362: }
2363: }
2364: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2365: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2366: }
1.1172.2.103 raeburn 2367: if ($domconfig{'coursedefaults'}{'texengine'}) {
2368: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2369: }
1.1047 raeburn 2370: }
1.1073 raeburn 2371: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2372: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2373: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2374: }
2375: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2376: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2377: }
1.1172.2.62 raeburn 2378: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2379: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2380: }
1.1073 raeburn 2381: }
1.1172.2.41 raeburn 2382: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2383: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2384: my @settings = ('types','registered','enroll_dates','access_dates','section',
2385: 'approval','limit');
2386: foreach my $type (@coursetypes) {
2387: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2388: my @mgrdc = ();
2389: foreach my $item (@settings) {
2390: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2391: push(@mgrdc,$item);
2392: }
2393: }
2394: if (@mgrdc) {
2395: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2396: }
2397: }
2398: }
2399: }
2400: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2401: foreach my $type (@coursetypes) {
2402: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2403: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2404: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2405: }
2406: }
2407: }
2408: }
2409: }
1.1172.2.46 raeburn 2410: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2411: $domdefaults{'catauth'} = 'std';
2412: $domdefaults{'catunauth'} = 'std';
2413: if ($domconfig{'coursecategories'}{'auth'}) {
2414: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2415: }
2416: if ($domconfig{'coursecategories'}{'unauth'}) {
2417: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2418: }
2419: }
1.1172.2.76 raeburn 2420: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2421: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2422: }
1.1172.2.89 raeburn 2423: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2424: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2425: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2426: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2427: }
2428: }
1.1172.2.23 raeburn 2429: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2430: return %domdefaults;
2431: }
2432:
1.1172.2.106 raeburn 2433: sub get_dom_cats {
2434: my ($dom) = @_;
2435: return unless (&domain($dom));
2436: my ($cats,$cached)=&is_cached_new('cats',$dom);
2437: unless (defined($cached)) {
2438: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2439: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2440: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2441: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2442: } else {
2443: $cats = {};
2444: }
2445: } else {
2446: $cats = {};
2447: }
2448: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2449: }
2450: return $cats;
2451: }
2452:
2453: sub get_dom_instcats {
2454: my ($dom) = @_;
2455: return unless (&domain($dom));
2456: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2457: unless (defined($cached)) {
2458: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2459: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2460: if ($totcodes > 0) {
2461: my $caller = 'global';
2462: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2463: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2464: $instcats = {
2465: codes => \%codes,
2466: codetitles => \@codetitles,
2467: cat_titles => \%cat_titles,
2468: cat_order => \%cat_order,
2469: };
2470: &do_cache_new('instcats',$dom,$instcats,3600);
2471: }
2472: }
2473: }
2474: return $instcats;
2475: }
2476:
2477: sub retrieve_instcodes {
2478: my ($coursecodes,$dom) = @_;
2479: my $totcodes;
2480: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2481: foreach my $course (keys(%courses)) {
2482: if (ref($courses{$course}) eq 'HASH') {
2483: if ($courses{$course}{'inst_code'} ne '') {
2484: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2485: $totcodes ++;
2486: }
2487: }
2488: }
2489: return $totcodes;
2490: }
2491:
1.1172.2.113 raeburn 2492: # --------------------------------------------- Get domain config for passwords
2493:
2494: sub get_passwdconf {
2495: my ($dom) = @_;
2496: my (%passwdconf,$gotconf,$lookup);
2497: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2498: if (defined($cached)) {
2499: if (ref($result) eq 'HASH') {
2500: %passwdconf = %{$result};
2501: $gotconf = 1;
2502: }
2503: }
2504: unless ($gotconf) {
2505: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2506: if (ref($domconfig{'passwords'}) eq 'HASH') {
2507: %passwdconf = %{$domconfig{'passwords'}};
2508: }
2509: my $cachetime = 24*60*60;
2510: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2511: }
2512: return %passwdconf;
2513: }
2514:
1.344 www 2515: # --------------------------------------------------- Assign a key to a student
2516:
2517: sub assign_access_key {
1.364 www 2518: #
2519: # a valid key looks like uname:udom#comments
2520: # comments are being appended
2521: #
1.498 www 2522: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2523: $kdom=
1.620 albertel 2524: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2525: $knum=
1.620 albertel 2526: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2527: $cdom=
1.620 albertel 2528: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2529: $cnum=
1.620 albertel 2530: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2531: $udom=$env{'user.name'} unless (defined($udom));
2532: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2533: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2534: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2535: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2536: # assigned to this person
2537: # - this should not happen,
1.345 www 2538: # unless something went wrong
2539: # the first time around
2540: # ready to assign
1.364 www 2541: $logentry=$1.'; '.$logentry;
1.496 www 2542: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2543: $kdom,$knum) eq 'ok') {
1.345 www 2544: # key now belongs to user
1.346 www 2545: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2546: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2547: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2548: return 'ok';
2549: } else {
2550: return
2551: 'error: Count not permanently assign key, will need to be re-entered later.';
2552: }
2553: } else {
2554: return 'error: Could not assign key, try again later.';
2555: }
1.364 www 2556: } elsif (!$existing{$ckey}) {
1.345 www 2557: # the key does not exist
2558: return 'error: The key does not exist';
2559: } else {
2560: # the key is somebody else's
2561: return 'error: The key is already in use';
2562: }
1.344 www 2563: }
2564:
1.364 www 2565: # ------------------------------------------ put an additional comment on a key
2566:
2567: sub comment_access_key {
2568: #
2569: # a valid key looks like uname:udom#comments
2570: # comments are being appended
2571: #
2572: my ($ckey,$cdom,$cnum,$logentry)=@_;
2573: $cdom=
1.620 albertel 2574: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2575: $cnum=
1.620 albertel 2576: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2577: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2578: if ($existing{$ckey}) {
2579: $existing{$ckey}.='; '.$logentry;
2580: # ready to assign
1.367 www 2581: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2582: $cdom,$cnum) eq 'ok') {
2583: return 'ok';
2584: } else {
2585: return 'error: Count not store comment.';
2586: }
2587: } else {
2588: # the key does not exist
2589: return 'error: The key does not exist';
2590: }
2591: }
2592:
1.344 www 2593: # ------------------------------------------------------ Generate a set of keys
2594:
2595: sub generate_access_keys {
1.364 www 2596: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2597: $cdom=
1.620 albertel 2598: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2599: $cnum=
1.620 albertel 2600: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2601: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2602: unless (($cdom) && ($cnum)) { return 0; }
2603: if ($number>10000) { return 0; }
2604: sleep(2); # make sure don't get same seed twice
2605: srand(time()^($$+($$<<15))); # from "Programming Perl"
2606: my $total=0;
2607: for (my $i=1;$i<=$number;$i++) {
2608: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2609: sprintf("%lx",int(100000*rand)).'-'.
2610: sprintf("%lx",int(100000*rand));
2611: $newkey=~s/1/g/g; # folks mix up 1 and l
2612: $newkey=~s/0/h/g; # and also 0 and O
2613: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2614: if ($existing{$newkey}) {
2615: $i--;
2616: } else {
1.364 www 2617: if (&put('accesskeys',
2618: { $newkey => '# generated '.localtime().
1.620 albertel 2619: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2620: '; '.$logentry },
2621: $cdom,$cnum) eq 'ok') {
1.344 www 2622: $total++;
2623: }
2624: }
2625: }
1.620 albertel 2626: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2627: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2628: return $total;
2629: }
2630:
2631: # ------------------------------------------------------- Validate an accesskey
2632:
2633: sub validate_access_key {
2634: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2635: $cdom=
1.620 albertel 2636: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2637: $cnum=
1.620 albertel 2638: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2639: $udom=$env{'user.domain'} unless (defined($udom));
2640: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2641: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2642: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2643: }
2644:
2645: # ------------------------------------- Find the section of student in a course
1.652 albertel 2646: sub devalidate_getsection_cache {
2647: my ($udom,$unam,$courseid)=@_;
2648: my $hashid="$udom:$unam:$courseid";
2649: &devalidate_cache_new('getsection',$hashid);
2650: }
1.298 matthew 2651:
1.815 albertel 2652: sub courseid_to_courseurl {
2653: my ($courseid) = @_;
2654: #already url style courseid
2655: return $courseid if ($courseid =~ m{^/});
2656:
2657: if (exists($env{'course.'.$courseid.'.num'})) {
2658: my $cnum = $env{'course.'.$courseid.'.num'};
2659: my $cdom = $env{'course.'.$courseid.'.domain'};
2660: return "/$cdom/$cnum";
2661: }
2662:
2663: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2664: if (exists($courseinfo{'num'})) {
2665: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2666: }
2667:
2668: return undef;
2669: }
2670:
1.298 matthew 2671: sub getsection {
2672: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2673: my $cachetime=1800;
1.551 albertel 2674:
2675: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2676: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2677: if (defined($cached)) { return $result; }
2678:
1.298 matthew 2679: my %Pending;
2680: my %Expired;
2681: #
2682: # Each role can either have not started yet (pending), be active,
2683: # or have expired.
2684: #
2685: # If there is an active role, we are done.
2686: #
2687: # If there is more than one role which has not started yet,
2688: # choose the one which will start sooner
2689: # If there is one role which has not started yet, return it.
2690: #
2691: # If there is more than one expired role, choose the one which ended last.
2692: # If there is a role which has expired, return it.
2693: #
1.815 albertel 2694: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2695: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2696: foreach my $key (keys(%roleshash)) {
1.479 albertel 2697: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2698: my $section=$1;
2699: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2700: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2701: my $now=time;
1.548 albertel 2702: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2703: $Expired{$end}=$section;
2704: next;
2705: }
1.548 albertel 2706: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2707: $Pending{$start}=$section;
2708: next;
2709: }
1.599 albertel 2710: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2711: }
2712: #
2713: # Presumedly there will be few matching roles from the above
2714: # loop and the sorting time will be negligible.
2715: if (scalar(keys(%Pending))) {
2716: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2717: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2718: }
2719: if (scalar(keys(%Expired))) {
2720: my @sorted = sort {$a <=> $b} keys(%Expired);
2721: my $time = pop(@sorted);
1.599 albertel 2722: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2723: }
1.599 albertel 2724: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2725: }
1.70 www 2726:
1.599 albertel 2727: sub save_cache {
2728: &purge_remembered();
1.722 albertel 2729: #&Apache::loncommon::validate_page();
1.620 albertel 2730: undef(%env);
1.780 albertel 2731: undef($env_loaded);
1.599 albertel 2732: }
1.452 albertel 2733:
1.599 albertel 2734: my $to_remember=-1;
2735: my %remembered;
2736: my %accessed;
2737: my $kicks=0;
2738: my $hits=0;
1.849 albertel 2739: sub make_key {
2740: my ($name,$id) = @_;
1.872 albertel 2741: if (length($id) > 65
2742: && length(&escape($id)) > 200) {
2743: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2744: }
1.849 albertel 2745: return &escape($name.':'.$id);
2746: }
2747:
1.599 albertel 2748: sub devalidate_cache_new {
2749: my ($name,$id,$debug) = @_;
2750: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2751: my $remembered_id=$name.':'.$id;
1.849 albertel 2752: $id=&make_key($name,$id);
1.599 albertel 2753: $memcache->delete($id);
1.1172.2.81 raeburn 2754: delete($remembered{$remembered_id});
2755: delete($accessed{$remembered_id});
1.599 albertel 2756: }
2757:
2758: sub is_cached_new {
2759: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2760: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2761: # keys in %remembered hash, which persists for
2762: # duration of request (no restriction on key length).
2763: if (exists($remembered{$remembered_id})) {
2764: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2765: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2766: $hits++;
1.1172.2.81 raeburn 2767: return ($remembered{$remembered_id},1);
1.599 albertel 2768: }
1.1172.2.81 raeburn 2769: $id=&make_key($name,$id);
1.599 albertel 2770: my $value = $memcache->get($id);
2771: if (!(defined($value))) {
2772: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2773: return (undef,undef);
1.416 albertel 2774: }
1.599 albertel 2775: if ($value eq '__undef__') {
2776: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2777: $value=undef;
2778: }
1.1172.2.81 raeburn 2779: &make_room($remembered_id,$value,$debug);
1.599 albertel 2780: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2781: return ($value,1);
2782: }
2783:
2784: sub do_cache_new {
2785: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2786: my $remembered_id=$name.':'.$id;
1.849 albertel 2787: $id=&make_key($name,$id);
1.599 albertel 2788: my $setvalue=$value;
2789: if (!defined($setvalue)) {
2790: $setvalue='__undef__';
2791: }
1.623 albertel 2792: if (!defined($time) ) {
2793: $time=600;
2794: }
1.599 albertel 2795: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2796: my $result = $memcache->set($id,$setvalue,$time);
2797: if (! $result) {
1.872 albertel 2798: &logthis("caching of id -> $id failed");
1.910 albertel 2799: $memcache->disconnect_all();
1.872 albertel 2800: }
1.600 albertel 2801: # need to make a copy of $value
1.1172.2.81 raeburn 2802: &make_room($remembered_id,$value,$debug);
1.599 albertel 2803: return $value;
2804: }
2805:
2806: sub make_room {
1.1172.2.81 raeburn 2807: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2808:
1.1172.2.81 raeburn 2809: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2810: : $value;
1.599 albertel 2811: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2812: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2813: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2814: my $to_kick;
2815: my $max_time=0;
2816: foreach my $other (keys(%accessed)) {
2817: if (&tv_interval($accessed{$other}) > $max_time) {
2818: $to_kick=$other;
2819: $max_time=&tv_interval($accessed{$other});
2820: }
2821: }
2822: delete($remembered{$to_kick});
2823: delete($accessed{$to_kick});
2824: $kicks++;
2825: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2826: return;
2827: }
2828:
1.599 albertel 2829: sub purge_remembered {
1.604 albertel 2830: #&logthis("Tossing ".scalar(keys(%remembered)));
2831: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2832: undef(%remembered);
2833: undef(%accessed);
1.428 albertel 2834: }
1.70 www 2835: # ------------------------------------- Read an entry from a user's environment
2836:
2837: sub userenvironment {
2838: my ($udom,$unam,@what)=@_;
1.976 raeburn 2839: my $items;
2840: foreach my $item (@what) {
2841: $items.=&escape($item).'&';
2842: }
2843: $items=~s/\&$//;
1.70 www 2844: my %returnhash=();
1.1009 raeburn 2845: my $uhome = &homeserver($unam,$udom);
2846: unless ($uhome eq 'no_host') {
2847: my @answer=split(/\&/,
2848: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2849: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2850: return %returnhash;
2851: }
1.1009 raeburn 2852: my $i;
2853: for ($i=0;$i<=$#what;$i++) {
2854: $returnhash{$what[$i]}=&unescape($answer[$i]);
2855: }
1.70 www 2856: }
2857: return %returnhash;
1.1 albertel 2858: }
2859:
1.617 albertel 2860: # ---------------------------------------------------------- Get a studentphoto
2861: sub studentphoto {
2862: my ($udom,$unam,$ext) = @_;
2863: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2864: if (defined($env{'request.course.id'})) {
1.708 raeburn 2865: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2866: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2867: return(&retrievestudentphoto($udom,$unam,$ext));
2868: } else {
2869: my ($result,$perm_reqd)=
1.707 albertel 2870: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2871: if ($result eq 'ok') {
2872: if (!($perm_reqd eq 'yes')) {
2873: return(&retrievestudentphoto($udom,$unam,$ext));
2874: }
2875: }
2876: }
2877: }
2878: } else {
2879: my ($result,$perm_reqd) =
1.707 albertel 2880: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2881: if ($result eq 'ok') {
2882: if (!($perm_reqd eq 'yes')) {
2883: return(&retrievestudentphoto($udom,$unam,$ext));
2884: }
2885: }
2886: }
2887: return '/adm/lonKaputt/lonlogo_broken.gif';
2888: }
2889:
2890: sub retrievestudentphoto {
2891: my ($udom,$unam,$ext,$type) = @_;
2892: my $home=&Apache::lonnet::homeserver($unam,$udom);
2893: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2894: if ($ret eq 'ok') {
2895: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2896: if ($type eq 'thumbnail') {
2897: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2898: }
2899: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2900: return $tokenurl;
2901: } else {
2902: if ($type eq 'thumbnail') {
2903: return '/adm/lonKaputt/genericstudent_tn.gif';
2904: } else {
2905: return '/adm/lonKaputt/lonlogo_broken.gif';
2906: }
1.617 albertel 2907: }
2908: }
2909:
1.263 www 2910: # -------------------------------------------------------------------- New chat
2911:
2912: sub chatsend {
1.724 raeburn 2913: my ($newentry,$anon,$group)=@_;
1.620 albertel 2914: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2915: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2916: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2917: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2918: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2919: &escape($newentry)).':'.$group,$chome);
1.292 www 2920: }
2921:
2922: # ------------------------------------------ Find current version of a resource
2923:
2924: sub getversion {
2925: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2926: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2927: return ¤tversion(&filelocation('',$fname));
2928: }
2929:
2930: sub currentversion {
2931: my $fname=shift;
2932: my $author=$fname;
2933: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2934: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2935: my $home=&homeserver($uname,$udom);
1.292 www 2936: if ($home eq 'no_host') {
2937: return -1;
2938: }
1.1112 www 2939: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2940: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2941: return -1;
2942: }
1.1112 www 2943: return $answer;
1.263 www 2944: }
2945:
1.1111 www 2946: #
2947: # Return special version number of resource if set by override, empty otherwise
2948: #
2949: sub usedversion {
2950: my $fname=shift;
2951: unless ($fname) { $fname=$env{'request.uri'}; }
2952: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2953: if ($urlversion) { return $urlversion; }
2954: return '';
2955: }
2956:
1.1 albertel 2957: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2958:
1.1 albertel 2959: sub subscribe {
2960: my $fname=shift;
1.761 raeburn 2961: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2962: $fname=~s/[\n\r]//g;
1.1 albertel 2963: my $author=$fname;
2964: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2965: my ($udom,$uname)=split(/\//,$author);
2966: my $home=homeserver($uname,$udom);
1.335 albertel 2967: if ($home eq 'no_host') {
2968: return 'not_found';
1.1 albertel 2969: }
2970: my $answer=reply("sub:$fname",$home);
1.64 www 2971: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2972: $answer.=' by '.$home;
2973: }
1.1 albertel 2974: return $answer;
2975: }
2976:
1.8 www 2977: # -------------------------------------------------------------- Replicate file
2978:
2979: sub repcopy {
2980: my $filename=shift;
1.23 www 2981: $filename=~s/\/+/\//g;
1.1142 raeburn 2982: my $londocroot = $perlvar{'lonDocRoot'};
2983: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2984: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2985: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2986: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2987: return &repcopy_userfile($filename);
2988: }
1.532 albertel 2989: $filename=~s/[\n\r]//g;
1.8 www 2990: my $transname="$filename.in.transfer";
1.828 www 2991: # FIXME: this should flock
1.607 raeburn 2992: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2993: my $remoteurl=subscribe($filename);
1.64 www 2994: if ($remoteurl =~ /^con_lost by/) {
2995: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2996: return 'unavailable';
1.8 www 2997: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2998: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2999: return 'not_found';
1.64 www 3000: } elsif ($remoteurl =~ /^rejected by/) {
3001: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3002: return 'forbidden';
1.20 www 3003: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3004: return 'ok';
1.8 www 3005: } else {
1.290 www 3006: my $author=$filename;
3007: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3008: my ($udom,$uname)=split(/\//,$author);
3009: my $home=homeserver($uname,$udom);
3010: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3011: my @parts=split(/\//,$filename);
3012: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3013: if ($path ne "$londocroot/res") {
1.8 www 3014: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3015: return 'bad_request';
1.8 www 3016: }
3017: my $count;
3018: for ($count=5;$count<$#parts;$count++) {
3019: $path.="/$parts[$count]";
3020: if ((-e $path)!=1) {
3021: mkdir($path,0777);
3022: }
3023: }
3024: my $ua=new LWP::UserAgent;
3025: my $request=new HTTP::Request('GET',"$remoteurl");
3026: my $response=$ua->request($request,$transname);
3027: if ($response->is_error()) {
3028: unlink($transname);
3029: my $message=$response->status_line;
1.672 albertel 3030: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3031: ." LWP get: $message: $filename</font>");
1.607 raeburn 3032: return 'unavailable';
1.8 www 3033: } else {
1.16 www 3034: if ($remoteurl!~/\.meta$/) {
3035: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3036: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3037: if ($mresponse->is_error()) {
3038: unlink($filename.'.meta');
3039: &logthis(
1.672 albertel 3040: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3041: }
3042: }
1.8 www 3043: rename($transname,$filename);
1.607 raeburn 3044: return 'ok';
1.8 www 3045: }
1.290 www 3046: }
1.8 www 3047: }
1.330 www 3048: }
3049:
3050: # ------------------------------------------------ Get server side include body
3051: sub ssi_body {
1.381 albertel 3052: my ($filelink,%form)=@_;
1.606 matthew 3053: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3054: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3055: }
1.953 www 3056: my $output='';
3057: my $response;
1.980 raeburn 3058: if ($filelink=~/^https?\:/) {
1.954 raeburn 3059: ($output,$response)=&externalssi($filelink);
1.953 www 3060: } else {
1.1004 droeschl 3061: $filelink .= $filelink=~/\?/ ? '&' : '?';
3062: $filelink .= 'inhibitmenu=yes';
1.953 www 3063: ($output,$response)=&ssi($filelink,%form);
3064: }
1.778 albertel 3065: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3066: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3067: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3068: if (wantarray) {
3069: return ($output, $response);
3070: } else {
3071: return $output;
3072: }
1.8 www 3073: }
3074:
1.15 www 3075: # --------------------------------------------------------- Server Side Include
3076:
1.782 albertel 3077: sub absolute_url {
3078: my ($host_name) = @_;
3079: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3080: if ($host_name eq '') {
3081: $host_name = $ENV{'SERVER_NAME'};
3082: }
3083: return $protocol.$host_name;
3084: }
3085:
1.942 foxr 3086: #
3087: # Server side include.
3088: # Parameters:
3089: # fn Possibly encrypted resource name/id.
3090: # form Hash that describes how the rendering should be done
3091: # and other things.
1.944 foxr 3092: # Returns:
1.950 raeburn 3093: # Scalar context: The content of the response.
3094: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3095: #
1.15 www 3096: sub ssi {
3097:
1.944 foxr 3098: my ($fn,%form)=@_;
1.1172.2.100 raeburn 3099: my ($request,$response);
1.711 albertel 3100:
3101: $form{'no_update_last_known'}=1;
1.895 albertel 3102: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3103: if (%form) {
1.782 albertel 3104: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 3105: $request->content(join('&',map {
3106: my $name = escape($_);
3107: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3108: ? join("&$name=", map {escape($_) } @{$form{$_}})
3109: : &escape($form{$_}) );
3110: } keys(%form)));
1.23 www 3111: } else {
1.782 albertel 3112: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3113: }
3114:
1.15 www 3115: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100 raeburn 3116:
1.1172.2.101 raeburn 3117: if (($env{'request.course.id'}) &&
3118: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3119: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3120: ($form{'grade_symb'} ne '') &&
3121: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3122: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100 raeburn 3123: if (LWP::UserAgent->VERSION >= 5.834) {
3124: my $ua=new LWP::UserAgent;
3125: $ua->local_address('127.0.0.1');
3126: $response = $ua->request($request);
3127: } else {
3128: {
3129: require LWP::Protocol::http;
3130: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3131: my $ua=new LWP::UserAgent;
3132: $response = $ua->request($request);
3133: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3134: }
3135: }
3136: } else {
3137: my $ua=new LWP::UserAgent;
3138: $response = $ua->request($request);
3139: }
1.944 foxr 3140: if (wantarray) {
1.1172.2.3 raeburn 3141: return ($response->content, $response);
1.944 foxr 3142: } else {
1.1172.2.3 raeburn 3143: return $response->content;
1.942 foxr 3144: }
1.324 www 3145: }
3146:
3147: sub externalssi {
3148: my ($url)=@_;
3149: my $ua=new LWP::UserAgent;
3150: my $request=new HTTP::Request('GET',$url);
3151: my $response=$ua->request($request);
1.954 raeburn 3152: if (wantarray) {
3153: return ($response->content, $response);
3154: } else {
3155: return $response->content;
3156: }
1.15 www 3157: }
1.254 www 3158:
1.1172.2.98 raeburn 3159: # If the local copy of a replicated resource is outdated, trigger a
3160: # connection from the homeserver to flush the delayed queue. If no update
3161: # happens, remove local copies of outdated resource (and corresponding
3162: # metadata file).
3163:
3164: sub remove_stale_resfile {
3165: my ($url) = @_;
3166: my $removed;
3167: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3168: my $audom = $1;
3169: my $auname = $2;
3170: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3171: my $homeserver = &homeserver($auname,$audom);
3172: unless (($homeserver eq 'no_host') ||
3173: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3174: my $fname = &filelocation('',$url);
3175: if (-e $fname) {
3176: my $hostname = &hostname($homeserver);
3177: if ($hostname) {
1.1172.2.120 raeburn 3178: my $protocol = $protocol{$homeserver};
3179: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98 raeburn 3180: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120 raeburn 3181: my $ua=new LWP::UserAgent;
3182: $ua->timeout(5);
1.1172.2.98 raeburn 3183: my $request=new HTTP::Request('HEAD',$uri);
3184: my $response=$ua->request($request);
3185: if ($response->is_success()) {
3186: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3187: my $locmodtime = (stat($fname))[9];
3188: if ($locmodtime < $remmodtime) {
3189: my $stale;
3190: my $answer = &reply('pong',$homeserver);
3191: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3192: sleep(0.2);
3193: $locmodtime = (stat($fname))[9];
3194: if ($locmodtime < $remmodtime) {
3195: my $posstransfer = $fname.'.in.transfer';
3196: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3197: $removed = 1;
3198: } else {
3199: $stale = 1;
3200: }
3201: } else {
3202: $removed = 1;
3203: }
3204: } else {
3205: $stale = 1;
3206: }
3207: if ($stale) {
3208: unlink($fname);
3209: if ($uri!~/\.meta$/) {
3210: unlink($fname.'.meta');
3211: }
3212: &reply("unsub:$fname",$homeserver);
3213: $removed = 1;
3214: }
3215: }
3216: }
3217: }
3218: }
3219: }
3220: }
3221: }
3222: return $removed;
3223: }
3224:
1.492 albertel 3225: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3226:
3227: sub allowuploaded {
3228: my ($srcurl,$url)=@_;
3229: $url=&clutter(&declutter($url));
3230: my $dir=$url;
3231: $dir=~s/\/[^\/]+$//;
3232: my %httpref=();
3233: my $httpurl=&hreflocation('',$url);
3234: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3235: &Apache::lonnet::appenv(\%httpref);
1.254 www 3236: }
1.477 raeburn 3237:
1.1172.2.13 raeburn 3238: #
3239: # Determine if the current user should be able to edit a particular resource,
3240: # when viewing in course context.
3241: # (a) When viewing resource used to determine if "Edit" item is included in
3242: # Functions.
3243: # (b) When displaying folder contents in course editor, used to determine if
3244: # "Edit" link will be displayed alongside resource.
3245: #
3246: # input: six args -- filename (decluttered), course number, course domain,
3247: # url, symb (if registered) and group (if this is a group
3248: # item -- e.g., bulletin board, group page etc.).
3249: # output: array of five scalars --
3250: # $cfile -- url for file editing if editable on current server
3251: # $home -- homeserver of resource (i.e., for author if published,
3252: # or course if uploaded.).
3253: # $switchserver -- 1 if server switch will be needed.
3254: # $forceedit -- 1 if icon/link should be to go to edit mode
3255: # $forceview -- 1 if icon/link should be to go to view mode
3256: #
3257:
3258: sub can_edit_resource {
3259: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3260: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3261: #
3262: # For aboutme pages user can only edit his/her own.
3263: #
3264: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3265: my ($sdom,$sname) = ($1,$2);
3266: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3267: $home = $env{'user.home'};
3268: $cfile = $resurl;
3269: if ($env{'form.forceedit'}) {
3270: $forceview = 1;
3271: } else {
3272: $forceedit = 1;
3273: }
3274: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3275: } else {
3276: return;
3277: }
3278: }
3279:
3280: if ($env{'request.course.id'}) {
3281: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3282: if ($group ne '') {
3283: # if this is a group homepage or group bulletin board, check group privs
3284: my $allowed = 0;
3285: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3286: if ((&allowed('mdg',$env{'request.course.id'}.
3287: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3288: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3289: $allowed = 1;
3290: }
3291: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3292: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3293: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3294: $allowed = 1;
3295: }
3296: }
3297: if ($allowed) {
3298: $home=&homeserver($cnum,$cdom);
3299: if ($env{'form.forceedit'}) {
3300: $forceview = 1;
3301: } else {
3302: $forceedit = 1;
3303: }
3304: $cfile = $resurl;
3305: } else {
3306: return;
3307: }
3308: } else {
1.1172.2.15 raeburn 3309: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3310: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3311: return;
3312: }
3313: } elsif (!$crsedit) {
1.1172.2.13 raeburn 3314: #
3315: # No edit allowed where CC has switched to student role.
3316: #
3317: return;
3318: }
3319: }
3320: }
3321:
3322: if ($file ne '') {
3323: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3324: if (&is_course_upload($file,$cnum,$cdom)) {
3325: $uploaded = 1;
3326: $incourse = 1;
3327: if ($file =~/\.(htm|html|css|js|txt)$/) {
3328: $cfile = &hreflocation('',$file);
3329: if ($env{'form.forceedit'}) {
3330: $forceview = 1;
3331: } else {
3332: $forceedit = 1;
3333: }
3334: }
3335: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3336: $incourse = 1;
3337: if ($env{'form.forceedit'}) {
3338: $forceview = 1;
3339: } else {
3340: $forceedit = 1;
3341: }
3342: $cfile = $resurl;
3343: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3344: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3345: $incourse = 1;
3346: if ($env{'form.forceedit'}) {
3347: $forceview = 1;
3348: } else {
3349: $forceedit = 1;
3350: }
3351: $cfile = $resurl;
3352: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3353: $incourse = 1;
3354: $cfile = $resurl.'/smpedit';
3355: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3356: $incourse = 1;
3357: if ($env{'form.forceedit'}) {
3358: $forceview = 1;
3359: } else {
3360: $forceedit = 1;
3361: }
3362: $cfile = $resurl;
1.1172.2.122! raeburn 3363: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
! 3364: my ($map,$id,$res) = &decode_symb($symb);
! 3365: if ($map =~ /\.page$/) {
! 3366: $incourse = 1;
! 3367: if ($env{'form.forceedit'}) {
! 3368: $forceview = 1;
! 3369: $cfile = $map;
! 3370: } else {
! 3371: $forceedit = 1;
! 3372: $cfile = '/adm/wrapper'.$resurl;
! 3373: }
! 3374: }
1.1172.2.15 raeburn 3375: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3376: $incourse = 1;
3377: if ($env{'form.forceedit'}) {
3378: $forceview = 1;
3379: } else {
3380: $forceedit = 1;
3381: }
3382: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3383: }
3384: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3385: my $template = '/res/lib/templates/simpleproblem.problem';
3386: if (&is_on_map($template)) {
3387: $incourse = 1;
3388: $forceview = 1;
3389: $cfile = $template;
3390: }
3391: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118 raeburn 3392: $incourse = 1;
3393: if ($env{'form.forceedit'}) {
3394: $forceview = 1;
3395: } else {
3396: $forceedit = 1;
3397: }
3398: $cfile = $resurl;
1.1172.2.13 raeburn 3399: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3400: $incourse = 1;
3401: $forceview = 1;
3402: if ($symb) {
3403: my ($map,$id,$res)=&decode_symb($symb);
3404: $env{'request.symb'} = $symb;
3405: $cfile = &clutter($res);
3406: } else {
3407: $cfile = $env{'form.suppurl'};
3408: $cfile =~ s{^http://}{};
3409: $cfile = '/adm/wrapper/ext/'.$cfile;
3410: }
1.1172.2.31 raeburn 3411: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3412: if ($env{'form.forceedit'}) {
3413: $forceview = 1;
3414: } else {
3415: $forceedit = 1;
3416: }
3417: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3418: }
3419: }
3420: if ($uploaded || $incourse) {
3421: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3422: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3423: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3424: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3425: # Check that the user has permission to edit this resource
3426: my $setpriv = 1;
3427: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3428: if (defined($cfudom)) {
3429: $home=&homeserver($cfuname,$cfudom);
3430: $cfile=$file;
3431: }
3432: }
3433: if (($cfile ne '') && (!$incourse || $uploaded) &&
3434: (($home ne '') && ($home ne 'no_host'))) {
3435: my @ids=¤t_machine_ids();
3436: unless (grep(/^\Q$home\E$/,@ids)) {
3437: $switchserver=1;
3438: }
3439: }
3440: }
3441: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3442: }
3443:
3444: sub is_course_upload {
3445: my ($file,$cnum,$cdom) = @_;
3446: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3447: $uploadpath =~ s{^\/}{};
3448: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3449: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3450: return 1;
3451: }
3452: return;
3453: }
3454:
3455: sub in_course {
3456: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3457: if ($hideprivileged) {
3458: my $skipuser;
1.1172.2.23 raeburn 3459: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3460: my @possdoms = ($cdom);
3461: if ($coursehash{'checkforpriv'}) {
3462: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3463: }
3464: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3465: $skipuser = 1;
3466: if ($coursehash{'nothideprivileged'}) {
3467: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3468: my $user;
3469: if ($item =~ /:/) {
3470: $user = $item;
3471: } else {
3472: $user = join(':',split(/[\@]/,$item));
3473: }
3474: if ($user eq $uname.':'.$udom) {
3475: undef($skipuser);
3476: last;
3477: }
3478: }
3479: }
3480: if ($skipuser) {
3481: return 0;
3482: }
3483: }
3484: }
3485: $type ||= 'any';
3486: if (!defined($cdom) || !defined($cnum)) {
3487: my $cid = $env{'request.course.id'};
3488: $cdom = $env{'course.'.$cid.'.domain'};
3489: $cnum = $env{'course.'.$cid.'.num'};
3490: }
3491: my $typesref;
3492: if (($type eq 'any') || ($type eq 'all')) {
3493: $typesref = ['active','previous','future'];
3494: } elsif ($type eq 'previous' || $type eq 'future') {
3495: $typesref = [$type];
3496: }
3497: my %roles = &get_my_roles($uname,$udom,'userroles',
3498: $typesref,undef,[$cdom]);
3499: my ($tmp) = keys(%roles);
3500: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3501: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3502: if (@course_roles > 0) {
3503: return 1;
3504: }
3505: return 0;
3506: }
3507:
1.478 albertel 3508: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3509: # input: action, courseID, current domain, intended
1.637 raeburn 3510: # path to file, source of file, instruction to parse file for objects,
3511: # ref to hash for embedded objects,
3512: # ref to hash for codebase of java objects.
1.1095 raeburn 3513: # reference to scalar to accommodate mime type determined
3514: # from File::MMagic if $parser = parse.
1.637 raeburn 3515: #
1.485 raeburn 3516: # output: url to file (if action was uploaddoc),
3517: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3518: #
1.478 albertel 3519: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3520: # course.
1.477 raeburn 3521: #
1.478 albertel 3522: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3523: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3524: # course's home server.
1.477 raeburn 3525: #
1.478 albertel 3526: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3527: # be copied from $source (current location) to
3528: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3529: # and will then be copied to
3530: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3531: # course's home server.
1.485 raeburn 3532: #
1.481 raeburn 3533: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3534: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3535: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3536: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3537: # in course's home server.
1.637 raeburn 3538: #
1.477 raeburn 3539:
3540: sub process_coursefile {
1.1095 raeburn 3541: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3542: $mimetype)=@_;
1.477 raeburn 3543: my $fetchresult;
1.638 albertel 3544: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3545: if ($action eq 'propagate') {
1.638 albertel 3546: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3547: $home);
1.481 raeburn 3548: } else {
1.477 raeburn 3549: my $fpath = '';
3550: my $fname = $file;
1.478 albertel 3551: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3552: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3553: my $filepath = &build_filepath($fpath);
1.481 raeburn 3554: if ($action eq 'copy') {
3555: if ($source eq '') {
3556: $fetchresult = 'no source file';
3557: return $fetchresult;
3558: } else {
3559: my $destination = $filepath.'/'.$fname;
3560: rename($source,$destination);
3561: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3562: $home);
1.481 raeburn 3563: }
3564: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3565: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3566: print $fh $env{'form.'.$source};
1.481 raeburn 3567: close($fh);
1.637 raeburn 3568: if ($parser eq 'parse') {
1.1024 raeburn 3569: my $mm = new File::MMagic;
1.1095 raeburn 3570: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3571: if ($type eq 'text/html') {
1.1024 raeburn 3572: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3573: unless ($parse_result eq 'ok') {
3574: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3575: }
1.637 raeburn 3576: }
1.1095 raeburn 3577: if (ref($mimetype)) {
3578: $$mimetype = $type;
3579: }
1.637 raeburn 3580: }
1.477 raeburn 3581: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3582: $home);
1.481 raeburn 3583: if ($fetchresult eq 'ok') {
3584: return '/uploaded/'.$fpath.'/'.$fname;
3585: } else {
3586: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3587: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3588: return '/adm/notfound.html';
3589: }
1.477 raeburn 3590: }
3591: }
1.485 raeburn 3592: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3593: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3594: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3595: }
3596: return $fetchresult;
3597: }
3598:
1.637 raeburn 3599: sub build_filepath {
3600: my ($fpath) = @_;
3601: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3602: unless ($fpath eq '') {
3603: my @parts=split('/',$fpath);
3604: foreach my $part (@parts) {
3605: $filepath.= '/'.$part;
3606: if ((-e $filepath)!=1) {
3607: mkdir($filepath,0777);
3608: }
3609: }
3610: }
3611: return $filepath;
3612: }
3613:
3614: sub store_edited_file {
1.638 albertel 3615: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3616: my $file = $primary_url;
3617: $file =~ s#^/uploaded/$docudom/$docuname/##;
3618: my $fpath = '';
3619: my $fname = $file;
3620: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3621: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3622: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 3623: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3624: print $fh $content;
3625: close($fh);
1.638 albertel 3626: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3627: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3628: $home);
1.637 raeburn 3629: if ($$fetchresult eq 'ok') {
3630: return '/uploaded/'.$fpath.'/'.$fname;
3631: } else {
1.638 albertel 3632: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3633: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3634: return '/adm/notfound.html';
3635: }
3636: }
3637:
1.531 albertel 3638: sub clean_filename {
1.831 albertel 3639: my ($fname,$args)=@_;
1.315 www 3640: # Replace Windows backslashes by forward slashes
1.257 www 3641: $fname=~s/\\/\//g;
1.831 albertel 3642: if (!$args->{'keep_path'}) {
3643: # Get rid of everything but the actual filename
3644: $fname=~s/^.*\/([^\/]+)$/$1/;
3645: }
1.315 www 3646: # Replace spaces by underscores
3647: $fname=~s/\s+/\_/g;
1.1172.2.110 raeburn 3648: # Transliterate non-ascii text to ascii
3649: my $lang = &Apache::lonlocal::current_language();
3650: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3651: # Replace all other weird characters by nothing
1.831 albertel 3652: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3653: # Replace all .\d. sequences with _\d. so they no longer look like version
3654: # numbers
3655: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3656: return $fname;
3657: }
1.1172.2.110 raeburn 3658:
1.1051 raeburn 3659: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3660: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3661: # image with the same aspect ratio as the original, but with dimensions which do
3662: # not exceed $resizewidth and $resizeheight.
3663:
1.984 neumanie 3664: sub resizeImage {
1.1051 raeburn 3665: my ($img_path,$resizewidth,$resizeheight) = @_;
3666: my $ima = Image::Magick->new;
3667: my $resized;
3668: if (-e $img_path) {
3669: $ima->Read($img_path);
3670: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3671: my $width = $ima->Get('width');
3672: my $height = $ima->Get('height');
3673: if ($width > $resizewidth) {
3674: my $factor = $width/$resizewidth;
3675: my $newheight = $height/$factor;
3676: $ima->Scale(width=>$resizewidth,height=>$newheight);
3677: $resized = 1;
3678: }
3679: }
3680: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3681: my $width = $ima->Get('width');
3682: my $height = $ima->Get('height');
3683: if ($height > $resizeheight) {
3684: my $factor = $height/$resizeheight;
3685: my $newwidth = $width/$factor;
3686: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3687: $resized = 1;
3688: }
3689: }
3690: if ($resized) {
3691: $ima->Write($img_path);
3692: }
3693: }
3694: return;
1.977 amueller 3695: }
3696:
1.608 albertel 3697: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3698: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3699: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3700: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.109 raeburn 3701: # canceloverwrite, scantron or ''.
1.1090 raeburn 3702: # if 'coursedoc': upload to the current course
3703: # if 'existingfile': write file to tmp/overwrites directory
3704: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3705: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3706: # $subdir - directory in userfile to store the file into
1.1172.2.109 raeburn 3707: # $parser - instruction to parse file for objects ($parser = parse) or
3708: # if context is 'scantron', $parser is hashref of csv column mapping
3709: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3710: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3711: # $allfiles - reference to hash for embedded objects
3712: # $codebase - reference to hash for codebase of java objects
3713: # $desuname - username for permanent storage of uploaded file
3714: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3715: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3716: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3717: # $resizewidth - width (pixels) to which to resize uploaded image
3718: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3719: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3720: # from File::MMagic.
1.858 raeburn 3721: #
1.686 albertel 3722: # output: url of file in userspace, or error: <message>
3723: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3724:
1.531 albertel 3725: sub userfileupload {
1.1090 raeburn 3726: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3727: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3728: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3729: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3730: $fname=&clean_filename($fname);
1.1090 raeburn 3731: # See if there is anything left
1.257 www 3732: unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110 raeburn 3733: # If filename now begins with a . prepend unix timestamp _ milliseconds
3734: if ($fname =~ /^\./) {
3735: my ($s,$usec) = &gettimeofday();
3736: while (length($usec) < 6) {
3737: $usec = '0'.$usec;
3738: }
3739: $fname = $s.'_'.substr($usec,0,3).$fname;
3740: }
1.1090 raeburn 3741: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3742: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3743: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3744: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3745: my $now = time;
1.1090 raeburn 3746: my $filepath;
1.1095 raeburn 3747: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3748: $filepath = 'tmp/helprequests/'.$now;
3749: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3750: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3751: '_'.$env{'user.domain'}.'/pending';
3752: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3753: my ($docuname,$docudom);
1.1172.2.96 raeburn 3754: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3755: $docudom = $destudom;
3756: } else {
3757: $docudom = $env{'user.domain'};
3758: }
1.1172.2.96 raeburn 3759: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3760: $docuname = $destuname;
3761: } else {
3762: $docuname = $env{'user.name'};
3763: }
3764: if (exists($env{'form.group'})) {
3765: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3766: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3767: }
3768: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3769: if ($context eq 'canceloverwrite') {
3770: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3771: if (-e $tempfile) {
3772: my @info = stat($tempfile);
3773: if ($info[9] eq $env{'form.timestamp'}) {
3774: unlink($tempfile);
3775: }
3776: }
3777: return;
1.523 raeburn 3778: }
3779: }
1.1090 raeburn 3780: # Create the directory if not present
1.741 raeburn 3781: my @parts=split(/\//,$filepath);
3782: my $fullpath = $perlvar{'lonDaemons'};
3783: for (my $i=0;$i<@parts;$i++) {
3784: $fullpath .= '/'.$parts[$i];
3785: if ((-e $fullpath)!=1) {
3786: mkdir($fullpath,0777);
3787: }
3788: }
1.1172.2.96 raeburn 3789: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3790: print $fh $env{'form.'.$formname};
3791: close($fh);
1.1090 raeburn 3792: if ($context eq 'existingfile') {
3793: my @info = stat($fullpath.'/'.$fname);
3794: return ($fullpath.'/'.$fname,$info[9]);
3795: } else {
3796: return $fullpath.'/'.$fname;
3797: }
1.523 raeburn 3798: }
1.995 raeburn 3799: if ($subdir eq 'scantron') {
3800: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3801: } else {
1.995 raeburn 3802: $fname="$subdir/$fname";
3803: }
1.1090 raeburn 3804: if ($context eq 'coursedoc') {
1.638 albertel 3805: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3806: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3807: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3808: return &finishuserfileupload($docuname,$docudom,
3809: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3810: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3811: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3812: } else {
1.1172.2.21 raeburn 3813: if ($env{'form.folder'}) {
3814: $fname=$env{'form.folder'}.'/'.$fname;
3815: }
1.638 albertel 3816: return &process_coursefile('uploaddoc',$docuname,$docudom,
3817: $fname,$formname,$parser,
1.1095 raeburn 3818: $allfiles,$codebase,$mimetype);
1.481 raeburn 3819: }
1.719 banghart 3820: } elsif (defined($destuname)) {
3821: my $docuname=$destuname;
3822: my $docudom=$destudom;
1.860 raeburn 3823: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3824: $parser,$allfiles,$codebase,
1.1051 raeburn 3825: $thumbwidth,$thumbheight,
1.1095 raeburn 3826: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3827: } else {
1.638 albertel 3828: my $docuname=$env{'user.name'};
3829: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3830: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3831: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3832: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3833: }
1.860 raeburn 3834: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3835: $parser,$allfiles,$codebase,
1.1051 raeburn 3836: $thumbwidth,$thumbheight,
1.1095 raeburn 3837: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3838: }
1.271 www 3839: }
3840:
3841: sub finishuserfileupload {
1.860 raeburn 3842: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3843: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3844: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3845: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3846:
1.860 raeburn 3847: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3848: $file=$fname;
3849: if ($fname=~m|/|) {
3850: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3851: $path.=$fnamepath.'/';
3852: }
1.259 www 3853: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3854: my $count;
3855: for ($count=4;$count<=$#parts;$count++) {
3856: $filepath.="/$parts[$count]";
3857: if ((-e $filepath)!=1) {
3858: mkdir($filepath,0777);
3859: }
3860: }
1.984 neumanie 3861:
1.258 www 3862: # Save the file
3863: {
1.1172.2.96 raeburn 3864: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 3865: &logthis('Failed to create '.$filepath.'/'.$file);
3866: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3867: return '/adm/notfound.html';
3868: }
1.1090 raeburn 3869: if ($context eq 'overwrite') {
1.1117 foxr 3870: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3871: my $target = $filepath.'/'.$file;
3872: if (-e $source) {
3873: my @info = stat($source);
3874: if ($info[9] eq $env{'form.timestamp'}) {
3875: unless (&File::Copy::move($source,$target)) {
3876: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3877: return "Moving from $source failed";
3878: }
3879: } else {
3880: return "Temporary file: $source had unexpected date/time for last modification";
3881: }
3882: } else {
3883: return "Temporary file: $source missing";
3884: }
3885: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3886: &logthis('Failed to write to '.$filepath.'/'.$file);
3887: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3888: return '/adm/notfound.html';
3889: }
1.570 albertel 3890: close(FH);
1.1051 raeburn 3891: if ($resizewidth && $resizeheight) {
3892: my $mm = new File::MMagic;
3893: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3894: if ($mime_type =~ m{^image/}) {
3895: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3896: }
1.977 amueller 3897: }
1.258 www 3898: }
1.1152 raeburn 3899: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3900: if (ref($mimetype)) {
3901: if ($$mimetype eq '') {
3902: my $mm = new File::MMagic;
3903: my $type = $mm->checktype_filename($filepath.'/'.$file);
3904: $$mimetype = $type;
3905: }
3906: }
3907: }
1.1172.2.109 raeburn 3908: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 3909: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3910: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3911: $allfiles,$codebase);
3912: unless ($parse_result eq 'ok') {
3913: &logthis('Failed to parse '.$filepath.$file.
3914: ' for embedded media: '.$parse_result);
3915: }
1.637 raeburn 3916: }
1.1172.2.109 raeburn 3917: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
3918: my $format = $env{'form.scantron_format'};
3919: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 3920: }
1.860 raeburn 3921: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3922: my $input = $filepath.'/'.$file;
3923: my $output = $filepath.'/'.'tn-'.$file;
3924: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96 raeburn 3925: my @args = ('convert','-sample',$thumbsize,$input,$output);
3926: system({$args[0]} @args);
1.860 raeburn 3927: if (-e $filepath.'/'.'tn-'.$file) {
3928: $fetchthumb = 1;
3929: }
3930: }
1.858 raeburn 3931:
1.259 www 3932: # Notify homeserver to grep it
3933: #
1.984 neumanie 3934: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3935: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3936: if ($fetchresult eq 'ok') {
1.860 raeburn 3937: if ($fetchthumb) {
3938: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3939: if ($thumbresult ne 'ok') {
3940: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3941: $docuhome.': '.$thumbresult);
3942: }
3943: }
1.259 www 3944: #
1.258 www 3945: # Return the URL to it
1.494 albertel 3946: return '/uploaded/'.$path.$file;
1.263 www 3947: } else {
1.494 albertel 3948: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3949: ': '.$fetchresult);
1.263 www 3950: return '/adm/notfound.html';
1.858 raeburn 3951: }
1.493 albertel 3952: }
3953:
1.637 raeburn 3954: sub extract_embedded_items {
1.961 raeburn 3955: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3956: my @state = ();
1.1164 raeburn 3957: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3958: my %javafiles = (
3959: codebase => '',
3960: code => '',
3961: archive => ''
3962: );
3963: my %mediafiles = (
3964: src => '',
3965: movie => '',
3966: );
1.648 raeburn 3967: my $p;
3968: if ($content) {
3969: $p = HTML::LCParser->new($content);
3970: } else {
1.961 raeburn 3971: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3972: }
1.641 albertel 3973: while (my $t=$p->get_token()) {
1.640 albertel 3974: if ($t->[0] eq 'S') {
3975: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3976: push(@state, $tagname);
1.648 raeburn 3977: if (lc($tagname) eq 'allow') {
3978: &add_filetype($allfiles,$attr->{'src'},'src');
3979: }
1.640 albertel 3980: if (lc($tagname) eq 'img') {
3981: &add_filetype($allfiles,$attr->{'src'},'src');
3982: }
1.886 albertel 3983: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3984: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3985: &add_filetype($allfiles,$attr->{'href'},'href');
3986: }
1.886 albertel 3987: }
1.645 raeburn 3988: if (lc($tagname) eq 'script') {
1.1164 raeburn 3989: my $src;
1.645 raeburn 3990: if ($attr->{'archive'} =~ /\.jar$/i) {
3991: &add_filetype($allfiles,$attr->{'archive'},'archive');
3992: } else {
1.1164 raeburn 3993: if ($attr->{'src'} ne '') {
3994: $src = $attr->{'src'};
3995: &add_filetype($allfiles,$src,'src');
3996: }
3997: }
3998: my $text = $p->get_trimmed_text();
3999: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4000: my @swfargs = split(/,/,$1);
4001: foreach my $item (@swfargs) {
4002: $item =~ s/["']//g;
4003: $item =~ s/^\s+//;
4004: $item =~ s/\s+$//;
4005: }
4006: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4007: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4008: push(@{$related{$swfargs[0]}},$swfargs[2]);
4009: } else {
4010: $related{$swfargs[0]} = [$swfargs[2]];
4011: }
4012: }
1.645 raeburn 4013: }
4014: }
4015: if (lc($tagname) eq 'link') {
4016: if (lc($attr->{'rel'}) eq 'stylesheet') {
4017: &add_filetype($allfiles,$attr->{'href'},'href');
4018: }
4019: }
1.640 albertel 4020: if (lc($tagname) eq 'object' ||
4021: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4022: foreach my $item (keys(%javafiles)) {
4023: $javafiles{$item} = '';
4024: }
1.1164 raeburn 4025: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4026: $lastids{lc($tagname)} = $attr->{'id'};
4027: }
1.640 albertel 4028: }
4029: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4030: my $name = lc($attr->{'name'});
4031: foreach my $item (keys(%javafiles)) {
4032: if ($name eq $item) {
4033: $javafiles{$item} = $attr->{'value'};
4034: last;
4035: }
4036: }
1.1164 raeburn 4037: my $pathfrom;
1.640 albertel 4038: foreach my $item (keys(%mediafiles)) {
4039: if ($name eq $item) {
1.1164 raeburn 4040: $pathfrom = $attr->{'value'};
4041: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4042: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4043: last;
4044: }
4045: }
1.1164 raeburn 4046: if ($name eq 'flashvars') {
4047: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4048: }
4049: if ($pathfrom ne '') {
4050: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4051: $pathfrom);
4052: }
1.640 albertel 4053: }
4054: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4055: foreach my $item (keys(%javafiles)) {
4056: if ($attr->{$item}) {
4057: $javafiles{$item} = $attr->{$item};
4058: last;
4059: }
4060: }
4061: foreach my $item (keys(%mediafiles)) {
4062: if ($attr->{$item}) {
4063: &add_filetype($allfiles,$attr->{$item},$item);
4064: last;
4065: }
4066: }
1.1164 raeburn 4067: if (lc($tagname) eq 'embed') {
4068: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4069: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4070: $attr->{'src'});
4071: }
4072: }
1.640 albertel 4073: }
1.1172.2.35 raeburn 4074: if (lc($tagname) eq 'iframe') {
4075: my $src = $attr->{'src'} ;
4076: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4077: &add_filetype($allfiles,$src,'src');
4078: } elsif ($src =~ m{^/}) {
4079: if ($env{'request.course.id'}) {
4080: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4081: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4082: my $url = &hreflocation('',$fullpath);
4083: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4084: my $relpath = $1;
4085: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4086: &add_filetype($allfiles,$1,'src');
4087: }
4088: }
4089: }
4090: }
4091: }
1.1164 raeburn 4092: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 4093: pop(@state);
1.1164 raeburn 4094: }
1.640 albertel 4095: } elsif ($t->[0] eq 'E') {
4096: my ($tagname) = ($t->[1]);
4097: if ($javafiles{'codebase'} ne '') {
4098: $javafiles{'codebase'} .= '/';
4099: }
4100: if (lc($tagname) eq 'applet' ||
4101: lc($tagname) eq 'object' ||
4102: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4103: ) {
4104: foreach my $item (keys(%javafiles)) {
4105: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4106: my $file=$javafiles{'codebase'}.$javafiles{$item};
4107: &add_filetype($allfiles,$file,$item);
4108: }
4109: }
4110: }
4111: pop @state;
4112: }
4113: }
1.1164 raeburn 4114: foreach my $id (sort(keys(%flashvars))) {
4115: if ($shockwave{$id} ne '') {
4116: my @pairs = split(/\&/,$flashvars{$id});
4117: foreach my $pair (@pairs) {
4118: my ($key,$value) = split(/\=/,$pair);
4119: if ($key eq 'thumb') {
4120: &add_filetype($allfiles,$value,$key);
4121: } elsif ($key eq 'content') {
4122: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4123: my ($ext) = ($value =~ /\.([^.]+)$/);
4124: if ($ext ne '') {
4125: &add_filetype($allfiles,$path.$value,$ext);
4126: }
4127: }
4128: }
4129: }
4130: }
1.637 raeburn 4131: return 'ok';
4132: }
4133:
1.639 albertel 4134: sub add_filetype {
4135: my ($allfiles,$file,$type)=@_;
4136: if (exists($allfiles->{$file})) {
4137: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4138: push(@{$allfiles->{$file}}, &escape($type));
4139: }
4140: } else {
4141: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4142: }
4143: }
4144:
1.1164 raeburn 4145: sub embedded_dependency {
4146: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4147: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4148: if (($identifier ne '') &&
4149: (ref($related->{$identifier}) eq 'ARRAY') &&
4150: ($pathfrom ne '')) {
4151: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4152: foreach my $dep (@{$related->{$identifier}}) {
4153: &add_filetype($allfiles,$path.$dep,'object');
4154: }
4155: }
4156: }
4157: return;
4158: }
4159:
1.1172.2.109 raeburn 4160: sub bubblesheet_converter {
4161: my ($cdom,$fullpath,$config,$format) = @_;
4162: if ((&domain($cdom) ne '') &&
4163: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4164: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4165: my (%csvcols,%csvoptions);
4166: if (ref($config->{'fields'}) eq 'HASH') {
4167: %csvcols = %{$config->{'fields'}};
4168: }
4169: if (ref($config->{'options'}) eq 'HASH') {
4170: %csvoptions = %{$config->{'options'}};
4171: }
4172: my %csvbynum = reverse(%csvcols);
4173: my %scantronconf = &get_scantron_config($format,$cdom);
4174: if (keys(%scantronconf)) {
4175: my %bynum = (
4176: $scantronconf{CODEstart} => 'CODEstart',
4177: $scantronconf{IDstart} => 'IDstart',
4178: $scantronconf{PaperID} => 'PaperID',
4179: $scantronconf{FirstName} => 'FirstName',
4180: $scantronconf{LastName} => 'LastName',
4181: $scantronconf{Qstart} => 'Qstart',
4182: );
4183: my @ordered;
4184: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4185: push(@ordered,$bynum{$item});
4186: }
4187: my %mapstart = (
4188: CODEstart => 'CODE',
4189: IDstart => 'ID',
4190: PaperID => 'PaperID',
4191: FirstName => 'FirstName',
4192: LastName => 'LastName',
4193: Qstart => 'FirstQuestion',
4194: );
4195: my %maplength = (
4196: CODEstart => 'CODElength',
4197: IDstart => 'IDlength',
4198: PaperID => 'PaperIDlength',
4199: FirstName => 'FirstNamelength',
4200: LastName => 'LastNamelength',
4201: );
4202: if (open(my $fh,'<',$fullpath)) {
4203: my $output;
4204: my %lettdig = &letter_to_digits();
4205: my %diglett = reverse(%lettdig);
4206: my $numletts = scalar(keys(%lettdig));
4207: my $num = 0;
4208: while (my $line=<$fh>) {
4209: $num ++;
4210: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4211: $line =~ s{[\r\n]+$}{};
4212: my %found;
4213: my @values = split(/,/,$line);
4214: my ($qstart,$record);
4215: for (my $i=0; $i<@values; $i++) {
4216: if ((($qstart ne '') && ($i > $qstart)) ||
4217: ($csvbynum{$i} eq 'FirstQuestion')) {
4218: if ($values[$i] eq '') {
4219: $values[$i] = $scantronconf{'Qoff'};
4220: } elsif ($scantronconf{'Qon'} eq 'number') {
4221: if ($values[$i] =~ /^[A-Ja-j]$/) {
4222: $values[$i] = $lettdig{uc($values[$i])};
4223: }
4224: } elsif ($scantronconf{'Qon'} eq 'letter') {
4225: if ($values[$i] =~ /^[0-9]$/) {
4226: $values[$i] = $diglett{$values[$i]};
4227: }
4228: } else {
4229: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4230: my $digit;
4231: if ($values[$i] =~ /^[A-Ja-j]$/) {
4232: $digit = $lettdig{uc($values[$i])}-1;
4233: if ($values[$i] eq 'J') {
4234: $digit += $numletts;
4235: }
4236: } elsif ($values[$i] =~ /^[0-9]$/) {
4237: $digit = $values[$i]-1;
4238: if ($values[$i] eq '0') {
4239: $digit += $numletts;
4240: }
4241: }
4242: my $qval='';
4243: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4244: if ($j == $digit) {
4245: $qval .= $scantronconf{'Qon'};
4246: } else {
4247: $qval .= $scantronconf{'Qoff'};
4248: }
4249: }
4250: $values[$i] = $qval;
4251: }
4252: }
4253: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4254: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4255: }
4256: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4257: if ($numblank > 0) {
4258: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4259: }
4260: if ($csvbynum{$i} eq 'FirstQuestion') {
4261: $qstart = $i;
4262: $found{$csvbynum{$i}} = $values[$i];
4263: } else {
4264: $found{'FirstQuestion'} .= $values[$i];
4265: }
4266: } elsif (exists($csvbynum{$i})) {
4267: if ($csvoptions{'rem'}) {
4268: $values[$i] =~ s/^\s+//;
4269: }
4270: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4271: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4272: $values[$i] = '0'.$values[$i];
4273: }
4274: }
4275: $found{$csvbynum{$i}} = $values[$i];
4276: }
4277: }
4278: foreach my $item (@ordered) {
4279: my $currlength = 1+length($record);
4280: my $numspaces = $scantronconf{$item} - $currlength;
4281: if ($numspaces > 0) {
4282: $record .= (' ' x $numspaces);
4283: }
4284: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4285: unless ($item eq 'Qstart') {
4286: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4287: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4288: }
4289: }
4290: $record .= $found{$mapstart{$item}};
4291: }
4292: }
4293: $output .= "$record\n";
4294: }
4295: close($fh);
4296: if ($output) {
4297: if (open(my $fh,'>',$fullpath)) {
4298: print $fh $output;
4299: close($fh);
4300: }
4301: }
4302: }
4303: }
4304: return;
4305: }
4306: }
4307:
4308: sub letter_to_digits {
4309: my %lettdig = (
4310: A => 1,
4311: B => 2,
4312: C => 3,
4313: D => 4,
4314: E => 5,
4315: F => 6,
4316: G => 7,
4317: H => 8,
4318: I => 9,
4319: J => 0,
4320: );
4321: return %lettdig;
4322: }
4323:
4324: sub get_scantron_config {
4325: my ($which,$cdom) = @_;
4326: my @lines = &get_scantronformat_file($cdom);
4327: my %config;
4328: #FIXME probably should move to XML it has already gotten a bit much now
4329: foreach my $line (@lines) {
4330: my ($name,$descrip)=split(/:/,$line);
4331: if ($name ne $which ) { next; }
4332: chomp($line);
4333: my @config=split(/:/,$line);
4334: $config{'name'}=$config[0];
4335: $config{'description'}=$config[1];
4336: $config{'CODElocation'}=$config[2];
4337: $config{'CODEstart'}=$config[3];
4338: $config{'CODElength'}=$config[4];
4339: $config{'IDstart'}=$config[5];
4340: $config{'IDlength'}=$config[6];
4341: $config{'Qstart'}=$config[7];
4342: $config{'Qlength'}=$config[8];
4343: $config{'Qoff'}=$config[9];
4344: $config{'Qon'}=$config[10];
4345: $config{'PaperID'}=$config[11];
4346: $config{'PaperIDlength'}=$config[12];
4347: $config{'FirstName'}=$config[13];
4348: $config{'FirstNamelength'}=$config[14];
4349: $config{'LastName'}=$config[15];
4350: $config{'LastNamelength'}=$config[16];
4351: $config{'BubblesPerRow'}=$config[17];
4352: last;
4353: }
4354: return %config;
4355: }
4356:
4357: sub get_scantronformat_file {
4358: my ($cdom) = @_;
4359: if ($cdom eq '') {
4360: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4361: }
4362: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4363: my $gottab = 0;
4364: my @lines;
4365: if (ref($domconfig{'scantron'}) eq 'HASH') {
4366: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4367: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4368: if ($formatfile ne '-1') {
4369: @lines = split("\n",$formatfile,-1);
4370: $gottab = 1;
4371: }
4372: }
4373: }
4374: if (!$gottab) {
4375: my $confname = $cdom.'-domainconfig';
4376: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4377: my $formatfile = &getfile($default);
4378: if ($formatfile ne '-1') {
4379: @lines = split("\n",$formatfile,-1);
4380: $gottab = 1;
4381: }
4382: }
4383: if (!$gottab) {
4384: my @domains = ¤t_machine_domains();
4385: if (grep(/^\Q$cdom\E$/,@domains)) {
4386: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4387: @lines = <$fh>;
4388: close($fh);
4389: }
4390: } else {
4391: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4392: @lines = <$fh>;
4393: close($fh);
4394: }
4395: }
4396: }
4397: return @lines;
4398: }
4399:
1.493 albertel 4400: sub removeuploadedurl {
1.984 neumanie 4401: my ($url)=@_;
4402: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4403: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4404: }
4405:
4406: sub removeuserfile {
4407: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4408: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4409: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4410: if ($result eq 'ok') {
1.798 raeburn 4411: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4412: my $metafile = $fname.'.meta';
4413: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4414: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4415: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4416: my $sqlresult =
1.823 albertel 4417: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4418: 'portfolio_metadata',$group,
4419: 'delete');
1.798 raeburn 4420: }
4421: }
4422: return $result;
1.257 www 4423: }
1.15 www 4424:
1.530 albertel 4425: sub mkdiruserfile {
4426: my ($docuname,$docudom,$dir)=@_;
4427: my $home=&homeserver($docuname,$docudom);
4428: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4429: }
4430:
1.531 albertel 4431: sub renameuserfile {
4432: my ($docuname,$docudom,$old,$new)=@_;
4433: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4434: my $result = &reply("renameuserfile:$docudom:$docuname:".
4435: &escape("$old").':'.&escape("$new"),$home);
4436: if ($result eq 'ok') {
4437: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4438: my $oldmeta = $old.'.meta';
4439: my $newmeta = $new.'.meta';
4440: my $metaresult =
4441: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4442: my $url = "/uploaded/$docudom/$docuname/$old";
4443: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4444: my $sqlresult =
1.823 albertel 4445: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4446: 'portfolio_metadata',$group,
4447: 'delete');
1.798 raeburn 4448: }
4449: }
4450: return $result;
1.531 albertel 4451: }
4452:
1.14 www 4453: # ------------------------------------------------------------------------- Log
4454:
4455: sub log {
4456: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4457: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4458: }
4459:
4460: # ------------------------------------------------------------------ Course Log
1.352 www 4461: #
4462: # This routine flushes several buffers of non-mission-critical nature
4463: #
1.157 www 4464:
4465: sub flushcourselogs {
1.352 www 4466: &logthis('Flushing log buffers');
4467: #
4468: # course logs
4469: # This is a log of all transactions in a course, which can be used
4470: # for data mining purposes
4471: #
4472: # It also collects the courseid database, which lists last transaction
4473: # times and course titles for all courseids
4474: #
4475: my %courseidbuffer=();
1.921 raeburn 4476: foreach my $crsid (keys(%courselogs)) {
1.352 www 4477: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4478: &escape($courselogs{$crsid}),
4479: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4480: delete $courselogs{$crsid};
4481: } else {
4482: &logthis('Failed to flush log buffer for '.$crsid);
4483: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4484: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4485: " exceeded maximum size, deleting.</font>");
4486: delete $courselogs{$crsid};
4487: }
1.352 www 4488: }
1.920 raeburn 4489: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4490: 'description' => $coursedescrbuf{$crsid},
4491: 'inst_code' => $courseinstcodebuf{$crsid},
4492: 'type' => $coursetypebuf{$crsid},
4493: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4494: };
1.191 harris41 4495: }
1.352 www 4496: #
4497: # Write course id database (reverse lookup) to homeserver of courses
4498: # Is used in pickcourse
4499: #
1.840 albertel 4500: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4501: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4502: $courseidbuffer{$crs_home},
4503: $crs_home,'timeonly');
1.352 www 4504: }
4505: #
4506: # File accesses
4507: # Writes to the dynamic metadata of resources to get hit counts, etc.
4508: #
1.449 matthew 4509: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4510: if ($entry =~ /___count$/) {
4511: my ($dom,$name);
1.807 albertel 4512: ($dom,$name,undef)=
1.811 albertel 4513: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4514: if (! defined($dom) || $dom eq '' ||
4515: ! defined($name) || $name eq '') {
1.620 albertel 4516: my $cid = $env{'request.course.id'};
4517: $dom = $env{'request.'.$cid.'.domain'};
4518: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4519: }
1.450 matthew 4520: my $value = $accesshash{$entry};
4521: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4522: my %temphash=($url => $value);
1.449 matthew 4523: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4524: if ($result eq 'ok') {
4525: delete $accesshash{$entry};
4526: }
4527: } else {
1.811 albertel 4528: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4529: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4530: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4531: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4532: delete $accesshash{$entry};
4533: }
1.185 www 4534: }
1.191 harris41 4535: }
1.352 www 4536: #
4537: # Roles
4538: # Reverse lookup of user roles for course faculty/staff and co-authorship
4539: #
1.800 albertel 4540: foreach my $entry (keys(%userrolehash)) {
1.351 www 4541: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4542: split(/\:/,$entry);
4543: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4544: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4545: $rudom,$runame) eq 'ok') {
4546: delete $userrolehash{$entry};
4547: }
4548: }
1.662 raeburn 4549: #
1.1172.2.90 raeburn 4550: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4551: #
4552: my %domrolebuffer = ();
1.1000 raeburn 4553: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4554: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4555: if ($domrolebuffer{$rudom}) {
4556: $domrolebuffer{$rudom}.='&'.&escape($entry).
4557: '='.&escape($domainrolehash{$entry});
4558: } else {
4559: $domrolebuffer{$rudom}.=&escape($entry).
4560: '='.&escape($domainrolehash{$entry});
4561: }
4562: delete $domainrolehash{$entry};
4563: }
4564: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4565: my %servers;
4566: if (defined(&domain($dom,'primary'))) {
4567: my $primary=&domain($dom,'primary');
4568: my $hostname=&hostname($primary);
4569: $servers{$primary} = $hostname;
4570: } else {
4571: %servers = &get_servers($dom,'library');
4572: }
1.841 albertel 4573: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4574: if (&reply('domroleput:'.$dom.':'.
4575: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4576: last;
4577: } else {
1.841 albertel 4578: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4579: }
1.662 raeburn 4580: }
4581: }
1.186 www 4582: $dumpcount++;
1.157 www 4583: }
4584:
4585: sub courselog {
4586: my $what=shift;
1.158 www 4587: $what=time.':'.$what;
1.620 albertel 4588: unless ($env{'request.course.id'}) { return ''; }
4589: $coursedombuf{$env{'request.course.id'}}=
4590: $env{'course.'.$env{'request.course.id'}.'.domain'};
4591: $coursenumbuf{$env{'request.course.id'}}=
4592: $env{'course.'.$env{'request.course.id'}.'.num'};
4593: $coursehombuf{$env{'request.course.id'}}=
4594: $env{'course.'.$env{'request.course.id'}.'.home'};
4595: $coursedescrbuf{$env{'request.course.id'}}=
4596: $env{'course.'.$env{'request.course.id'}.'.description'};
4597: $courseinstcodebuf{$env{'request.course.id'}}=
4598: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4599: $courseownerbuf{$env{'request.course.id'}}=
4600: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4601: $coursetypebuf{$env{'request.course.id'}}=
4602: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4603: if (defined $courselogs{$env{'request.course.id'}}) {
4604: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4605: } else {
1.620 albertel 4606: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4607: }
1.620 albertel 4608: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4609: &flushcourselogs();
4610: }
1.158 www 4611: }
4612:
4613: sub courseacclog {
4614: my $fnsymb=shift;
1.620 albertel 4615: unless ($env{'request.course.id'}) { return ''; }
4616: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4617: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4618: $what.=':POST';
1.583 matthew 4619: # FIXME: Probably ought to escape things....
1.800 albertel 4620: foreach my $key (keys(%env)) {
4621: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4622: my $formitem = $1;
4623: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4624: $what.=':'.$formitem.'='.$env{$key};
4625: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4626: $what.=':'.$formitem.'='.$env{$key};
4627: }
1.158 www 4628: }
1.191 harris41 4629: }
1.583 matthew 4630: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4631: # FIXME: We should not be depending on a form parameter that someone
4632: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4633: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4634: $what.= ':POST';
4635: # FIXME: Probably ought to escape things....
4636: foreach my $element ('courseexp','crsfulltext','crsrelated',
4637: 'crsdiscuss') {
1.620 albertel 4638: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4639: }
4640: }
1.158 www 4641: }
4642: &courselog($what);
1.149 www 4643: }
4644:
1.185 www 4645: sub countacc {
4646: my $url=&declutter(shift);
1.458 matthew 4647: return if (! defined($url) || $url eq '');
1.620 albertel 4648: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4649: #
4650: # Mark that this url was used in this course
4651: #
1.620 albertel 4652: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4653: #
4654: # Increase the access count for this resource in this child process
4655: #
1.281 www 4656: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4657: $accesshash{$key}++;
1.185 www 4658: }
1.349 www 4659:
1.361 www 4660: sub linklog {
4661: my ($from,$to)=@_;
4662: $from=&declutter($from);
4663: $to=&declutter($to);
4664: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4665: $accesshash{$to.'___'.$from.'___goto'}=1;
4666: }
1.1160 www 4667:
4668: sub statslog {
4669: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4670: if ($users<2) { return; }
4671: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4672: 'course' => $env{'request.course.id'},
4673: 'sections' => '"all"',
4674: 'num_students' => $users,
4675: 'part' => $part,
4676: 'symb' => $symb,
4677: 'mean_tries' => $av_attempts,
4678: 'deg_of_diff' => $degdiff});
4679: foreach my $key (keys(%dynstore)) {
4680: $accesshash{$key}=$dynstore{$key};
4681: }
4682: }
1.361 www 4683:
1.349 www 4684: sub userrolelog {
4685: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4686: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4687: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4688: $userrolehash
4689: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4690: =$tend.':'.$tstart;
1.662 raeburn 4691: }
1.1169 droeschl 4692: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4693: $userrolehash
4694: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4695: =$tend.':'.$tstart;
4696: }
1.1172.2.90 raeburn 4697: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4698: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4699: $domainrolehash
4700: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4701: = $tend.':'.$tstart;
4702: }
1.351 www 4703: }
4704:
1.957 raeburn 4705: sub courserolelog {
4706: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4707: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4708: my $cdom = $1;
4709: my $cnum = $2;
4710: my $sec = $3;
4711: my $namespace = 'rolelog';
4712: my %storehash = (
4713: role => $trole,
4714: start => $tstart,
4715: end => $tend,
4716: selfenroll => $selfenroll,
4717: context => $context,
4718: );
4719: if ($trole eq 'gr') {
4720: $namespace = 'groupslog';
4721: $storehash{'group'} = $sec;
4722: } else {
4723: $storehash{'section'} = $sec;
4724: }
4725: &write_log('course',$namespace,\%storehash,$delflag,$username,
4726: $domain,$cnum,$cdom);
4727: if (($trole ne 'st') || ($sec ne '')) {
4728: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4729: }
4730: }
4731: return;
4732: }
4733:
1.1172.2.9 raeburn 4734: sub domainrolelog {
4735: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4736: if ($area =~ m{^/($match_domain)/$}) {
4737: my $cdom = $1;
4738: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4739: my $namespace = 'rolelog';
4740: my %storehash = (
4741: role => $trole,
4742: start => $tstart,
4743: end => $tend,
4744: context => $context,
4745: );
4746: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4747: $domain,$domconfiguser,$cdom);
4748: }
4749: return;
4750:
4751: }
4752:
4753: sub coauthorrolelog {
4754: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4755: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4756: my $audom = $1;
4757: my $auname = $2;
4758: my $namespace = 'rolelog';
4759: my %storehash = (
4760: role => $trole,
4761: start => $tstart,
4762: end => $tend,
4763: context => $context,
4764: );
4765: &write_log('author',$namespace,\%storehash,$delflag,$username,
4766: $domain,$auname,$audom);
4767: }
4768: return;
4769: }
4770:
1.351 www 4771: sub get_course_adv_roles {
1.948 raeburn 4772: my ($cid,$codes) = @_;
1.620 albertel 4773: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4774: my %coursehash=&coursedescription($cid);
1.988 raeburn 4775: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4776: my %nothide=();
1.800 albertel 4777: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4778: if ($user !~ /:/) {
4779: $nothide{join(':',split(/[\@]/,$user))}=1;
4780: } else {
4781: $nothide{$user}=1;
4782: }
1.470 www 4783: }
1.1172.2.23 raeburn 4784: my @possdoms = ($coursehash{'domain'});
4785: if ($coursehash{'checkforpriv'}) {
4786: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4787: }
1.351 www 4788: my %returnhash=();
4789: my %dumphash=
4790: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4791: my $now=time;
1.997 raeburn 4792: my %privileged;
1.1000 raeburn 4793: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4794: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4795: if (($tstart) && ($tstart<0)) { next; }
4796: if (($tend) && ($tend<$now)) { next; }
4797: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4798: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4799: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4800: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4801: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4802: if ($role eq 'cr') { next; }
1.948 raeburn 4803: if ($codes) {
4804: if ($section) { $role .= ':'.$section; }
4805: if ($returnhash{$role}) {
4806: $returnhash{$role}.=','.$username.':'.$domain;
4807: } else {
4808: $returnhash{$role}=$username.':'.$domain;
4809: }
1.351 www 4810: } else {
1.988 raeburn 4811: my $key=&plaintext($role,$crstype);
1.973 bisitz 4812: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4813: if ($returnhash{$key}) {
4814: $returnhash{$key}.=','.$username.':'.$domain;
4815: } else {
4816: $returnhash{$key}=$username.':'.$domain;
4817: }
1.351 www 4818: }
1.948 raeburn 4819: }
1.400 www 4820: return %returnhash;
4821: }
4822:
4823: sub get_my_roles {
1.937 raeburn 4824: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4825: unless (defined($uname)) { $uname=$env{'user.name'}; }
4826: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4827: my (%dumphash,%nothide);
1.1086 raeburn 4828: if ($context eq 'userroles') {
1.1166 raeburn 4829: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4830: } else {
1.1172.2.23 raeburn 4831: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4832: if ($hidepriv) {
4833: my %coursehash=&coursedescription($udom.'_'.$uname);
4834: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4835: if ($user !~ /:/) {
4836: $nothide{join(':',split(/[\@]/,$user))} = 1;
4837: } else {
4838: $nothide{$user} = 1;
4839: }
4840: }
4841: }
1.858 raeburn 4842: }
1.400 www 4843: my %returnhash=();
4844: my $now=time;
1.999 raeburn 4845: my %privileged;
1.800 albertel 4846: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4847: my ($role,$tend,$tstart);
4848: if ($context eq 'userroles') {
1.1149 raeburn 4849: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4850: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4851: } else {
4852: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4853: }
1.400 www 4854: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4855: my $status = 'active';
1.939 raeburn 4856: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4857: $status = 'previous';
4858: }
4859: if (($tstart) && ($now<$tstart)) {
4860: $status = 'future';
4861: }
4862: if (ref($types) eq 'ARRAY') {
4863: if (!grep(/^\Q$status\E$/,@{$types})) {
4864: next;
4865: }
4866: } else {
4867: if ($status ne 'active') {
4868: next;
4869: }
4870: }
1.867 raeburn 4871: my ($rolecode,$username,$domain,$section,$area);
4872: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4873: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4874: (undef,$domain,$username,$section) = split(/\//,$area);
4875: } else {
4876: ($role,$username,$domain,$section) = split(/\:/,$entry);
4877: }
1.832 raeburn 4878: if (ref($roledoms) eq 'ARRAY') {
4879: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4880: next;
4881: }
4882: }
4883: if (ref($roles) eq 'ARRAY') {
4884: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4885: if ($role =~ /^cr\//) {
4886: if (!grep(/^cr$/,@{$roles})) {
4887: next;
4888: }
1.1104 raeburn 4889: } elsif ($role =~ /^gr\//) {
4890: if (!grep(/^gr$/,@{$roles})) {
4891: next;
4892: }
1.922 raeburn 4893: } else {
4894: next;
4895: }
1.832 raeburn 4896: }
1.867 raeburn 4897: }
1.937 raeburn 4898: if ($hidepriv) {
1.1172.2.23 raeburn 4899: my @privroles = ('dc','su');
1.999 raeburn 4900: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4901: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4902: } else {
1.1172.2.23 raeburn 4903: my $possdoms = [$domain];
4904: if (ref($roledoms) eq 'ARRAY') {
4905: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4906: }
1.1172.2.23 raeburn 4907: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4908: if (!$nothide{$username.':'.$domain}) {
4909: next;
4910: }
4911: }
1.937 raeburn 4912: }
4913: }
1.933 raeburn 4914: if ($withsec) {
4915: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4916: $tstart.':'.$tend;
4917: } else {
4918: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4919: }
1.832 raeburn 4920: }
1.373 www 4921: return %returnhash;
1.399 www 4922: }
4923:
1.1172.2.89 raeburn 4924: sub get_all_adhocroles {
4925: my ($dom) = @_;
4926: my @roles_by_num = ();
4927: my %domdefaults = &get_domain_defaults($dom);
4928: my (%description,%access_in_dom,%access_info);
4929: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4930: my $count = 0;
4931: my %domcurrent = %{$domdefaults{'adhocroles'}};
4932: my %ordered;
4933: foreach my $role (sort(keys(%domcurrent))) {
4934: my ($order,$desc,$access_in_dom);
4935: if (ref($domcurrent{$role}) eq 'HASH') {
4936: $order = $domcurrent{$role}{'order'};
4937: $desc = $domcurrent{$role}{'desc'};
4938: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4939: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4940: }
4941: if ($order eq '') {
4942: $order = $count;
4943: }
4944: $ordered{$order} = $role;
4945: if ($desc ne '') {
4946: $description{$role} = $desc;
4947: } else {
4948: $description{$role}= $role;
4949: }
4950: $count++;
4951: }
4952: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4953: push(@roles_by_num,$ordered{$item});
4954: }
4955: }
4956: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4957: }
4958:
4959: sub get_my_adhocroles {
4960: my ($cid,$checkreg) = @_;
4961: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4962: if ($env{'request.course.id'} eq $cid) {
4963: $cdom = $env{'course.'.$cid.'.domain'};
4964: $cnum = $env{'course.'.$cid.'.num'};
4965: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4966: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4967: $cdom = $1;
4968: $cnum = $2;
4969: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4970: $cdom,$cnum);
4971: }
4972: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4973: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4974: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4975: if ($rosterhash{$user} ne '') {
4976: my $type = (split(/:/,$rosterhash{$user}))[5];
4977: return ([],{}) if ($type eq 'auto');
4978: }
4979: }
4980: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 4981: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 4982: my $then=$env{'user.login.time'};
4983: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 4984: if (!$update) {
4985: $update = $then;
4986: }
4987: my @liveroles;
4988: foreach my $role ('dh','da') {
4989: if ($env{"user.role.$role./$cdom/"}) {
4990: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
4991: my $limit = $update;
4992: if ($env{'request.role'} eq "$role./$cdom/") {
4993: $limit = $then;
4994: }
4995: my $activerole = 1;
4996: if ($tstart && $tstart>$limit) { $activerole = 0; }
4997: if ($tend && $tend <$limit) { $activerole = 0; }
4998: if ($activerole) {
4999: push(@liveroles,$role);
5000: }
5001: }
5002: }
5003: if (@liveroles) {
1.1172.2.89 raeburn 5004: if (&homeserver($cnum,$cdom) ne 'no_host') {
5005: my ($accessref,$accessinfo,%access_in_dom);
5006: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5007: if (ref($roles_by_num) eq 'ARRAY') {
5008: if (@{$roles_by_num}) {
5009: my %settings;
5010: if ($env{'request.course.id'} eq $cid) {
5011: foreach my $envkey (keys(%env)) {
5012: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5013: $settings{$1} = $env{$envkey};
5014: }
5015: }
5016: } else {
5017: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5018: }
5019: my %setincrs;
5020: if ($settings{'internal.adhocaccess'}) {
5021: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5022: }
5023: my @statuses;
5024: if ($env{'environment.inststatus'}) {
5025: @statuses = split(/,/,$env{'environment.inststatus'});
5026: }
5027: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5028: if (ref($accessref) eq 'HASH') {
5029: %access_in_dom = %{$accessref};
5030: }
5031: foreach my $role (@{$roles_by_num}) {
5032: my ($curraccess,@okstatus,@personnel);
5033: if ($setincrs{$role}) {
5034: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5035: if ($curraccess eq 'status') {
5036: @okstatus = split(/\&/,$rest);
5037: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5038: @personnel = split(/\&/,$rest);
5039: }
5040: } else {
5041: $curraccess = $access_in_dom{$role};
5042: if (ref($accessinfo) eq 'HASH') {
5043: if ($curraccess eq 'status') {
5044: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5045: @okstatus = @{$accessinfo->{$role}};
5046: }
5047: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5048: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5049: @personnel = @{$accessinfo->{$role}};
5050: }
5051: }
5052: }
5053: }
5054: if ($curraccess eq 'none') {
5055: next;
5056: } elsif ($curraccess eq 'all') {
5057: push(@possroles,$role);
1.1172.2.90 raeburn 5058: } elsif ($curraccess eq 'dh') {
5059: if (grep(/^dh$/,@liveroles)) {
5060: push(@possroles,$role);
5061: } else {
5062: next;
5063: }
5064: } elsif ($curraccess eq 'da') {
5065: if (grep(/^da$/,@liveroles)) {
5066: push(@possroles,$role);
5067: } else {
5068: next;
5069: }
1.1172.2.89 raeburn 5070: } elsif ($curraccess eq 'status') {
5071: if (@okstatus) {
5072: if (!@statuses) {
5073: if (grep(/^default$/,@okstatus)) {
5074: push(@possroles,$role);
5075: }
5076: } else {
5077: foreach my $status (@okstatus) {
5078: if (grep(/^\Q$status\E$/,@statuses)) {
5079: push(@possroles,$role);
5080: last;
5081: }
5082: }
5083: }
5084: }
5085: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5086: if (grep(/^\Q$user\E$/,@personnel)) {
5087: if ($curraccess eq 'exc') {
5088: push(@possroles,$role);
5089: }
5090: } elsif ($curraccess eq 'inc') {
5091: push(@possroles,$role);
5092: }
5093: }
5094: }
5095: }
5096: }
5097: }
5098: }
5099: }
5100: }
5101: unless (ref($description) eq 'HASH') {
5102: if (ref($roles_by_num) eq 'ARRAY') {
5103: my %desc;
5104: map { $desc{$_} = $_; } (@{$roles_by_num});
5105: $description = \%desc;
5106: } else {
5107: $description = {};
5108: }
5109: }
5110: return (\@possroles,$description);
5111: }
5112:
1.399 www 5113: # ----------------------------------------------------- Frontpage Announcements
5114: #
5115: #
5116:
5117: sub postannounce {
5118: my ($server,$text)=@_;
1.844 albertel 5119: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5120: unless ($text=~/\w/) { $text=''; }
5121: return &reply('setannounce:'.&escape($text),$server);
5122: }
5123:
5124: sub getannounce {
1.448 albertel 5125:
1.1172.2.96 raeburn 5126: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5127: my $announcement='';
1.800 albertel 5128: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5129: close($fh);
1.399 www 5130: if ($announcement=~/\w/) {
5131: return
5132: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5133: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5134: } else {
5135: return '';
5136: }
5137: } else {
5138: return '';
5139: }
1.351 www 5140: }
1.353 www 5141:
5142: # ---------------------------------------------------------- Course ID routines
5143: # Deal with domain's nohist_courseid.db files
5144: #
5145:
5146: sub courseidput {
1.921 raeburn 5147: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5148: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5149: my $outcome;
5150: if ($caller eq 'timeonly') {
5151: my $cids = '';
5152: foreach my $item (keys(%$storehash)) {
5153: $cids.=&escape($item).'&';
5154: }
5155: $cids=~s/\&$//;
5156: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5157: $coursehome);
5158: } else {
5159: my $items = '';
5160: foreach my $item (keys(%$storehash)) {
5161: $items.= &escape($item).'='.
5162: &freeze_escape($$storehash{$item}).'&';
5163: }
5164: $items=~s/\&$//;
5165: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5166: $coursehome);
1.918 raeburn 5167: }
5168: if ($outcome eq 'unknown_cmd') {
5169: my $what;
5170: foreach my $cid (keys(%$storehash)) {
5171: $what .= &escape($cid).'=';
1.921 raeburn 5172: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5173: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5174: }
5175: $what =~ s/\:$/&/;
5176: }
5177: $what =~ s/\&$//;
5178: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5179: } else {
5180: return $outcome;
5181: }
1.353 www 5182: }
5183:
5184: sub courseiddump {
1.921 raeburn 5185: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5186: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5187: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5188: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5189: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5190: my $as_hash = 1;
5191: my %returnhash;
5192: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5193: my %libserv = &all_library();
5194: foreach my $tryserver (keys(%libserv)) {
5195: if ( ( $hostidflag == 1
5196: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5197: || (!defined($hostidflag)) ) {
5198:
1.918 raeburn 5199: if (($domfilter eq '') ||
5200: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5201: my $rep;
5202: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5203: $rep = &LONCAPA::Lond::dump_course_id_handler(
5204: join(":", (&host_domain($tryserver), $sincefilter,
5205: &escape($descfilter), &escape($instcodefilter),
5206: &escape($ownerfilter), &escape($coursefilter),
5207: &escape($typefilter), &escape($regexp_ok),
5208: $as_hash, &escape($selfenrollonly),
5209: &escape($catfilter), $showhidden, $caller,
5210: &escape($cloner), &escape($cc_clone), $cloneonly,
5211: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5212: &escape($creationcontext),$domcloner,$hasuniquecode,
5213: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5214: } else {
5215: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5216: $sincefilter.':'.&escape($descfilter).':'.
5217: &escape($instcodefilter).':'.&escape($ownerfilter).
5218: ':'.&escape($coursefilter).':'.&escape($typefilter).
5219: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5220: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5221: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5222: &escape($cc_clone).':'.$cloneonly.':'.
5223: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5224: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5225: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5226: }
5227:
1.918 raeburn 5228: my @pairs=split(/\&/,$rep);
5229: foreach my $item (@pairs) {
5230: my ($key,$value)=split(/\=/,$item,2);
5231: $key = &unescape($key);
5232: next if ($key =~ /^error: 2 /);
5233: my $result = &thaw_unescape($value);
5234: if (ref($result) eq 'HASH') {
5235: $returnhash{$key}=$result;
5236: } else {
1.921 raeburn 5237: my @responses = split(/:/,$value);
5238: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5239: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5240: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5241: }
1.1008 raeburn 5242: }
1.353 www 5243: }
5244: }
5245: }
5246: }
5247: return %returnhash;
5248: }
5249:
1.1055 raeburn 5250: sub courselastaccess {
5251: my ($cdom,$cnum,$hostidref) = @_;
5252: my %returnhash;
5253: if ($cdom && $cnum) {
5254: my $chome = &homeserver($cnum,$cdom);
5255: if ($chome ne 'no_host') {
5256: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5257: &extract_lastaccess(\%returnhash,$rep);
5258: }
5259: } else {
5260: if (!$cdom) { $cdom=''; }
5261: my %libserv = &all_library();
5262: foreach my $tryserver (keys(%libserv)) {
5263: if (ref($hostidref) eq 'ARRAY') {
5264: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5265: }
5266: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5267: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5268: &extract_lastaccess(\%returnhash,$rep);
5269: }
5270: }
5271: }
5272: return %returnhash;
5273: }
5274:
5275: sub extract_lastaccess {
5276: my ($returnhash,$rep) = @_;
5277: if (ref($returnhash) eq 'HASH') {
5278: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5279: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5280: $rep eq '') {
5281: my @pairs=split(/\&/,$rep);
5282: foreach my $item (@pairs) {
5283: my ($key,$value)=split(/\=/,$item,2);
5284: $key = &unescape($key);
5285: next if ($key =~ /^error: 2 /);
5286: $returnhash->{$key} = &thaw_unescape($value);
5287: }
5288: }
5289: }
5290: return;
5291: }
5292:
1.658 raeburn 5293: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5294:
5295: sub dcmailput {
1.685 raeburn 5296: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5297: my $status = &Apache::lonnet::critical(
1.740 www 5298: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5299: &escape($message),$server);
1.662 raeburn 5300: return $status;
5301: }
5302:
1.658 raeburn 5303: sub dcmaildump {
5304: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5305: my %returnhash=();
1.846 albertel 5306:
5307: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5308: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5309: &escape($enddate).':';
5310: my @esc_senders=map { &escape($_)} @$senders;
5311: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5312: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5313: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5314: if (($key) && ($value)) {
5315: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5316: }
5317: }
5318: }
5319: return %returnhash;
5320: }
1.662 raeburn 5321: # ---------------------------------------------------------- Domain roles
5322:
5323: sub get_domain_roles {
5324: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5325: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5326: $startdate = '.';
5327: }
1.1018 raeburn 5328: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5329: $enddate = '.';
5330: }
1.922 raeburn 5331: my $rolelist;
5332: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5333: $rolelist = join('&',@{$roles});
1.922 raeburn 5334: }
1.662 raeburn 5335: my %personnel = ();
1.841 albertel 5336:
5337: my %servers = &get_servers($dom,'library');
5338: foreach my $tryserver (keys(%servers)) {
5339: %{$personnel{$tryserver}}=();
5340: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5341: &escape($startdate).':'.
5342: &escape($enddate).':'.
5343: &escape($rolelist), $tryserver))) {
5344: my ($key,$value) = split(/\=/,$line,2);
5345: if (($key) && ($value)) {
5346: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5347: }
5348: }
1.662 raeburn 5349: }
5350: return %personnel;
5351: }
1.658 raeburn 5352:
1.1172.2.89 raeburn 5353: sub get_active_domroles {
5354: my ($dom,$roles) = @_;
5355: return () unless (ref($roles) eq 'ARRAY');
5356: my $now = time;
5357: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5358: my %domroles;
5359: foreach my $server (keys(%dompersonnel)) {
5360: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5361: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5362: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5363: }
5364: }
5365: return %domroles;
5366: }
5367:
1.1057 www 5368: # ----------------------------------------------------------- Interval timing
1.149 www 5369:
1.1153 www 5370: {
5371: # Caches needed for speedup of navmaps
5372: # We don't want to cache this for very long at all (5 seconds at most)
5373: #
5374: # The user for whom we cache
5375: my $cachedkey='';
5376: # The cached times for this user
5377: my %cachedtimes=();
5378: # When this was last done
1.1172.2.66 raeburn 5379: my $cachedtime='';
1.1153 www 5380:
5381: sub load_all_first_access {
1.1154 raeburn 5382: my ($uname,$udom)=@_;
1.1156 www 5383: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 5384: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 5385: return;
5386: }
5387: $cachedtime=time;
5388: $cachedkey=$uname.':'.$udom;
5389: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5390: }
5391:
1.504 albertel 5392: sub get_first_access {
1.1162 raeburn 5393: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 5394: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5395: if ($argsymb) { $symb=$argsymb; }
5396: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5397: if ($argmap) { $map = $argmap; }
1.926 albertel 5398: if ($type eq 'course') {
5399: $res='course';
5400: } elsif ($type eq 'map') {
1.588 albertel 5401: $res=&symbread($map);
5402: } else {
5403: $res=$symb;
5404: }
1.1153 www 5405: &load_all_first_access($uname,$udom);
5406: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5407: }
5408:
5409: sub set_first_access {
1.1162 raeburn 5410: my ($type,$interval)=@_;
1.790 albertel 5411: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5412: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5413: if ($type eq 'course') {
5414: $res='course';
5415: } elsif ($type eq 'map') {
1.588 albertel 5416: $res=&symbread($map);
5417: } else {
5418: $res=$symb;
5419: }
1.1153 www 5420: $cachedkey='';
1.1162 raeburn 5421: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5422: if ($firstaccess) {
5423: &logthis("First access time already set ($firstaccess) when attempting ".
5424: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5425: "in $courseid");
5426: return 'already_set';
5427: } else {
1.1162 raeburn 5428: my $start = time;
5429: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5430: $udom,$uname);
5431: if ($putres eq 'ok') {
5432: &put('timerinterval',{"$courseid\0$res"=>$interval},
5433: $udom,$uname);
5434: &appenv(
5435: {
5436: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5437: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5438: }
5439: );
1.1172.2.97 raeburn 5440: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5441: $cachedtimes{"$courseid\0$res"} = $start;
5442: }
1.1172.2.102 raeburn 5443: } elsif ($putres ne 'refused') {
5444: &logthis("Result: $putres when attempting to set first access time ".
5445: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5446: }
5447: return $putres;
1.505 albertel 5448: }
5449: return 'already_set';
1.504 albertel 5450: }
1.1153 www 5451: }
1.1172.2.32 raeburn 5452:
5453: sub checkout {
5454: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5455: my $now=time;
5456: my $lonhost=$perlvar{'lonHostID'};
5457: my $infostr=&escape(
5458: 'CHECKOUTTOKEN&'.
5459: $tuname.'&'.
5460: $tudom.'&'.
5461: $tcrsid.'&'.
5462: $symb.'&'.
5463: $now.'&'.$ENV{'REMOTE_ADDR'});
5464: my $token=&reply('tmpput:'.$infostr,$lonhost);
5465: if ($token=~/^error\:/) {
5466: &logthis("<font color=\"blue\">WARNING: ".
5467: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5468: "</font>");
5469: return '';
5470: }
5471:
5472: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5473: $token=~tr/a-z/A-Z/;
5474:
5475: my %infohash=('resource.0.outtoken' => $token,
5476: 'resource.0.checkouttime' => $now,
5477: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
5478:
5479: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5480: return '';
5481: } else {
5482: &logthis("<font color=\"blue\">WARNING: ".
5483: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5484: "</font>");
5485: }
5486:
5487: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5488: &escape('Checkout '.$infostr.' - '.
5489: $token)) ne 'ok') {
5490: return '';
5491: } else {
5492: &logthis("<font color=\"blue\">WARNING: ".
5493: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5494: "</font>");
5495: }
5496: return $token;
5497: }
5498:
5499: # ------------------------------------------------------------ Check in an item
5500:
5501: sub checkin {
5502: my $token=shift;
5503: my $now=time;
5504: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5505: $lonhost=~tr/A-Z/a-z/;
5506: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5507: $dtoken=~s/\W/\_/g;
5508: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5509: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5510:
5511: unless (($tuname) && ($tudom)) {
5512: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5513: return '';
5514: }
5515:
5516: unless (&allowed('mgr',$tcrsid)) {
5517: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5518: $env{'user.name'}.' - '.$env{'user.domain'});
5519: return '';
5520: }
5521:
5522: my %infohash=('resource.0.intoken' => $token,
5523: 'resource.0.checkintime' => $now,
5524: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
5525:
5526: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5527: return '';
5528: }
5529:
5530: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5531: &escape('Checkin - '.$token)) ne 'ok') {
5532: return '';
5533: }
5534:
5535: return ($symb,$tuname,$tudom,$tcrsid);
5536: }
5537:
1.110 www 5538: # --------------------------------------------- Set Expire Date for Spreadsheet
5539:
5540: sub expirespread {
5541: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5542: my $cid=$env{'request.course.id'};
1.110 www 5543: if ($cid) {
5544: my $now=time;
5545: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5546: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5547: $env{'course.'.$cid.'.num'}.
1.110 www 5548: ':nohist_expirationdates:'.
5549: &escape($key).'='.$now,
1.620 albertel 5550: $env{'course.'.$cid.'.home'})
1.110 www 5551: }
5552: return 'ok';
1.14 www 5553: }
5554:
1.109 www 5555: # ----------------------------------------------------- Devalidate Spreadsheets
5556:
5557: sub devalidate {
1.325 www 5558: my ($symb,$uname,$udom)=@_;
1.620 albertel 5559: my $cid=$env{'request.course.id'};
1.109 www 5560: if ($cid) {
1.391 matthew 5561: # delete the stored spreadsheets for
5562: # - the student level sheet of this user in course's homespace
5563: # - the assessment level sheet for this resource
5564: # for this user in user's homespace
1.553 albertel 5565: # - current conditional state info
1.325 www 5566: my $key=$uname.':'.$udom.':';
1.109 www 5567: my $status=
1.299 matthew 5568: &del('nohist_calculatedsheets',
1.391 matthew 5569: [$key.'studentcalc:'],
1.620 albertel 5570: $env{'course.'.$cid.'.domain'},
5571: $env{'course.'.$cid.'.num'})
1.133 albertel 5572: .' '.
5573: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5574: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5575: unless ($status eq 'ok ok') {
5576: &logthis('Could not devalidate spreadsheet '.
1.325 www 5577: $uname.' at '.$udom.' for '.
1.109 www 5578: $symb.': '.$status);
1.133 albertel 5579: }
1.553 albertel 5580: &delenv('user.state.'.$cid);
1.109 www 5581: }
5582: }
5583:
1.265 albertel 5584: sub get_scalar {
5585: my ($string,$end) = @_;
5586: my $value;
5587: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5588: $value = $1;
5589: } elsif ($$string =~ s/^([^&]*?)&//) {
5590: $value = $1;
5591: }
5592: return &unescape($value);
5593: }
5594:
5595: sub array2str {
5596: my (@array) = @_;
5597: my $result=&arrayref2str(\@array);
5598: $result=~s/^__ARRAY_REF__//;
5599: $result=~s/__END_ARRAY_REF__$//;
5600: return $result;
5601: }
5602:
1.204 albertel 5603: sub arrayref2str {
5604: my ($arrayref) = @_;
1.265 albertel 5605: my $result='__ARRAY_REF__';
1.204 albertel 5606: foreach my $elem (@$arrayref) {
1.265 albertel 5607: if(ref($elem) eq 'ARRAY') {
5608: $result.=&arrayref2str($elem).'&';
5609: } elsif(ref($elem) eq 'HASH') {
5610: $result.=&hashref2str($elem).'&';
5611: } elsif(ref($elem)) {
5612: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5613: } else {
5614: $result.=&escape($elem).'&';
5615: }
5616: }
5617: $result=~s/\&$//;
1.265 albertel 5618: $result .= '__END_ARRAY_REF__';
1.204 albertel 5619: return $result;
5620: }
5621:
1.168 albertel 5622: sub hash2str {
1.204 albertel 5623: my (%hash) = @_;
5624: my $result=&hashref2str(\%hash);
1.265 albertel 5625: $result=~s/^__HASH_REF__//;
5626: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5627: return $result;
5628: }
5629:
5630: sub hashref2str {
5631: my ($hashref)=@_;
1.265 albertel 5632: my $result='__HASH_REF__';
1.800 albertel 5633: foreach my $key (sort(keys(%$hashref))) {
5634: if (ref($key) eq 'ARRAY') {
5635: $result.=&arrayref2str($key).'=';
5636: } elsif (ref($key) eq 'HASH') {
5637: $result.=&hashref2str($key).'=';
5638: } elsif (ref($key)) {
1.265 albertel 5639: $result.='=';
1.800 albertel 5640: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5641: } else {
1.1132 raeburn 5642: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5643: }
5644:
1.800 albertel 5645: if(ref($hashref->{$key}) eq 'ARRAY') {
5646: $result.=&arrayref2str($hashref->{$key}).'&';
5647: } elsif(ref($hashref->{$key}) eq 'HASH') {
5648: $result.=&hashref2str($hashref->{$key}).'&';
5649: } elsif(ref($hashref->{$key})) {
1.265 albertel 5650: $result.='&';
1.800 albertel 5651: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5652: } else {
1.800 albertel 5653: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5654: }
5655: }
1.168 albertel 5656: $result=~s/\&$//;
1.265 albertel 5657: $result .= '__END_HASH_REF__';
1.168 albertel 5658: return $result;
5659: }
5660:
5661: sub str2hash {
1.265 albertel 5662: my ($string)=@_;
5663: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5664: return %$hash;
5665: }
5666:
5667: sub str2hashref {
1.168 albertel 5668: my ($string) = @_;
1.265 albertel 5669:
5670: my %hash;
5671:
5672: if($string !~ /^__HASH_REF__/) {
5673: if (! ($string eq '' || !defined($string))) {
5674: $hash{'error'}='Not hash reference';
5675: }
5676: return (\%hash, $string);
5677: }
5678:
5679: $string =~ s/^__HASH_REF__//;
5680:
5681: while($string !~ /^__END_HASH_REF__/) {
5682: #key
5683: my $key='';
5684: if($string =~ /^__HASH_REF__/) {
5685: ($key, $string)=&str2hashref($string);
5686: if(defined($key->{'error'})) {
5687: $hash{'error'}='Bad data';
5688: return (\%hash, $string);
5689: }
5690: } elsif($string =~ /^__ARRAY_REF__/) {
5691: ($key, $string)=&str2arrayref($string);
5692: if($key->[0] eq 'Array reference error') {
5693: $hash{'error'}='Bad data';
5694: return (\%hash, $string);
5695: }
5696: } else {
5697: $string =~ s/^(.*?)=//;
1.267 albertel 5698: $key=&unescape($1);
1.265 albertel 5699: }
5700: $string =~ s/^=//;
5701:
5702: #value
5703: my $value='';
5704: if($string =~ /^__HASH_REF__/) {
5705: ($value, $string)=&str2hashref($string);
5706: if(defined($value->{'error'})) {
5707: $hash{'error'}='Bad data';
5708: return (\%hash, $string);
5709: }
5710: } elsif($string =~ /^__ARRAY_REF__/) {
5711: ($value, $string)=&str2arrayref($string);
5712: if($value->[0] eq 'Array reference error') {
5713: $hash{'error'}='Bad data';
5714: return (\%hash, $string);
5715: }
5716: } else {
5717: $value=&get_scalar(\$string,'__END_HASH_REF__');
5718: }
5719: $string =~ s/^&//;
5720:
5721: $hash{$key}=$value;
1.204 albertel 5722: }
1.265 albertel 5723:
5724: $string =~ s/^__END_HASH_REF__//;
5725:
5726: return (\%hash, $string);
1.204 albertel 5727: }
5728:
5729: sub str2array {
1.265 albertel 5730: my ($string)=@_;
5731: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5732: return @$array;
5733: }
5734:
5735: sub str2arrayref {
1.204 albertel 5736: my ($string) = @_;
1.265 albertel 5737: my @array;
5738:
5739: if($string !~ /^__ARRAY_REF__/) {
5740: if (! ($string eq '' || !defined($string))) {
5741: $array[0]='Array reference error';
5742: }
5743: return (\@array, $string);
5744: }
5745:
5746: $string =~ s/^__ARRAY_REF__//;
5747:
5748: while($string !~ /^__END_ARRAY_REF__/) {
5749: my $value='';
5750: if($string =~ /^__HASH_REF__/) {
5751: ($value, $string)=&str2hashref($string);
5752: if(defined($value->{'error'})) {
5753: $array[0] ='Array reference error';
5754: return (\@array, $string);
5755: }
5756: } elsif($string =~ /^__ARRAY_REF__/) {
5757: ($value, $string)=&str2arrayref($string);
5758: if($value->[0] eq 'Array reference error') {
5759: $array[0] ='Array reference error';
5760: return (\@array, $string);
5761: }
5762: } else {
5763: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5764: }
5765: $string =~ s/^&//;
5766:
5767: push(@array, $value);
1.191 harris41 5768: }
1.265 albertel 5769:
5770: $string =~ s/^__END_ARRAY_REF__//;
5771:
5772: return (\@array, $string);
1.168 albertel 5773: }
5774:
1.167 albertel 5775: # -------------------------------------------------------------------Temp Store
5776:
1.168 albertel 5777: sub tmpreset {
5778: my ($symb,$namespace,$domain,$stuname) = @_;
5779: if (!$symb) {
5780: $symb=&symbread();
1.620 albertel 5781: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5782: }
5783: $symb=escape($symb);
5784:
1.620 albertel 5785: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5786: $namespace=~s/\//\_/g;
5787: $namespace=~s/\W//g;
5788:
1.620 albertel 5789: if (!$domain) { $domain=$env{'user.domain'}; }
5790: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5791: if ($domain eq 'public' && $stuname eq 'public') {
5792: $stuname=$ENV{'REMOTE_ADDR'};
5793: }
1.1117 foxr 5794: my $path=LONCAPA::tempdir();
1.168 albertel 5795: my %hash;
5796: if (tie(%hash,'GDBM_File',
5797: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5798: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5799: foreach my $key (keys(%hash)) {
1.180 albertel 5800: if ($key=~ /:$symb/) {
1.168 albertel 5801: delete($hash{$key});
5802: }
5803: }
5804: }
5805: }
5806:
1.167 albertel 5807: sub tmpstore {
1.168 albertel 5808: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5809:
5810: if (!$symb) {
5811: $symb=&symbread();
1.620 albertel 5812: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5813: }
5814: $symb=escape($symb);
5815:
5816: if (!$namespace) {
5817: # I don't think we would ever want to store this for a course.
5818: # it seems this will only be used if we don't have a course.
1.620 albertel 5819: #$namespace=$env{'request.course.id'};
1.168 albertel 5820: #if (!$namespace) {
1.620 albertel 5821: $namespace=$env{'request.state'};
1.168 albertel 5822: #}
5823: }
5824: $namespace=~s/\//\_/g;
5825: $namespace=~s/\W//g;
1.620 albertel 5826: if (!$domain) { $domain=$env{'user.domain'}; }
5827: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5828: if ($domain eq 'public' && $stuname eq 'public') {
5829: $stuname=$ENV{'REMOTE_ADDR'};
5830: }
1.168 albertel 5831: my $now=time;
5832: my %hash;
1.1117 foxr 5833: my $path=LONCAPA::tempdir();
1.168 albertel 5834: if (tie(%hash,'GDBM_File',
5835: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5836: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5837: $hash{"version:$symb"}++;
5838: my $version=$hash{"version:$symb"};
5839: my $allkeys='';
5840: foreach my $key (keys(%$storehash)) {
5841: $allkeys.=$key.':';
1.591 albertel 5842: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5843: }
5844: $hash{"$version:$symb:timestamp"}=$now;
5845: $allkeys.='timestamp';
5846: $hash{"$version:keys:$symb"}=$allkeys;
5847: if (untie(%hash)) {
5848: return 'ok';
5849: } else {
5850: return "error:$!";
5851: }
5852: } else {
5853: return "error:$!";
5854: }
5855: }
1.167 albertel 5856:
1.168 albertel 5857: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5858:
1.168 albertel 5859: sub tmprestore {
5860: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5861:
1.168 albertel 5862: if (!$symb) {
5863: $symb=&symbread();
1.620 albertel 5864: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5865: }
5866: $symb=escape($symb);
5867:
1.620 albertel 5868: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5869:
1.620 albertel 5870: if (!$domain) { $domain=$env{'user.domain'}; }
5871: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5872: if ($domain eq 'public' && $stuname eq 'public') {
5873: $stuname=$ENV{'REMOTE_ADDR'};
5874: }
1.168 albertel 5875: my %returnhash;
5876: $namespace=~s/\//\_/g;
5877: $namespace=~s/\W//g;
5878: my %hash;
1.1117 foxr 5879: my $path=LONCAPA::tempdir();
1.168 albertel 5880: if (tie(%hash,'GDBM_File',
5881: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5882: &GDBM_READER(),0640)) {
1.168 albertel 5883: my $version=$hash{"version:$symb"};
5884: $returnhash{'version'}=$version;
5885: my $scope;
5886: for ($scope=1;$scope<=$version;$scope++) {
5887: my $vkeys=$hash{"$scope:keys:$symb"};
5888: my @keys=split(/:/,$vkeys);
5889: my $key;
5890: $returnhash{"$scope:keys"}=$vkeys;
5891: foreach $key (@keys) {
1.591 albertel 5892: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5893: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5894: }
5895: }
1.168 albertel 5896: if (!(untie(%hash))) {
5897: return "error:$!";
5898: }
5899: } else {
5900: return "error:$!";
5901: }
5902: return %returnhash;
1.167 albertel 5903: }
5904:
1.9 www 5905: # ----------------------------------------------------------------------- Store
5906:
5907: sub store {
1.1172.2.64 raeburn 5908: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5909: my $home='';
5910:
1.168 albertel 5911: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5912:
1.213 www 5913: $symb=&symbclean($symb);
1.122 albertel 5914: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5915:
1.620 albertel 5916: if (!$domain) { $domain=$env{'user.domain'}; }
5917: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5918:
5919: &devalidate($symb,$stuname,$domain);
1.109 www 5920:
5921: $symb=escape($symb);
1.187 www 5922: if (!$namespace) {
1.620 albertel 5923: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5924: return '';
5925: }
5926: }
1.620 albertel 5927: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5928:
5929: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5930: $$storehash{'host'}=$perlvar{'lonHostID'};
5931:
1.12 www 5932: my $namevalue='';
1.800 albertel 5933: foreach my $key (keys(%$storehash)) {
5934: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5935: }
1.12 www 5936: $namevalue=~s/\&$//;
1.187 www 5937: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5938: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5939: }
5940:
1.47 www 5941: # -------------------------------------------------------------- Critical Store
5942:
5943: sub cstore {
1.1172.2.64 raeburn 5944: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5945: my $home='';
5946:
1.168 albertel 5947: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5948:
1.213 www 5949: $symb=&symbclean($symb);
1.122 albertel 5950: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5951:
1.620 albertel 5952: if (!$domain) { $domain=$env{'user.domain'}; }
5953: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5954:
5955: &devalidate($symb,$stuname,$domain);
1.109 www 5956:
5957: $symb=escape($symb);
1.187 www 5958: if (!$namespace) {
1.620 albertel 5959: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5960: return '';
5961: }
5962: }
1.620 albertel 5963: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5964:
5965: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5966: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5967:
1.47 www 5968: my $namevalue='';
1.800 albertel 5969: foreach my $key (keys(%$storehash)) {
5970: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5971: }
1.47 www 5972: $namevalue=~s/\&$//;
1.187 www 5973: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5974: return critical
1.1172.2.64 raeburn 5975: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5976: }
5977:
1.9 www 5978: # --------------------------------------------------------------------- Restore
5979:
5980: sub restore {
1.124 www 5981: my ($symb,$namespace,$domain,$stuname) = @_;
5982: my $home='';
5983:
1.168 albertel 5984: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5985:
1.122 albertel 5986: if (!$symb) {
1.1172.2.26 raeburn 5987: return if ($namespace eq 'courserequests');
5988: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5989: } else {
1.1172.2.26 raeburn 5990: unless ($namespace eq 'courserequests') {
5991: $symb=&escape(&symbclean($symb));
5992: }
1.122 albertel 5993: }
1.188 www 5994: if (!$namespace) {
1.620 albertel 5995: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5996: return '';
5997: }
5998: }
1.620 albertel 5999: if (!$domain) { $domain=$env{'user.domain'}; }
6000: if (!$stuname) { $stuname=$env{'user.name'}; }
6001: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6002: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6003:
1.12 www 6004: my %returnhash=();
1.800 albertel 6005: foreach my $line (split(/\&/,$answer)) {
6006: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6007: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6008: }
1.75 www 6009: my $version;
6010: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6011: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6012: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6013: }
1.75 www 6014: }
1.13 www 6015: return %returnhash;
1.34 www 6016: }
6017:
6018: # ---------------------------------------------------------- Course Description
1.1118 foxr 6019: #
6020: #
1.34 www 6021:
6022: sub coursedescription {
1.731 albertel 6023: my ($courseid,$args)=@_;
1.34 www 6024: $courseid=~s/^\///;
1.49 www 6025: $courseid=~s/\_/\//g;
1.34 www 6026: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6027: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6028: my $normalid=$cdomain.'_'.$cnum;
6029: # need to always cache even if we get errors otherwise we keep
6030: # trying and trying and trying to get the course description.
6031: my %envhash=();
6032: my %returnhash=();
1.731 albertel 6033:
6034: my $expiretime=600;
6035: if ($env{'request.course.id'} eq $normalid) {
6036: $expiretime=120;
6037: }
6038:
6039: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6040: if (!$args->{'freshen_cache'}
6041: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6042: foreach my $key (keys(%env)) {
6043: next if ($key !~ /^\Q$prefix\E(.*)/);
6044: my ($setting) = $1;
6045: $returnhash{$setting} = $env{$key};
6046: }
6047: return %returnhash;
6048: }
6049:
1.1118 foxr 6050: # get the data again
6051:
1.731 albertel 6052: if (!$args->{'one_time'}) {
6053: $envhash{'course.'.$normalid.'.last_cache'}=time;
6054: }
1.811 albertel 6055:
1.34 www 6056: if ($chome ne 'no_host') {
1.302 albertel 6057: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6058: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6059: my $username = $env{'user.name'}; # Defult username
6060: if(defined $args->{'user'}) {
6061: $username = $args->{'user'};
6062: }
1.129 albertel 6063: $returnhash{'home'}= $chome;
6064: $returnhash{'domain'} = $cdomain;
6065: $returnhash{'num'} = $cnum;
1.741 raeburn 6066: if (!defined($returnhash{'type'})) {
6067: $returnhash{'type'} = 'Course';
6068: }
1.130 albertel 6069: while (my ($name,$value) = each %returnhash) {
1.53 www 6070: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6071: }
1.270 www 6072: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6073: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6074: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6075: $envhash{'course.'.$normalid.'.home'}=$chome;
6076: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6077: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6078: }
6079: }
1.731 albertel 6080: if (!$args->{'one_time'}) {
1.949 raeburn 6081: &appenv(\%envhash);
1.731 albertel 6082: }
1.302 albertel 6083: return %returnhash;
1.461 www 6084: }
6085:
1.1080 raeburn 6086: sub update_released_required {
6087: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6088: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6089: $cid = $env{'request.course.id'};
6090: $cdom = $env{'course.'.$cid.'.domain'};
6091: $cnum = $env{'course.'.$cid.'.num'};
6092: $chome = $env{'course.'.$cid.'.home'};
6093: }
6094: if ($needsrelease) {
6095: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6096: my $needsupdate;
6097: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6098: $needsupdate = 1;
6099: } else {
6100: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6101: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6102: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6103: $needsupdate = 1;
6104: }
6105: }
6106: if ($needsupdate) {
6107: my %needshash = (
6108: 'internal.releaserequired' => $needsrelease,
6109: );
6110: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6111: if ($putresult eq 'ok') {
6112: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6113: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6114: if (ref($crsinfo{$cid}) eq 'HASH') {
6115: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6116: &courseidput($cdom,\%crsinfo,$chome,'notime');
6117: }
6118: }
6119: }
6120: }
6121: return;
6122: }
6123:
1.461 www 6124: # -------------------------------------------------See if a user is privileged
6125:
6126: sub privileged {
1.1172.2.23 raeburn 6127: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6128: my $now = time;
1.1172.2.23 raeburn 6129: my $roles;
6130: if (ref($possroles) eq 'ARRAY') {
6131: $roles = $possroles;
6132: } else {
6133: $roles = ['dc','su'];
6134: }
6135: if (ref($possdomains) eq 'ARRAY') {
6136: my %privileged = &privileged_by_domain($possdomains,$roles);
6137: foreach my $dom (@{$possdomains}) {
6138: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6139: (ref($privileged{$dom}) eq 'HASH')) {
6140: foreach my $role (@{$roles}) {
6141: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6142: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6143: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6144: return 1 unless (($end && $end < $now) ||
6145: ($start && $start > $now));
6146: }
6147: }
6148: }
6149: }
6150: }
6151: } else {
6152: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6153: my $now = time;
1.1170 droeschl 6154:
1.1172.2.58 raeburn 6155: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6156: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6157: if (grep(/^\Q$trole\E$/,@{$roles})) {
6158: return 1 unless ($tend && $tend < $now)
6159: or ($tstart && $tstart > $now);
1.1170 droeschl 6160: }
1.1172.2.23 raeburn 6161: }
6162: }
1.461 www 6163: return 0;
1.9 www 6164: }
1.1 albertel 6165:
1.1172.2.23 raeburn 6166: sub privileged_by_domain {
6167: my ($domains,$roles) = @_;
6168: my %privileged = ();
6169: my $cachetime = 60*60*24;
6170: my $now = time;
6171: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6172: return %privileged;
6173: }
6174: foreach my $dom (@{$domains}) {
6175: next if (ref($privileged{$dom}) eq 'HASH');
6176: my $needroles;
6177: foreach my $role (@{$roles}) {
6178: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6179: if (defined($cached)) {
6180: if (ref($result) eq 'HASH') {
6181: $privileged{$dom}{$role} = $result;
6182: }
6183: } else {
6184: $needroles = 1;
6185: }
6186: }
6187: if ($needroles) {
6188: my %dompersonnel = &get_domain_roles($dom,$roles);
6189: $privileged{$dom} = {};
6190: foreach my $server (keys(%dompersonnel)) {
6191: if (ref($dompersonnel{$server}) eq 'HASH') {
6192: foreach my $item (keys(%{$dompersonnel{$server}})) {
6193: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6194: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6195: next if ($end && $end < $now);
6196: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6197: $dompersonnel{$server}{$item};
6198: }
6199: }
6200: }
6201: if (ref($privileged{$dom}) eq 'HASH') {
6202: foreach my $role (@{$roles}) {
6203: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6204: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6205: } else {
6206: my %hash = ();
6207: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6208: }
6209: }
6210: }
6211: }
6212: }
6213: return %privileged;
6214: }
6215:
1.103 harris41 6216: # -------------------------------------------------------- Get user privileges
1.11 www 6217:
6218: sub rolesinit {
1.1169 droeschl 6219: my ($domain, $username) = @_;
6220: my %userroles = ('user.login.time' => time);
6221: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6222:
6223: # firstaccess and timerinterval are related to timed maps/resources.
6224: # also, blocking can be triggered by an activating timer
6225: # it's saved in the user's %env.
6226: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6227: my %timerinterval = &dump('timerinterval', $domain, $username);
6228: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6229: %timerintchk, %timerintenv);
6230:
1.1162 raeburn 6231: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6232: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6233: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6234: }
1.1169 droeschl 6235:
1.1162 raeburn 6236: foreach my $key (keys(%timerinterval)) {
6237: my ($cid,$rest) = split(/\0/,$key);
6238: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6239: }
1.1169 droeschl 6240:
1.11 www 6241: my %allroles=();
1.1162 raeburn 6242: my %allgroups=();
1.11 www 6243:
1.1172.2.58 raeburn 6244: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6245: my $role = $rolesdump{$area};
6246: $area =~ s/\_\w\w$//;
6247:
6248: my ($trole, $tend, $tstart, $group_privs);
6249:
6250: if ($role =~ /^cr/) {
6251: # Custom role, defined by a user
6252: # e.g., user.role.cr/msu/smith/mynewrole
6253: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6254: $trole = $1;
6255: ($tend, $tstart) = split('_', $2);
6256: } else {
6257: $trole = $role;
6258: }
6259: } elsif ($role =~ m|^gr/|) {
6260: # Role of member in a group, defined within a course/community
6261: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6262: ($trole, $tend, $tstart) = split(/_/, $role);
6263: next if $tstart eq '-1';
6264: ($trole, $group_privs) = split(/\//, $trole);
6265: $group_privs = &unescape($group_privs);
6266: } else {
6267: # Just a normal role, defined in roles.tab
6268: ($trole, $tend, $tstart) = split(/_/,$role);
6269: }
6270:
6271: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6272: $username);
6273: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6274:
6275: # role expired or not available yet?
6276: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6277: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6278:
6279: next if $area eq '' or $trole eq '';
6280:
6281: my $spec = "$trole.$area";
6282: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6283:
6284: if ($trole =~ /^cr\//) {
6285: # Custom role, defined by a user
6286: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6287: } elsif ($trole eq 'gr') {
6288: # Role of a member in a group, defined within a course/community
6289: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6290: next;
6291: } else {
6292: # Normal role, defined in roles.tab
6293: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6294: }
6295:
6296: my $cid = $tdomain.'_'.$trest;
6297: unless ($firstaccchk{$cid}) {
6298: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6299: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6300: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6301: $coursetimerstarts{$cid}{$item};
6302: }
6303: }
6304: $firstaccchk{$cid} = 1;
6305: }
6306: unless ($timerintchk{$cid}) {
6307: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6308: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6309: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6310: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6311: }
1.12 www 6312: }
1.1169 droeschl 6313: $timerintchk{$cid} = 1;
1.191 harris41 6314: }
1.11 www 6315: }
1.1169 droeschl 6316:
1.1172.2.91 raeburn 6317: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6318: \%allroles, \%allgroups);
1.1169 droeschl 6319: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6320: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6321:
1.1162 raeburn 6322: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6323: }
6324:
1.567 raeburn 6325: sub set_arearole {
1.1172.2.19 raeburn 6326: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6327: unless ($nolog) {
1.567 raeburn 6328: # log the associated role with the area
1.1172.2.19 raeburn 6329: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6330: }
1.743 albertel 6331: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6332: }
6333:
6334: sub custom_roleprivs {
6335: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6336: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6337: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6338: if (&hostname($homsvr) ne '') {
1.567 raeburn 6339: my ($rdummy,$roledef)=
6340: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6341: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6342: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6343: if (defined($syspriv)) {
1.1043 raeburn 6344: if ($trest =~ /^$match_community$/) {
6345: $syspriv =~ s/bre\&S//;
6346: }
1.567 raeburn 6347: $$allroles{'cm./'}.=':'.$syspriv;
6348: $$allroles{$spec.'./'}.=':'.$syspriv;
6349: }
6350: if ($tdomain ne '') {
6351: if (defined($dompriv)) {
6352: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6353: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6354: }
6355: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6356: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6357: my $rolename = $1;
6358: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6359: }
1.567 raeburn 6360: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6361: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6362: }
6363: }
6364: }
6365: }
6366: }
6367:
1.1172.2.89 raeburn 6368: sub course_adhocrole_privs {
6369: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6370: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6371: if ($overrides{"internal.adhocpriv.$rolename"}) {
6372: my (%currprivs,%storeprivs);
6373: foreach my $item (split(/:/,$coursepriv)) {
6374: my ($priv,$restrict) = split(/\&/,$item);
6375: $currprivs{$priv} = $restrict;
6376: }
6377: my (%possadd,%possremove,%full);
6378: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6379: my ($priv,$restrict)=split(/\&/,$item);
6380: $full{$priv} = $restrict;
6381: }
6382: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6383: next if ($item eq '');
6384: my ($rule,$rest) = split(/=/,$item);
6385: next unless (($rule eq 'off') || ($rule eq 'on'));
6386: foreach my $priv (split(/:/,$rest)) {
6387: if ($priv ne '') {
6388: if ($rule eq 'off') {
6389: $possremove{$priv} = 1;
6390: } else {
6391: $possadd{$priv} = 1;
6392: }
6393: }
6394: }
6395: }
6396: foreach my $priv (sort(keys(%full))) {
6397: if (exists($currprivs{$priv})) {
6398: unless (exists($possremove{$priv})) {
6399: $storeprivs{$priv} = $currprivs{$priv};
6400: }
6401: } elsif (exists($possadd{$priv})) {
6402: $storeprivs{$priv} = $full{$priv};
6403: }
6404: }
6405: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6406: }
6407: return $coursepriv;
6408: }
6409:
1.678 raeburn 6410: sub group_roleprivs {
6411: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6412: my $access = 1;
6413: my $now = time;
6414: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6415: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6416: if ($access) {
1.811 albertel 6417: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6418: $$allgroups{$course}{$group} .=':'.$group_privs;
6419: }
6420: }
1.567 raeburn 6421:
6422: sub standard_roleprivs {
6423: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6424: if (defined($pr{$trole.':s'})) {
6425: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6426: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6427: }
6428: if ($tdomain ne '') {
6429: if (defined($pr{$trole.':d'})) {
6430: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6431: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6432: }
6433: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6434: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6435: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6436: }
6437: }
6438: }
6439:
6440: sub set_userprivs {
1.1064 raeburn 6441: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6442: my $author=0;
6443: my $adv=0;
1.1172.2.91 raeburn 6444: my $rar=0;
1.678 raeburn 6445: my %grouproles = ();
6446: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6447: my @groupkeys;
1.1000 raeburn 6448: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6449: push(@groupkeys,$role);
6450: }
6451: if (ref($groups_roles) eq 'HASH') {
6452: foreach my $key (keys(%{$groups_roles})) {
6453: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6454: push(@groupkeys,$key);
6455: }
6456: }
6457: }
6458: if (@groupkeys > 0) {
6459: foreach my $role (@groupkeys) {
6460: my ($trole,$area,$sec,$extendedarea);
6461: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6462: $trole = $1;
6463: $area = $2;
6464: $sec = $3;
6465: $extendedarea = $area.$sec;
6466: if (exists($$allgroups{$area})) {
6467: foreach my $group (keys(%{$$allgroups{$area}})) {
6468: my $spec = $trole.'.'.$extendedarea;
6469: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6470: $$allgroups{$area}{$group};
1.1064 raeburn 6471: }
1.678 raeburn 6472: }
6473: }
6474: }
6475: }
6476: }
1.800 albertel 6477: foreach my $group (keys(%grouproles)) {
6478: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6479: }
1.800 albertel 6480: foreach my $role (keys(%{$allroles})) {
6481: my %thesepriv;
1.941 raeburn 6482: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6483: foreach my $item (split(/:/,$$allroles{$role})) {
6484: if ($item ne '') {
6485: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6486: if ($restrictions eq '') {
6487: $thesepriv{$privilege}='F';
6488: } elsif ($thesepriv{$privilege} ne 'F') {
6489: $thesepriv{$privilege}.=$restrictions;
6490: }
6491: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 6492: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6493: }
6494: }
6495: my $thesestr='';
1.1104 raeburn 6496: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6497: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6498: }
6499: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6500: }
1.1172.2.91 raeburn 6501: return ($author,$adv,$rar);
1.567 raeburn 6502: }
6503:
1.994 raeburn 6504: sub role_status {
1.1104 raeburn 6505: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6506: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 6507: my ($one,$two) = split(m{\./},$rolekey,2);
6508: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6509: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 6510: $$where = '/'.$two;
1.994 raeburn 6511: $$trolecode=$$role.'.'.$$where;
6512: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6513: $$tstatus='is';
1.1104 raeburn 6514: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6515: $$tstatus='future';
1.1034 raeburn 6516: if ($$tstart<$now) {
6517: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6518: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6519: my (%allroles,%allgroups,$group_privs,
6520: %groups_roles,@rolecodes);
1.1002 raeburn 6521: my %userroles = (
6522: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6523: );
1.1064 raeburn 6524: @rolecodes = ('cm');
1.1002 raeburn 6525: my $spec=$$role.'.'.$$where;
6526: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6527: if ($$role =~ /^cr\//) {
6528: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6529: push(@rolecodes,'cr');
1.1002 raeburn 6530: } elsif ($$role eq 'gr') {
1.1064 raeburn 6531: push(@rolecodes,$$role);
1.1002 raeburn 6532: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6533: $env{'user.name'});
1.1064 raeburn 6534: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6535: (undef,my $group_privs) = split(/\//,$trole);
6536: $group_privs = &unescape($group_privs);
6537: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6538: 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 6539: &get_groups_roles($tdomain,$trest,
6540: \%course_roles,\@rolecodes,
6541: \%groups_roles);
1.1002 raeburn 6542: } else {
1.1064 raeburn 6543: push(@rolecodes,$$role);
1.1002 raeburn 6544: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6545: }
1.1172.2.91 raeburn 6546: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6547: \%groups_roles);
1.1064 raeburn 6548: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6549: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6550: }
6551: }
1.1034 raeburn 6552: $$tstatus = 'is';
1.1002 raeburn 6553: }
1.994 raeburn 6554: }
6555: if ($$tend) {
1.1104 raeburn 6556: if ($$tend<$update) {
1.994 raeburn 6557: $$tstatus='expired';
6558: } elsif ($$tend<$now) {
6559: $$tstatus='will_not';
6560: }
6561: }
6562: }
6563: }
6564: }
6565:
1.1104 raeburn 6566: sub get_groups_roles {
6567: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6568: return unless((ref($cdom_courseroles) eq 'HASH') &&
6569: (ref($rolecodes) eq 'ARRAY') &&
6570: (ref($groups_roles) eq 'HASH'));
6571: if (keys(%{$cdom_courseroles}) > 0) {
6572: my ($cnum) = ($rest =~ /^($match_courseid)/);
6573: if ($cdom ne '' && $cnum ne '') {
6574: foreach my $key (keys(%{$cdom_courseroles})) {
6575: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6576: my $crsrole = $1;
6577: my $crssec = $2;
6578: if ($crsrole =~ /^cr/) {
6579: unless (grep(/^cr$/,@{$rolecodes})) {
6580: push(@{$rolecodes},'cr');
6581: }
6582: } else {
6583: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6584: push(@{$rolecodes},$crsrole);
6585: }
6586: }
6587: my $rolekey = "$crsrole./$cdom/$cnum";
6588: if ($crssec ne '') {
6589: $rolekey .= "/$crssec";
6590: }
6591: $rolekey .= './';
6592: $groups_roles->{$rolekey} = $rolecodes;
6593: }
6594: }
6595: }
6596: }
6597: return;
6598: }
6599:
6600: sub delete_env_groupprivs {
6601: my ($where,$courseroles,$possroles) = @_;
6602: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6603: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6604: unless (ref($courseroles->{$udom}) eq 'HASH') {
6605: %{$courseroles->{$udom}} =
6606: &get_my_roles('','','userroles',['active'],
6607: $possroles,[$udom],1);
6608: }
6609: if (ref($courseroles->{$udom}) eq 'HASH') {
6610: foreach my $item (keys(%{$courseroles->{$udom}})) {
6611: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6612: my $area = '/'.$cdom.'/'.$cnum;
6613: my $privkey = "user.priv.$crsrole.$area";
6614: if ($crssec ne '') {
6615: $privkey .= '/'.$crssec;
6616: }
6617: $privkey .= ".$area/$group";
6618: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6619: }
6620: }
6621: return;
6622: }
6623:
1.994 raeburn 6624: sub check_adhoc_privs {
1.1172.2.86 raeburn 6625: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6626: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6627: if ($sec) {
6628: $cckey .= '/'.$sec;
6629: }
1.1172.2.9 raeburn 6630: my $setprivs;
1.994 raeburn 6631: if ($env{$cckey}) {
6632: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6633: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6634: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6635: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6636: $setprivs = 1;
1.994 raeburn 6637: }
6638: } else {
1.1172.2.87 raeburn 6639: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6640: $setprivs = 1;
1.994 raeburn 6641: }
1.1172.2.9 raeburn 6642: return $setprivs;
1.994 raeburn 6643: }
6644:
6645: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6646: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6647: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6648: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6649: if ($sec ne '') {
6650: $area .= '/'.$sec;
6651: }
1.994 raeburn 6652: my $spec = $role.'.'.$area;
6653: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6654: $env{'user.name'},1);
1.1172.2.84 raeburn 6655: my %rolehash = ();
1.1172.2.89 raeburn 6656: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6657: my $rolename = $1;
1.1172.2.84 raeburn 6658: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6659: my %domdef = &get_domain_defaults($dcdom);
6660: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6661: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6662: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6663: }
6664: }
1.1172.2.84 raeburn 6665: } else {
6666: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6667: }
1.1172.2.91 raeburn 6668: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6669: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6670: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6671: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6672: &appenv( {'request.role' => $spec,
6673: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6674: 'request.course.sec' => $sec,
1.1088 raeburn 6675: }
6676: );
6677: my $tadv=0;
6678: if (&allowed('adv') eq 'F') { $tadv=1; }
6679: &appenv({'request.role.adv' => $tadv});
6680: }
1.994 raeburn 6681: }
6682:
1.12 www 6683: # --------------------------------------------------------------- get interface
6684:
6685: sub get {
1.131 albertel 6686: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6687: my $items='';
1.800 albertel 6688: foreach my $item (@$storearr) {
6689: $items.=&escape($item).'&';
1.191 harris41 6690: }
1.12 www 6691: $items=~s/\&$//;
1.620 albertel 6692: if (!$udomain) { $udomain=$env{'user.domain'}; }
6693: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6694: my $uhome=&homeserver($uname,$udomain);
6695:
1.133 albertel 6696: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6697: my @pairs=split(/\&/,$rep);
1.273 albertel 6698: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6699: return @pairs;
6700: }
1.15 www 6701: my %returnhash=();
1.42 www 6702: my $i=0;
1.800 albertel 6703: foreach my $item (@$storearr) {
6704: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6705: $i++;
1.191 harris41 6706: }
1.15 www 6707: return %returnhash;
1.27 www 6708: }
6709:
6710: # --------------------------------------------------------------- del interface
6711:
6712: sub del {
1.133 albertel 6713: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6714: my $items='';
1.800 albertel 6715: foreach my $item (@$storearr) {
6716: $items.=&escape($item).'&';
1.191 harris41 6717: }
1.984 neumanie 6718:
1.27 www 6719: $items=~s/\&$//;
1.620 albertel 6720: if (!$udomain) { $udomain=$env{'user.domain'}; }
6721: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6722: my $uhome=&homeserver($uname,$udomain);
6723: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6724: }
6725:
6726: # -------------------------------------------------------------- dump interface
6727:
1.1172.2.22 raeburn 6728: sub unserialize {
6729: my ($rep, $escapedkeys) = @_;
6730:
6731: return {} if $rep =~ /^error/;
6732:
6733: my %returnhash=();
6734: foreach my $item (split(/\&/,$rep)) {
6735: my ($key, $value) = split(/=/, $item, 2);
6736: $key = unescape($key) unless $escapedkeys;
6737: next if $key =~ /^error: 2 /;
6738: $returnhash{$key} = &thaw_unescape($value);
6739: }
6740: return \%returnhash;
6741: }
6742:
6743: # see Lond::dump_with_regexp
6744: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6745: sub dump {
1.1172.2.22 raeburn 6746: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6747: if (!$udomain) { $udomain=$env{'user.domain'}; }
6748: if (!$uname) { $uname=$env{'user.name'}; }
6749: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6750:
1.1172.2.55 raeburn 6751: if ($regexp) {
6752: $regexp=&escape($regexp);
6753: } else {
6754: $regexp='.';
6755: }
1.1172.2.22 raeburn 6756: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6757: # user is hosted on this machine
1.1172.2.55 raeburn 6758: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6759: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6760: return %{&unserialize($reply, $escapedkeys)};
6761: }
1.1166 raeburn 6762: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6763: my @pairs=split(/\&/,$rep);
6764: my %returnhash=();
1.1098 foxr 6765: if (!($rep =~ /^error/ )) {
6766: foreach my $item (@pairs) {
6767: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6768: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6769: next if ($key =~ /^error: 2 /);
6770: $returnhash{$key}=&thaw_unescape($value);
6771: }
1.755 albertel 6772: }
6773: return %returnhash;
1.407 www 6774: }
6775:
1.1098 foxr 6776:
1.717 albertel 6777: # --------------------------------------------------------- dumpstore interface
6778:
6779: sub dumpstore {
6780: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6781: # same as dump but keys must be escaped. They may contain colon separated
6782: # lists of values that may themself contain colons (e.g. symbs).
6783: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6784: }
6785:
1.407 www 6786: # -------------------------------------------------------------- keys interface
6787:
6788: sub getkeys {
6789: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6790: if (!$udomain) { $udomain=$env{'user.domain'}; }
6791: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6792: my $uhome=&homeserver($uname,$udomain);
6793: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6794: my @keyarray=();
1.800 albertel 6795: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6796: next if ($key =~ /^error: 2 /);
1.800 albertel 6797: push(@keyarray,&unescape($key));
1.407 www 6798: }
6799: return @keyarray;
1.318 matthew 6800: }
6801:
1.319 matthew 6802: # --------------------------------------------------------------- currentdump
6803: sub currentdump {
1.328 matthew 6804: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6805: $courseid = $env{'request.course.id'} if (! defined($courseid));
6806: $sdom = $env{'user.domain'} if (! defined($sdom));
6807: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6808: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6809: my $rep;
6810:
6811: if (grep { $_ eq $uhome } current_machine_ids()) {
6812: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6813: $courseid)));
6814: } else {
6815: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6816: }
6817:
1.318 matthew 6818: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6819: #
1.318 matthew 6820: my %returnhash=();
1.319 matthew 6821: #
6822: if ($rep eq "unknown_cmd") {
6823: # an old lond will not know currentdump
6824: # Do a dump and make it look like a currentdump
1.822 albertel 6825: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6826: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6827: my %hash = @tmp;
6828: @tmp=();
1.424 matthew 6829: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6830: } else {
6831: my @pairs=split(/\&/,$rep);
1.800 albertel 6832: foreach my $pair (@pairs) {
6833: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6834: my ($symb,$param) = split(/:/,$key);
6835: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6836: &thaw_unescape($value);
1.319 matthew 6837: }
1.191 harris41 6838: }
1.12 www 6839: return %returnhash;
1.424 matthew 6840: }
6841:
6842: sub convert_dump_to_currentdump{
6843: my %hash = %{shift()};
6844: my %returnhash;
6845: # Code ripped from lond, essentially. The only difference
6846: # here is the unescaping done by lonnet::dump(). Conceivably
6847: # we might run in to problems with parameter names =~ /^v\./
6848: while (my ($key,$value) = each(%hash)) {
6849: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6850: $symb = &unescape($symb);
6851: $param = &unescape($param);
1.424 matthew 6852: next if ($v eq 'version' || $symb eq 'keys');
6853: next if (exists($returnhash{$symb}) &&
6854: exists($returnhash{$symb}->{$param}) &&
6855: $returnhash{$symb}->{'v.'.$param} > $v);
6856: $returnhash{$symb}->{$param}=$value;
6857: $returnhash{$symb}->{'v.'.$param}=$v;
6858: }
6859: #
6860: # Remove all of the keys in the hashes which keep track of
6861: # the version of the parameter.
6862: while (my ($symb,$param_hash) = each(%returnhash)) {
6863: # use a foreach because we are going to delete from the hash.
6864: foreach my $key (keys(%$param_hash)) {
6865: delete($param_hash->{$key}) if ($key =~ /^v\./);
6866: }
6867: }
6868: return \%returnhash;
1.12 www 6869: }
6870:
1.627 albertel 6871: # ------------------------------------------------------ critical inc interface
6872:
6873: sub cinc {
6874: return &inc(@_,'critical');
6875: }
6876:
1.449 matthew 6877: # --------------------------------------------------------------- inc interface
6878:
6879: sub inc {
1.627 albertel 6880: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6881: if (!$udomain) { $udomain=$env{'user.domain'}; }
6882: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6883: my $uhome=&homeserver($uname,$udomain);
6884: my $items='';
6885: if (! ref($store)) {
6886: # got a single value, so use that instead
6887: $items = &escape($store).'=&';
6888: } elsif (ref($store) eq 'SCALAR') {
6889: $items = &escape($$store).'=&';
6890: } elsif (ref($store) eq 'ARRAY') {
6891: $items = join('=&',map {&escape($_);} @{$store});
6892: } elsif (ref($store) eq 'HASH') {
6893: while (my($key,$value) = each(%{$store})) {
6894: $items.= &escape($key).'='.&escape($value).'&';
6895: }
6896: }
6897: $items=~s/\&$//;
1.627 albertel 6898: if ($critical) {
6899: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6900: } else {
6901: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6902: }
1.449 matthew 6903: }
6904:
1.12 www 6905: # --------------------------------------------------------------- put interface
6906:
6907: sub put {
1.134 albertel 6908: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6909: if (!$udomain) { $udomain=$env{'user.domain'}; }
6910: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6911: my $uhome=&homeserver($uname,$udomain);
1.12 www 6912: my $items='';
1.800 albertel 6913: foreach my $item (keys(%$storehash)) {
6914: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6915: }
1.12 www 6916: $items=~s/\&$//;
1.134 albertel 6917: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6918: }
6919:
1.631 albertel 6920: # ------------------------------------------------------------ newput interface
6921:
6922: sub newput {
6923: my ($namespace,$storehash,$udomain,$uname)=@_;
6924: if (!$udomain) { $udomain=$env{'user.domain'}; }
6925: if (!$uname) { $uname=$env{'user.name'}; }
6926: my $uhome=&homeserver($uname,$udomain);
6927: my $items='';
6928: foreach my $key (keys(%$storehash)) {
6929: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6930: }
6931: $items=~s/\&$//;
6932: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6933: }
6934:
6935: # --------------------------------------------------------- putstore interface
6936:
1.524 raeburn 6937: sub putstore {
1.1172.2.59 raeburn 6938: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6939: if (!$udomain) { $udomain=$env{'user.domain'}; }
6940: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6941: my $uhome=&homeserver($uname,$udomain);
6942: my $items='';
1.715 albertel 6943: foreach my $key (keys(%$storehash)) {
6944: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6945: }
1.715 albertel 6946: $items=~s/\&$//;
1.716 albertel 6947: my $esc_symb=&escape($symb);
6948: my $esc_v=&escape($version);
1.715 albertel 6949: my $reply =
1.716 albertel 6950: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6951: $uhome);
1.1172.2.59 raeburn 6952: if (($tolog) && ($reply eq 'ok')) {
6953: my $namevalue='';
6954: foreach my $key (keys(%{$storehash})) {
6955: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6956: }
6957: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6958: '&host='.&escape($perlvar{'lonHostID'}).
6959: '&version='.$esc_v.
6960: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6961: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6962: }
1.715 albertel 6963: if ($reply eq 'unknown_cmd') {
1.716 albertel 6964: # gfall back to way things use to be done
1.715 albertel 6965: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6966: $uname);
1.524 raeburn 6967: }
1.715 albertel 6968: return $reply;
6969: }
6970:
6971: sub old_putstore {
1.716 albertel 6972: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6973: if (!$udomain) { $udomain=$env{'user.domain'}; }
6974: if (!$uname) { $uname=$env{'user.name'}; }
6975: my $uhome=&homeserver($uname,$udomain);
6976: my %newstorehash;
1.800 albertel 6977: foreach my $item (keys(%$storehash)) {
6978: my $key = $version.':'.&escape($symb).':'.$item;
6979: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6980: }
6981: my $items='';
6982: my %allitems = ();
1.800 albertel 6983: foreach my $item (keys(%newstorehash)) {
6984: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6985: my $key = $1.':keys:'.$2;
6986: $allitems{$key} .= $3.':';
6987: }
1.800 albertel 6988: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6989: }
1.800 albertel 6990: foreach my $item (keys(%allitems)) {
6991: $allitems{$item} =~ s/\:$//;
6992: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6993: }
6994: $items=~s/\&$//;
6995: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6996: }
6997:
1.47 www 6998: # ------------------------------------------------------ critical put interface
6999:
7000: sub cput {
1.134 albertel 7001: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7002: if (!$udomain) { $udomain=$env{'user.domain'}; }
7003: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7004: my $uhome=&homeserver($uname,$udomain);
1.47 www 7005: my $items='';
1.800 albertel 7006: foreach my $item (keys(%$storehash)) {
7007: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7008: }
1.47 www 7009: $items=~s/\&$//;
1.134 albertel 7010: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7011: }
7012:
7013: # -------------------------------------------------------------- eget interface
7014:
7015: sub eget {
1.133 albertel 7016: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7017: my $items='';
1.800 albertel 7018: foreach my $item (@$storearr) {
7019: $items.=&escape($item).'&';
1.191 harris41 7020: }
1.12 www 7021: $items=~s/\&$//;
1.620 albertel 7022: if (!$udomain) { $udomain=$env{'user.domain'}; }
7023: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7024: my $uhome=&homeserver($uname,$udomain);
7025: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7026: my @pairs=split(/\&/,$rep);
7027: my %returnhash=();
1.42 www 7028: my $i=0;
1.800 albertel 7029: foreach my $item (@$storearr) {
7030: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7031: $i++;
1.191 harris41 7032: }
1.12 www 7033: return %returnhash;
7034: }
7035:
1.667 albertel 7036: # ------------------------------------------------------------ tmpput interface
7037: sub tmpput {
1.802 raeburn 7038: my ($storehash,$server,$context)=@_;
1.667 albertel 7039: my $items='';
1.800 albertel 7040: foreach my $item (keys(%$storehash)) {
7041: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7042: }
7043: $items=~s/\&$//;
1.802 raeburn 7044: if (defined($context)) {
7045: $items .= ':'.&escape($context);
7046: }
1.667 albertel 7047: return &reply("tmpput:$items",$server);
7048: }
7049:
7050: # ------------------------------------------------------------ tmpget interface
7051: sub tmpget {
1.688 albertel 7052: my ($token,$server)=@_;
7053: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7054: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7055: my %returnhash;
1.1172.2.85 raeburn 7056: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7057: return %returnhash;
7058: }
1.667 albertel 7059: foreach my $item (split(/\&/,$rep)) {
7060: my ($key,$value)=split(/=/,$item);
7061: $returnhash{&unescape($key)}=&thaw_unescape($value);
7062: }
7063: return %returnhash;
7064: }
7065:
1.1113 raeburn 7066: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7067: sub tmpdel {
7068: my ($token,$server)=@_;
7069: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7070: return &reply("tmpdel:$token",$server);
7071: }
7072:
1.1172.2.13 raeburn 7073: # ------------------------------------------------------------ get_timebased_id
7074:
7075: sub get_timebased_id {
7076: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7077: $maxtries) = @_;
7078: my ($newid,$error,$dellock);
7079: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7080: return ('','ok','invalid call to get suffix');
7081: }
7082:
7083: # set defaults for any optional args for which values were not supplied
7084: if ($who eq '') {
7085: $who = $env{'user.name'}.':'.$env{'user.domain'};
7086: }
7087: if (!$locktries) {
7088: $locktries = 3;
7089: }
7090: if (!$maxtries) {
7091: $maxtries = 10;
7092: }
7093:
7094: if (($cdom eq '') || ($cnum eq '')) {
7095: if ($env{'request.course.id'}) {
7096: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7097: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7098: }
7099: if (($cdom eq '') || ($cnum eq '')) {
7100: return ('','ok','call to get suffix not in course context');
7101: }
7102: }
7103:
7104: # construct locking item
7105: my $lockhash = {
7106: $prefix."\0".'locked_'.$keyid => $who,
7107: };
7108: my $tries = 0;
7109:
7110: # attempt to get lock on nohist_$namespace file
7111: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7112: while (($gotlock ne 'ok') && $tries <$locktries) {
7113: $tries ++;
7114: sleep 1;
7115: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7116: }
7117:
7118: # attempt to get unique identifier, based on current timestamp
7119: if ($gotlock eq 'ok') {
7120: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7121: my $id = time;
7122: $newid = $id;
1.1172.2.56 raeburn 7123: if ($idtype eq 'addcode') {
7124: $newid .= &sixnum_code();
7125: }
1.1172.2.13 raeburn 7126: my $idtries = 0;
7127: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7128: if ($idtype eq 'concat') {
7129: $newid = $id.$idtries;
1.1172.2.56 raeburn 7130: } elsif ($idtype eq 'addcode') {
7131: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7132: } else {
7133: $newid ++;
7134: }
7135: $idtries ++;
7136: }
7137: if (!exists($inuse{$prefix."\0".$newid})) {
7138: my %new_item = (
7139: $prefix."\0".$newid => $who,
7140: );
7141: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7142: $cdom,$cnum);
7143: if ($putresult ne 'ok') {
7144: undef($newid);
7145: $error = 'error saving new item: '.$putresult;
7146: }
7147: } else {
1.1172.2.56 raeburn 7148: undef($newid);
1.1172.2.13 raeburn 7149: $error = ('error: no unique suffix available for the new item ');
7150: }
7151: # remove lock
7152: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7153: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7154: } else {
7155: $error = "error: could not obtain lockfile\n";
7156: $dellock = 'ok';
1.1172.2.58 raeburn 7157: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7158: $dellock = 'nolock';
7159: }
1.1172.2.13 raeburn 7160: }
7161: return ($newid,$dellock,$error);
7162: }
7163:
1.1172.2.56 raeburn 7164: sub sixnum_code {
7165: my $code;
7166: for (0..6) {
7167: $code .= int( rand(9) );
7168: }
7169: return $code;
7170: }
7171:
1.765 albertel 7172: # -------------------------------------------------- portfolio access checking
7173:
7174: sub portfolio_access {
1.1172.2.77 raeburn 7175: my ($requrl,$clientip) = @_;
1.765 albertel 7176: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7177: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7178: if ($result) {
7179: my %setters;
7180: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7181: my ($startblock,$endblock) =
7182: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7183: if ($startblock && $endblock) {
7184: return 'B';
7185: }
7186: } else {
7187: my ($startblock,$endblock) =
7188: &Apache::loncommon::blockcheck(\%setters,'port');
7189: if ($startblock && $endblock) {
7190: return 'B';
7191: }
7192: }
7193: }
1.765 albertel 7194: if ($result eq 'ok') {
1.766 albertel 7195: return 'F';
1.765 albertel 7196: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7197: return 'A';
1.765 albertel 7198: }
1.766 albertel 7199: return '';
1.765 albertel 7200: }
7201:
7202: sub get_portfolio_access {
1.1172.2.77 raeburn 7203: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7204:
7205: if (!ref($access_hash)) {
7206: my $current_perms = &get_portfile_permissions($udom,$unum);
7207: my %access_controls = &get_access_controls($current_perms,$group,
7208: $file_name);
7209: $access_hash = $access_controls{$file_name};
7210: }
7211:
1.1172.2.77 raeburn 7212: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7213: my $now = time;
7214: if (ref($access_hash) eq 'HASH') {
7215: foreach my $key (keys(%{$access_hash})) {
7216: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7217: if ($start > $now) {
7218: next;
7219: }
7220: if ($end && $end<$now) {
7221: next;
7222: }
7223: if ($scope eq 'public') {
7224: $public = $key;
7225: last;
7226: } elsif ($scope eq 'guest') {
7227: $guest = $key;
7228: } elsif ($scope eq 'domains') {
7229: push(@domains,$key);
7230: } elsif ($scope eq 'users') {
7231: push(@users,$key);
7232: } elsif ($scope eq 'course') {
7233: push(@courses,$key);
7234: } elsif ($scope eq 'group') {
7235: push(@groups,$key);
1.1172.2.77 raeburn 7236: } elsif ($scope eq 'ip') {
7237: push(@ips,$key);
1.765 albertel 7238: }
7239: }
7240: if ($public) {
7241: return 'ok';
1.1172.2.77 raeburn 7242: } elsif (@ips > 0) {
7243: my $allowed;
7244: foreach my $ipkey (@ips) {
7245: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7246: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7247: $allowed = 1;
7248: last;
7249: }
7250: }
7251: }
7252: if ($allowed) {
7253: return 'ok';
7254: }
1.765 albertel 7255: }
7256: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7257: if ($guest) {
7258: return $guest;
7259: }
7260: } else {
7261: if (@domains > 0) {
7262: foreach my $domkey (@domains) {
7263: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7264: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7265: return 'ok';
7266: }
7267: }
7268: }
7269: }
7270: if (@users > 0) {
7271: foreach my $userkey (@users) {
1.865 raeburn 7272: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7273: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7274: if (ref($item) eq 'HASH') {
7275: if (($item->{'uname'} eq $env{'user.name'}) &&
7276: ($item->{'udom'} eq $env{'user.domain'})) {
7277: return 'ok';
7278: }
7279: }
7280: }
7281: }
1.765 albertel 7282: }
7283: }
7284: my %roleshash;
7285: my @courses_and_groups = @courses;
7286: push(@courses_and_groups,@groups);
7287: if (@courses_and_groups > 0) {
7288: my (%allgroups,%allroles);
7289: my ($start,$end,$role,$sec,$group);
7290: foreach my $envkey (%env) {
1.1060 raeburn 7291: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7292: my $cid = $2.'_'.$3;
7293: if ($1 eq 'gr') {
7294: $group = $4;
7295: $allgroups{$cid}{$group} = $env{$envkey};
7296: } else {
7297: if ($4 eq '') {
7298: $sec = 'none';
7299: } else {
7300: $sec = $4;
7301: }
7302: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7303: }
1.811 albertel 7304: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7305: my $cid = $2.'_'.$3;
7306: if ($4 eq '') {
7307: $sec = 'none';
7308: } else {
7309: $sec = $4;
7310: }
7311: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7312: }
7313: }
7314: if (keys(%allroles) == 0) {
7315: return;
7316: }
7317: foreach my $key (@courses_and_groups) {
7318: my %content = %{$$access_hash{$key}};
7319: my $cnum = $content{'number'};
7320: my $cdom = $content{'domain'};
7321: my $cid = $cdom.'_'.$cnum;
7322: if (!exists($allroles{$cid})) {
7323: next;
7324: }
7325: foreach my $role_id (keys(%{$content{'roles'}})) {
7326: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7327: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7328: my @status = @{$content{'roles'}{$role_id}{'access'}};
7329: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7330: foreach my $role (keys(%{$allroles{$cid}})) {
7331: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7332: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7333: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7334: if (grep/^all$/,@sections) {
7335: return 'ok';
7336: } else {
7337: if (grep/^$sec$/,@sections) {
7338: return 'ok';
7339: }
7340: }
7341: }
7342: }
7343: if (keys(%{$allgroups{$cid}}) == 0) {
7344: if (grep/^none$/,@groups) {
7345: return 'ok';
7346: }
7347: } else {
7348: if (grep/^all$/,@groups) {
7349: return 'ok';
7350: }
7351: foreach my $group (keys(%{$allgroups{$cid}})) {
7352: if (grep/^$group$/,@groups) {
7353: return 'ok';
7354: }
7355: }
7356: }
7357: }
7358: }
7359: }
7360: }
7361: }
7362: if ($guest) {
7363: return $guest;
7364: }
7365: }
7366: }
7367: return;
7368: }
7369:
7370: sub course_group_datechecker {
7371: my ($dates,$now,$status) = @_;
7372: my ($start,$end) = split(/\./,$dates);
7373: if (!$start && !$end) {
7374: return 'ok';
7375: }
7376: if (grep/^active$/,@{$status}) {
7377: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7378: return 'ok';
7379: }
7380: }
7381: if (grep/^previous$/,@{$status}) {
7382: if ($end > $now ) {
7383: return 'ok';
7384: }
7385: }
7386: if (grep/^future$/,@{$status}) {
7387: if ($start > $now) {
7388: return 'ok';
7389: }
7390: }
7391: return;
7392: }
7393:
7394: sub parse_portfolio_url {
7395: my ($url) = @_;
7396:
7397: my ($type,$udom,$unum,$group,$file_name);
7398:
1.823 albertel 7399: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7400: $type = 1;
7401: $udom = $1;
7402: $unum = $2;
7403: $file_name = $3;
1.823 albertel 7404: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7405: $type = 2;
7406: $udom = $1;
7407: $unum = $2;
7408: $group = $3;
7409: $file_name = $3.'/'.$4;
7410: }
7411: if (wantarray) {
7412: return ($type,$udom,$unum,$file_name,$group);
7413: }
7414: return $type;
7415: }
7416:
7417: sub is_portfolio_url {
7418: my ($url) = @_;
7419: return scalar(&parse_portfolio_url($url));
7420: }
7421:
1.798 raeburn 7422: sub is_portfolio_file {
7423: my ($file) = @_;
1.820 raeburn 7424: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7425: return 1;
7426: }
7427: return;
7428: }
7429:
1.976 raeburn 7430: sub usertools_access {
1.1084 raeburn 7431: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7432: my ($access,%tools);
7433: if ($context eq '') {
7434: $context = 'tools';
7435: }
7436: if ($context eq 'requestcourses') {
7437: %tools = (
7438: official => 1,
7439: unofficial => 1,
1.1006 raeburn 7440: community => 1,
1.1172.2.37 raeburn 7441: textbook => 1,
1.985 raeburn 7442: );
1.1172.2.9 raeburn 7443: } elsif ($context eq 'requestauthor') {
7444: %tools = (
7445: requestauthor => 1,
7446: );
1.985 raeburn 7447: } else {
7448: %tools = (
7449: aboutme => 1,
7450: blog => 1,
1.1172.2.6 raeburn 7451: webdav => 1,
1.985 raeburn 7452: portfolio => 1,
7453: );
7454: }
1.976 raeburn 7455: return if (!defined($tools{$tool}));
7456:
1.1172.2.35 raeburn 7457: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7458: $udom = $env{'user.domain'};
7459: $uname = $env{'user.name'};
7460: }
7461:
1.978 raeburn 7462: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7463: if ($action ne 'reload') {
1.985 raeburn 7464: if ($context eq 'requestcourses') {
7465: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 7466: } elsif ($context eq 'requestauthor') {
7467: return $env{'environment.canrequest.author'};
1.985 raeburn 7468: } else {
7469: return $env{'environment.availabletools.'.$tool};
7470: }
7471: }
1.976 raeburn 7472: }
7473:
1.1172.2.9 raeburn 7474: my ($toolstatus,$inststatus,$envkey);
7475: if ($context eq 'requestauthor') {
7476: $envkey = $context;
7477: } else {
7478: $envkey = $context.'.'.$tool;
7479: }
1.976 raeburn 7480:
1.985 raeburn 7481: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7482: ($action ne 'reload')) {
1.1172.2.9 raeburn 7483: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7484: $inststatus = $env{'environment.inststatus'};
7485: } else {
1.1084 raeburn 7486: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 7487: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7488: $inststatus = $userenvref->{'inststatus'};
7489: } else {
1.1172.2.9 raeburn 7490: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7491: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7492: $inststatus = $userenv{'inststatus'};
7493: }
1.976 raeburn 7494: }
7495:
7496: if ($toolstatus ne '') {
7497: if ($toolstatus) {
7498: $access = 1;
7499: } else {
7500: $access = 0;
7501: }
7502: return $access;
7503: }
7504:
1.1084 raeburn 7505: my ($is_adv,%domdef);
7506: if (ref($is_advref) eq 'HASH') {
7507: $is_adv = $is_advref->{'is_adv'};
7508: } else {
7509: $is_adv = &is_advanced_user($udom,$uname);
7510: }
7511: if (ref($domdefref) eq 'HASH') {
7512: %domdef = %{$domdefref};
7513: } else {
7514: %domdef = &get_domain_defaults($udom);
7515: }
1.976 raeburn 7516: if (ref($domdef{$tool}) eq 'HASH') {
7517: if ($is_adv) {
7518: if ($domdef{$tool}{'_LC_adv'} ne '') {
7519: if ($domdef{$tool}{'_LC_adv'}) {
7520: $access = 1;
7521: } else {
7522: $access = 0;
7523: }
7524: return $access;
7525: }
7526: }
7527: if ($inststatus ne '') {
7528: my ($hasaccess,$hasnoaccess);
7529: foreach my $affiliation (split(/:/,$inststatus)) {
7530: if ($domdef{$tool}{$affiliation} ne '') {
7531: if ($domdef{$tool}{$affiliation}) {
7532: $hasaccess = 1;
7533: } else {
7534: $hasnoaccess = 1;
7535: }
7536: }
7537: }
7538: if ($hasaccess || $hasnoaccess) {
7539: if ($hasaccess) {
7540: $access = 1;
7541: } elsif ($hasnoaccess) {
7542: $access = 0;
7543: }
7544: return $access;
7545: }
7546: } else {
7547: if ($domdef{$tool}{'default'} ne '') {
7548: if ($domdef{$tool}{'default'}) {
7549: $access = 1;
7550: } elsif ($domdef{$tool}{'default'} == 0) {
7551: $access = 0;
7552: }
7553: return $access;
7554: }
7555: }
7556: } else {
1.1172.2.6 raeburn 7557: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7558: $access = 1;
7559: } else {
7560: $access = 0;
7561: }
1.976 raeburn 7562: return $access;
7563: }
7564: }
7565:
1.1050 raeburn 7566: sub is_course_owner {
7567: my ($cdom,$cnum,$udom,$uname) = @_;
7568: if (($udom eq '') || ($uname eq '')) {
7569: $udom = $env{'user.domain'};
7570: $uname = $env{'user.name'};
7571: }
7572: unless (($udom eq '') || ($uname eq '')) {
7573: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7574: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7575: return 1;
7576: } else {
7577: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7578: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7579: return 1;
7580: }
7581: }
7582: }
7583: }
7584: return;
7585: }
7586:
1.976 raeburn 7587: sub is_advanced_user {
7588: my ($udom,$uname) = @_;
1.1085 raeburn 7589: if ($udom ne '' && $uname ne '') {
7590: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7591: if (wantarray) {
7592: return ($env{'user.adv'},$env{'user.author'});
7593: } else {
7594: return $env{'user.adv'};
7595: }
1.1085 raeburn 7596: }
7597: }
1.976 raeburn 7598: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7599: my %allroles;
1.1128 raeburn 7600: my ($is_adv,$is_author);
1.976 raeburn 7601: foreach my $role (keys(%roleshash)) {
7602: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7603: my $area = '/'.$tdomain.'/'.$trest;
7604: if ($sec ne '') {
7605: $area .= '/'.$sec;
7606: }
7607: if (($area ne '') && ($trole ne '')) {
7608: my $spec=$trole.'.'.$area;
7609: if ($trole =~ /^cr\//) {
7610: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7611: } elsif ($trole ne 'gr') {
7612: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7613: }
1.1128 raeburn 7614: if ($trole eq 'au') {
7615: $is_author = 1;
7616: }
1.976 raeburn 7617: }
7618: }
7619: foreach my $role (keys(%allroles)) {
7620: last if ($is_adv);
7621: foreach my $item (split(/:/,$allroles{$role})) {
7622: if ($item ne '') {
7623: my ($privilege,$restrictions)=split(/&/,$item);
7624: if ($privilege eq 'adv') {
7625: $is_adv = 1;
7626: last;
7627: }
7628: }
7629: }
7630: }
1.1128 raeburn 7631: if (wantarray) {
7632: return ($is_adv,$is_author);
7633: }
1.976 raeburn 7634: return $is_adv;
7635: }
1.798 raeburn 7636:
1.1035 raeburn 7637: sub check_can_request {
1.1036 raeburn 7638: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7639: my $canreq = 0;
7640: my ($types,$typename) = &Apache::loncommon::course_types();
7641: my @options = ('approval','validate','autolimit');
7642: my $optregex = join('|',@options);
7643: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7644: foreach my $type (@{$types}) {
7645: if (&usertools_access($env{'user.name'},
7646: $env{'user.domain'},
7647: $type,undef,'requestcourses')) {
7648: $canreq ++;
1.1036 raeburn 7649: if (ref($request_domains) eq 'HASH') {
7650: push(@{$request_domains->{$type}},$env{'user.domain'});
7651: }
1.1035 raeburn 7652: if ($dom eq $env{'user.domain'}) {
7653: $can_request->{$type} = 1;
7654: }
7655: }
7656: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7657: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7658: if (@curr > 0) {
1.1036 raeburn 7659: foreach my $item (@curr) {
7660: if (ref($request_domains) eq 'HASH') {
7661: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7662: if ($otherdom ne '') {
7663: if (ref($request_domains->{$type}) eq 'ARRAY') {
7664: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7665: push(@{$request_domains->{$type}},$otherdom);
7666: }
7667: } else {
7668: push(@{$request_domains->{$type}},$otherdom);
7669: }
7670: }
7671: }
7672: }
7673: unless($dom eq $env{'user.domain'}) {
7674: $canreq ++;
1.1035 raeburn 7675: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7676: $can_request->{$type} = 1;
7677: }
7678: }
7679: }
7680: }
7681: }
7682: }
7683: return $canreq;
7684: }
7685:
1.341 www 7686: # ---------------------------------------------- Custom access rule evaluation
7687:
7688: sub customaccess {
7689: my ($priv,$uri)=@_;
1.807 albertel 7690: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7691: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7692: $udom = &LONCAPA::clean_domain($udom);
7693: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7694: my $access=0;
1.800 albertel 7695: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7696: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7697: if ($type eq 'user') {
7698: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7699: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7700: if ($tdom) {
7701: if ($tdom ne $env{'user.domain'}) { next; }
7702: }
1.896 albertel 7703: if ($tuname) {
7704: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7705: }
7706: $access=($effect eq 'allow');
7707: last;
7708: }
7709: } else {
7710: if ($role) {
7711: if ($role ne $urole) { next; }
7712: }
7713: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7714: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7715: if ($tdom) {
7716: if ($tdom ne $udom) { next; }
7717: }
7718: if ($tcrs) {
7719: if ($tcrs ne $ucrs) { next; }
7720: }
7721: if ($tsec) {
7722: if ($tsec ne $usec) { next; }
7723: }
7724: $access=($effect eq 'allow');
7725: last;
7726: }
7727: if ($realm eq '' && $role eq '') {
7728: $access=($effect eq 'allow');
7729: }
1.402 bowersj2 7730: }
1.341 www 7731: }
7732: return $access;
7733: }
7734:
1.103 harris41 7735: # ------------------------------------------------- Check for a user privilege
1.12 www 7736:
7737: sub allowed {
1.1172.2.65 raeburn 7738: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7739: my $ver_orguri=$uri;
1.439 www 7740: $uri=&deversion($uri);
1.152 www 7741: my $orguri=$uri;
1.52 www 7742: $uri=&declutter($uri);
1.809 raeburn 7743:
1.810 raeburn 7744: if ($priv eq 'evb') {
7745: # Evade communication block restrictions for specified role in a course
7746: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7747: return $1;
7748: } else {
7749: return;
7750: }
7751: }
7752:
1.620 albertel 7753: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7754: # Free bre access to adm and meta resources
1.775 albertel 7755: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 7756: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7757: && ($priv eq 'bre')) {
1.14 www 7758: return 'F';
1.159 www 7759: }
7760:
1.545 banghart 7761: # Free bre access to user's own portfolio contents
1.714 raeburn 7762: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7763: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7764: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7765: my %setters;
7766: my ($startblock,$endblock) =
7767: &Apache::loncommon::blockcheck(\%setters,'port');
7768: if ($startblock && $endblock) {
7769: return 'B';
7770: } else {
7771: return 'F';
7772: }
1.545 banghart 7773: }
7774:
1.762 raeburn 7775: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7776: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7777: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7778: if (exists($env{'request.course.id'})) {
7779: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7780: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7781: if (($domain eq $cdom) && ($name eq $cnum)) {
7782: my $courseprivid=$env{'request.course.id'};
7783: $courseprivid=~s/\_/\//;
7784: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7785: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7786: return $1;
1.762 raeburn 7787: } else {
7788: if ($env{'request.course.sec'}) {
7789: $courseprivid.='/'.$env{'request.course.sec'};
7790: }
7791: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7792: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7793: return $2;
7794: }
1.714 raeburn 7795: }
7796: }
7797: }
7798: }
7799:
1.159 www 7800: # Free bre to public access
7801:
7802: if ($priv eq 'bre') {
1.238 www 7803: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7804: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7805: return 'F';
7806: }
1.238 www 7807: if ($copyright eq 'priv') {
7808: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7809: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7810: return '';
7811: }
7812: }
7813: if ($copyright eq 'domain') {
7814: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7815: unless (($env{'user.domain'} eq $1) ||
7816: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7817: return '';
7818: }
1.262 matthew 7819: }
1.620 albertel 7820: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7821: # Library role, so allow browsing of resources in this domain.
7822: return 'F';
1.238 www 7823: }
1.341 www 7824: if ($copyright eq 'custom') {
7825: unless (&customaccess($priv,$uri)) { return ''; }
7826: }
1.14 www 7827: }
1.264 matthew 7828: # Domain coordinator is trying to create a course
1.620 albertel 7829: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7830: # uri is the requested domain in this case.
7831: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7832: # a role of dc for the domain in question.
1.620 albertel 7833: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7834: }
1.29 www 7835:
1.52 www 7836: my $thisallowed='';
7837: my $statecond=0;
7838: my $courseprivid='';
7839:
1.1039 raeburn 7840: my $ownaccess;
1.1043 raeburn 7841: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7842: if (($priv eq 'bro') && ($env{'user.author'})) {
7843: if ($uri eq '') {
7844: $ownaccess = 1;
7845: } else {
7846: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7847: my $udom = $env{'user.domain'};
7848: my $uname = $env{'user.name'};
7849: if ($uri =~ m{^\Q$udom\E/?$}) {
7850: $ownaccess = 1;
1.1040 raeburn 7851: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7852: unless ($uri =~ m{\.\./}) {
7853: $ownaccess = 1;
7854: }
7855: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7856: my $now = time;
7857: if ($uri =~ m{^([^/]+)/?$}) {
7858: my $adom = $1;
7859: foreach my $key (keys(%env)) {
1.1042 raeburn 7860: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7861: my ($start,$end) = split('.',$env{$key});
7862: if (($now >= $start) && (!$end || $end < $now)) {
7863: $ownaccess = 1;
7864: last;
7865: }
7866: }
7867: }
7868: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7869: my $adom = $1;
7870: my $aname = $2;
1.1042 raeburn 7871: foreach my $role ('ca','aa') {
7872: if ($env{"user.role.$role./$adom/$aname"}) {
7873: my ($start,$end) =
7874: split('.',$env{"user.role.$role./$adom/$aname"});
7875: if (($now >= $start) && (!$end || $end < $now)) {
7876: $ownaccess = 1;
7877: last;
7878: }
1.1039 raeburn 7879: }
7880: }
7881: }
7882: }
7883: }
7884: }
7885: }
7886:
1.52 www 7887: # Course
7888:
1.620 albertel 7889: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7890: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7891: $thisallowed.=$1;
7892: }
1.52 www 7893: }
1.29 www 7894:
1.52 www 7895: # Domain
7896:
1.620 albertel 7897: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7898: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7899: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7900: $thisallowed.=$1;
7901: }
1.12 www 7902: }
1.52 www 7903:
1.1141 raeburn 7904: # User who is not author or co-author might still be able to edit
7905: # resource of an author in the domain (e.g., if Domain Coordinator).
7906: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7907: (&allowed('mdc',$env{'request.course.id'}))) {
7908: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7909: $thisallowed.=$1;
7910: }
7911: }
7912:
1.52 www 7913: # Course: uri itself is a course
1.66 www 7914: my $courseuri=$uri;
7915: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7916: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7917:
1.620 albertel 7918: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7919: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 7920: if ($priv eq 'mip') {
7921: my $rem = $1;
7922: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
7923: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
7924: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7925: if ($cdom ne '') {
7926: my %passwdconf = &get_passwdconf($cdom);
7927: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
7928: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
7929: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
7930: my @inststatuses = split(':',$env{'environment.inststatus'});
7931: unless (@inststatuses) {
7932: @inststatuses = ('default');
7933: }
7934: foreach my $status (@inststatuses) {
7935: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
7936: $thisallowed.=$rem;
7937: }
7938: }
7939: }
7940: }
7941: }
7942: }
7943: }
7944: } else {
7945: unless (($priv eq 'bro') && (!$ownaccess)) {
7946: $thisallowed.=$1;
7947: }
1.1039 raeburn 7948: }
1.12 www 7949: }
1.29 www 7950:
1.665 albertel 7951: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7952: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7953: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7954: $thisallowed='';
1.671 raeburn 7955: my ($match)=&is_on_map($uri);
7956: if ($match) {
7957: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7958: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 7959: my $value = $1;
7960: if ($noblockcheck) {
7961: $thisallowed.=$value;
1.1162 raeburn 7962: } else {
1.1172.2.65 raeburn 7963: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7964: if (@blockers > 0) {
7965: $thisallowed = 'B';
7966: } else {
7967: $thisallowed.=$value;
7968: }
1.1162 raeburn 7969: }
1.671 raeburn 7970: }
7971: } else {
1.705 albertel 7972: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7973: if ($refuri) {
7974: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7975: $thisallowed='F';
1.671 raeburn 7976: } else {
7977: $refuri=&declutter($refuri);
7978: my ($match) = &is_on_map($refuri);
7979: if ($match) {
1.1172.2.65 raeburn 7980: if ($noblockcheck) {
1.1162 raeburn 7981: $thisallowed='F';
1.1172.2.65 raeburn 7982: } else {
7983: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7984: if (@blockers > 0) {
7985: $thisallowed = 'B';
7986: } else {
7987: $thisallowed='F';
7988: }
1.1162 raeburn 7989: }
1.671 raeburn 7990: }
1.669 raeburn 7991: }
1.671 raeburn 7992: }
7993: }
1.314 www 7994: }
1.492 albertel 7995:
1.766 albertel 7996: if ($priv eq 'bre'
7997: && $thisallowed ne 'F'
7998: && $thisallowed ne '2'
7999: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8000: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8001: }
8002:
1.52 www 8003: # Full access at system, domain or course-wide level? Exit.
1.29 www 8004: if ($thisallowed=~/F/) {
8005: return 'F';
8006: }
8007:
1.52 www 8008: # If this is generating or modifying users, exit with special codes
1.29 www 8009:
1.643 www 8010: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8011: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8012: my ($audom,$auname)=split('/',$uri);
1.643 www 8013: # no author name given, so this just checks on the general right to make a co-author in this domain
8014: unless ($auname) { return $thisallowed; }
8015: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8016: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8017: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8018: ($audom ne $env{'request.role.domain'}))) { return ''; }
8019: }
1.52 www 8020: return $thisallowed;
8021: }
8022: #
1.103 harris41 8023: # Gathered so far: system, domain and course wide privileges
1.52 www 8024: #
8025: # Course: See if uri or referer is an individual resource that is part of
8026: # the course
8027:
1.620 albertel 8028: if ($env{'request.course.id'}) {
1.232 www 8029:
1.1172.2.115 raeburn 8030: # If this is modifying password (internal auth) domains must match for user and user's role.
8031:
8032: if ($priv eq 'mip') {
8033: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8034: return $thisallowed;
8035: } else {
8036: return '';
8037: }
8038: }
8039:
1.620 albertel 8040: $courseprivid=$env{'request.course.id'};
8041: if ($env{'request.course.sec'}) {
8042: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8043: }
8044: $courseprivid=~s/\_/\//;
8045: my $checkreferer=1;
1.232 www 8046: my ($match,$cond)=&is_on_map($uri);
8047: if ($match) {
8048: $statecond=$cond;
1.620 albertel 8049: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8050: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8051: my $value = $1;
8052: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8053: if ($noblockcheck) {
1.1162 raeburn 8054: $thisallowed.=$value;
1.1172.2.65 raeburn 8055: } else {
8056: my @blockers = &has_comm_blocking($priv,$symb,$uri);
8057: if (@blockers > 0) {
8058: $thisallowed = 'B';
8059: } else {
8060: $thisallowed.=$value;
8061: }
1.1162 raeburn 8062: }
8063: } else {
8064: $thisallowed.=$value;
8065: }
1.52 www 8066: $checkreferer=0;
8067: }
1.29 www 8068: }
1.83 www 8069:
1.148 www 8070: if ($checkreferer) {
1.620 albertel 8071: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8072: unless ($refuri) {
1.800 albertel 8073: foreach my $key (keys(%env)) {
8074: if ($key=~/^httpref\..*\*/) {
8075: my $pattern=$key;
1.156 www 8076: $pattern=~s/^httpref\.\/res\///;
1.148 www 8077: $pattern=~s/\*/\[\^\/\]\+/g;
8078: $pattern=~s/\//\\\//g;
1.152 www 8079: if ($orguri=~/$pattern/) {
1.800 albertel 8080: $refuri=$env{$key};
1.148 www 8081: }
8082: }
1.191 harris41 8083: }
1.148 www 8084: }
1.232 www 8085:
1.148 www 8086: if ($refuri) {
1.152 www 8087: $refuri=&declutter($refuri);
1.232 www 8088: my ($match,$cond)=&is_on_map($refuri);
8089: if ($match) {
8090: my $refstatecond=$cond;
1.620 albertel 8091: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8092: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8093: my $value = $1;
8094: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8095: if ($noblockcheck) {
1.1162 raeburn 8096: $thisallowed.=$value;
1.1172.2.65 raeburn 8097: } else {
8098: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
8099: if (@blockers > 0) {
8100: $thisallowed = 'B';
8101: } else {
8102: $thisallowed.=$value;
8103: }
1.1162 raeburn 8104: }
8105: } else {
8106: $thisallowed.=$value;
8107: }
1.53 www 8108: $uri=$refuri;
8109: $statecond=$refstatecond;
1.52 www 8110: }
8111: }
1.148 www 8112: }
1.29 www 8113: }
1.52 www 8114: }
1.29 www 8115:
1.52 www 8116: #
1.103 harris41 8117: # Gathered now: all privileges that could apply, and condition number
1.52 www 8118: #
8119: #
8120: # Full or no access?
8121: #
1.29 www 8122:
1.52 www 8123: if ($thisallowed=~/F/) {
8124: return 'F';
8125: }
1.29 www 8126:
1.52 www 8127: unless ($thisallowed) {
8128: return '';
8129: }
1.29 www 8130:
1.52 www 8131: # Restrictions exist, deal with them
8132: #
8133: # C:according to course preferences
8134: # R:according to resource settings
8135: # L:unless locked
8136: # X:according to user session state
8137: #
8138:
8139: # Possibly locked functionality, check all courses
1.54 www 8140: # Locks might take effect only after 10 minutes cache expiration for other
8141: # courses, and 2 minutes for current course
1.52 www 8142:
8143: my $envkey;
8144: if ($thisallowed=~/L/) {
1.1000 raeburn 8145: foreach $envkey (keys(%env)) {
1.54 www 8146: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8147: my $courseid=$2;
8148: my $roleid=$1.'.'.$2;
1.92 www 8149: $courseid=~s/^\///;
1.54 www 8150: my $expiretime=600;
1.620 albertel 8151: if ($env{'request.role'} eq $roleid) {
1.54 www 8152: $expiretime=120;
8153: }
8154: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8155: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8156: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8157: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8158: }
1.620 albertel 8159: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8160: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8161: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8162: &log($env{'user.domain'},$env{'user.name'},
8163: $env{'user.home'},
1.57 www 8164: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8165: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8166: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8167: return '';
8168: }
8169: }
1.620 albertel 8170: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8171: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8172: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8173: &log($env{'user.domain'},$env{'user.name'},
8174: $env{'user.home'},
1.57 www 8175: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8176: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8177: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8178: return '';
8179: }
8180: }
8181: }
1.29 www 8182: }
1.52 www 8183: }
8184:
8185: #
8186: # Rest of the restrictions depend on selected course
8187: #
8188:
1.620 albertel 8189: unless ($env{'request.course.id'}) {
1.766 albertel 8190: if ($thisallowed eq 'A') {
8191: return 'A';
1.814 raeburn 8192: } elsif ($thisallowed eq 'B') {
8193: return 'B';
1.766 albertel 8194: } else {
8195: return '1';
8196: }
1.52 www 8197: }
1.29 www 8198:
1.52 www 8199: #
8200: # Now user is definitely in a course
8201: #
1.53 www 8202:
8203:
8204: # Course preferences
8205:
8206: if ($thisallowed=~/C/) {
1.620 albertel 8207: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8208: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8209: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8210: =~/\Q$rolecode\E/) {
1.1103 raeburn 8211: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8212: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8213: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8214: $env{'request.course.id'});
8215: }
1.237 www 8216: return '';
8217: }
8218:
1.620 albertel 8219: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8220: =~/\Q$unamedom\E/) {
1.1103 raeburn 8221: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8222: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8223: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8224: $env{'request.course.id'});
8225: }
1.54 www 8226: return '';
8227: }
1.53 www 8228: }
8229:
8230: # Resource preferences
8231:
8232: if ($thisallowed=~/R/) {
1.620 albertel 8233: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8234: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8235: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8236: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8237: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8238: }
8239: return '';
1.54 www 8240: }
1.53 www 8241: }
1.30 www 8242:
1.246 www 8243: # Restricted by state or randomout?
1.30 www 8244:
1.52 www 8245: if ($thisallowed=~/X/) {
1.620 albertel 8246: if ($env{'acc.randomout'}) {
1.579 albertel 8247: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8248: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8249: return '';
8250: }
1.247 www 8251: }
8252: if (&condval($statecond)) {
1.52 www 8253: return '2';
8254: } else {
8255: return '';
8256: }
8257: }
1.30 www 8258:
1.766 albertel 8259: if ($thisallowed eq 'A') {
8260: return 'A';
1.814 raeburn 8261: } elsif ($thisallowed eq 'B') {
8262: return 'B';
1.766 albertel 8263: }
1.52 www 8264: return 'F';
1.232 www 8265: }
1.1162 raeburn 8266:
1.1172.2.13 raeburn 8267: # ------------------------------------------- Check construction space access
8268:
8269: sub constructaccess {
8270: my ($url,$setpriv)=@_;
8271:
8272: # We do not allow editing of previous versions of files
8273: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8274:
8275: # Get username and domain from URL
8276: my ($ownername,$ownerdomain,$ownerhome);
8277:
8278: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 8279: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8280:
8281: # The URL does not really point to any authorspace, forget it
8282: unless (($ownername) && ($ownerdomain)) { return ''; }
8283:
8284: # Now we need to see if the user has access to the authorspace of
8285: # $ownername at $ownerdomain
8286:
8287: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8288: # Real author for this?
8289: $ownerhome = $env{'user.home'};
8290: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8291: return ($ownername,$ownerdomain,$ownerhome);
8292: }
8293: } else {
8294: # Co-author for this?
8295: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8296: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8297: $ownerhome = &homeserver($ownername,$ownerdomain);
8298: return ($ownername,$ownerdomain,$ownerhome);
8299: }
8300: }
8301:
8302: # We don't have any access right now. If we are not possibly going to do anything about this,
8303: # we might as well leave
8304: unless ($setpriv) { return ''; }
8305:
8306: # Backdoor access?
8307: my $allowed=&allowed('eco',$ownerdomain);
8308: # Nope
8309: unless ($allowed) { return ''; }
8310: # Looks like we may have access, but could be locked by the owner of the construction space
8311: if ($allowed eq 'U') {
8312: my %blocked=&get('environment',['domcoord.author'],
8313: $ownerdomain,$ownername);
8314: # Is blocked by owner
8315: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8316: }
8317: if (($allowed eq 'F') || ($allowed eq 'U')) {
8318: # Grant temporary access
8319: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 8320: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 8321: if (!$update) { $update = $then; }
8322: my $refresh=$env{'user.refresh.time'};
8323: if (!$refresh) { $refresh = $update; }
8324: my $now = time;
8325: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8326: $now,'ca','constructaccess');
8327: $ownerhome = &homeserver($ownername,$ownerdomain);
8328: return($ownername,$ownerdomain,$ownerhome);
8329: }
8330: # No business here
8331: return '';
8332: }
8333:
1.1172.2.66 raeburn 8334: # ----------------------------------------------------------- Content Blocking
8335:
8336: {
8337: # Caches for faster Course Contents display where content blocking
8338: # is in operation (i.e., interval param set) for timed quiz.
8339: #
8340: # User for whom data are being temporarily cached.
8341: my $cacheduser='';
8342: # Cached blockers for this user (a hash of blocking items).
8343: my %cachedblockers=();
8344: # When the data were last cached.
8345: my $cachedlast='';
8346:
8347: sub load_all_blockers {
8348: my ($uname,$udom,$blocks)=@_;
8349: if (($uname ne '') && ($udom ne '')) {
8350: if (($cacheduser eq $uname.':'.$udom) &&
8351: (abs($cachedlast-time)<5)) {
8352: return;
8353: }
8354: }
8355: $cachedlast=time;
8356: $cacheduser=$uname.':'.$udom;
8357: %cachedblockers = &get_commblock_resources($blocks);
8358: }
8359:
1.1162 raeburn 8360: sub get_comm_blocks {
8361: my ($cdom,$cnum) = @_;
8362: if ($cdom eq '' || $cnum eq '') {
8363: return unless ($env{'request.course.id'});
8364: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8365: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8366: }
8367: my %commblocks;
8368: my $hashid=$cdom.'_'.$cnum;
8369: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8370: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8371: %commblocks = %{$blocksref};
8372: } else {
8373: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8374: my $cachetime = 600;
8375: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8376: }
8377: return %commblocks;
8378: }
8379:
1.1172.2.66 raeburn 8380: sub get_commblock_resources {
8381: my ($blocks) = @_;
8382: my %blockers = ();
8383: return %blockers unless ($env{'request.course.id'});
8384: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8385: my %commblocks;
8386: if (ref($blocks) eq 'HASH') {
8387: %commblocks = %{$blocks};
8388: } else {
8389: %commblocks = &get_comm_blocks();
8390: }
1.1172.2.66 raeburn 8391: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8392: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8393: return %blockers unless (ref($navmap));
8394: my $now = time;
1.1162 raeburn 8395: foreach my $block (keys(%commblocks)) {
8396: if ($block =~ /^(\d+)____(\d+)$/) {
8397: my ($start,$end) = ($1,$2);
8398: if ($start <= $now && $end >= $now) {
8399: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8400: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8401: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8402: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8403: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8404: }
8405: }
8406: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8407: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8408: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8409: }
8410: }
8411: }
8412: }
8413: }
8414: } elsif ($block =~ /^firstaccess____(.+)$/) {
8415: my $item = $1;
1.1163 raeburn 8416: my @to_test;
1.1162 raeburn 8417: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8418: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 8419: my @interval;
8420: my $type = 'map';
8421: if ($item eq 'course') {
8422: $type = 'course';
8423: @interval=&EXT("resource.0.interval");
8424: } else {
8425: if ($item =~ /___\d+___/) {
8426: $type = 'resource';
8427: @interval=&EXT("resource.0.interval",$item);
8428: if (ref($navmap)) {
8429: my $res = $navmap->getBySymb($item);
8430: push(@to_test,$res);
8431: }
1.1162 raeburn 8432: } else {
1.1172.2.66 raeburn 8433: my $mapsymb = &symbread($item,1);
8434: if ($mapsymb) {
8435: if (ref($navmap)) {
8436: my $mapres = $navmap->getBySymb($mapsymb);
8437: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8438: foreach my $res (@to_test) {
8439: my $symb = $res->symb();
8440: next if ($symb eq $mapsymb);
8441: if ($symb ne '') {
8442: @interval=&EXT("resource.0.interval",$symb);
8443: if ($interval[1] eq 'map') {
8444: last;
1.1162 raeburn 8445: }
8446: }
8447: }
8448: }
8449: }
8450: }
1.1172.2.66 raeburn 8451: }
8452: if ($interval[0] =~ /^\d+$/) {
8453: my $first_access;
8454: if ($type eq 'resource') {
8455: $first_access=&get_first_access($interval[1],$item);
8456: } elsif ($type eq 'map') {
8457: $first_access=&get_first_access($interval[1],undef,$item);
8458: } else {
8459: $first_access=&get_first_access($interval[1]);
8460: }
8461: if ($first_access) {
8462: my $timesup = $first_access+$interval[0];
8463: if ($timesup > $now) {
8464: my $activeblock;
8465: foreach my $res (@to_test) {
8466: if ($res->answerable()) {
8467: $activeblock = 1;
8468: last;
8469: }
8470: }
8471: if ($activeblock) {
8472: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8473: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8474: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8475: }
8476: }
8477: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8478: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8479: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8480: }
1.1162 raeburn 8481: }
8482: }
8483: }
8484: }
8485: }
8486: }
8487: }
8488: }
8489: }
1.1172.2.66 raeburn 8490: return %blockers;
1.1162 raeburn 8491: }
8492:
1.1172.2.66 raeburn 8493: sub has_comm_blocking {
8494: my ($priv,$symb,$uri,$blocks) = @_;
8495: my @blockers;
8496: return unless ($env{'request.course.id'});
8497: return unless ($priv eq 'bre');
8498: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8499: return if ($env{'request.state'} eq 'construct');
8500: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8501: return unless (keys(%cachedblockers) > 0);
8502: my (%possibles,@symbs);
8503: if (!$symb) {
8504: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 8505: }
1.1172.2.66 raeburn 8506: if ($symb) {
8507: @symbs = ($symb);
8508: } elsif (keys(%possibles)) {
8509: @symbs = keys(%possibles);
8510: }
8511: my $noblock;
8512: foreach my $symb (@symbs) {
8513: last if ($noblock);
8514: my ($map,$resid,$resurl)=&decode_symb($symb);
8515: foreach my $block (keys(%cachedblockers)) {
8516: if ($block =~ /^firstaccess____(.+)$/) {
8517: my $item = $1;
8518: if (($item eq $map) || ($item eq $symb)) {
8519: $noblock = 1;
8520: last;
8521: }
1.1162 raeburn 8522: }
1.1172.2.66 raeburn 8523: if (ref($cachedblockers{$block}) eq 'HASH') {
8524: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8525: if ($cachedblockers{$block}{'resources'}{$symb}) {
8526: unless (grep(/^\Q$block\E$/,@blockers)) {
8527: push(@blockers,$block);
8528: }
8529: }
8530: }
8531: }
8532: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8533: if ($cachedblockers{$block}{'maps'}{$map}) {
8534: unless (grep(/^\Q$block\E$/,@blockers)) {
8535: push(@blockers,$block);
8536: }
8537: }
1.1162 raeburn 8538: }
8539: }
8540: }
1.1172.2.66 raeburn 8541: return if ($noblock);
8542: return @blockers;
8543: }
1.1162 raeburn 8544: }
8545:
1.1172.2.66 raeburn 8546: # -------------------------------- Deversion and split uri into path an filename
8547:
1.1133 foxr 8548: #
1.1172.2.66 raeburn 8549: # Removes the version from a URI and
1.1133 foxr 8550: # splits it in to its filename and path to the filename.
8551: # Seems like File::Basename could have done this more clearly.
8552: # Parameters:
8553: # $uri - input URI
8554: # Returns:
8555: # Two element list consisting of
8556: # $pathname - the URI up to and excluding the trailing /
8557: # $filename - The part of the URI following the last /
8558: # NOTE:
8559: # Another realization of this is simply:
8560: # use File::Basename;
8561: # ...
8562: # $uri = shift;
8563: # $filename = basename($uri);
8564: # $path = dirname($uri);
8565: # return ($filename, $path);
8566: #
8567: # The implementation below is probably faster however.
8568: #
1.710 albertel 8569: sub split_uri_for_cond {
8570: my $uri=&deversion(&declutter(shift));
8571: my @uriparts=split(/\//,$uri);
8572: my $filename=pop(@uriparts);
8573: my $pathname=join('/',@uriparts);
8574: return ($pathname,$filename);
8575: }
1.232 www 8576: # --------------------------------------------------- Is a resource on the map?
8577:
8578: sub is_on_map {
1.710 albertel 8579: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8580: #Trying to find the conditional for the file
1.620 albertel 8581: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8582: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8583: if ($match) {
1.289 bowersj2 8584: return (1,$1);
8585: } else {
1.434 www 8586: return (0,0);
1.289 bowersj2 8587: }
1.12 www 8588: }
8589:
1.427 www 8590: # --------------------------------------------------------- Get symb from alias
8591:
8592: sub get_symb_from_alias {
8593: my $symb=shift;
8594: my ($map,$resid,$url)=&decode_symb($symb);
8595: # Already is a symb
8596: if ($url) { return $symb; }
8597: # Must be an alias
8598: my $aliassymb='';
8599: my %bighash;
1.620 albertel 8600: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8601: &GDBM_READER(),0640)) {
8602: my $rid=$bighash{'mapalias_'.$symb};
8603: if ($rid) {
8604: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8605: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8606: $resid,$bighash{'src_'.$rid});
1.427 www 8607: }
8608: untie %bighash;
8609: }
8610: return $aliassymb;
8611: }
8612:
1.12 www 8613: # ----------------------------------------------------------------- Define Role
8614:
8615: sub definerole {
8616: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8617: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8618: foreach my $role (split(':',$sysrole)) {
8619: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8620: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8621: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8622: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8623: return "refused:s:$crole&$cqual";
8624: }
8625: }
1.191 harris41 8626: }
1.800 albertel 8627: foreach my $role (split(':',$domrole)) {
8628: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8629: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8630: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8631: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8632: return "refused:d:$crole&$cqual";
8633: }
8634: }
1.191 harris41 8635: }
1.800 albertel 8636: foreach my $role (split(':',$courole)) {
8637: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8638: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8639: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8640: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8641: return "refused:c:$crole&$cqual";
8642: }
8643: }
1.191 harris41 8644: }
1.1172.2.84 raeburn 8645: my $uhome;
8646: if (($uname ne '') && ($udom ne '')) {
8647: $uhome = &homeserver($uname,$udom);
8648: return $uhome if ($uhome eq 'no_host');
8649: } else {
8650: $uname = $env{'user.name'};
8651: $udom = $env{'user.domain'};
8652: $uhome = $env{'user.home'};
8653: }
1.620 albertel 8654: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8655: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8656: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8657: return reply($command,$uhome);
1.12 www 8658: } else {
8659: return 'refused';
8660: }
1.105 harris41 8661: }
8662:
8663: # ---------------- Make a metadata query against the network of library servers
8664:
8665: sub metadata_query {
1.1172.2.33 raeburn 8666: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8667: my %rhash;
1.845 albertel 8668: my %libserv = &all_library();
1.244 matthew 8669: my @server_list = (defined($server_array) ? @$server_array
8670: : keys(%libserv) );
8671: for my $server (@server_list) {
1.1172.2.33 raeburn 8672: my $domains = '';
8673: if (ref($domains_hash) eq 'HASH') {
8674: $domains = $domains_hash->{$server};
8675: }
1.118 harris41 8676: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8677: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8678: $rhash{$server}=$reply;
8679: }
8680: else {
8681: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8682: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8683: $server);
8684: $rhash{$server}=$reply;
8685: }
1.112 harris41 8686: }
1.118 harris41 8687: return \%rhash;
1.240 www 8688: }
8689:
8690: # ----------------------------------------- Send log queries and wait for reply
8691:
8692: sub log_query {
8693: my ($uname,$udom,$query,%filters)=@_;
8694: my $uhome=&homeserver($uname,$udom);
8695: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8696: my $uhost=&hostname($uhome);
1.800 albertel 8697: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8698: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8699: $uhome);
1.479 albertel 8700: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8701: return get_query_reply($queryid);
8702: }
8703:
1.818 raeburn 8704: # -------------------------- Update MySQL table for portfolio file
8705:
8706: sub update_portfolio_table {
1.821 raeburn 8707: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8708: if ($group ne '') {
8709: $file_name =~s /^\Q$group\E//;
8710: }
1.818 raeburn 8711: my $homeserver = &homeserver($uname,$udom);
8712: my $queryid=
1.821 raeburn 8713: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8714: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8715: my $reply = &get_query_reply($queryid);
8716: return $reply;
8717: }
8718:
1.899 raeburn 8719: # -------------------------- Update MySQL allusers table
8720:
8721: sub update_allusers_table {
8722: my ($uname,$udom,$names) = @_;
8723: my $homeserver = &homeserver($uname,$udom);
8724: my $queryid=
8725: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8726: 'lastname='.&escape($names->{'lastname'}).'%%'.
8727: 'firstname='.&escape($names->{'firstname'}).'%%'.
8728: 'middlename='.&escape($names->{'middlename'}).'%%'.
8729: 'generation='.&escape($names->{'generation'}).'%%'.
8730: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8731: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8732: return;
1.899 raeburn 8733: }
8734:
1.508 raeburn 8735: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8736:
8737: sub fetch_enrollment_query {
1.511 raeburn 8738: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8739: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8740: my $maxtries = 1;
1.508 raeburn 8741: if ($context eq 'automated') {
8742: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8743: $sleep = 2;
8744: $loopmax = 100;
1.547 raeburn 8745: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8746: } else {
8747: $homeserver = &homeserver($cnum,$dom);
8748: }
1.838 albertel 8749: my $host=&hostname($homeserver);
1.506 raeburn 8750: my $cmd = '';
1.1000 raeburn 8751: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8752: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8753: }
8754: $cmd =~ s/%%$//;
8755: $cmd = &escape($cmd);
8756: my $query = 'fetchenrollment';
1.620 albertel 8757: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8758: unless ($queryid=~/^\Q$host\E\_/) {
8759: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8760: return 'error: '.$queryid;
8761: }
1.1172.2.93 raeburn 8762: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8763: my $tries = 1;
8764: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8765: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8766: $tries ++;
8767: }
1.526 raeburn 8768: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8769: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8770: } else {
1.901 albertel 8771: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8772: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8773: foreach my $line (@responses) {
8774: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8775: $$replyref{$key} = $value;
8776: }
8777: } else {
1.1117 foxr 8778: my $pathname = LONCAPA::tempdir();
1.800 albertel 8779: foreach my $line (@responses) {
8780: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8781: $$replyref{$key} = $value;
8782: if ($value > 0) {
1.800 albertel 8783: foreach my $item (@{$$affiliatesref{$key}}) {
8784: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8785: my $destname = $pathname.'/'.$filename;
8786: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8787: if ($xml_classlist =~ /^error/) {
8788: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8789: } else {
1.1172.2.96 raeburn 8790: if ( open(FILE,">",$destname) ) {
1.506 raeburn 8791: print FILE &unescape($xml_classlist);
8792: close(FILE);
1.526 raeburn 8793: } else {
8794: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8795: }
8796: }
8797: }
8798: }
8799: }
8800: }
8801: return 'ok';
8802: }
8803: return 'error';
8804: }
8805:
1.242 www 8806: sub get_query_reply {
1.1172.2.79 raeburn 8807: my ($queryid,$sleep,$loopmax) = @_;
8808: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8809: $sleep = 0.2;
8810: }
8811: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8812: $loopmax = 100;
8813: }
1.1117 foxr 8814: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8815: my $reply='';
1.1172.2.79 raeburn 8816: for (1..$loopmax) {
8817: sleep($sleep);
1.240 www 8818: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 8819: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 8820: $reply = join('',<$fh>);
8821: close($fh);
1.240 www 8822: } else { return 'error: reply_file_error'; }
1.242 www 8823: return &unescape($reply);
8824: }
1.240 www 8825: }
1.242 www 8826: return 'timeout:'.$queryid;
1.240 www 8827: }
8828:
8829: sub courselog_query {
1.241 www 8830: #
8831: # possible filters:
8832: # url: url or symb
8833: # username
8834: # domain
8835: # action: view, submit, grade
8836: # start: timestamp
8837: # end: timestamp
8838: #
1.240 www 8839: my (%filters)=@_;
1.620 albertel 8840: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8841: if ($filters{'url'}) {
8842: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8843: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8844: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8845: }
1.620 albertel 8846: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8847: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8848: return &log_query($cname,$cdom,'courselog',%filters);
8849: }
8850:
8851: sub userlog_query {
1.858 raeburn 8852: #
8853: # possible filters:
8854: # action: log check role
8855: # start: timestamp
8856: # end: timestamp
8857: #
1.240 www 8858: my ($uname,$udom,%filters)=@_;
8859: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8860: }
8861:
1.506 raeburn 8862: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8863:
8864: sub auto_run {
1.508 raeburn 8865: my ($cnum,$cdom) = @_;
1.876 raeburn 8866: my $response = 0;
8867: my $settings;
8868: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8869: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8870: $settings = $domconfig{'autoenroll'};
8871: if ($settings->{'run'} eq '1') {
8872: $response = 1;
8873: }
8874: } else {
1.934 raeburn 8875: my $homeserver;
8876: if (&is_course($cdom,$cnum)) {
8877: $homeserver = &homeserver($cnum,$cdom);
8878: } else {
8879: $homeserver = &domain($cdom,'primary');
8880: }
8881: if ($homeserver ne 'no_host') {
8882: $response = &reply('autorun:'.$cdom,$homeserver);
8883: }
1.876 raeburn 8884: }
1.506 raeburn 8885: return $response;
8886: }
1.776 albertel 8887:
1.506 raeburn 8888: sub auto_get_sections {
1.508 raeburn 8889: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8890: my $homeserver;
8891: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8892: $homeserver = &homeserver($cnum,$cdom);
8893: }
8894: if (!defined($homeserver)) {
8895: if ($cdom =~ /^$match_domain$/) {
8896: $homeserver = &domain($cdom,'primary');
8897: }
8898: }
8899: my @secs;
8900: if (defined($homeserver)) {
8901: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8902: unless ($response eq 'refused') {
8903: @secs = split(/:/,$response);
8904: }
1.506 raeburn 8905: }
8906: return @secs;
8907: }
1.776 albertel 8908:
1.506 raeburn 8909: sub auto_new_course {
1.1099 raeburn 8910: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8911: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8912: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8913: return $response;
8914: }
1.776 albertel 8915:
1.506 raeburn 8916: sub auto_validate_courseID {
1.508 raeburn 8917: my ($cnum,$cdom,$inst_course_id) = @_;
8918: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8919: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8920: return $response;
8921: }
1.776 albertel 8922:
1.1007 raeburn 8923: sub auto_validate_instcode {
1.1020 raeburn 8924: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8925: my ($homeserver,$response);
8926: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8927: $homeserver = &homeserver($cnum,$cdom);
8928: }
8929: if (!defined($homeserver)) {
8930: if ($cdom =~ /^$match_domain$/) {
8931: $homeserver = &domain($cdom,'primary');
8932: }
8933: }
1.1065 raeburn 8934: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8935: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 8936: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8937: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8938: }
8939:
1.506 raeburn 8940: sub auto_create_password {
1.873 raeburn 8941: my ($cnum,$cdom,$authparam,$udom) = @_;
8942: my ($homeserver,$response);
1.506 raeburn 8943: my $create_passwd = 0;
8944: my $authchk = '';
1.873 raeburn 8945: if ($udom =~ /^$match_domain$/) {
8946: $homeserver = &domain($udom,'primary');
8947: }
8948: if ($homeserver eq '') {
8949: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8950: $homeserver = &homeserver($cnum,$cdom);
8951: }
8952: }
8953: if ($homeserver eq '') {
8954: $authchk = 'nodomain';
1.506 raeburn 8955: } else {
1.873 raeburn 8956: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8957: if ($response eq 'refused') {
8958: $authchk = 'refused';
8959: } else {
1.901 albertel 8960: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8961: }
1.506 raeburn 8962: }
8963: return ($authparam,$create_passwd,$authchk);
8964: }
8965:
1.706 raeburn 8966: sub auto_photo_permission {
8967: my ($cnum,$cdom,$students) = @_;
8968: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8969: my ($outcome,$perm_reqd,$conditions) =
8970: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8971: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8972: return (undef,undef);
8973: }
1.706 raeburn 8974: return ($outcome,$perm_reqd,$conditions);
8975: }
8976:
8977: sub auto_checkphotos {
8978: my ($uname,$udom,$pid) = @_;
8979: my $homeserver = &homeserver($uname,$udom);
8980: my ($result,$resulttype);
8981: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8982: &escape($uname).':'.&escape($pid),
8983: $homeserver));
1.709 albertel 8984: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8985: return (undef,undef);
8986: }
1.706 raeburn 8987: if ($outcome) {
8988: ($result,$resulttype) = split(/:/,$outcome);
8989: }
8990: return ($result,$resulttype);
8991: }
8992:
8993: sub auto_photochoice {
8994: my ($cnum,$cdom) = @_;
8995: my $homeserver = &homeserver($cnum,$cdom);
8996: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8997: &escape($cdom),
8998: $homeserver)));
1.709 albertel 8999: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9000: return (undef,undef);
9001: }
1.706 raeburn 9002: return ($update,$comment);
9003: }
9004:
9005: sub auto_photoupdate {
9006: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9007: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9008: my $host=&hostname($homeserver);
1.706 raeburn 9009: my $cmd = '';
9010: my $maxtries = 1;
1.800 albertel 9011: foreach my $affiliate (keys(%{$affiliatesref})) {
9012: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9013: }
9014: $cmd =~ s/%%$//;
9015: $cmd = &escape($cmd);
9016: my $query = 'institutionalphotos';
9017: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9018: unless ($queryid=~/^\Q$host\E\_/) {
9019: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9020: return 'error: '.$queryid;
9021: }
9022: my $reply = &get_query_reply($queryid);
9023: my $tries = 1;
9024: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9025: $reply = &get_query_reply($queryid);
9026: $tries ++;
9027: }
9028: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9029: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9030: } else {
9031: my @responses = split(/:/,$reply);
9032: my $outcome = shift(@responses);
9033: foreach my $item (@responses) {
9034: my ($key,$value) = split(/=/,$item);
9035: $$photo{$key} = $value;
9036: }
9037: return $outcome;
9038: }
9039: return 'error';
9040: }
9041:
1.521 raeburn 9042: sub auto_instcode_format {
1.793 albertel 9043: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9044: $cat_order) = @_;
1.521 raeburn 9045: my $courses = '';
1.772 raeburn 9046: my @homeservers;
1.521 raeburn 9047: if ($caller eq 'global') {
1.841 albertel 9048: my %servers = &get_servers($codedom,'library');
9049: foreach my $tryserver (keys(%servers)) {
9050: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9051: push(@homeservers,$tryserver);
9052: }
1.584 raeburn 9053: }
1.1022 raeburn 9054: } elsif ($caller eq 'requests') {
9055: if ($codedom =~ /^$match_domain$/) {
9056: my $chome = &domain($codedom,'primary');
9057: unless ($chome eq 'no_host') {
9058: push(@homeservers,$chome);
9059: }
9060: }
1.521 raeburn 9061: } else {
1.772 raeburn 9062: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9063: }
1.793 albertel 9064: foreach my $code (keys(%{$instcodes})) {
9065: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9066: }
9067: chop($courses);
1.772 raeburn 9068: my $ok_response = 0;
9069: my $response;
9070: while (@homeservers > 0 && $ok_response == 0) {
9071: my $server = shift(@homeservers);
9072: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9073: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9074: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9075: split(/:/,$response);
1.772 raeburn 9076: %{$codes} = (%{$codes},&str2hash($codes_str));
9077: push(@{$codetitles},&str2array($codetitles_str));
9078: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9079: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9080: $ok_response = 1;
9081: }
9082: }
9083: if ($ok_response) {
1.521 raeburn 9084: return 'ok';
1.772 raeburn 9085: } else {
9086: return $response;
1.521 raeburn 9087: }
9088: }
9089:
1.792 raeburn 9090: sub auto_instcode_defaults {
9091: my ($domain,$returnhash,$code_order) = @_;
9092: my @homeservers;
1.841 albertel 9093:
9094: my %servers = &get_servers($domain,'library');
9095: foreach my $tryserver (keys(%servers)) {
9096: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9097: push(@homeservers,$tryserver);
9098: }
1.792 raeburn 9099: }
1.841 albertel 9100:
1.792 raeburn 9101: my $response;
1.841 albertel 9102: foreach my $server (@homeservers) {
1.792 raeburn 9103: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9104: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9105:
9106: foreach my $pair (split(/\&/,$response)) {
9107: my ($name,$value)=split(/\=/,$pair);
9108: if ($name eq 'code_order') {
9109: @{$code_order} = split(/\&/,&unescape($value));
9110: } else {
9111: $returnhash->{&unescape($name)}=&unescape($value);
9112: }
9113: }
9114: return 'ok';
1.792 raeburn 9115: }
1.841 albertel 9116:
9117: return $response;
1.1003 raeburn 9118: }
9119:
9120: sub auto_possible_instcodes {
1.1007 raeburn 9121: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9122: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9123: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9124: return;
9125: }
1.1003 raeburn 9126: my (@homeservers,$uhome);
9127: if (defined(&domain($domain,'primary'))) {
9128: $uhome=&domain($domain,'primary');
9129: push(@homeservers,&domain($domain,'primary'));
9130: } else {
9131: my %servers = &get_servers($domain,'library');
9132: foreach my $tryserver (keys(%servers)) {
9133: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9134: push(@homeservers,$tryserver);
9135: }
9136: }
9137: }
9138: my $response;
9139: foreach my $server (@homeservers) {
9140: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9141: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9142: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9143: split(':',$response);
9144: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9145: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9146: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9147: my ($name,$value)=split('=',$item);
9148: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9149: }
9150: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9151: my ($name,$value)=split('=',$item);
9152: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9153: }
9154: return 'ok';
9155: }
9156: return $response;
9157: }
1.792 raeburn 9158:
1.1010 raeburn 9159: sub auto_courserequest_checks {
9160: my ($dom) = @_;
1.1020 raeburn 9161: my ($homeserver,%validations);
9162: if ($dom =~ /^$match_domain$/) {
9163: $homeserver = &domain($dom,'primary');
9164: }
9165: unless ($homeserver eq 'no_host') {
9166: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9167: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9168: my @items = split(/&/,$response);
9169: foreach my $item (@items) {
9170: my ($key,$value) = split('=',$item);
9171: $validations{&unescape($key)} = &thaw_unescape($value);
9172: }
9173: }
9174: }
1.1010 raeburn 9175: return %validations;
9176: }
9177:
1.1020 raeburn 9178: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9179: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9180: my ($homeserver,$response);
9181: if ($dom =~ /^$match_domain$/) {
9182: $homeserver = &domain($dom,'primary');
9183: }
1.1172.2.43 raeburn 9184: unless ($homeserver eq 'no_host') {
9185: my $customdata;
9186: if (ref($custominfo) eq 'HASH') {
9187: $customdata = &freeze_escape($custominfo);
9188: }
1.1020 raeburn 9189: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9190: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9191: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9192: $customdata,$homeserver));
1.1020 raeburn 9193: }
9194: return $response;
9195: }
9196:
1.777 albertel 9197: sub auto_validate_class_sec {
1.918 raeburn 9198: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9199: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9200: my $ownerlist;
9201: if (ref($owners) eq 'ARRAY') {
9202: $ownerlist = join(',',@{$owners});
9203: } else {
9204: $ownerlist = $owners;
9205: }
1.773 raeburn 9206: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9207: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9208: return $response;
9209: }
9210:
1.1172.2.94 raeburn 9211: sub auto_validate_instclasses {
9212: my ($cdom,$cnum,$owners,$classesref) = @_;
9213: my ($homeserver,%validations);
9214: $homeserver = &homeserver($cnum,$cdom);
9215: unless ($homeserver eq 'no_host') {
9216: my $ownerlist;
9217: if (ref($owners) eq 'ARRAY') {
9218: $ownerlist = join(',',@{$owners});
9219: } else {
9220: $ownerlist = $owners;
9221: }
9222: if (ref($classesref) eq 'HASH') {
9223: my $classes = &freeze_escape($classesref);
9224: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9225: ':'.$cdom.':'.$classes,$homeserver);
9226: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9227: my @items = split(/&/,$response);
9228: foreach my $item (@items) {
9229: my ($key,$value) = split('=',$item);
9230: $validations{&unescape($key)} = &thaw_unescape($value);
9231: }
9232: }
9233: }
9234: }
9235: return %validations;
9236: }
9237:
1.1172.2.38 raeburn 9238: sub auto_crsreq_update {
9239: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 9240: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 9241: my ($homeserver,%crsreqresponse);
9242: if ($cdom =~ /^$match_domain$/) {
9243: $homeserver = &domain($cdom,'primary');
9244: }
9245: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9246: my $info;
9247: if (ref($inbound) eq 'HASH') {
9248: $info = &freeze_escape($inbound);
9249: }
9250: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9251: ':'.&escape($action).':'.&escape($ownername).':'.
9252: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 9253: &escape($title).':'.&escape($code).':'.
9254: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 9255: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9256: my @items = split(/&/,$response);
9257: foreach my $item (@items) {
9258: my ($key,$value) = split('=',$item);
9259: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9260: }
9261: }
9262: }
9263: return \%crsreqresponse;
9264: }
9265:
1.1172.2.78 raeburn 9266: sub auto_export_grades {
9267: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9268: my ($homeserver,%exportresponse);
9269: if ($cdom =~ /^$match_domain$/) {
9270: $homeserver = &domain($cdom,'primary');
9271: }
9272: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9273: my $info;
9274: if (ref($inforef) eq 'HASH') {
9275: $info = &freeze_escape($inforef);
9276: }
9277: if (ref($gradesref) eq 'HASH') {
9278: my $grades = &freeze_escape($gradesref);
9279: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9280: $info.':'.$grades,$homeserver);
9281: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9282: my @items = split(/&/,$response);
9283: foreach my $item (@items) {
9284: my ($key,$value) = split('=',$item);
9285: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9286: }
9287: }
9288: }
9289: }
9290: return \%exportresponse;
9291: }
9292:
1.1172.2.68 raeburn 9293: sub check_instcode_cloning {
9294: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9295: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9296: return;
9297: }
9298: my $canclone;
9299: if (@{$code_order} > 0) {
9300: my $instcoderegexp ='^';
9301: my @clonecodes = split(/\&/,$cloner);
9302: foreach my $item (@{$code_order}) {
9303: if (grep(/^\Q$item\E=/,@clonecodes)) {
9304: foreach my $pair (@clonecodes) {
9305: my ($key,$val) = split(/\=/,$pair,2);
9306: $val = &unescape($val);
9307: if ($key eq $item) {
9308: $instcoderegexp .= '('.$val.')';
9309: last;
9310: }
9311: }
9312: } else {
9313: $instcoderegexp .= $codedefaults->{$item};
9314: }
9315: }
9316: $instcoderegexp .= '$';
9317: my (@from,@to);
9318: eval {
9319: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9320: (@to) = ($clonetocode =~ /$instcoderegexp/);
9321: };
9322: if ((@from > 0) && (@to > 0)) {
9323: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9324: if (!@diffs) {
9325: $canclone = 1;
9326: }
9327: }
9328: }
9329: return $canclone;
9330: }
9331:
9332: sub default_instcode_cloning {
9333: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9334: my (%codedefaults,@code_order,$canclone);
9335: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9336: %codedefaults = %{$codedefaultsref};
9337: @code_order = @{$codeorderref};
9338: } elsif ($clonedom) {
9339: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9340: }
9341: if (($domdefclone) && (@code_order)) {
9342: my @clonecodes = split(/\+/,$domdefclone);
9343: my $instcoderegexp ='^';
9344: foreach my $item (@code_order) {
9345: if (grep(/^\Q$item\E$/,@clonecodes)) {
9346: $instcoderegexp .= '('.$codedefaults{$item}.')';
9347: } else {
9348: $instcoderegexp .= $codedefaults{$item};
9349: }
9350: }
9351: $instcoderegexp .= '$';
9352: my (@from,@to);
9353: eval {
9354: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9355: (@to) = ($clonetocode =~ /$instcoderegexp/);
9356: };
9357: if ((@from > 0) && (@to > 0)) {
9358: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9359: if (!@diffs) {
9360: $canclone = 1;
9361: }
9362: }
9363: }
9364: return $canclone;
9365: }
9366:
1.679 raeburn 9367: # ------------------------------------------------------- Course Group routines
9368:
9369: sub get_coursegroups {
1.809 raeburn 9370: my ($cdom,$cnum,$group,$namespace) = @_;
9371: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9372: }
9373:
1.679 raeburn 9374: sub modify_coursegroup {
9375: my ($cdom,$cnum,$groupsettings) = @_;
9376: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9377: }
9378:
1.809 raeburn 9379: sub toggle_coursegroup_status {
9380: my ($cdom,$cnum,$group,$action) = @_;
9381: my ($from_namespace,$to_namespace);
9382: if ($action eq 'delete') {
9383: $from_namespace = 'coursegroups';
9384: $to_namespace = 'deleted_groups';
9385: } else {
9386: $from_namespace = 'deleted_groups';
9387: $to_namespace = 'coursegroups';
9388: }
9389: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9390: if (my $tmp = &error(%curr_group)) {
9391: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9392: return ('read error',$tmp);
9393: } else {
9394: my %savedsettings = %curr_group;
1.809 raeburn 9395: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9396: my $deloutcome;
9397: if ($result eq 'ok') {
1.809 raeburn 9398: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9399: } else {
9400: return ('write error',$result);
9401: }
9402: if ($deloutcome eq 'ok') {
9403: return 'ok';
9404: } else {
9405: return ('delete error',$deloutcome);
9406: }
9407: }
9408: }
9409:
1.679 raeburn 9410: sub modify_group_roles {
1.957 raeburn 9411: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9412: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9413: my $role = 'gr/'.&escape($userprivs);
9414: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9415: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9416: if ($result eq 'ok') {
9417: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9418: }
1.679 raeburn 9419: return $result;
9420: }
9421:
9422: sub modify_coursegroup_membership {
9423: my ($cdom,$cnum,$membership) = @_;
9424: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9425: return $result;
9426: }
9427:
1.682 raeburn 9428: sub get_active_groups {
9429: my ($udom,$uname,$cdom,$cnum) = @_;
9430: my $now = time;
9431: my %groups = ();
9432: foreach my $key (keys(%env)) {
1.811 albertel 9433: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9434: my ($start,$end) = split(/\./,$env{$key});
9435: if (($end!=0) && ($end<$now)) { next; }
9436: if (($start!=0) && ($start>$now)) { next; }
9437: if ($1 eq $cdom && $2 eq $cnum) {
9438: $groups{$3} = $env{$key} ;
9439: }
9440: }
9441: }
9442: return %groups;
9443: }
9444:
1.683 raeburn 9445: sub get_group_membership {
9446: my ($cdom,$cnum,$group) = @_;
9447: return(&dump('groupmembership',$cdom,$cnum,$group));
9448: }
9449:
9450: sub get_users_groups {
9451: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9452: my @usersgroups;
1.683 raeburn 9453: my $cachetime=1800;
9454:
9455: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9456: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9457: if (defined($cached)) {
1.734 albertel 9458: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9459: } else {
9460: $grouplist = '';
1.816 raeburn 9461: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9462: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9463: my $access_end = $env{'course.'.$courseid.
9464: '.default_enrollment_end_date'};
9465: my $now = time;
9466: foreach my $key (keys(%roleshash)) {
9467: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9468: my $group = $1;
9469: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9470: my $start = $2;
9471: my $end = $1;
9472: if ($start == -1) { next; } # deleted from group
9473: if (($start!=0) && ($start>$now)) { next; }
9474: if (($end!=0) && ($end<$now)) {
9475: if ($access_end && $access_end < $now) {
9476: if ($access_end - $end < 86400) {
9477: push(@usersgroups,$group);
1.733 raeburn 9478: }
9479: }
1.817 raeburn 9480: next;
1.733 raeburn 9481: }
1.817 raeburn 9482: push(@usersgroups,$group);
1.683 raeburn 9483: }
9484: }
9485: }
1.817 raeburn 9486: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9487: $grouplist = join(':',@usersgroups);
9488: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9489: }
1.733 raeburn 9490: return @usersgroups;
1.683 raeburn 9491: }
9492:
9493: sub devalidate_getgroups_cache {
9494: my ($udom,$uname,$cdom,$cnum)=@_;
9495: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9496:
1.683 raeburn 9497: my $hashid="$udom:$uname:$courseid";
9498: &devalidate_cache_new('getgroups',$hashid);
9499: }
9500:
1.12 www 9501: # ------------------------------------------------------------------ Plain Text
9502:
9503: sub plaintext {
1.988 raeburn 9504: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9505: if ($short =~ m{^cr/}) {
1.758 albertel 9506: return (split('/',$short))[-1];
9507: }
1.742 raeburn 9508: if (!defined($cid)) {
9509: $cid = $env{'request.course.id'};
9510: }
9511: my %rolenames = (
1.1008 raeburn 9512: Course => 'std',
9513: Community => 'alt1',
1.742 raeburn 9514: );
1.1037 raeburn 9515: if ($cid ne '') {
9516: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9517: unless ($forcedefault) {
9518: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9519: &Apache::lonlocal::mt_escape(\$roletext);
9520: return &Apache::lonlocal::mt($roletext);
9521: }
9522: }
9523: }
9524: if ((defined($type)) && (defined($rolenames{$type})) &&
9525: (defined($rolenames{$type})) &&
9526: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9527: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9528: } elsif ($cid ne '') {
9529: my $crstype = $env{'course.'.$cid.'.type'};
9530: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9531: (defined($prp{$short}{$rolenames{$crstype}}))) {
9532: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9533: }
1.742 raeburn 9534: }
1.1037 raeburn 9535: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9536: }
9537:
9538: # ----------------------------------------------------------------- Assign Role
9539:
9540: sub assignrole {
1.957 raeburn 9541: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9542: $context)=@_;
1.21 www 9543: my $mrole;
9544: if ($role =~ /^cr\//) {
1.393 www 9545: my $cwosec=$url;
1.811 albertel 9546: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9547: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9548: my $refused = 1;
9549: if ($context eq 'requestcourses') {
9550: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9551: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9552: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9553: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9554: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9555: if ($crsenv{'internal.courseowner'} eq
9556: $env{'user.name'}.':'.$env{'user.domain'}) {
9557: $refused = '';
9558: }
9559: }
9560: }
9561: }
9562: }
9563: if ($refused) {
9564: &logthis('Refused custom assignrole: '.
9565: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9566: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9567: return 'refused';
9568: }
1.104 www 9569: }
1.21 www 9570: $mrole='cr';
1.678 raeburn 9571: } elsif ($role =~ /^gr\//) {
9572: my $cwogrp=$url;
1.811 albertel 9573: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9574: unless (&allowed('mdg',$cwogrp)) {
9575: &logthis('Refused group assignrole: '.
9576: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9577: $env{'user.name'}.' at '.$env{'user.domain'});
9578: return 'refused';
9579: }
9580: $mrole='gr';
1.21 www 9581: } else {
1.82 www 9582: my $cwosec=$url;
1.811 albertel 9583: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9584: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9585: my $refused;
9586: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9587: if (!(&allowed('c'.$role,$url))) {
9588: $refused = 1;
9589: }
9590: } else {
9591: $refused = 1;
9592: }
1.947 raeburn 9593: if ($refused) {
1.1045 raeburn 9594: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9595: if (!$selfenroll && $context eq 'course') {
9596: my %crsenv;
9597: if ($role eq 'cc' || $role eq 'co') {
9598: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9599: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9600: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9601: if ($crsenv{'internal.courseowner'} eq
9602: $env{'user.name'}.':'.$env{'user.domain'}) {
9603: $refused = '';
9604: }
9605: }
9606: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9607: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9608: if ($crsenv{'internal.courseowner'} eq
9609: $env{'user.name'}.':'.$env{'user.domain'}) {
9610: $refused = '';
9611: }
9612: }
9613: }
9614: }
9615: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9616: $refused = '';
1.1017 raeburn 9617: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9618: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9619: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9620: my $wrongcc;
9621: if ($cnum =~ /^$match_community$/) {
9622: $wrongcc = 1 if ($role eq 'cc');
9623: } else {
9624: $wrongcc = 1 if ($role eq 'co');
9625: }
9626: unless ($wrongcc) {
9627: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9628: if ($crsenv{'internal.courseowner'} eq
9629: $env{'user.name'}.':'.$env{'user.domain'}) {
9630: $refused = '';
9631: }
1.1017 raeburn 9632: }
9633: }
1.1172.2.9 raeburn 9634: } elsif ($context eq 'requestauthor') {
9635: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9636: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9637: if ($env{'environment.requestauthor'} eq 'automatic') {
9638: $refused = '';
9639: } else {
9640: my %domdefaults = &get_domain_defaults($udom);
9641: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9642: my $checkbystatus;
9643: if ($env{'user.adv'}) {
9644: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9645: if ($disposition eq 'automatic') {
9646: $refused = '';
9647: } elsif ($disposition eq '') {
9648: $checkbystatus = 1;
9649: }
9650: } else {
9651: $checkbystatus = 1;
9652: }
9653: if ($checkbystatus) {
9654: if ($env{'environment.inststatus'}) {
9655: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9656: foreach my $type (@inststatuses) {
9657: if (($type ne '') &&
9658: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9659: $refused = '';
9660: }
9661: }
9662: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9663: $refused = '';
9664: }
9665: }
9666: }
9667: }
9668: }
1.1017 raeburn 9669: }
9670: if ($refused) {
1.947 raeburn 9671: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9672: ' '.$role.' '.$end.' '.$start.' by '.
9673: $env{'user.name'}.' at '.$env{'user.domain'});
9674: return 'refused';
9675: }
1.932 raeburn 9676: }
1.1131 raeburn 9677: } elsif ($role eq 'au') {
9678: if ($url ne '/'.$udom.'/') {
9679: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9680: ' to assign author role for '.$uname.':'.$udom.
9681: ' in domain: '.$url.' refused (wrong domain).');
9682: return 'refused';
9683: }
1.104 www 9684: }
1.21 www 9685: $mrole=$role;
9686: }
1.620 albertel 9687: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9688: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9689: if ($end) { $command.='_'.$end; }
1.21 www 9690: if ($start) {
9691: if ($end) {
1.81 www 9692: $command.='_'.$start;
1.21 www 9693: } else {
1.81 www 9694: $command.='_0_'.$start;
1.21 www 9695: }
9696: }
1.739 raeburn 9697: my $origstart = $start;
9698: my $origend = $end;
1.957 raeburn 9699: my $delflag;
1.357 www 9700: # actually delete
9701: if ($deleteflag) {
1.373 www 9702: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9703: # modify command to delete the role
1.620 albertel 9704: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9705: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9706: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9707: # set start and finish to negative values for userrolelog
9708: $start=-1;
9709: $end=-1;
1.957 raeburn 9710: $delflag = 1;
1.357 www 9711: }
9712: }
9713: # send command
1.349 www 9714: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9715: # log new user role if status is ok
1.349 www 9716: if ($answer eq 'ok') {
1.663 raeburn 9717: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9718: if (($role eq 'cc') || ($role eq 'in') ||
9719: ($role eq 'ep') || ($role eq 'ad') ||
9720: ($role eq 'ta') || ($role eq 'st') ||
9721: ($role=~/^cr/) || ($role eq 'gr') ||
9722: ($role eq 'co')) {
1.1172.2.13 raeburn 9723: # for course roles, perform group memberships changes triggered by role change.
9724: unless ($role =~ /^gr/) {
9725: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9726: $origstart,$selfenroll,$context);
9727: }
1.1172.2.9 raeburn 9728: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9729: $selfenroll,$context);
9730: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9731: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9732: ($role eq 'da')) {
1.1172.2.9 raeburn 9733: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9734: $context);
9735: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9736: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9737: $context);
9738: }
1.1053 raeburn 9739: if ($role eq 'cc') {
9740: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9741: }
1.349 www 9742: }
9743: return $answer;
1.169 harris41 9744: }
9745:
1.1053 raeburn 9746: sub autoupdate_coowners {
9747: my ($url,$end,$start,$uname,$udom) = @_;
9748: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9749: if (($cdom ne '') && ($cnum ne '')) {
9750: my $now = time;
9751: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9752: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9753: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9754: my $instcode = $coursehash{'internal.coursecode'};
9755: if ($instcode ne '') {
1.1056 raeburn 9756: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9757: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9758: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9759: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9760: if ($result eq 'valid') {
9761: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9762: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9763: push(@newcoowners,$coowner);
9764: }
9765: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9766: push(@newcoowners,$uname.':'.$udom);
9767: }
9768: @newcoowners = sort(@newcoowners);
9769: } else {
9770: push(@newcoowners,$uname.':'.$udom);
9771: }
9772: } else {
9773: if ($coursehash{'internal.co-owners'}) {
9774: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9775: unless ($coowner eq $uname.':'.$udom) {
9776: push(@newcoowners,$coowner);
9777: }
9778: }
9779: unless (@newcoowners > 0) {
9780: $delcoowners = 1;
9781: $coowners = '';
9782: }
9783: }
9784: }
9785: if (@newcoowners || $delcoowners) {
9786: &store_coowners($cdom,$cnum,$coursehash{'home'},
9787: $delcoowners,@newcoowners);
9788: }
9789: }
9790: }
9791: }
9792: }
9793: }
9794: }
9795:
9796: sub store_coowners {
9797: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9798: my $cid = $cdom.'_'.$cnum;
9799: my ($coowners,$delresult,$putresult);
9800: if (@newcoowners) {
9801: $coowners = join(',',@newcoowners);
9802: my %coownershash = (
9803: 'internal.co-owners' => $coowners,
9804: );
9805: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9806: if ($putresult eq 'ok') {
9807: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9808: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9809: }
9810: }
9811: }
9812: if ($delcoowners) {
9813: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9814: if ($delresult eq 'ok') {
9815: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9816: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9817: }
9818: }
9819: }
9820: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9821: my %crsinfo =
9822: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9823: if (ref($crsinfo{$cid}) eq 'HASH') {
9824: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9825: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9826: }
9827: }
9828: }
9829:
1.169 harris41 9830: # -------------------------------------------------- Modify user authentication
1.197 www 9831: # Overrides without validation
9832:
1.169 harris41 9833: sub modifyuserauth {
9834: my ($udom,$uname,$umode,$upass)=@_;
9835: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 9836: my $allowed;
9837: if (&allowed('mau',$udom)) {
9838: $allowed = 1;
9839: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
9840: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
9841: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
9842: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9843: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9844: if (($cdom ne '') && ($cnum ne '')) {
9845: my $is_owner = &is_course_owner($cdom,$cnum);
9846: if ($is_owner) {
9847: $allowed = 1;
9848: }
9849: }
9850: }
9851: unless ($allowed) { return 'refused'; }
1.197 www 9852: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9853: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9854: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9855: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9856: &escape($upass),$uhome);
1.620 albertel 9857: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9858: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9859: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9860: &log($udom,,$uname,$uhome,
1.620 albertel 9861: 'Authentication changed by '.$env{'user.domain'}.', '.
9862: $env{'user.name'}.', '.$umode.
1.197 www 9863: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9864: unless ($reply eq 'ok') {
1.197 www 9865: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9866: return 'error: '.$reply;
9867: }
1.170 harris41 9868: return 'ok';
1.80 www 9869: }
9870:
1.81 www 9871: # --------------------------------------------------------------- Modify a user
1.80 www 9872:
1.81 www 9873: sub modifyuser {
1.206 matthew 9874: my ($udom, $uname, $uid,
9875: $umode, $upass, $first,
9876: $middle, $last, $gene,
1.1058 raeburn 9877: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9878: $udom= &LONCAPA::clean_domain($udom);
9879: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9880: my $showcandelete = 'none';
9881: if (ref($candelete) eq 'ARRAY') {
9882: if (@{$candelete} > 0) {
9883: $showcandelete = join(', ',@{$candelete});
9884: }
9885: }
1.81 www 9886: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9887: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9888: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9889: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9890: ' desiredhome not specified').
1.620 albertel 9891: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9892: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9893: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9894: my $newuser;
9895: if ($uhome eq 'no_host') {
9896: $newuser = 1;
9897: }
1.80 www 9898: # ----------------------------------------------------------------- Create User
1.406 albertel 9899: if (($uhome eq 'no_host') &&
9900: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9901: my $unhome='';
1.844 albertel 9902: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9903: $unhome = $desiredhome;
1.620 albertel 9904: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9905: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9906: } else { # load balancing routine for determining $unhome
1.81 www 9907: my $loadm=10000000;
1.841 albertel 9908: my %servers = &get_servers($udom,'library');
9909: foreach my $tryserver (keys(%servers)) {
9910: my $answer=reply('load',$tryserver);
9911: if (($answer=~/\d+/) && ($answer<$loadm)) {
9912: $loadm=$answer;
9913: $unhome=$tryserver;
9914: }
1.80 www 9915: }
9916: }
9917: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9918: return 'error: unable to find a home server for '.$uname.
9919: ' in domain '.$udom;
1.80 www 9920: }
9921: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9922: &escape($upass),$unhome);
9923: unless ($reply eq 'ok') {
9924: return 'error: '.$reply;
9925: }
1.230 stredwic 9926: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9927: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9928: return 'error: unable verify users home machine.';
1.80 www 9929: }
1.209 matthew 9930: } # End of creation of new user
1.80 www 9931: # ---------------------------------------------------------------------- Add ID
9932: if ($uid) {
9933: $uid=~tr/A-Z/a-z/;
9934: my %uidhash=&idrget($udom,$uname);
1.196 www 9935: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9936: && (!$forceid)) {
1.80 www 9937: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9938: return 'error: user id "'.$uid.'" does not match '.
9939: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9940: }
9941: } else {
9942: &idput($udom,($uname => $uid));
9943: }
9944: }
9945: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9946: my @tmp=&get('environment',
1.899 raeburn 9947: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9948: 'permanentemail','inststatus'],
1.134 albertel 9949: $udom,$uname);
1.1075 raeburn 9950: my (%names,%oldnames);
1.313 matthew 9951: if ($tmp[0] =~ m/^error:.*/) {
9952: %names=();
9953: } else {
9954: %names = @tmp;
1.1075 raeburn 9955: %oldnames = %names;
1.313 matthew 9956: }
1.388 www 9957: #
1.1058 raeburn 9958: # If name, email and/or uid are blank (e.g., because an uploaded file
9959: # of users did not contain them), do not overwrite existing values
9960: # unless field is in $candelete array ref.
9961: #
9962:
9963: my @fields = ('firstname','middlename','lastname','generation',
9964: 'permanentemail','id');
9965: my %newvalues;
9966: if (ref($candelete) eq 'ARRAY') {
9967: foreach my $field (@fields) {
9968: if (grep(/^\Q$field\E$/,@{$candelete})) {
9969: if ($field eq 'firstname') {
9970: $names{$field} = $first;
9971: } elsif ($field eq 'middlename') {
9972: $names{$field} = $middle;
9973: } elsif ($field eq 'lastname') {
9974: $names{$field} = $last;
9975: } elsif ($field eq 'generation') {
9976: $names{$field} = $gene;
9977: } elsif ($field eq 'permanentemail') {
9978: $names{$field} = $email;
9979: } elsif ($field eq 'id') {
9980: $names{$field} = $uid;
9981: }
9982: }
9983: }
9984: }
1.388 www 9985: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9986: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9987: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9988: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9989: if ($email) {
9990: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9991: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9992: }
1.899 raeburn 9993: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9994: if (defined($inststatus)) {
9995: $names{'inststatus'} = '';
9996: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9997: if (ref($usertypes) eq 'HASH') {
9998: my @okstatuses;
9999: foreach my $item (split(/:/,$inststatus)) {
10000: if (defined($usertypes->{$item})) {
10001: push(@okstatuses,$item);
10002: }
10003: }
10004: if (@okstatuses) {
10005: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10006: }
10007: }
10008: }
1.1075 raeburn 10009: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10010: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10011: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10012: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10013: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10014: } else {
10015: $logmsg .= ' during self creation';
10016: }
1.1075 raeburn 10017: my $changed;
10018: if ($newuser) {
10019: $changed = 1;
10020: } else {
10021: foreach my $field (@fields) {
10022: if ($names{$field} ne $oldnames{$field}) {
10023: $changed = 1;
10024: last;
10025: }
10026: }
10027: }
10028: unless ($changed) {
10029: $logmsg = 'No changes in user information needed for: '.$logmsg;
10030: &logthis($logmsg);
10031: return 'ok';
10032: }
10033: my $reply = &put('environment', \%names, $udom,$uname);
10034: if ($reply ne 'ok') {
10035: return 'error: '.$reply;
10036: }
1.1087 raeburn 10037: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10038: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10039: }
1.1075 raeburn 10040: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10041: &devalidate_cache_new('namescache',$uname.':'.$udom);
10042: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10043: &logthis($logmsg);
1.134 albertel 10044: return 'ok';
1.80 www 10045: }
10046:
1.81 www 10047: # -------------------------------------------------------------- Modify student
1.80 www 10048:
1.81 www 10049: sub modifystudent {
10050: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10051: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10052: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10053: if (!$cid) {
1.620 albertel 10054: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10055: return 'not_in_class';
10056: }
1.80 www 10057: }
10058: # --------------------------------------------------------------- Make the user
1.81 www 10059: my $reply=&modifyuser
1.209 matthew 10060: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10061: $desiredhome,$email,$inststatus);
1.80 www 10062: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10063: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10064: # student's environment
1.297 matthew 10065: $uid = undef if (!$forceid);
1.455 albertel 10066: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10067: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10068: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10069: return $reply;
10070: }
10071:
10072: sub modify_student_enrollment {
1.1172.2.23 raeburn 10073: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10074: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10075: my ($cdom,$cnum,$chome);
10076: if (!$cid) {
1.620 albertel 10077: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10078: return 'not_in_class';
10079: }
1.620 albertel 10080: $cdom=$env{'course.'.$cid.'.domain'};
10081: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10082: } else {
10083: ($cdom,$cnum)=split(/_/,$cid);
10084: }
1.620 albertel 10085: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10086: if (!$chome) {
1.457 raeburn 10087: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10088: }
1.455 albertel 10089: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10090: # Make sure the user exists
1.81 www 10091: my $uhome=&homeserver($uname,$udom);
10092: if (($uhome eq '') || ($uhome eq 'no_host')) {
10093: return 'error: no such user';
10094: }
1.297 matthew 10095: # Get student data if we were not given enough information
10096: if (!defined($first) || $first eq '' ||
10097: !defined($last) || $last eq '' ||
10098: !defined($uid) || $uid eq '' ||
10099: !defined($middle) || $middle eq '' ||
10100: !defined($gene) || $gene eq '') {
1.294 matthew 10101: # They did not supply us with enough data to enroll the student, so
10102: # we need to pick up more information.
1.297 matthew 10103: my %tmp = &get('environment',
1.294 matthew 10104: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10105: ,$udom,$uname);
10106:
1.800 albertel 10107: #foreach my $key (keys(%tmp)) {
10108: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10109: #}
1.294 matthew 10110: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10111: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10112: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10113: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10114: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10115: }
1.556 albertel 10116: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10117: my $user = "$uname:$udom";
10118: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10119: my $reply=cput('classlist',
1.1148 raeburn 10120: {$user =>
1.1172.2.76 raeburn 10121: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10122: $cdom,$cnum);
1.1148 raeburn 10123: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10124: &devalidate_getsection_cache($udom,$uname,$cid);
10125: } else {
1.81 www 10126: return 'error: '.$reply;
10127: }
1.297 matthew 10128: # Add student role to user
1.83 www 10129: my $uurl='/'.$cid;
1.81 www 10130: $uurl=~s/\_/\//g;
10131: if ($usec) {
10132: $uurl.='/'.$usec;
10133: }
1.1148 raeburn 10134: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10135: $selfenroll,$context);
10136: if ($result ne 'ok') {
10137: if ($old_entry{$user} ne '') {
10138: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10139: } else {
10140: $reply = &del('classlist',[$user],$cdom,$cnum);
10141: }
10142: }
10143: return $result;
1.21 www 10144: }
10145:
1.556 albertel 10146: sub format_name {
10147: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10148: my $name;
10149: if ($first ne 'lastname') {
10150: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10151: } else {
10152: if ($lastname=~/\S/) {
10153: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10154: $name=~s/\s+,/,/;
10155: } else {
10156: $name.= $firstname.' '.$middlename.' '.$generation;
10157: }
10158: }
10159: $name=~s/^\s+//;
10160: $name=~s/\s+$//;
10161: $name=~s/\s+/ /g;
10162: return $name;
10163: }
10164:
1.84 www 10165: # ------------------------------------------------- Write to course preferences
10166:
10167: sub writecoursepref {
10168: my ($courseid,%prefs)=@_;
10169: $courseid=~s/^\///;
10170: $courseid=~s/\_/\//g;
10171: my ($cdomain,$cnum)=split(/\//,$courseid);
10172: my $chome=homeserver($cnum,$cdomain);
10173: if (($chome eq '') || ($chome eq 'no_host')) {
10174: return 'error: no such course';
10175: }
10176: my $cstring='';
1.800 albertel 10177: foreach my $pref (keys(%prefs)) {
10178: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10179: }
1.84 www 10180: $cstring=~s/\&$//;
10181: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10182: }
10183:
10184: # ---------------------------------------------------------- Make/modify course
10185:
10186: sub createcourse {
1.741 raeburn 10187: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10188: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10189: $url=&declutter($url);
10190: my $cid='';
1.1028 raeburn 10191: if ($context eq 'requestcourses') {
10192: my $can_create = 0;
10193: my ($ownername,$ownerdom) = split(':',$course_owner);
10194: if ($udom eq $ownerdom) {
10195: if (&usertools_access($ownername,$ownerdom,$category,undef,
10196: $context)) {
10197: $can_create = 1;
10198: }
10199: } else {
10200: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10201: $category);
10202: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10203: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10204: if (@curr > 0) {
10205: my @options = qw(approval validate autolimit);
10206: my $optregex = join('|',@options);
10207: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10208: $can_create = 1;
10209: }
10210: }
10211: }
10212: }
10213: if ($can_create) {
10214: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10215: unless (&allowed('ccc',$udom)) {
10216: return 'refused';
10217: }
1.1017 raeburn 10218: }
10219: } else {
10220: return 'refused';
10221: }
1.1028 raeburn 10222: } elsif (!&allowed('ccc',$udom)) {
10223: return 'refused';
1.84 www 10224: }
1.1011 raeburn 10225: # --------------------------------------------------------------- Get Unique ID
10226: my $uname;
10227: if ($cnum =~ /^$match_courseid$/) {
10228: my $chome=&homeserver($cnum,$udom,'true');
10229: if (($chome eq '') || ($chome eq 'no_host')) {
10230: $uname = $cnum;
10231: } else {
1.1038 raeburn 10232: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10233: }
10234: } else {
1.1038 raeburn 10235: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10236: }
10237: return $uname if ($uname =~ /^error/);
10238: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10239: if (!defined($course_server)) {
10240: if (defined(&domain($udom,'primary'))) {
10241: $course_server = &domain($udom,'primary');
10242: } else {
10243: $course_server = $env{'user.home'};
10244: }
10245: }
10246: my %host_servers =
10247: &Apache::lonnet::get_servers($udom,'library');
10248: unless ($host_servers{$course_server}) {
10249: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10250: }
1.84 www 10251: # ------------------------------------------------------------- Make the course
10252: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10253: $course_server);
1.84 www 10254: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10255: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10256: if (($uhome eq '') || ($uhome eq 'no_host')) {
10257: return 'error: no such course';
10258: }
1.271 www 10259: # ----------------------------------------------------------------- Course made
1.516 raeburn 10260: # log existence
1.1029 raeburn 10261: my $now = time;
1.918 raeburn 10262: my $newcourse = {
10263: $udom.'_'.$uname => {
1.921 raeburn 10264: description => $description,
10265: inst_code => $inst_code,
10266: owner => $course_owner,
10267: type => $crstype,
1.1029 raeburn 10268: creator => $env{'user.name'}.':'.
10269: $env{'user.domain'},
10270: created => $now,
10271: context => $context,
1.918 raeburn 10272: },
10273: };
1.921 raeburn 10274: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10275: # set toplevel url
1.271 www 10276: my $topurl=$url;
10277: unless ($nonstandard) {
10278: # ------------------------------------------ For standard courses, make top url
10279: my $mapurl=&clutter($url);
1.278 www 10280: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10281: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10282: <map>
10283: <resource id="1" type="start"></resource>
10284: <resource id="2" src="$mapurl"></resource>
10285: <resource id="3" type="finish"></resource>
10286: <link index="1" from="1" to="2"></link>
10287: <link index="2" from="2" to="3"></link>
10288: </map>
10289: ENDINITMAP
10290: $topurl=&declutter(
1.638 albertel 10291: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10292: );
10293: }
10294: # ----------------------------------------------------------- Write preferences
1.84 www 10295: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10296: ('description' => $description,
10297: 'url' => $topurl,
10298: 'internal.creator' => $env{'user.name'}.':'.
10299: $env{'user.domain'},
10300: 'internal.created' => $now,
10301: 'internal.creationcontext' => $context)
10302: );
1.84 www 10303: return '/'.$udom.'/'.$uname;
10304: }
10305:
1.1011 raeburn 10306: # ------------------------------------------------------------------- Create ID
10307: sub generate_coursenum {
1.1038 raeburn 10308: my ($udom,$crstype) = @_;
1.1011 raeburn 10309: my $domdesc = &domain($udom);
10310: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10311: my $first;
10312: if ($crstype eq 'Community') {
10313: $first = '0';
10314: } else {
10315: $first = int(1+rand(9));
10316: }
10317: my $uname=$first.
1.1011 raeburn 10318: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10319: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10320: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10321: # ----------------------------------------------- Make sure that does not exist
10322: my $uhome=&homeserver($uname,$udom,'true');
10323: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10324: if ($crstype eq 'Community') {
10325: $first = '0';
10326: } else {
10327: $first = int(1+rand(9));
10328: }
10329: $uname=$first.
1.1011 raeburn 10330: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10331: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10332: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10333: $uhome=&homeserver($uname,$udom,'true');
10334: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10335: return 'error: unable to generate unique course-ID';
10336: }
10337: }
10338: return $uname;
10339: }
10340:
1.813 albertel 10341: sub is_course {
1.1167 droeschl 10342: my ($cdom, $cnum) = scalar(@_) == 1 ?
10343: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 10344: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10345: my $uhome=&homeserver($cnum,$cdom);
10346: my $iscourse;
10347: if (grep { $_ eq $uhome } current_machine_ids()) {
10348: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10349: } else {
10350: my $hashid = $cdom.':'.$cnum;
10351: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10352: unless (defined($cached)) {
10353: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10354: $cnum,undef,undef,'.');
10355: $iscourse = 0;
10356: if (exists($courses{$cdom.'_'.$cnum})) {
10357: $iscourse = 1;
10358: }
10359: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10360: }
10361: }
10362: return unless($iscourse);
1.1167 droeschl 10363: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10364: }
10365:
1.1015 raeburn 10366: sub store_userdata {
10367: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10368: my $result;
1.1016 raeburn 10369: if ($datakey ne '') {
1.1013 raeburn 10370: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10371: if ($udom eq '' || $uname eq '') {
10372: $udom = $env{'user.domain'};
10373: $uname = $env{'user.name'};
10374: }
10375: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10376: if (($uhome eq '') || ($uhome eq 'no_host')) {
10377: $result = 'error: no_host';
10378: } else {
10379: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10380: $storehash->{'host'} = $perlvar{'lonHostID'};
10381:
10382: my $namevalue='';
10383: foreach my $key (keys(%{$storehash})) {
10384: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10385: }
10386: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10387: unless ($namespace eq 'courserequests') {
10388: $datakey = &escape($datakey);
10389: }
1.1105 raeburn 10390: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10391: $namevalue,$uhome);
1.1013 raeburn 10392: }
10393: } else {
10394: $result = 'error: data to store was not a hash reference';
10395: }
10396: } else {
10397: $result= 'error: invalid requestkey';
10398: }
10399: return $result;
10400: }
10401:
1.21 www 10402: # ---------------------------------------------------------- Assign Custom Role
10403:
10404: sub assigncustomrole {
1.957 raeburn 10405: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10406: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10407: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10408: }
10409:
10410: # ----------------------------------------------------------------- Revoke Role
10411:
10412: sub revokerole {
1.957 raeburn 10413: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10414: my $now=time;
1.965 raeburn 10415: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10416: }
10417:
10418: # ---------------------------------------------------------- Revoke Custom Role
10419:
10420: sub revokecustomrole {
1.957 raeburn 10421: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10422: my $now=time;
1.357 www 10423: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10424: $deleteflag,$selfenroll,$context);
1.17 www 10425: }
10426:
1.533 banghart 10427: # ------------------------------------------------------------ Disk usage
1.535 albertel 10428: sub diskusage {
1.955 raeburn 10429: my ($udom,$uname,$directorypath,$getpropath)=@_;
10430: $directorypath =~ s/\/$//;
10431: my $listing=&reply('du2:'.&escape($directorypath).':'
10432: .&escape($getpropath).':'.&escape($uname).':'
10433: .&escape($udom),homeserver($uname,$udom));
10434: if ($listing eq 'unknown_cmd') {
10435: if ($getpropath) {
10436: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10437: }
10438: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10439: }
1.514 albertel 10440: return $listing;
1.512 banghart 10441: }
10442:
1.566 banghart 10443: sub is_locked {
1.1096 raeburn 10444: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10445: my @check;
10446: my $is_locked;
1.1093 raeburn 10447: push (@check,$file_name);
1.613 albertel 10448: my %locked = &get('file_permissions',\@check,
1.620 albertel 10449: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10450: my ($tmp)=keys(%locked);
10451: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10452:
1.566 banghart 10453: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10454: $is_locked = 'false';
10455: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10456: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10457: $is_locked = 'true';
1.1096 raeburn 10458: if (ref($which) eq 'ARRAY') {
10459: push(@{$which},$entry);
10460: } else {
10461: last;
10462: }
1.745 raeburn 10463: }
10464: }
1.566 banghart 10465: } else {
10466: $is_locked = 'false';
10467: }
1.1093 raeburn 10468: return $is_locked;
1.566 banghart 10469: }
10470:
1.759 albertel 10471: sub declutter_portfile {
10472: my ($file) = @_;
1.833 albertel 10473: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10474: return $file;
10475: }
10476:
1.559 banghart 10477: # ------------------------------------------------------------- Mark as Read Only
10478:
10479: sub mark_as_readonly {
10480: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10481: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10482: my ($tmp)=keys(%current_permissions);
10483: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10484: foreach my $file (@{$files}) {
1.759 albertel 10485: $file = &declutter_portfile($file);
1.561 banghart 10486: push(@{$current_permissions{$file}},$what);
1.559 banghart 10487: }
1.613 albertel 10488: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10489: return;
10490: }
10491:
1.572 banghart 10492: # ------------------------------------------------------------Save Selected Files
10493:
10494: sub save_selected_files {
10495: my ($user, $path, @files) = @_;
10496: my $filename = $user."savedfiles";
1.573 banghart 10497: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 10498: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10499: foreach my $file (@files) {
1.620 albertel 10500: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10501: }
10502: foreach my $file (@other_files) {
1.574 banghart 10503: print (OUT $file."\n");
1.572 banghart 10504: }
1.574 banghart 10505: close (OUT);
1.572 banghart 10506: return 'ok';
10507: }
10508:
1.574 banghart 10509: sub clear_selected_files {
10510: my ($user) = @_;
10511: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 10512: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10513: print (OUT undef);
10514: close (OUT);
10515: return ("ok");
10516: }
10517:
1.572 banghart 10518: sub files_in_path {
10519: my ($user, $path) = @_;
10520: my $filename = $user."savedfiles";
10521: my %return_files;
1.1172.2.96 raeburn 10522: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10523: while (my $line_in = <IN>) {
1.574 banghart 10524: chomp ($line_in);
10525: my @paths_and_file = split (m!/!, $line_in);
10526: my $file_part = pop (@paths_and_file);
10527: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10528: $path_part.='/';
10529: my $path_and_file = $path_part.$file_part;
10530: if ($path_part eq $path) {
10531: $return_files{$file_part}= 'selected';
10532: }
10533: }
1.574 banghart 10534: close (IN);
10535: return (\%return_files);
1.572 banghart 10536: }
10537:
10538: # called in portfolio select mode, to show files selected NOT in current directory
10539: sub files_not_in_path {
10540: my ($user, $path) = @_;
10541: my $filename = $user."savedfiles";
10542: my @return_files;
10543: my $path_part;
1.1172.2.96 raeburn 10544: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10545: while (my $line = <IN>) {
1.572 banghart 10546: #ok, I know it's clunky, but I want it to work
1.800 albertel 10547: my @paths_and_file = split(m|/|, $line);
10548: my $file_part = pop(@paths_and_file);
10549: chomp($file_part);
10550: my $path_part = join('/', @paths_and_file);
1.572 banghart 10551: $path_part .= '/';
10552: my $path_and_file = $path_part.$file_part;
10553: if ($path_part ne $path) {
1.800 albertel 10554: push(@return_files, ($path_and_file));
1.572 banghart 10555: }
10556: }
1.800 albertel 10557: close(OUT);
1.574 banghart 10558: return (@return_files);
1.572 banghart 10559: }
10560:
1.745 raeburn 10561: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10562:
1.745 raeburn 10563: sub get_portfile_permissions {
10564: my ($domain,$user) = @_;
1.613 albertel 10565: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10566: my ($tmp)=keys(%current_permissions);
10567: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10568: return \%current_permissions;
10569: }
10570:
10571: #---------------------------------------------Get portfolio file access controls
10572:
1.749 raeburn 10573: sub get_access_controls {
1.745 raeburn 10574: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10575: my %access;
10576: my $real_file = $file;
10577: $file =~ s/\.meta$//;
1.745 raeburn 10578: if (defined($file)) {
1.749 raeburn 10579: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10580: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10581: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10582: }
10583: }
1.745 raeburn 10584: } else {
1.749 raeburn 10585: foreach my $key (keys(%{$current_permissions})) {
10586: if ($key =~ /\0accesscontrol$/) {
10587: if (defined($group)) {
10588: if ($key !~ m-^\Q$group\E/-) {
10589: next;
10590: }
10591: }
10592: my ($fullpath) = split(/\0/,$key);
10593: if (ref($$current_permissions{$key}) eq 'HASH') {
10594: foreach my $control (keys(%{$$current_permissions{$key}})) {
10595: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10596: }
10597: }
10598: }
10599: }
10600: }
10601: return %access;
10602: }
10603:
10604: sub modify_access_controls {
10605: my ($file_name,$changes,$domain,$user)=@_;
10606: my ($outcome,$deloutcome);
10607: my %store_permissions;
10608: my %new_values;
10609: my %new_control;
10610: my %translation;
10611: my @deletions = ();
10612: my $now = time;
10613: if (exists($$changes{'activate'})) {
10614: if (ref($$changes{'activate'}) eq 'HASH') {
10615: my @newitems = sort(keys(%{$$changes{'activate'}}));
10616: my $numnew = scalar(@newitems);
10617: for (my $i=0; $i<$numnew; $i++) {
10618: my $newkey = $newitems[$i];
10619: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10620: if ($newkey =~ /^\d+:/) {
10621: $newkey =~ s/^(\d+)/$newid/;
10622: $translation{$1} = $newid;
10623: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10624: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10625: $translation{$1} = $newid;
10626: }
1.749 raeburn 10627: $new_values{$file_name."\0".$newkey} =
10628: $$changes{'activate'}{$newitems[$i]};
10629: $new_control{$newkey} = $now;
10630: }
10631: }
10632: }
10633: my %todelete;
10634: my %changed_items;
10635: foreach my $action ('delete','update') {
10636: if (exists($$changes{$action})) {
10637: if (ref($$changes{$action}) eq 'HASH') {
10638: foreach my $key (keys(%{$$changes{$action}})) {
10639: my ($itemnum) = ($key =~ /^([^:]+):/);
10640: if ($action eq 'delete') {
10641: $todelete{$itemnum} = 1;
10642: } else {
10643: $changed_items{$itemnum} = $key;
10644: }
10645: }
1.745 raeburn 10646: }
10647: }
1.749 raeburn 10648: }
10649: # get lock on access controls for file.
10650: my $lockhash = {
10651: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10652: ':'.$env{'user.domain'},
10653: };
10654: my $tries = 0;
10655: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10656:
1.1172.2.79 raeburn 10657: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10658: $tries ++;
1.1172.2.79 raeburn 10659: sleep(0.1);
1.749 raeburn 10660: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10661: }
10662: if ($gotlock eq 'ok') {
10663: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10664: my ($tmp)=keys(%curr_permissions);
10665: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10666: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10667: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10668: if (ref($curr_controls) eq 'HASH') {
10669: foreach my $control_item (keys(%{$curr_controls})) {
10670: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10671: if (defined($todelete{$itemnum})) {
10672: push(@deletions,$file_name."\0".$control_item);
10673: } else {
10674: if (defined($changed_items{$itemnum})) {
10675: $new_control{$changed_items{$itemnum}} = $now;
10676: push(@deletions,$file_name."\0".$control_item);
10677: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10678: } else {
10679: $new_control{$control_item} = $$curr_controls{$control_item};
10680: }
10681: }
1.745 raeburn 10682: }
10683: }
10684: }
1.970 raeburn 10685: my ($group);
10686: if (&is_course($domain,$user)) {
10687: ($group,my $file) = split(/\//,$file_name,2);
10688: }
1.749 raeburn 10689: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10690: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10691: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10692: # remove lock
10693: my @del_lock = ($file_name."\0".'locked_access_records');
10694: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10695: my $sqlresult =
1.970 raeburn 10696: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10697: $group);
1.749 raeburn 10698: } else {
10699: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10700: }
1.749 raeburn 10701: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10702: }
10703:
1.827 raeburn 10704: sub make_public_indefinitely {
10705: my ($requrl) = @_;
10706: my $now = time;
10707: my $action = 'activate';
10708: my $aclnum = 0;
10709: if (&is_portfolio_url($requrl)) {
10710: my (undef,$udom,$unum,$file_name,$group) =
10711: &parse_portfolio_url($requrl);
10712: my $current_perms = &get_portfile_permissions($udom,$unum);
10713: my %access_controls = &get_access_controls($current_perms,
10714: $group,$file_name);
10715: foreach my $key (keys(%{$access_controls{$file_name}})) {
10716: my ($num,$scope,$end,$start) =
10717: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10718: if ($scope eq 'public') {
10719: if ($start <= $now && $end == 0) {
10720: $action = 'none';
10721: } else {
10722: $action = 'update';
10723: $aclnum = $num;
10724: }
10725: last;
10726: }
10727: }
10728: if ($action eq 'none') {
10729: return 'ok';
10730: } else {
10731: my %changes;
10732: my $newend = 0;
10733: my $newstart = $now;
10734: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10735: $changes{$action}{$newkey} = {
10736: type => 'public',
10737: time => {
10738: start => $newstart,
10739: end => $newend,
10740: },
10741: };
10742: my ($outcome,$deloutcome,$new_values,$translation) =
10743: &modify_access_controls($file_name,\%changes,$udom,$unum);
10744: return $outcome;
10745: }
10746: } else {
10747: return 'invalid';
10748: }
10749: }
10750:
1.745 raeburn 10751: #------------------------------------------------------Get Marked as Read Only
10752:
10753: sub get_marked_as_readonly {
10754: my ($domain,$user,$what,$group) = @_;
10755: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10756: my @readonly_files;
1.629 banghart 10757: my $cmp1=$what;
10758: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10759: while (my ($file_name,$value) = each(%{$current_permissions})) {
10760: if (defined($group)) {
10761: if ($file_name !~ m-^\Q$group\E/-) {
10762: next;
10763: }
10764: }
1.561 banghart 10765: if (ref($value) eq "ARRAY"){
10766: foreach my $stored_what (@{$value}) {
1.629 banghart 10767: my $cmp2=$stored_what;
1.759 albertel 10768: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10769: $cmp2=join('',@{$stored_what});
1.745 raeburn 10770: }
1.629 banghart 10771: if ($cmp1 eq $cmp2) {
1.561 banghart 10772: push(@readonly_files, $file_name);
1.745 raeburn 10773: last;
1.563 banghart 10774: } elsif (!defined($what)) {
10775: push(@readonly_files, $file_name);
1.745 raeburn 10776: last;
1.561 banghart 10777: }
10778: }
1.745 raeburn 10779: }
1.561 banghart 10780: }
10781: return @readonly_files;
10782: }
1.577 banghart 10783: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10784:
1.577 banghart 10785: sub get_marked_as_readonly_hash {
1.745 raeburn 10786: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10787: my %readonly_files;
1.745 raeburn 10788: while (my ($file_name,$value) = each(%{$current_permissions})) {
10789: if (defined($group)) {
10790: if ($file_name !~ m-^\Q$group\E/-) {
10791: next;
10792: }
10793: }
1.577 banghart 10794: if (ref($value) eq "ARRAY"){
10795: foreach my $stored_what (@{$value}) {
1.745 raeburn 10796: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10797: foreach my $lock_descriptor(@{$stored_what}) {
10798: if ($lock_descriptor eq 'graded') {
10799: $readonly_files{$file_name} = 'graded';
10800: } elsif ($lock_descriptor eq 'handback') {
10801: $readonly_files{$file_name} = 'handback';
10802: } else {
10803: if (!exists($readonly_files{$file_name})) {
10804: $readonly_files{$file_name} = 'locked';
10805: }
10806: }
1.745 raeburn 10807: }
1.750 banghart 10808: }
1.577 banghart 10809: }
10810: }
10811: }
10812: return %readonly_files;
10813: }
1.559 banghart 10814: # ------------------------------------------------------------ Unmark as Read Only
10815:
10816: sub unmark_as_readonly {
1.629 banghart 10817: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10818: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10819: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10820: $file_name = &declutter_portfile($file_name);
1.634 albertel 10821: my $symb_crs = $what;
10822: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10823: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10824: my ($tmp)=keys(%current_permissions);
10825: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10826: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10827: foreach my $file (@readonly_files) {
1.759 albertel 10828: my $clean_file = &declutter_portfile($file);
10829: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10830: my $current_locks = $current_permissions{$file};
1.563 banghart 10831: my @new_locks;
10832: my @del_keys;
10833: if (ref($current_locks) eq "ARRAY"){
10834: foreach my $locker (@{$current_locks}) {
1.632 albertel 10835: my $compare=$locker;
1.749 raeburn 10836: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10837: $compare=join('',@{$locker});
1.746 raeburn 10838: if ($compare ne $symb_crs) {
10839: push(@new_locks, $locker);
10840: }
1.563 banghart 10841: }
10842: }
1.650 albertel 10843: if (scalar(@new_locks) > 0) {
1.563 banghart 10844: $current_permissions{$file} = \@new_locks;
10845: } else {
10846: push(@del_keys, $file);
1.613 albertel 10847: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10848: delete($current_permissions{$file});
1.563 banghart 10849: }
10850: }
1.561 banghart 10851: }
1.613 albertel 10852: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10853: return;
10854: }
1.512 banghart 10855:
1.17 www 10856: # ------------------------------------------------------------ Directory lister
10857:
10858: sub dirlist {
1.955 raeburn 10859: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10860: $uri=~s/^\///;
10861: $uri=~s/\/$//;
1.253 stredwic 10862: my ($udom, $uname);
1.955 raeburn 10863: if ($getuserdir) {
1.253 stredwic 10864: $udom = $userdomain;
10865: $uname = $username;
1.955 raeburn 10866: } else {
10867: (undef,$udom,$uname)=split(/\//,$uri);
10868: if(defined($userdomain)) {
10869: $udom = $userdomain;
10870: }
10871: if(defined($username)) {
10872: $uname = $username;
10873: }
1.253 stredwic 10874: }
1.955 raeburn 10875: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10876:
1.955 raeburn 10877: $dirRoot = $perlvar{'lonDocRoot'};
10878: if (defined($getpropath)) {
10879: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10880: $dirRoot =~ s/\/$//;
1.955 raeburn 10881: } elsif (defined($getuserdir)) {
10882: my $subdir=$uname.'__';
10883: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10884: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10885: ."/$udom/$subdir/$uname";
10886: } elsif (defined($alternateRoot)) {
10887: $dirRoot = $alternateRoot;
1.751 banghart 10888: }
1.253 stredwic 10889:
10890: if($udom) {
10891: if($uname) {
1.1135 raeburn 10892: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10893: if ($uhome eq 'no_host') {
10894: return ([],'no_host');
10895: }
1.955 raeburn 10896: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10897: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10898: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10899: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10900: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10901: } else {
10902: @listing_results = map { &unescape($_); } split(/:/,$listing);
10903: }
1.605 matthew 10904: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10905: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10906: @listing_results = split(/:/,$listing);
10907: } else {
10908: @listing_results = map { &unescape($_); } split(/:/,$listing);
10909: }
1.1135 raeburn 10910: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10911: ($listing eq 'rejected') || ($listing eq 'refused') ||
10912: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10913: return ([],$listing);
10914: } else {
10915: return (\@listing_results);
1.1135 raeburn 10916: }
1.955 raeburn 10917: } elsif(!$alternateRoot) {
1.1136 raeburn 10918: my (%allusers,%listerror);
1.841 albertel 10919: my %servers = &get_servers($udom,'library');
1.955 raeburn 10920: foreach my $tryserver (keys(%servers)) {
10921: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10922: &escape($udom),$tryserver);
10923: if ($listing eq 'unknown_cmd') {
10924: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10925: $udom, $tryserver);
10926: } else {
10927: @listing_results = map { &unescape($_); } split(/:/,$listing);
10928: }
1.841 albertel 10929: if ($listing eq 'unknown_cmd') {
10930: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10931: $udom, $tryserver);
10932: @listing_results = split(/:/,$listing);
10933: } else {
10934: @listing_results =
10935: map { &unescape($_); } split(/:/,$listing);
10936: }
1.1136 raeburn 10937: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10938: ($listing eq 'rejected') || ($listing eq 'refused') ||
10939: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10940: $listerror{$tryserver} = $listing;
10941: } else {
1.841 albertel 10942: foreach my $line (@listing_results) {
10943: my ($entry) = split(/&/,$line,2);
10944: $allusers{$entry} = 1;
10945: }
10946: }
1.253 stredwic 10947: }
1.1136 raeburn 10948: my @alluserslist=();
1.800 albertel 10949: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10950: push(@alluserslist,$user.'&user');
1.253 stredwic 10951: }
1.1172.2.80 raeburn 10952: if (!%listerror) {
10953: # no errors
10954: return (\@alluserslist);
10955: } elsif (scalar(keys(%servers)) == 1) {
10956: # one library server, one error
10957: my ($key) = keys(%listerror);
10958: return (\@alluserslist, $listerror{$key});
10959: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10960: # con_lost indicates that we might miss data from at least one
10961: # library server
10962: return (\@alluserslist, 'con_lost');
10963: } else {
10964: # multiple library servers and no con_lost -> data should be
10965: # complete.
10966: return (\@alluserslist);
10967: }
10968:
1.253 stredwic 10969: } else {
1.1136 raeburn 10970: return ([],'missing username');
1.253 stredwic 10971: }
1.955 raeburn 10972: } elsif(!defined($getpropath)) {
1.1136 raeburn 10973: my $path = $perlvar{'lonDocRoot'}.'/res/';
10974: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10975: return (\@all_domains);
1.955 raeburn 10976: } else {
1.1136 raeburn 10977: return ([],'missing domain');
1.275 stredwic 10978: }
10979: }
10980:
10981: # --------------------------------------------- GetFileTimestamp
10982: # This function utilizes dirlist and returns the date stamp for
10983: # when it was last modified. It will also return an error of -1
10984: # if an error occurs
10985:
10986: sub GetFileTimestamp {
1.955 raeburn 10987: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10988: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10989: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10990: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10991: undef,$getuserdir);
10992: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10993: return -1;
10994: }
10995: if (ref($fileref) eq 'ARRAY') {
10996: my @stats = split('&',$fileref->[0]);
1.375 matthew 10997: # @stats contains first the filename, then the stat output
10998: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10999: } else {
11000: return -1;
1.253 stredwic 11001: }
1.26 www 11002: }
11003:
1.712 albertel 11004: sub stat_file {
11005: my ($uri) = @_;
1.787 albertel 11006: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11007:
1.955 raeburn 11008: my ($udom,$uname,$file);
1.712 albertel 11009: if ($uri =~ m-^/(uploaded|editupload)/-) {
11010: ($udom,$uname,$file) =
1.811 albertel 11011: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11012: $file = 'userfiles/'.$file;
11013: }
11014: if ($uri =~ m-^/res/-) {
11015: ($udom,$uname) =
1.807 albertel 11016: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11017: $file = $uri;
11018: }
11019:
11020: if (!$udom || !$uname || !$file) {
11021: # unable to handle the uri
11022: return ();
11023: }
1.956 raeburn 11024: my $getpropath;
11025: if ($file =~ /^userfiles\//) {
11026: $getpropath = 1;
11027: }
1.1136 raeburn 11028: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11029: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11030: return ();
11031: } else {
11032: if (ref($listref) eq 'ARRAY') {
11033: my @stats = split('&',$listref->[0]);
11034: shift(@stats); #filename is first
11035: return @stats;
11036: }
1.712 albertel 11037: }
11038: return ();
11039: }
11040:
1.26 www 11041: # -------------------------------------------------------- Value of a Condition
11042:
1.713 albertel 11043: # gets the value of a specific preevaluated condition
11044: # stored in the string $env{user.state.<cid>}
11045: # or looks up a condition reference in the bighash and if if hasn't
11046: # already been evaluated recurses into docondval to get the value of
11047: # the condition, then memoizing it to
11048: # $env{user.state.<cid>.<condition>}
1.40 www 11049: sub directcondval {
11050: my $number=shift;
1.620 albertel 11051: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11052: &Apache::lonuserstate::evalstate();
11053: }
1.713 albertel 11054: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11055: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11056: } elsif ($number =~ /^_/) {
11057: my $sub_condition;
11058: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11059: &GDBM_READER(),0640)) {
11060: $sub_condition=$bighash{'conditions'.$number};
11061: untie(%bighash);
11062: }
11063: my $value = &docondval($sub_condition);
1.949 raeburn 11064: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11065: return $value;
11066: }
1.620 albertel 11067: if ($env{'user.state.'.$env{'request.course.id'}}) {
11068: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11069: } else {
11070: return 2;
11071: }
11072: }
11073:
1.713 albertel 11074: # get the collection of conditions for this resource
1.26 www 11075: sub condval {
11076: my $condidx=shift;
1.54 www 11077: my $allpathcond='';
1.713 albertel 11078: foreach my $cond (split(/\|/,$condidx)) {
11079: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11080: $allpathcond.=
11081: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11082: }
1.191 harris41 11083: }
1.54 www 11084: $allpathcond=~s/\|$//;
1.713 albertel 11085: return &docondval($allpathcond);
11086: }
11087:
11088: #evaluates an expression of conditions
11089: sub docondval {
11090: my ($allpathcond) = @_;
11091: my $result=0;
11092: if ($env{'request.course.id'}
11093: && defined($allpathcond)) {
11094: my $operand='|';
11095: my @stack;
11096: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11097: if ($chunk eq '(') {
11098: push @stack,($operand,$result);
11099: } elsif ($chunk eq ')') {
11100: my $before=pop @stack;
11101: if (pop @stack eq '&') {
11102: $result=$result>$before?$before:$result;
11103: } else {
11104: $result=$result>$before?$result:$before;
11105: }
11106: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11107: $operand=$chunk;
11108: } else {
11109: my $new=directcondval($chunk);
11110: if ($operand eq '&') {
11111: $result=$result>$new?$new:$result;
11112: } else {
11113: $result=$result>$new?$result:$new;
11114: }
11115: }
11116: }
1.26 www 11117: }
11118: return $result;
1.421 albertel 11119: }
11120:
11121: # ---------------------------------------------------- Devalidate courseresdata
11122:
11123: sub devalidatecourseresdata {
11124: my ($coursenum,$coursedomain)=@_;
11125: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11126: &devalidate_cache_new('courseres',$hashid);
1.28 www 11127: }
11128:
1.763 www 11129:
1.200 www 11130: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11131: #
11132: # Parameters:
11133: # $coursenum - Number of the course.
11134: # $coursedomain - Domain at which the course was created.
11135: # Returns:
11136: # A hash of the course parameters along (I think) with timestamps
11137: # and version info.
1.877 foxr 11138:
1.624 albertel 11139: sub get_courseresdata {
11140: my ($coursenum,$coursedomain)=@_;
1.200 www 11141: my $coursehom=&homeserver($coursenum,$coursedomain);
11142: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11143: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11144: my %dumpreply;
1.417 albertel 11145: unless (defined($cached)) {
1.624 albertel 11146: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11147: $result=\%dumpreply;
1.251 albertel 11148: my ($tmp) = keys(%dumpreply);
11149: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11150: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11151: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11152: return $tmp;
1.416 albertel 11153: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11154: $result=undef;
1.599 albertel 11155: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11156: }
11157: }
1.624 albertel 11158: return $result;
11159: }
11160:
1.633 albertel 11161: sub devalidateuserresdata {
11162: my ($uname,$udom)=@_;
11163: my $hashid="$udom:$uname";
11164: &devalidate_cache_new('userres',$hashid);
11165: }
11166:
1.624 albertel 11167: sub get_userresdata {
11168: my ($uname,$udom)=@_;
11169: #most student don\'t have any data set, check if there is some data
11170: if (&EXT_cache_status($udom,$uname)) { return undef; }
11171:
11172: my $hashid="$udom:$uname";
11173: my ($result,$cached)=&is_cached_new('userres',$hashid);
11174: if (!defined($cached)) {
11175: my %resourcedata=&dump('resourcedata',$udom,$uname);
11176: $result=\%resourcedata;
11177: &do_cache_new('userres',$hashid,$result,600);
11178: }
11179: my ($tmp)=keys(%$result);
11180: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11181: return $result;
11182: }
11183: #error 2 occurs when the .db doesn't exist
11184: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 11185: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11186: &logthis("<font color=\"blue\">WARNING:".
11187: " Trying to get resource data for ".
11188: $uname." at ".$udom.": ".
11189: $tmp."</font>");
11190: }
1.624 albertel 11191: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11192: #&EXT_cache_set($udom,$uname);
11193: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11194: undef($tmp); # not really an error so don't send it back
1.624 albertel 11195: }
11196: return $tmp;
11197: }
1.879 foxr 11198: #----------------------------------------------- resdata - return resource data
11199: # Purpose:
11200: # Return resource data for either users or for a course.
11201: # Parameters:
11202: # $name - Course/user name.
11203: # $domain - Name of the domain the user/course is registered on.
11204: # $type - Type of thing $name is (must be 'course' or 'user'
11205: # @which - Array of names of resources desired.
11206: # Returns:
11207: # The value of the first reasource in @which that is found in the
11208: # resource hash.
11209: # Exceptional Conditions:
11210: # If the $type passed in is not valid (not the string 'course' or
11211: # 'user', an undefined reference is returned.
11212: # If none of the resources are found, an undef is returned
1.624 albertel 11213: sub resdata {
11214: my ($name,$domain,$type,@which)=@_;
11215: my $result;
11216: if ($type eq 'course') {
11217: $result=&get_courseresdata($name,$domain);
11218: } elsif ($type eq 'user') {
11219: $result=&get_userresdata($name,$domain);
11220: }
11221: if (!ref($result)) { return $result; }
1.251 albertel 11222: foreach my $item (@which) {
1.927 albertel 11223: if (defined($result->{$item->[0]})) {
11224: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11225: }
1.250 albertel 11226: }
1.291 albertel 11227: return undef;
1.200 www 11228: }
11229:
1.1172.2.31 raeburn 11230: sub get_numsuppfiles {
11231: my ($cnum,$cdom,$ignorecache)=@_;
11232: my $hashid=$cnum.':'.$cdom;
11233: my ($suppcount,$cached);
11234: unless ($ignorecache) {
11235: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11236: }
11237: unless (defined($cached)) {
11238: my $chome=&homeserver($cnum,$cdom);
11239: unless ($chome eq 'no_host') {
11240: ($suppcount,my $errors) = (0,0);
11241: my $suppmap = 'supplemental.sequence';
11242: ($suppcount,$errors) =
11243: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11244: }
11245: &do_cache_new('suppcount',$hashid,$suppcount,600);
11246: }
11247: return $suppcount;
11248: }
11249:
1.379 matthew 11250: #
11251: # EXT resource caching routines
11252: #
11253:
11254: sub clear_EXT_cache_status {
1.383 albertel 11255: &delenv('cache.EXT.');
1.379 matthew 11256: }
11257:
11258: sub EXT_cache_status {
11259: my ($target_domain,$target_user) = @_;
1.383 albertel 11260: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11261: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11262: # We know already the user has no data
11263: return 1;
11264: } else {
11265: return 0;
11266: }
11267: }
11268:
11269: sub EXT_cache_set {
11270: my ($target_domain,$target_user) = @_;
1.383 albertel 11271: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11272: #&appenv({$cachename => time});
1.379 matthew 11273: }
11274:
1.28 www 11275: # --------------------------------------------------------- Value of a Variable
1.58 www 11276: sub EXT {
1.715 albertel 11277:
1.1172.2.28 raeburn 11278: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11279: unless ($varname) { return ''; }
1.218 albertel 11280: #get real user name/domain, courseid and symb
11281: my $courseid;
1.359 albertel 11282: my $publicuser;
1.427 www 11283: if ($symbparm) {
11284: $symbparm=&get_symb_from_alias($symbparm);
11285: }
1.218 albertel 11286: if (!($uname && $udom)) {
1.790 albertel 11287: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11288: if (!$symbparm) { $symbparm=$cursymb; }
11289: } else {
1.620 albertel 11290: $courseid=$env{'request.course.id'};
1.218 albertel 11291: }
1.48 www 11292: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11293: my $rest;
1.320 albertel 11294: if (defined($therest[0])) {
1.48 www 11295: $rest=join('.',@therest);
11296: } else {
11297: $rest='';
11298: }
1.320 albertel 11299:
1.57 www 11300: my $qualifierrest=$qualifier;
11301: if ($rest) { $qualifierrest.='.'.$rest; }
11302: my $spacequalifierrest=$space;
11303: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11304: if ($realm eq 'user') {
1.48 www 11305: # --------------------------------------------------------------- user.resource
11306: if ($space eq 'resource') {
1.651 albertel 11307: if ( (defined($Apache::lonhomework::parsing_a_problem)
11308: || defined($Apache::lonhomework::parsing_a_task))
11309: &&
1.744 albertel 11310: ($symbparm eq &symbread()) ) {
11311: # if we are in the middle of processing the resource the
11312: # get the value we are planning on committing
11313: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11314: return $Apache::lonhomework::results{$qualifierrest};
11315: } else {
11316: return $Apache::lonhomework::history{$qualifierrest};
11317: }
1.335 albertel 11318: } else {
1.359 albertel 11319: my %restored;
1.620 albertel 11320: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11321: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11322: } else {
11323: %restored=&restore($symbparm,$courseid,$udom,$uname);
11324: }
1.335 albertel 11325: return $restored{$qualifierrest};
11326: }
1.48 www 11327: # ----------------------------------------------------------------- user.access
11328: } elsif ($space eq 'access') {
1.218 albertel 11329: # FIXME - not supporting calls for a specific user
1.48 www 11330: return &allowed($qualifier,$rest);
11331: # ------------------------------------------ user.preferences, user.environment
11332: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11333: if (($uname eq $env{'user.name'}) &&
11334: ($udom eq $env{'user.domain'})) {
11335: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11336: } else {
1.359 albertel 11337: my %returnhash;
11338: if (!$publicuser) {
11339: %returnhash=&userenvironment($udom,$uname,
11340: $qualifierrest);
11341: }
1.218 albertel 11342: return $returnhash{$qualifierrest};
11343: }
1.48 www 11344: # ----------------------------------------------------------------- user.course
11345: } elsif ($space eq 'course') {
1.218 albertel 11346: # FIXME - not supporting calls for a specific user
1.620 albertel 11347: return $env{join('.',('request.course',$qualifier))};
1.48 www 11348: # ------------------------------------------------------------------- user.role
11349: } elsif ($space eq 'role') {
1.218 albertel 11350: # FIXME - not supporting calls for a specific user
1.620 albertel 11351: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11352: if ($qualifier eq 'value') {
11353: return $role;
11354: } elsif ($qualifier eq 'extent') {
11355: return $where;
11356: }
11357: # ----------------------------------------------------------------- user.domain
11358: } elsif ($space eq 'domain') {
1.218 albertel 11359: return $udom;
1.48 www 11360: # ------------------------------------------------------------------- user.name
11361: } elsif ($space eq 'name') {
1.218 albertel 11362: return $uname;
1.48 www 11363: # ---------------------------------------------------- Any other user namespace
1.29 www 11364: } else {
1.359 albertel 11365: my %reply;
11366: if (!$publicuser) {
11367: %reply=&get($space,[$qualifierrest],$udom,$uname);
11368: }
11369: return $reply{$qualifierrest};
1.48 www 11370: }
1.236 www 11371: } elsif ($realm eq 'query') {
11372: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11373: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11374: [$spacequalifierrest]);
1.620 albertel 11375: return $env{'form.'.$spacequalifierrest};
1.236 www 11376: } elsif ($realm eq 'request') {
1.48 www 11377: # ------------------------------------------------------------- request.browser
11378: if ($space eq 'browser') {
1.1145 bisitz 11379: return $env{'browser.'.$qualifier};
1.57 www 11380: # ------------------------------------------------------------ request.filename
11381: } else {
1.620 albertel 11382: return $env{'request.'.$spacequalifierrest};
1.29 www 11383: }
1.28 www 11384: } elsif ($realm eq 'course') {
1.48 www 11385: # ---------------------------------------------------------- course.description
1.620 albertel 11386: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11387: } elsif ($realm eq 'resource') {
1.165 www 11388:
1.620 albertel 11389: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11390: if (!$symbparm) { $symbparm=&symbread(); }
11391: }
1.693 albertel 11392:
1.1172.2.30 raeburn 11393: if ($qualifier eq '') {
11394: if ($space eq 'title') {
11395: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11396: return &gettitle($symbparm);
11397: }
1.693 albertel 11398:
1.1172.2.30 raeburn 11399: if ($space eq 'map') {
11400: my ($map) = &decode_symb($symbparm);
11401: return &symbread($map);
11402: }
11403: if ($space eq 'maptitle') {
11404: my ($map) = &decode_symb($symbparm);
11405: return &gettitle($map);
11406: }
11407: if ($space eq 'filename') {
11408: if ($symbparm) {
11409: return &clutter((&decode_symb($symbparm))[2]);
11410: }
11411: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11412: }
1.1172.2.30 raeburn 11413:
11414: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11415: if ($space eq 'visibleparts') {
11416: my $navmap = Apache::lonnavmaps::navmap->new();
11417: my $item;
11418: if (ref($navmap)) {
11419: my $res = $navmap->getBySymb($symbparm);
11420: my $parts = $res->parts();
11421: if (ref($parts) eq 'ARRAY') {
11422: $item = join(',',@{$parts});
11423: }
11424: undef($navmap);
11425: }
11426: return $item;
11427: }
11428: }
11429: }
1.693 albertel 11430:
11431: my ($section, $group, @groups);
1.593 albertel 11432: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11433: if (($courseid eq '') && ($cid)) {
11434: $courseid = $cid;
11435: }
11436: if (($symbparm && $courseid) &&
11437: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11438:
1.218 albertel 11439: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11440:
1.60 www 11441: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11442: my $symbp=$symbparm;
1.735 albertel 11443: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11444:
11445: my $symbparm=$symbp.'.'.$spacequalifierrest;
11446: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11447:
1.620 albertel 11448: if (($env{'user.name'} eq $uname) &&
11449: ($env{'user.domain'} eq $udom)) {
11450: $section=$env{'request.course.sec'};
1.733 raeburn 11451: @groups = split(/:/,$env{'request.course.groups'});
11452: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11453: } else {
1.539 albertel 11454: if (! defined($usection)) {
1.551 albertel 11455: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11456: } else {
11457: $section = $usection;
11458: }
1.733 raeburn 11459: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11460: }
11461:
11462: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11463: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11464: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11465:
1.593 albertel 11466: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11467: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11468: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11469:
1.60 www 11470: # ----------------------------------------------------------- first, check user
1.624 albertel 11471:
11472: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11473: ([$courselevelr,'resource'],
11474: [$courselevelm,'map' ],
11475: [$courselevel, 'course' ]));
1.931 albertel 11476: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11477:
1.594 albertel 11478: # ------------------------------------------------ second, check some of course
1.684 raeburn 11479: my $coursereply;
1.691 raeburn 11480: if (@groups > 0) {
11481: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11482: $mapparm,$spacequalifierrest);
1.927 albertel 11483: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11484: }
1.96 www 11485:
1.684 raeburn 11486: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11487: $env{'course.'.$courseid.'.domain'},
11488: 'course',
11489: ([$seclevelr, 'resource'],
11490: [$seclevelm, 'map' ],
11491: [$seclevel, 'course' ],
11492: [$courselevelr,'resource']));
11493: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11494:
1.60 www 11495: # ------------------------------------------------------ third, check map parms
1.218 albertel 11496: my %parmhash=();
11497: my $thisparm='';
11498: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11499: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11500: &GDBM_READER(),0640)) {
1.218 albertel 11501: $thisparm=$parmhash{$symbparm};
11502: untie(%parmhash);
11503: }
1.927 albertel 11504: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11505: }
1.594 albertel 11506: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11507:
1.218 albertel 11508: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11509: my $filename;
11510: if (!$symbparm) { $symbparm=&symbread(); }
11511: if ($symbparm) {
1.409 www 11512: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11513: } else {
1.620 albertel 11514: $filename=$env{'request.filename'};
1.282 albertel 11515: }
11516: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11517: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11518: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11519: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11520:
1.927 albertel 11521: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11522: if ($symbparm && defined($courseid) &&
1.620 albertel 11523: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11524: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11525: $env{'course.'.$courseid.'.domain'},
11526: 'course',
1.927 albertel 11527: ([$courselevelm,'map' ],
11528: [$courselevel, 'course']));
11529: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11530: }
1.145 www 11531: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11532: unless ($space eq '0') {
1.336 albertel 11533: my @parts=split(/_/,$space);
11534: my $id=pop(@parts);
11535: my $part=join('_',@parts);
11536: if ($part eq '') { $part='0'; }
1.927 albertel 11537: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11538: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11539: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11540: }
1.395 albertel 11541: if ($recurse) { return undef; }
11542: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11543: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11544: # ---------------------------------------------------- Any other user namespace
11545: } elsif ($realm eq 'environment') {
11546: # ----------------------------------------------------------------- environment
1.620 albertel 11547: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11548: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11549: } else {
1.770 albertel 11550: if ($uname eq 'anonymous' && $udom eq '') {
11551: return '';
11552: }
1.219 albertel 11553: my %returnhash=&userenvironment($udom,$uname,
11554: $spacequalifierrest);
11555: return $returnhash{$spacequalifierrest};
11556: }
1.28 www 11557: } elsif ($realm eq 'system') {
1.48 www 11558: # ----------------------------------------------------------------- system.time
11559: if ($space eq 'time') {
11560: return time;
11561: }
1.696 albertel 11562: } elsif ($realm eq 'server') {
11563: # ----------------------------------------------------------------- system.time
11564: if ($space eq 'name') {
11565: return $ENV{'SERVER_NAME'};
11566: }
1.28 www 11567: }
1.48 www 11568: return '';
1.61 www 11569: }
11570:
1.927 albertel 11571: sub get_reply {
11572: my ($reply_value) = @_;
1.940 raeburn 11573: if (ref($reply_value) eq 'ARRAY') {
11574: if (wantarray) {
11575: return @$reply_value;
11576: }
11577: return $reply_value->[0];
11578: } else {
11579: return $reply_value;
1.927 albertel 11580: }
11581: }
11582:
1.691 raeburn 11583: sub check_group_parms {
11584: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11585: my @groupitems = ();
11586: my $resultitem;
1.927 albertel 11587: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11588: foreach my $group (@{$groups}) {
11589: foreach my $level (@levels) {
1.927 albertel 11590: my $item = $courseid.'.['.$group.'].'.$level->[0];
11591: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11592: }
11593: }
11594: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11595: $env{'course.'.$courseid.'.domain'},
11596: 'course',@groupitems);
11597: return $coursereply;
11598: }
11599:
11600: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11601: my ($courseid,@groups) = @_;
11602: @groups = sort(@groups);
1.691 raeburn 11603: return @groups;
11604: }
11605:
1.395 albertel 11606: sub packages_tab_default {
11607: my ($uri,$varname)=@_;
11608: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11609:
11610: my (@extension,@specifics,$do_default);
11611: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11612: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11613: if ($pack_type eq 'default') {
11614: $do_default=1;
11615: } elsif ($pack_type eq 'extension') {
11616: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11617: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11618: # only look at packages defaults for packages that this id is
1.738 albertel 11619: push(@specifics,[$package,$pack_type,$pack_part]);
11620: }
11621: }
11622: # first look for a package that matches the requested part id
11623: foreach my $package (@specifics) {
11624: my (undef,$pack_type,$pack_part)=@{$package};
11625: next if ($pack_part ne $part);
11626: if (defined($packagetab{"$pack_type&$name&default"})) {
11627: return $packagetab{"$pack_type&$name&default"};
11628: }
11629: }
11630: # look for any possible matching non extension_ package
11631: foreach my $package (@specifics) {
11632: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11633: if (defined($packagetab{"$pack_type&$name&default"})) {
11634: return $packagetab{"$pack_type&$name&default"};
11635: }
1.585 albertel 11636: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11637: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11638: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11639: }
11640: }
1.738 albertel 11641: # look for any posible extension_ match
11642: foreach my $package (@extension) {
11643: my ($package,$pack_type)=@{$package};
11644: if (defined($packagetab{"$pack_type&$name&default"})) {
11645: return $packagetab{"$pack_type&$name&default"};
11646: }
11647: if (defined($packagetab{$package."&$name&default"})) {
11648: return $packagetab{$package."&$name&default"};
11649: }
11650: }
11651: # look for a global default setting
11652: if ($do_default && defined($packagetab{"default&$name&default"})) {
11653: return $packagetab{"default&$name&default"};
11654: }
1.395 albertel 11655: return undef;
11656: }
11657:
1.334 albertel 11658: sub add_prefix_and_part {
11659: my ($prefix,$part)=@_;
11660: my $keyroot;
11661: if (defined($prefix) && $prefix !~ /^__/) {
11662: # prefix that has a part already
11663: $keyroot=$prefix;
11664: } elsif (defined($prefix)) {
11665: # prefix that is missing a part
11666: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11667: } else {
11668: # no prefix at all
11669: if (defined($part)) { $keyroot='_'.$part; }
11670: }
11671: return $keyroot;
11672: }
11673:
1.71 www 11674: # ---------------------------------------------------------------- Get metadata
11675:
1.599 albertel 11676: my %metaentry;
1.1070 www 11677: my %importedpartids;
1.1172.2.99 raeburn 11678: my %importedrespids;
1.71 www 11679: sub metadata {
1.176 www 11680: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11681: $uri=&declutter($uri);
1.288 albertel 11682: # if it is a non metadata possible uri return quickly
1.529 albertel 11683: if (($uri eq '') ||
11684: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 11685: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 11686: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11687: return undef;
11688: }
1.1172.2.49 raeburn 11689: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11690: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11691: return undef;
1.288 albertel 11692: }
1.73 www 11693: my $filename=$uri;
11694: $uri=~s/\.meta$//;
1.172 www 11695: #
11696: # Is the metadata already cached?
1.177 www 11697: # Look at timestamp of caching
1.172 www 11698: # Everything is cached by the main uri, libraries are never directly cached
11699: #
1.428 albertel 11700: if (!defined($liburi)) {
1.599 albertel 11701: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11702: if (defined($cached)) { return $result->{':'.$what}; }
11703: }
11704: {
1.1069 www 11705: # Imported parts would go here
1.1172.2.99 raeburn 11706: my @origfiletagids=();
1.1069 www 11707: my $importedparts=0;
1.1172.2.99 raeburn 11708:
11709: # Imported responseids would go here
11710: my $importedresponses=0;
1.172 www 11711: #
11712: # Is this a recursive call for a library?
11713: #
1.599 albertel 11714: # if (! exists($metacache{$uri})) {
11715: # $metacache{$uri}={};
11716: # }
1.924 albertel 11717: my $cachetime = 60*60;
1.171 www 11718: if ($liburi) {
11719: $liburi=&declutter($liburi);
11720: $filename=$liburi;
1.401 bowersj2 11721: } else {
1.599 albertel 11722: &devalidate_cache_new('meta',$uri);
11723: undef(%metaentry);
1.401 bowersj2 11724: }
1.140 www 11725: my %metathesekeys=();
1.73 www 11726: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11727: my $metastring;
1.1140 www 11728: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11729: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11730: $metastring =
1.929 albertel 11731: &Apache::lonnet::ssi_body($which,
1.924 albertel 11732: ('grade_target' => 'meta'));
11733: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11734: } elsif (($uri !~ m -^(editupload)/-) &&
11735: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11736: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11737: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11738: $metastring=&getfile($file);
1.489 albertel 11739: }
1.208 albertel 11740: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11741: my $token;
1.140 www 11742: undef %metathesekeys;
1.71 www 11743: while ($token=$parser->get_token) {
1.339 albertel 11744: if ($token->[0] eq 'S') {
11745: if (defined($token->[2]->{'package'})) {
1.172 www 11746: #
11747: # This is a package - get package info
11748: #
1.339 albertel 11749: my $package=$token->[2]->{'package'};
11750: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11751: if (defined($token->[2]->{'id'})) {
11752: $keyroot.='_'.$token->[2]->{'id'};
11753: }
1.599 albertel 11754: if ($metaentry{':packages'}) {
11755: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11756: } else {
1.599 albertel 11757: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11758: }
1.736 albertel 11759: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11760: my $part=$keyroot;
11761: $part=~s/^\_//;
1.736 albertel 11762: if ($pack_entry=~/^\Q$package\E\&/ ||
11763: $pack_entry=~/^\Q$package\E_0\&/) {
11764: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11765: # ignore package.tab specified default values
11766: # here &package_tab_default() will fetch those
11767: if ($subp eq 'default') { next; }
1.736 albertel 11768: my $value=$packagetab{$pack_entry};
1.432 albertel 11769: my $unikey;
11770: if ($pack =~ /_0$/) {
11771: $unikey='parameter_0_'.$name;
11772: $part=0;
11773: } else {
11774: $unikey='parameter'.$keyroot.'_'.$name;
11775: }
1.339 albertel 11776: if ($subp eq 'display') {
11777: $value.=' [Part: '.$part.']';
11778: }
1.599 albertel 11779: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11780: $metathesekeys{$unikey}=1;
1.599 albertel 11781: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11782: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11783: }
1.599 albertel 11784: if (defined($metaentry{':'.$unikey.'.default'})) {
11785: $metaentry{':'.$unikey}=
11786: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11787: }
1.339 albertel 11788: }
11789: }
11790: } else {
1.172 www 11791: #
11792: # This is not a package - some other kind of start tag
1.339 albertel 11793: #
11794: my $entry=$token->[1];
1.1068 www 11795: my $unikey='';
1.175 www 11796:
1.339 albertel 11797: if ($entry eq 'import') {
1.175 www 11798: #
11799: # Importing a library here
1.339 albertel 11800: #
1.1067 www 11801: my $location=$parser->get_text('/import');
11802: my $dir=$filename;
11803: $dir=~s|[^/]*$||;
11804: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 11805:
11806: my $importid=$token->[2]->{'id'};
1.1068 www 11807: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 11808: #
11809: # Check metadata for imported file to
11810: # see if it contained response items
11811: #
11812: my %currmetaentry = %metaentry;
11813: my $libresponseorder = &metadata($location,'responseorder');
11814: my $origfile;
11815: if ($libresponseorder ne '') {
11816: if ($#origfiletagids<0) {
11817: undef(%importedrespids);
11818: undef(%importedpartids);
11819: }
11820: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11821: if (@{$importedrespids{$importid}} > 0) {
11822: $importedresponses = 1;
11823: # We need to get the original file and the imported file to get the response order correct
11824: # Load and inspect original file
11825: if ($#origfiletagids<0) {
11826: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11827: $origfile=&getfile($origfilelocation);
11828: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11829: }
11830: }
11831: }
11832: # Do not overwrite contents of %metaentry hash for resource itself with
11833: # hash populated for imported library file
11834: %metaentry = %currmetaentry;
11835: undef(%currmetaentry);
1.1068 www 11836: if ($importmode eq 'problem') {
1.1069 www 11837: # Import as problem/response
1.1068 www 11838: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11839: } elsif ($importmode eq 'part') {
11840: # Import as part(s)
1.1069 www 11841: $importedparts=1;
11842: # We need to get the original file and the imported file to get the part order correct
11843: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 11844: # Load and inspect original file if we didn't do that already
11845: if ($#origfiletagids<0) {
11846: undef(%importedrespids);
11847: undef(%importedpartids);
11848: if ($origfile eq '') {
11849: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11850: $origfile=&getfile($origfilelocation);
11851: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11852: }
1.1070 www 11853: }
11854:
1.1069 www 11855: # Load and inspect imported file
11856: my $impfile=&getfile($location);
11857: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11858: if ($#impfilepartids>=0) {
11859: # This problem had parts
1.1070 www 11860: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11861: } else {
11862: # Importing by turning a single problem into a problem part
11863: # It gets the import-tags ID as part-ID
11864: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11865: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11866: }
1.1068 www 11867: } else {
11868: # Normal import
11869: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11870: if (defined($token->[2]->{'id'})) {
11871: $unikey.='_'.$token->[2]->{'id'};
11872: }
1.1067 www 11873: }
11874:
1.339 albertel 11875: if ($depthcount<20) {
1.736 albertel 11876: my $metadata =
11877: &metadata($uri,'keys', $location,$unikey,
11878: $depthcount+1);
11879: foreach my $meta (split(',',$metadata)) {
11880: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11881: $metathesekeys{$meta}=1;
1.339 albertel 11882: }
1.1068 www 11883:
11884: }
1.1067 www 11885: } else {
11886: #
11887: # Not importing, some other kind of non-package, non-library start tag
11888: #
11889: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11890: if (defined($token->[2]->{'id'})) {
11891: $unikey.='_'.$token->[2]->{'id'};
11892: }
1.339 albertel 11893: if (defined($token->[2]->{'name'})) {
11894: $unikey.='_'.$token->[2]->{'name'};
11895: }
11896: $metathesekeys{$unikey}=1;
1.736 albertel 11897: foreach my $param (@{$token->[3]}) {
11898: $metaentry{':'.$unikey.'.'.$param} =
11899: $token->[2]->{$param};
1.339 albertel 11900: }
11901: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11902: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11903: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11904: # only ws inside the tag, and not in default, so use default
11905: # as value
1.599 albertel 11906: $metaentry{':'.$unikey}=$default;
1.908 albertel 11907: } elsif ( $internaltext =~ /\S/ ) {
11908: # something interesting inside the tag
11909: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11910: } else {
1.908 albertel 11911: # no interesting values, don't set a default
1.339 albertel 11912: }
1.172 www 11913: # end of not-a-package not-a-library import
1.339 albertel 11914: }
1.172 www 11915: # end of not-a-package start tag
1.339 albertel 11916: }
1.172 www 11917: # the next is the end of "start tag"
1.339 albertel 11918: }
11919: }
1.483 albertel 11920: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11921: $extension = lc($extension);
11922: if ($extension eq 'htm') { $extension='html'; }
11923:
1.737 albertel 11924: foreach my $key (keys(%packagetab)) {
1.483 albertel 11925: #no specific packages #how's our extension
11926: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11927: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11928: \%metathesekeys);
11929: }
1.883 albertel 11930:
11931: if (!exists($metaentry{':packages'})
11932: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11933: foreach my $key (keys(%packagetab)) {
1.483 albertel 11934: #no specific packages well let's get default then
11935: if ($key!~/^default&/) { next; }
1.488 albertel 11936: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11937: \%metathesekeys);
11938: }
11939: }
1.338 www 11940: # are there custom rights to evaluate
1.599 albertel 11941: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11942:
1.338 www 11943: #
11944: # Importing a rights file here
1.339 albertel 11945: #
11946: unless ($depthcount) {
1.599 albertel 11947: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11948: my $dir=$filename;
11949: $dir=~s|[^/]*$||;
11950: $location=&filelocation($dir,$location);
1.736 albertel 11951: my $rights_metadata =
11952: &metadata($uri,'keys',$location,'_rights',
11953: $depthcount+1);
11954: foreach my $rights (split(',',$rights_metadata)) {
11955: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11956: $metathesekeys{$rights}=1;
1.339 albertel 11957: }
11958: }
11959: }
1.737 albertel 11960: # uniqifiy package listing
11961: my %seen;
11962: my @uniq_packages =
11963: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11964: $metaentry{':packages'} = join(',',@uniq_packages);
11965:
1.1172.2.99 raeburn 11966: if (($importedresponses) || ($importedparts)) {
11967: if ($importedparts) {
1.1070 www 11968: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 11969: $metaentry{':partorder'}='';
11970: $metathesekeys{'partorder'}=1;
11971: }
11972: if ($importedresponses) {
11973: # We had imported responses and need to rebuild responseorder
11974: $metaentry{':responseorder'}='';
11975: $metathesekeys{'responseorder'}=1;
11976: }
11977: for (my $index=0;$index<$#origfiletagids;$index+=2) {
11978: my $origid = $origfiletagids[$index+1];
11979: if ($origfiletagids[$index] eq 'part') {
11980: # Original part, part of the problem
11981: if ($importedparts) {
11982: $metaentry{':partorder'}.=','.$origid;
11983: }
11984: } elsif ($origfiletagids[$index] eq 'import') {
11985: if ($importedparts) {
11986: # We have imported parts at this position
11987: $metaentry{':partorder'}.=','.$importedpartids{$origid};
11988: }
11989: if ($importedresponses) {
11990: # We have imported responses at this position
11991: if (ref($importedrespids{$origid}) eq 'ARRAY') {
11992: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
11993: }
11994: }
11995: } else {
11996: # Original response item, part of the problem
11997: if ($importedresponses) {
11998: $metaentry{':responseorder'}.=','.$origid;
11999: }
12000: }
12001: }
12002: if ($importedparts) {
12003: $metaentry{':partorder'}=~s/^\,//;
12004: }
12005: if ($importedresponses) {
12006: $metaentry{':responseorder'}=~s/^\,//;
12007: }
1.1070 www 12008: }
12009:
1.737 albertel 12010: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12011: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 12012: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 12013: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 12014: # this is the end of "was not already recently cached
1.71 www 12015: }
1.599 albertel 12016: return $metaentry{':'.$what};
1.261 albertel 12017: }
12018:
1.488 albertel 12019: sub metadata_create_package_def {
1.483 albertel 12020: my ($uri,$key,$package,$metathesekeys)=@_;
12021: my ($pack,$name,$subp)=split(/\&/,$key);
12022: if ($subp eq 'default') { next; }
12023:
1.599 albertel 12024: if (defined($metaentry{':packages'})) {
12025: $metaentry{':packages'}.=','.$package;
1.483 albertel 12026: } else {
1.599 albertel 12027: $metaentry{':packages'}=$package;
1.483 albertel 12028: }
12029: my $value=$packagetab{$key};
12030: my $unikey;
12031: $unikey='parameter_0_'.$name;
1.599 albertel 12032: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12033: $$metathesekeys{$unikey}=1;
1.599 albertel 12034: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12035: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12036: }
1.599 albertel 12037: if (defined($metaentry{':'.$unikey.'.default'})) {
12038: $metaentry{':'.$unikey}=
12039: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12040: }
12041: }
12042:
1.261 albertel 12043: sub metadata_generate_part0 {
12044: my ($metadata,$metacache,$uri) = @_;
12045: my %allnames;
1.737 albertel 12046: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12047: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12048: my $part=$$metacache{':'.$metakey.'.part'};
12049: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12050: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12051: $allnames{$name}=$part;
12052: }
12053: }
12054: }
12055: foreach my $name (keys(%allnames)) {
12056: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12057: my $key=":parameter_0_$name";
1.261 albertel 12058: $$metacache{"$key.part"}='0';
12059: $$metacache{"$key.name"}=$name;
1.428 albertel 12060: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12061: $allnames{$name}.'_'.$name.
12062: '.type'};
1.428 albertel 12063: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12064: '.display'};
1.644 www 12065: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12066: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12067: $$metacache{"$key.display"}=$olddis;
12068: }
1.71 www 12069: }
12070:
1.764 albertel 12071: # ------------------------------------------------------ Devalidate title cache
12072:
12073: sub devalidate_title_cache {
12074: my ($url)=@_;
12075: if (!$env{'request.course.id'}) { return; }
12076: my $symb=&symbread($url);
12077: if (!$symb) { return; }
12078: my $key=$env{'request.course.id'}."\0".$symb;
12079: &devalidate_cache_new('title',$key);
12080: }
12081:
1.1014 droeschl 12082: # ------------------------------------------------- Get the title of a course
12083:
12084: sub current_course_title {
12085: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12086: }
1.301 www 12087: # ------------------------------------------------- Get the title of a resource
12088:
12089: sub gettitle {
12090: my $urlsymb=shift;
12091: my $symb=&symbread($urlsymb);
1.534 albertel 12092: if ($symb) {
1.620 albertel 12093: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12094: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12095: if (defined($cached)) {
12096: return $result;
12097: }
1.534 albertel 12098: my ($map,$resid,$url)=&decode_symb($symb);
12099: my $title='';
1.907 albertel 12100: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12101: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12102: } else {
12103: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12104: &GDBM_READER(),0640)) {
12105: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12106: $title=$bighash{'title_'.$mapid.'.'.$resid};
12107: untie(%bighash);
12108: }
1.534 albertel 12109: }
12110: $title=~s/\&colon\;/\:/gs;
12111: if ($title) {
1.1159 www 12112: # Remember both $symb and $title for dynamic metadata
12113: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12114: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12115: # Cache this title and then return it
1.599 albertel 12116: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12117: }
12118: $urlsymb=$url;
12119: }
12120: my $title=&metadata($urlsymb,'title');
12121: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12122: return $title;
1.301 www 12123: }
1.613 albertel 12124:
1.614 albertel 12125: sub get_slot {
12126: my ($which,$cnum,$cdom)=@_;
12127: if (!$cnum || !$cdom) {
1.790 albertel 12128: (undef,my $courseid)=&whichuser();
1.620 albertel 12129: $cdom=$env{'course.'.$courseid.'.domain'};
12130: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12131: }
1.703 albertel 12132: my $key=join("\0",'slots',$cdom,$cnum,$which);
12133: my %slotinfo;
12134: if (exists($remembered{$key})) {
12135: $slotinfo{$which} = $remembered{$key};
12136: } else {
12137: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12138: &Apache::lonhomework::showhash(%slotinfo);
12139: my ($tmp)=keys(%slotinfo);
12140: if ($tmp=~/^error:/) { return (); }
12141: $remembered{$key} = $slotinfo{$which};
12142: }
1.616 albertel 12143: if (ref($slotinfo{$which}) eq 'HASH') {
12144: return %{$slotinfo{$which}};
12145: }
12146: return $slotinfo{$which};
1.614 albertel 12147: }
1.1150 raeburn 12148:
12149: sub get_reservable_slots {
12150: my ($cnum,$cdom,$uname,$udom) = @_;
12151: my $now = time;
12152: my $reservable_info;
12153: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12154: if (exists($remembered{$key})) {
12155: $reservable_info = $remembered{$key};
12156: } else {
12157: my %resv;
12158: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12159: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12160: $reservable_info = \%resv;
12161: $remembered{$key} = $reservable_info;
12162: }
12163: return $reservable_info;
12164: }
12165:
12166: sub get_course_slots {
12167: my ($cnum,$cdom) = @_;
12168: my $hashid=$cnum.':'.$cdom;
12169: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12170: if (defined($cached)) {
12171: if (ref($result) eq 'HASH') {
12172: return %{$result};
12173: }
12174: } else {
12175: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12176: my ($tmp) = keys(%slots);
12177: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 12178: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12179: return %slots;
12180: }
12181: }
12182: return;
12183: }
12184:
12185: sub devalidate_slots_cache {
12186: my ($cnum,$cdom)=@_;
12187: my $hashid=$cnum.':'.$cdom;
12188: &devalidate_cache_new('allslots',$hashid);
12189: }
12190:
1.1172.2.8 raeburn 12191: sub get_coursechange {
12192: my ($cdom,$cnum) = @_;
12193: if ($cdom eq '' || $cnum eq '') {
12194: return unless ($env{'request.course.id'});
12195: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12196: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12197: }
12198: my $hashid=$cdom.'_'.$cnum;
12199: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12200: if ((defined($cached)) && ($change ne '')) {
12201: return $change;
12202: } else {
12203: my %crshash;
12204: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12205: if ($crshash{'internal.contentchange'} eq '') {
12206: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12207: if ($change eq '') {
12208: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12209: $change = $crshash{'internal.created'};
12210: }
12211: } else {
12212: $change = $crshash{'internal.contentchange'};
12213: }
12214: my $cachetime = 600;
12215: &do_cache_new('crschange',$hashid,$change,$cachetime);
12216: }
12217: return $change;
12218: }
12219:
12220: sub devalidate_coursechange_cache {
12221: my ($cnum,$cdom)=@_;
12222: my $hashid=$cnum.':'.$cdom;
12223: &devalidate_cache_new('crschange',$hashid);
12224: }
12225:
1.31 www 12226: # ------------------------------------------------- Update symbolic store links
12227:
12228: sub symblist {
12229: my ($mapname,%newhash)=@_;
1.438 www 12230: $mapname=&deversion(&declutter($mapname));
1.31 www 12231: my %hash;
1.620 albertel 12232: if (($env{'request.course.fn'}) && (%newhash)) {
12233: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12234: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12235: foreach my $url (keys(%newhash)) {
1.711 albertel 12236: next if ($url eq 'last_known'
12237: && $env{'form.no_update_last_known'});
12238: $hash{declutter($url)}=&encode_symb($mapname,
12239: $newhash{$url}->[1],
12240: $newhash{$url}->[0]);
1.191 harris41 12241: }
1.31 www 12242: if (untie(%hash)) {
12243: return 'ok';
12244: }
12245: }
12246: }
12247: return 'error';
1.212 www 12248: }
12249:
12250: # --------------------------------------------------------------- Verify a symb
12251:
12252: sub symbverify {
1.1172.2.11 raeburn 12253: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12254: my $thisfn=$thisurl;
1.439 www 12255: $thisfn=&declutter($thisfn);
1.215 www 12256: # direct jump to resource in page or to a sequence - will construct own symbs
12257: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12258: # check URL part
1.409 www 12259: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12260:
1.431 www 12261: unless ($url eq $thisfn) { return 0; }
1.213 www 12262:
1.216 www 12263: $symb=&symbclean($symb);
1.510 www 12264: $thisurl=&deversion($thisurl);
1.439 www 12265: $thisfn=&deversion($thisfn);
1.213 www 12266:
12267: my %bighash;
12268: my $okay=0;
1.431 www 12269:
1.620 albertel 12270: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12271: &GDBM_READER(),0640)) {
1.1032 raeburn 12272: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12273: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 12274: if ($map =~ m{^uploaded/.+\.page$}) {
12275: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12276: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12277: }
12278: }
12279: my $ids;
1.1172.2.122! raeburn 12280: if ($map =~ m{^uploaded/.+\.page$}) {
! 12281: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 12282: } else {
12283: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12284: }
1.1102 raeburn 12285: unless ($ids) {
1.1172.2.13 raeburn 12286: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 12287: $ids=$bighash{$idkey};
1.216 www 12288: }
12289: if ($ids) {
12290: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 12291: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12292: $symb =~ s/\?.+$//;
12293: }
1.800 albertel 12294: foreach my $id (split(/\,/,$ids)) {
12295: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12296: if (
12297: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 12298: eq $symb) {
1.1172.2.11 raeburn 12299: if (ref($encstate)) {
12300: $$encstate = $bighash{'encrypted_'.$id};
12301: }
1.1172.2.13 raeburn 12302: if (($env{'request.role.adv'}) ||
12303: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 12304: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 12305: $okay=1;
12306: last;
12307: }
12308: }
12309: }
1.216 www 12310: }
1.213 www 12311: untie(%bighash);
12312: }
12313: return $okay;
1.31 www 12314: }
12315:
1.210 www 12316: # --------------------------------------------------------------- Clean-up symb
12317:
12318: sub symbclean {
12319: my $symb=shift;
1.568 albertel 12320: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12321: # remove version from map
12322: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12323:
1.210 www 12324: # remove version from URL
12325: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12326:
1.507 www 12327: # remove wrapper
12328:
1.510 www 12329: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12330: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12331: return $symb;
1.409 www 12332: }
12333:
12334: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12335:
12336: sub encode_symb {
12337: my ($map,$resid,$url)=@_;
12338: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12339: }
1.409 www 12340:
12341: sub decode_symb {
1.568 albertel 12342: my $symb=shift;
12343: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12344: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12345: return (&fixversion($map),$resid,&fixversion($url));
12346: }
12347:
12348: sub fixversion {
12349: my $fn=shift;
1.609 banghart 12350: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12351: my %bighash;
12352: my $uri=&clutter($fn);
1.620 albertel 12353: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12354: # is this cached?
1.599 albertel 12355: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12356: if (defined($cached)) { return $result; }
12357: # unfortunately not cached, or expired
1.620 albertel 12358: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12359: &GDBM_READER(),0640)) {
12360: if ($bighash{'version_'.$uri}) {
12361: my $version=$bighash{'version_'.$uri};
1.444 www 12362: unless (($version eq 'mostrecent') ||
12363: ($version==&getversion($uri))) {
1.440 www 12364: $uri=~s/\.(\w+)$/\.$version\.$1/;
12365: }
12366: }
12367: untie %bighash;
1.413 www 12368: }
1.599 albertel 12369: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12370: }
12371:
12372: sub deversion {
12373: my $url=shift;
12374: $url=~s/\.\d+\.(\w+)$/\.$1/;
12375: return $url;
1.210 www 12376: }
12377:
1.31 www 12378: # ------------------------------------------------------ Return symb list entry
12379:
12380: sub symbread {
1.1172.2.66 raeburn 12381: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 12382: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 12383: if (defined($env{$cache_str})) {
12384: if ($ignorecachednull) {
12385: return $env{$cache_str} unless ($env{$cache_str} eq '');
12386: } else {
12387: return $env{$cache_str};
12388: }
12389: }
1.242 www 12390: # no filename provided? try from environment
1.1172.2.54 raeburn 12391: unless ($thisfn) {
1.620 albertel 12392: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 12393: return $env{$cache_str}=&symbclean($env{'request.symb'});
12394: }
12395: $thisfn=$env{'request.filename'};
1.44 www 12396: }
1.569 albertel 12397: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12398: # is that filename actually a symb? Verify, clean, and return
12399: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12400: if (&symbverify($thisfn,$1)) {
1.620 albertel 12401: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12402: }
1.242 www 12403: }
1.44 www 12404: $thisfn=declutter($thisfn);
1.31 www 12405: my %hash;
1.37 www 12406: my %bighash;
12407: my $syval='';
1.620 albertel 12408: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12409: my $targetfn = $thisfn;
1.609 banghart 12410: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12411: $targetfn = 'adm/wrapper/'.$thisfn;
12412: }
1.687 albertel 12413: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12414: $targetfn=$1;
12415: }
1.620 albertel 12416: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12417: &GDBM_READER(),0640)) {
1.481 raeburn 12418: $syval=$hash{$targetfn};
1.37 www 12419: untie(%hash);
12420: }
12421: # ---------------------------------------------------------- There was an entry
12422: if ($syval) {
1.601 albertel 12423: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12424: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12425: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12426: #return $env{$cache_str}='';
1.601 albertel 12427: #}
12428: #$syval.=$1;
12429: #}
1.37 www 12430: } else {
12431: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12432: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12433: &GDBM_READER(),0640)) {
1.37 www 12434: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12435: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12436: unless ($ids) {
12437: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12438: }
12439: unless ($ids) {
12440: # alias?
12441: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12442: }
1.37 www 12443: if ($ids) {
12444: # ------------------------------------------------------------------- Has ID(s)
12445: my @possibilities=split(/\,/,$ids);
1.39 www 12446: if ($#possibilities==0) {
12447: # ----------------------------------------------- There is only one possibility
1.37 www 12448: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12449: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12450: $resid,$thisfn);
1.1172.2.66 raeburn 12451: if (ref($possibles) eq 'HASH') {
12452: $possibles->{$syval} = 1;
12453: }
12454: if ($checkforblock) {
12455: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12456: if (@blockers) {
12457: $syval = '';
12458: return;
12459: }
12460: }
12461: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12462: # ------------------------------------------ There is more than one possibility
12463: my $realpossible=0;
1.800 albertel 12464: foreach my $id (@possibilities) {
12465: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12466: my $canaccess;
12467: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12468: $canaccess = 1;
12469: } else {
12470: $canaccess = &allowed('bre',$file);
12471: }
12472: if ($canaccess) {
12473: my ($mapid,$resid)=split(/\./,$id);
12474: if ($bighash{'map_type_'.$mapid} ne 'page') {
12475: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12476: $resid,$thisfn);
12477: if (ref($possibles) eq 'HASH') {
12478: $possibles->{$syval} = 1;
12479: }
12480: if ($checkforblock) {
12481: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12482: unless (@blockers > 0) {
12483: $syval = $poss_syval;
12484: $realpossible++;
12485: }
12486: } else {
12487: $syval = $poss_syval;
12488: $realpossible++;
12489: }
12490: }
1.39 www 12491: }
1.191 harris41 12492: }
1.39 www 12493: if ($realpossible!=1) { $syval=''; }
1.249 www 12494: } else {
12495: $syval='';
1.37 www 12496: }
12497: }
1.1172.2.66 raeburn 12498: untie(%bighash);
1.481 raeburn 12499: }
1.31 www 12500: }
1.62 www 12501: if ($syval) {
1.620 albertel 12502: return $env{$cache_str}=$syval;
1.62 www 12503: }
1.31 www 12504: }
1.949 raeburn 12505: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12506: return $env{$cache_str}='';
1.31 www 12507: }
12508:
12509: # ---------------------------------------------------------- Return random seed
12510:
1.32 www 12511: sub numval {
12512: my $txt=shift;
12513: $txt=~tr/A-J/0-9/;
12514: $txt=~tr/a-j/0-9/;
12515: $txt=~tr/K-T/0-9/;
12516: $txt=~tr/k-t/0-9/;
12517: $txt=~tr/U-Z/0-5/;
12518: $txt=~tr/u-z/0-5/;
12519: $txt=~s/\D//g;
1.564 albertel 12520: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12521: return int($txt);
1.368 albertel 12522: }
12523:
1.484 albertel 12524: sub numval2 {
12525: my $txt=shift;
12526: $txt=~tr/A-J/0-9/;
12527: $txt=~tr/a-j/0-9/;
12528: $txt=~tr/K-T/0-9/;
12529: $txt=~tr/k-t/0-9/;
12530: $txt=~tr/U-Z/0-5/;
12531: $txt=~tr/u-z/0-5/;
12532: $txt=~s/\D//g;
12533: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12534: my $total;
12535: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12536: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12537: return int($total);
12538: }
12539:
1.575 albertel 12540: sub numval3 {
12541: use integer;
12542: my $txt=shift;
12543: $txt=~tr/A-J/0-9/;
12544: $txt=~tr/a-j/0-9/;
12545: $txt=~tr/K-T/0-9/;
12546: $txt=~tr/k-t/0-9/;
12547: $txt=~tr/U-Z/0-5/;
12548: $txt=~tr/u-z/0-5/;
12549: $txt=~s/\D//g;
12550: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12551: my $total;
12552: foreach my $val (@txts) { $total+=$val; }
12553: if ($_64bit) { $total=(($total<<32)>>32); }
12554: return $total;
12555: }
12556:
1.675 albertel 12557: sub digest {
12558: my ($data)=@_;
12559: my $digest=&Digest::MD5::md5($data);
12560: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12561: my ($e,$f);
12562: {
12563: use integer;
12564: $e=($a+$b);
12565: $f=($c+$d);
12566: if ($_64bit) {
12567: $e=(($e<<32)>>32);
12568: $f=(($f<<32)>>32);
12569: }
12570: }
12571: if (wantarray) {
12572: return ($e,$f);
12573: } else {
12574: my $g;
12575: {
12576: use integer;
12577: $g=($e+$f);
12578: if ($_64bit) {
12579: $g=(($g<<32)>>32);
12580: }
12581: }
12582: return $g;
12583: }
12584: }
12585:
1.368 albertel 12586: sub latest_rnd_algorithm_id {
1.675 albertel 12587: return '64bit5';
1.366 albertel 12588: }
1.32 www 12589:
1.503 albertel 12590: sub get_rand_alg {
12591: my ($courseid)=@_;
1.790 albertel 12592: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12593: if ($courseid) {
1.620 albertel 12594: return $env{"course.$courseid.rndseed"};
1.503 albertel 12595: }
12596: return &latest_rnd_algorithm_id();
12597: }
12598:
1.562 albertel 12599: sub validCODE {
12600: my ($CODE)=@_;
12601: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12602: return 0;
12603: }
12604:
1.491 albertel 12605: sub getCODE {
1.620 albertel 12606: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12607: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12608: defined($Apache::lonhomework::parsing_a_task) ) &&
12609: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12610: return $Apache::lonhomework::history{'resource.CODE'};
12611: }
12612: return undef;
12613: }
1.1133 foxr 12614: #
12615: # Determines the random seed for a specific context:
12616: #
12617: # parameters:
12618: # symb - in course context the symb for the seed.
12619: # course_id - The course id of the form domain_coursenum.
12620: # domain - Domain for the user.
12621: # course - Course for the user.
12622: # cenv - environment of the course.
12623: #
12624: # NOTE:
12625: # All parameters are picked out of the environment if missing
12626: # or not defined.
12627: # If a symb cannot be determined the current time is used instead.
12628: #
12629: # For a given well defined symb, courside, domain, username,
12630: # and course environment, the seed is reproducible.
12631: #
1.31 www 12632: sub rndseed {
1.1133 foxr 12633: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12634: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12635: if (!defined($symb)) {
1.366 albertel 12636: unless ($symb=$wsymb) { return time; }
12637: }
1.1146 foxr 12638: if (!defined $courseid) {
12639: $courseid=$wcourseid;
12640: }
12641: if (!defined $domain) { $domain=$wdomain; }
12642: if (!defined $username) { $username=$wusername }
1.1133 foxr 12643:
12644: my $which;
12645: if (defined($cenv->{'rndseed'})) {
12646: $which = $cenv->{'rndseed'};
12647: } else {
12648: $which =&get_rand_alg($courseid);
12649: }
1.491 albertel 12650: if (defined(&getCODE())) {
1.675 albertel 12651: if ($which eq '64bit5') {
12652: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12653: } elsif ($which eq '64bit4') {
1.575 albertel 12654: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12655: } else {
12656: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12657: }
1.675 albertel 12658: } elsif ($which eq '64bit5') {
12659: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12660: } elsif ($which eq '64bit4') {
12661: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12662: } elsif ($which eq '64bit3') {
12663: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12664: } elsif ($which eq '64bit2') {
12665: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12666: } elsif ($which eq '64bit') {
12667: return &rndseed_64bit($symb,$courseid,$domain,$username);
12668: }
12669: return &rndseed_32bit($symb,$courseid,$domain,$username);
12670: }
12671:
12672: sub rndseed_32bit {
12673: my ($symb,$courseid,$domain,$username)=@_;
12674: {
12675: use integer;
12676: my $symbchck=unpack("%32C*",$symb) << 27;
12677: my $symbseed=numval($symb) << 22;
12678: my $namechck=unpack("%32C*",$username) << 17;
12679: my $nameseed=numval($username) << 12;
12680: my $domainseed=unpack("%32C*",$domain) << 7;
12681: my $courseseed=unpack("%32C*",$courseid);
12682: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12683: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12684: #&logthis("rndseed :$num:$symb");
1.564 albertel 12685: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12686: return $num;
12687: }
12688: }
12689:
12690: sub rndseed_64bit {
12691: my ($symb,$courseid,$domain,$username)=@_;
12692: {
12693: use integer;
12694: my $symbchck=unpack("%32S*",$symb) << 21;
12695: my $symbseed=numval($symb) << 10;
12696: my $namechck=unpack("%32S*",$username);
12697:
12698: my $nameseed=numval($username) << 21;
12699: my $domainseed=unpack("%32S*",$domain) << 10;
12700: my $courseseed=unpack("%32S*",$courseid);
12701:
12702: my $num1=$symbchck+$symbseed+$namechck;
12703: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12704: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12705: #&logthis("rndseed :$num:$symb");
1.564 albertel 12706: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12707: return "$num1,$num2";
1.155 albertel 12708: }
1.366 albertel 12709: }
12710:
1.443 albertel 12711: sub rndseed_64bit2 {
12712: my ($symb,$courseid,$domain,$username)=@_;
12713: {
12714: use integer;
12715: # strings need to be an even # of cahracters long, it it is odd the
12716: # last characters gets thrown away
12717: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12718: my $symbseed=numval($symb) << 10;
12719: my $namechck=unpack("%32S*",$username.' ');
12720:
12721: my $nameseed=numval($username) << 21;
1.501 albertel 12722: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12723: my $courseseed=unpack("%32S*",$courseid.' ');
12724:
12725: my $num1=$symbchck+$symbseed+$namechck;
12726: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12727: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12728: #&logthis("rndseed :$num:$symb");
1.803 albertel 12729: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12730: return "$num1,$num2";
12731: }
12732: }
12733:
12734: sub rndseed_64bit3 {
12735: my ($symb,$courseid,$domain,$username)=@_;
12736: {
12737: use integer;
12738: # strings need to be an even # of cahracters long, it it is odd the
12739: # last characters gets thrown away
12740: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12741: my $symbseed=numval2($symb) << 10;
12742: my $namechck=unpack("%32S*",$username.' ');
12743:
12744: my $nameseed=numval2($username) << 21;
1.443 albertel 12745: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12746: my $courseseed=unpack("%32S*",$courseid.' ');
12747:
12748: my $num1=$symbchck+$symbseed+$namechck;
12749: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12750: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12751: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12752: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12753:
1.503 albertel 12754: return "$num1:$num2";
1.443 albertel 12755: }
12756: }
12757:
1.575 albertel 12758: sub rndseed_64bit4 {
12759: my ($symb,$courseid,$domain,$username)=@_;
12760: {
12761: use integer;
12762: # strings need to be an even # of cahracters long, it it is odd the
12763: # last characters gets thrown away
12764: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12765: my $symbseed=numval3($symb) << 10;
12766: my $namechck=unpack("%32S*",$username.' ');
12767:
12768: my $nameseed=numval3($username) << 21;
12769: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12770: my $courseseed=unpack("%32S*",$courseid.' ');
12771:
12772: my $num1=$symbchck+$symbseed+$namechck;
12773: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12774: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12775: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12776: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12777:
1.575 albertel 12778: return "$num1:$num2";
12779: }
12780: }
12781:
1.675 albertel 12782: sub rndseed_64bit5 {
12783: my ($symb,$courseid,$domain,$username)=@_;
12784: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12785: return "$num1:$num2";
12786: }
12787:
1.366 albertel 12788: sub rndseed_CODE_64bit {
12789: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12790: {
1.366 albertel 12791: use integer;
1.443 albertel 12792: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12793: my $symbseed=numval2($symb);
1.491 albertel 12794: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12795: my $CODEseed=numval(&getCODE());
1.443 albertel 12796: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12797: my $num1=$symbseed+$CODEchck;
12798: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12799: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12800: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12801: if ($_64bit) { $num1=(($num1<<32)>>32); }
12802: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12803: return "$num1:$num2";
1.366 albertel 12804: }
12805: }
12806:
1.575 albertel 12807: sub rndseed_CODE_64bit4 {
12808: my ($symb,$courseid,$domain,$username)=@_;
12809: {
12810: use integer;
12811: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12812: my $symbseed=numval3($symb);
12813: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12814: my $CODEseed=numval3(&getCODE());
12815: my $courseseed=unpack("%32S*",$courseid.' ');
12816: my $num1=$symbseed+$CODEchck;
12817: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12818: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12819: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12820: if ($_64bit) { $num1=(($num1<<32)>>32); }
12821: if ($_64bit) { $num2=(($num2<<32)>>32); }
12822: return "$num1:$num2";
12823: }
12824: }
12825:
1.675 albertel 12826: sub rndseed_CODE_64bit5 {
12827: my ($symb,$courseid,$domain,$username)=@_;
12828: my $code = &getCODE();
12829: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12830: return "$num1:$num2";
12831: }
12832:
1.366 albertel 12833: sub setup_random_from_rndseed {
12834: my ($rndseed)=@_;
1.503 albertel 12835: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 12836: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12837: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12838: &Math::Random::random_set_seed_from_phrase($rndseed);
12839: } else {
12840: &Math::Random::random_set_seed($num1,$num2);
12841: }
1.366 albertel 12842: } else {
12843: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12844: }
1.36 albertel 12845: }
12846:
1.474 albertel 12847: sub latest_receipt_algorithm_id {
1.835 albertel 12848: return 'receipt3';
1.474 albertel 12849: }
12850:
1.480 www 12851: sub recunique {
12852: my $fucourseid=shift;
12853: my $unique;
1.835 albertel 12854: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12855: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12856: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12857: } else {
12858: $unique=$perlvar{'lonReceipt'};
12859: }
12860: return unpack("%32C*",$unique);
12861: }
12862:
12863: sub recprefix {
12864: my $fucourseid=shift;
12865: my $prefix;
1.835 albertel 12866: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12867: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12868: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12869: } else {
12870: $prefix=$perlvar{'lonHostID'};
12871: }
12872: return unpack("%32C*",$prefix);
12873: }
12874:
1.76 www 12875: sub ireceipt {
1.474 albertel 12876: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12877:
12878: my $return =&recprefix($fucourseid).'-';
12879:
12880: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12881: $env{'request.state'} eq 'construct') {
12882: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12883: return $return;
12884: }
12885:
1.76 www 12886: my $cuname=unpack("%32C*",$funame);
12887: my $cudom=unpack("%32C*",$fudom);
12888: my $cucourseid=unpack("%32C*",$fucourseid);
12889: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12890: my $cunique=&recunique($fucourseid);
1.474 albertel 12891: my $cpart=unpack("%32S*",$part);
1.835 albertel 12892: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12893:
1.790 albertel 12894: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12895:
12896: $return.= ($cunique%$cuname+
12897: $cunique%$cudom+
12898: $cusymb%$cuname+
12899: $cusymb%$cudom+
12900: $cucourseid%$cuname+
12901: $cucourseid%$cudom+
12902: $cpart%$cuname+
12903: $cpart%$cudom);
12904: } else {
12905: $return.= ($cunique%$cuname+
12906: $cunique%$cudom+
12907: $cusymb%$cuname+
12908: $cusymb%$cudom+
12909: $cucourseid%$cuname+
12910: $cucourseid%$cudom);
12911: }
12912: return $return;
1.76 www 12913: }
12914:
12915: sub receipt {
1.474 albertel 12916: my ($part)=@_;
1.790 albertel 12917: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12918: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12919: }
1.260 ng 12920:
1.790 albertel 12921: sub whichuser {
12922: my ($passedsymb)=@_;
12923: my ($symb,$courseid,$domain,$name,$publicuser);
12924: if (defined($env{'form.grade_symb'})) {
12925: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12926: my $allowed=&allowed('vgr',$tmp_courseid);
12927: if (!$allowed &&
12928: exists($env{'request.course.sec'}) &&
12929: $env{'request.course.sec'} !~ /^\s*$/) {
12930: $allowed=&allowed('vgr',$tmp_courseid.
12931: '/'.$env{'request.course.sec'});
12932: }
12933: if ($allowed) {
12934: ($symb)=&get_env_multiple('form.grade_symb');
12935: $courseid=$tmp_courseid;
12936: ($domain)=&get_env_multiple('form.grade_domain');
12937: ($name)=&get_env_multiple('form.grade_username');
12938: return ($symb,$courseid,$domain,$name,$publicuser);
12939: }
12940: }
12941: if (!$passedsymb) {
12942: $symb=&symbread();
12943: } else {
12944: $symb=$passedsymb;
12945: }
12946: $courseid=$env{'request.course.id'};
12947: $domain=$env{'user.domain'};
12948: $name=$env{'user.name'};
12949: if ($name eq 'public' && $domain eq 'public') {
12950: if (!defined($env{'form.username'})) {
12951: $env{'form.username'}.=time.rand(10000000);
12952: }
12953: $name.=$env{'form.username'};
12954: }
12955: return ($symb,$courseid,$domain,$name,$publicuser);
12956:
12957: }
12958:
1.36 albertel 12959: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12960: # returns either the contents of the file or
12961: # -1 if the file doesn't exist
1.481 raeburn 12962: #
12963: # if the target is a file that was uploaded via DOCS,
12964: # a check will be made to see if a current copy exists on the local server,
12965: # if it does this will be served, otherwise a copy will be retrieved from
12966: # the home server for the course and stored in /home/httpd/html/userfiles on
12967: # the local server.
1.472 albertel 12968:
1.36 albertel 12969: sub getfile {
1.538 albertel 12970: my ($file) = @_;
1.609 banghart 12971: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12972: &repcopy($file);
12973: return &readfile($file);
12974: }
12975:
12976: sub repcopy_userfile {
12977: my ($file)=@_;
1.1142 raeburn 12978: my $londocroot = $perlvar{'lonDocRoot'};
12979: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12980: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12981: my ($cdom,$cnum,$filename) =
1.811 albertel 12982: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12983: my $uri="/uploaded/$cdom/$cnum/$filename";
12984: if (-e "$file") {
1.828 www 12985: # we already have a local copy, check it out
1.538 albertel 12986: my @fileinfo = stat($file);
1.828 www 12987: my $rtncode;
12988: my $info;
1.538 albertel 12989: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12990: if ($lwpresp ne 'ok') {
1.828 www 12991: # there is no such file anymore, even though we had a local copy
1.482 albertel 12992: if ($rtncode eq '404') {
1.538 albertel 12993: unlink($file);
1.482 albertel 12994: }
12995: return -1;
12996: }
12997: if ($info < $fileinfo[9]) {
1.828 www 12998: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12999: return 'ok';
1.828 www 13000: } else {
13001: # the file is outdated, get rid of it
13002: unlink($file);
1.482 albertel 13003: }
1.828 www 13004: }
13005: # one way or the other, at this point, we don't have the file
13006: # construct the correct path for the file
13007: my @parts = ($cdom,$cnum);
13008: if ($filename =~ m|^(.+)/[^/]+$|) {
13009: push @parts, split(/\//,$1);
13010: }
13011: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13012: foreach my $part (@parts) {
13013: $path .= '/'.$part;
13014: if (!-e $path) {
13015: mkdir($path,0770);
1.482 albertel 13016: }
13017: }
1.828 www 13018: # now the path exists for sure
13019: # get a user agent
13020: my $ua=new LWP::UserAgent;
13021: my $transferfile=$file.'.in.transfer';
13022: # FIXME: this should flock
13023: if (-e $transferfile) { return 'ok'; }
13024: my $request;
13025: $uri=~s/^\///;
1.980 raeburn 13026: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13027: my $hostname = &hostname($homeserver);
1.980 raeburn 13028: my $protocol = $protocol{$homeserver};
13029: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13030: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 13031: my $response=$ua->request($request,$transferfile);
13032: # did it work?
13033: if ($response->is_error()) {
13034: unlink($transferfile);
13035: &logthis("Userfile repcopy failed for $uri");
13036: return -1;
13037: }
13038: # worked, rename the transfer file
13039: rename($transferfile,$file);
1.607 raeburn 13040: return 'ok';
1.481 raeburn 13041: }
13042:
1.517 albertel 13043: sub tokenwrapper {
13044: my $uri=shift;
1.980 raeburn 13045: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13046: $uri=~s|^/||;
1.620 albertel 13047: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13048: my $token=$1;
1.552 albertel 13049: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13050: if ($udom && $uname && $file) {
13051: $file=~s|(\?\.*)*$||;
1.949 raeburn 13052: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13053: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 13054: my $hostname = &hostname($homeserver);
1.980 raeburn 13055: my $protocol = $protocol{$homeserver};
13056: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13057: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13058: (($uri=~/\?/)?'&':'?').'token='.$token.
13059: '&tokenissued='.$perlvar{'lonHostID'};
13060: } else {
13061: return '/adm/notfound.html';
13062: }
13063: }
13064:
1.828 www 13065: # call with reqtype HEAD: get last modification time
13066: # call with reqtype GET: get the file contents
13067: # Do not call this with reqtype GET for large files! It loads everything into memory
13068: #
1.481 raeburn 13069: sub getuploaded {
13070: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13071: $uri=~s/^\///;
1.980 raeburn 13072: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13073: my $hostname = &hostname($homeserver);
1.980 raeburn 13074: my $protocol = $protocol{$homeserver};
13075: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13076: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13077: my $ua=new LWP::UserAgent;
13078: my $request=new HTTP::Request($reqtype,$uri);
13079: my $response=$ua->request($request);
13080: $$rtncode = $response->code;
1.482 albertel 13081: if (! $response->is_success()) {
13082: return 'failed';
13083: }
13084: if ($reqtype eq 'HEAD') {
1.486 www 13085: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13086: } elsif ($reqtype eq 'GET') {
13087: $$info = $response->content;
1.472 albertel 13088: }
1.482 albertel 13089: return 'ok';
1.36 albertel 13090: }
13091:
1.481 raeburn 13092: sub readfile {
13093: my $file = shift;
13094: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13095: my $fh;
1.1172.2.96 raeburn 13096: open($fh,"<",$file);
1.481 raeburn 13097: my $a='';
1.800 albertel 13098: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13099: return $a;
13100: }
13101:
1.36 albertel 13102: sub filelocation {
1.590 banghart 13103: my ($dir,$file) = @_;
13104: my $location;
13105: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13106:
13107: if ($file =~ m-^/adm/-) {
13108: $file=~s-^/adm/wrapper/-/-;
13109: $file=~s-^/adm/coursedocs/showdoc/-/-;
13110: }
1.882 albertel 13111:
1.1139 www 13112: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13113: $location = $file;
1.609 banghart 13114: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13115: my ($udom,$uname,$filename)=
1.811 albertel 13116: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13117: my $home=&homeserver($uname,$udom);
13118: my $is_me=0;
13119: my @ids=¤t_machine_ids();
13120: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13121: if ($is_me) {
1.1117 foxr 13122: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13123: } else {
13124: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13125: $udom.'/'.$uname.'/'.$filename;
13126: }
1.882 albertel 13127: } elsif ($file =~ m-^/adm/-) {
13128: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13129: } else {
13130: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13131: $file=~s:^/(res|priv)/:/:;
13132: my $space=$1;
1.590 banghart 13133: if ( !( $file =~ m:^/:) ) {
13134: $location = $dir. '/'.$file;
13135: } else {
1.1142 raeburn 13136: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13137: }
1.59 albertel 13138: }
1.590 banghart 13139: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13140: while ($location=~m{/\.\./}) {
13141: if ($location =~ m{/[^/]+/\.\./}) {
13142: $location=~ s{/[^/]+/\.\./}{/}g;
13143: } else {
13144: $location=~ s{/\.\./}{/}g;
13145: }
13146: } #remove dir/..
1.590 banghart 13147: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13148: return $location;
1.46 www 13149: }
1.36 albertel 13150:
1.46 www 13151: sub hreflocation {
13152: my ($dir,$file)=@_;
1.980 raeburn 13153: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13154: $file=filelocation($dir,$file);
1.700 albertel 13155: } elsif ($file=~m-^/adm/-) {
13156: $file=~s-^/adm/wrapper/-/-;
13157: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13158: }
13159: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13160: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13161: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13162: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13163: {/uploaded/$1/$2/}x;
1.46 www 13164: }
1.913 albertel 13165: if ($file=~ m{^/userfiles/}) {
13166: $file =~ s{^/userfiles/}{/uploaded/};
13167: }
1.462 albertel 13168: return $file;
1.465 albertel 13169: }
13170:
1.1139 www 13171:
13172:
13173:
13174:
1.465 albertel 13175: sub current_machine_domains {
1.853 albertel 13176: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13177: }
13178:
13179: sub machine_domains {
13180: my ($hostname) = @_;
1.465 albertel 13181: my @domains;
1.838 albertel 13182: my %hostname = &all_hostnames();
1.465 albertel 13183: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13184: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13185: if ($hostname eq $name) {
1.844 albertel 13186: push(@domains,&host_domain($id));
1.465 albertel 13187: }
13188: }
13189: return @domains;
13190: }
13191:
13192: sub current_machine_ids {
1.853 albertel 13193: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13194: }
13195:
13196: sub machine_ids {
13197: my ($hostname) = @_;
13198: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13199: my @ids;
1.888 albertel 13200: my %name_to_host = &all_names();
1.889 albertel 13201: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13202: return @{ $name_to_host{$hostname} };
13203: }
13204: return;
1.31 www 13205: }
13206:
1.824 raeburn 13207: sub additional_machine_domains {
13208: my @domains;
1.1172.2.96 raeburn 13209: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 13210: while( my $line = <$fh>) {
13211: $line =~ s/\s//g;
13212: push(@domains,$line);
13213: }
13214: return @domains;
13215: }
13216:
13217: sub default_login_domain {
13218: my $domain = $perlvar{'lonDefDomain'};
13219: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13220: foreach my $posdom (¤t_machine_domains(),
13221: &additional_machine_domains()) {
13222: if (lc($posdom) eq lc($testdomain)) {
13223: $domain=$posdom;
13224: last;
13225: }
13226: }
13227: return $domain;
13228: }
13229:
1.1172.2.106 raeburn 13230: sub shared_institution {
13231: my ($dom) = @_;
13232: my $same_intdom;
13233: my $hostintdom = &internet_dom($perlvar{'lonHostID'});
13234: if ($hostintdom ne '') {
13235: my %iphost = &get_iphost();
13236: my $primary_id = &domain($dom,'primary');
13237: my $primary_ip = &get_host_ip($primary_id);
13238: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13239: foreach my $id (@{$iphost{$primary_ip}}) {
13240: my $intdom = &internet_dom($id);
13241: if ($intdom eq $hostintdom) {
13242: $same_intdom = 1;
13243: last;
13244: }
13245: }
13246: }
13247: }
13248: return $same_intdom;
13249: }
13250:
1.1172.2.120 raeburn 13251: sub uses_sts {
13252: my ($ignore_cache) = @_;
13253: my $lonhost = $perlvar{'lonHostID'};
13254: my $hostname = &hostname($lonhost);
13255: my $sts_on;
13256: if ($protocol{$lonhost} eq 'https') {
13257: my $cachetime = 12*3600;
13258: if (!$ignore_cache) {
13259: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13260: if (defined($cached)) {
13261: return $sts_on;
13262: }
13263: }
1.1172.2.121 raeburn 13264: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 13265: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13266: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 13267: my $response=$ua->request($request);
1.1172.2.120 raeburn 13268: if ($response->is_success) {
13269: my $has_sts = $response->header('Strict-Transport-Security');
13270: if ($has_sts eq '') {
13271: $sts_on = 0;
13272: } else {
13273: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13274: my $maxage = $1;
13275: if ($maxage) {
13276: $sts_on = 1;
13277: } else {
13278: $sts_on = 0;
13279: }
13280: } else {
13281: $sts_on = 0;
13282: }
13283: }
13284: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13285: }
13286: }
13287: return;
13288: }
13289:
1.31 www 13290: # ------------------------------------------------------------- Declutters URLs
13291:
13292: sub declutter {
13293: my $thisfn=shift;
1.569 albertel 13294: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 13295: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13296: $thisfn=~s{^/home/httpd/html}{};
13297: }
1.31 www 13298: $thisfn=~s/^\///;
1.697 albertel 13299: $thisfn=~s|^adm/wrapper/||;
13300: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13301: $thisfn=~s/^res\///;
1.1172 bisitz 13302: $thisfn=~s/^priv\///;
1.1032 raeburn 13303: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13304: $thisfn=~s/\?.+$//;
13305: }
1.268 www 13306: return $thisfn;
13307: }
13308:
13309: # ------------------------------------------------------------- Clutter up URLs
13310:
13311: sub clutter {
13312: my $thisfn='/'.&declutter(shift);
1.887 albertel 13313: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13314: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13315: $thisfn='/res'.$thisfn;
13316: }
1.1031 raeburn 13317: if ($thisfn !~m|^/adm|) {
13318: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13319: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13320: } else {
13321: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13322: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13323: if ($embstyle eq 'ssi'
13324: || ($embstyle eq 'hdn')
13325: || ($embstyle eq 'rat')
13326: || ($embstyle eq 'prv')
13327: || ($embstyle eq 'ign')) {
13328: #do nothing with these
13329: } elsif (($embstyle eq 'img')
1.695 albertel 13330: || ($embstyle eq 'emb')
13331: || ($embstyle eq 'wrp')) {
13332: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13333: } elsif ($embstyle eq 'unk'
13334: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13335: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13336: } else {
1.718 www 13337: # &logthis("Got a blank emb style");
1.695 albertel 13338: }
1.694 albertel 13339: }
13340: }
1.31 www 13341: return $thisfn;
1.12 www 13342: }
13343:
1.787 albertel 13344: sub clutter_with_no_wrapper {
13345: my $uri = &clutter(shift);
13346: if ($uri =~ m-^/adm/-) {
13347: $uri =~ s-^/adm/wrapper/-/-;
13348: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13349: }
13350: return $uri;
13351: }
13352:
1.557 albertel 13353: sub freeze_escape {
13354: my ($value)=@_;
13355: if (ref($value)) {
13356: $value=&nfreeze($value);
13357: return '__FROZEN__'.&escape($value);
13358: }
13359: return &escape($value);
13360: }
13361:
1.11 www 13362:
1.557 albertel 13363: sub thaw_unescape {
13364: my ($value)=@_;
13365: if ($value =~ /^__FROZEN__/) {
13366: substr($value,0,10,undef);
13367: $value=&unescape($value);
13368: return &thaw($value);
13369: }
13370: return &unescape($value);
13371: }
13372:
1.436 albertel 13373: sub correct_line_ends {
13374: my ($result)=@_;
13375: $$result =~s/\r\n/\n/mg;
13376: $$result =~s/\r/\n/mg;
1.415 albertel 13377: }
1.1 albertel 13378: # ================================================================ Main Program
13379:
1.184 www 13380: sub goodbye {
1.204 albertel 13381: &logthis("Starting Shut down");
1.443 albertel 13382: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13383: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13384: #converted
1.599 albertel 13385: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13386: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13387: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13388: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13389: #1.1 only
1.870 albertel 13390: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13391: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13392: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13393: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13394: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13395: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13396: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13397: &flushcourselogs();
13398: &logthis("Shutting down");
13399: }
13400:
1.852 albertel 13401: sub get_dns {
1.1172.2.17 raeburn 13402: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13403: if (!$ignore_cache) {
13404: my ($content,$cached)=
13405: &Apache::lonnet::is_cached_new('dns',$url);
13406: if ($cached) {
1.1172.2.17 raeburn 13407: &$func($content,$hashref);
1.869 albertel 13408: return;
13409: }
13410: }
13411:
13412: my %alldns;
1.1172.2.96 raeburn 13413: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13414: foreach my $dns (<$config>) {
13415: next if ($dns !~ /^\^(\S*)/x);
13416: my $line = $1;
13417: my ($host,$protocol) = split(/:/,$line);
13418: if ($protocol ne 'https') {
13419: $protocol = 'http';
13420: }
13421: $alldns{$host} = $protocol;
1.979 raeburn 13422: }
1.1172.2.96 raeburn 13423: close($config);
1.869 albertel 13424: }
13425: while (%alldns) {
1.1172.2.52 raeburn 13426: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 13427: my $ua=new LWP::UserAgent;
1.1134 raeburn 13428: $ua->timeout(30);
1.979 raeburn 13429: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 13430: my $response=$ua->request($request);
1.979 raeburn 13431: delete($alldns{$dns});
1.852 albertel 13432: next if ($response->is_error());
13433: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 13434: unless ($nocache) {
1.1172.2.23 raeburn 13435: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 13436: }
13437: &$func(\@content,$hashref);
1.869 albertel 13438: return;
1.852 albertel 13439: }
1.871 albertel 13440: my $which = (split('/',$url))[3];
13441: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 13442: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13443: my @content = <$config>;
13444: &$func(\@content,$hashref);
13445: }
1.1172.2.17 raeburn 13446: return;
13447: }
13448:
13449: # ------------------------------------------------------Get DNS checksums file
13450: sub parse_dns_checksums_tab {
13451: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 13452: my $lonhost = $perlvar{'lonHostID'};
13453: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 13454: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 13455: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13456: my $webconfdir = '/etc/httpd/conf';
13457: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13458: $webconfdir = '/etc/apache2';
13459: } elsif ($distro =~ /^sles(\d+)$/) {
13460: if ($1 >= 10) {
13461: $webconfdir = '/etc/apache2';
13462: }
13463: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13464: if ($1 >= 10.0) {
13465: $webconfdir = '/etc/apache2';
13466: }
13467: }
1.1172.2.17 raeburn 13468: my ($release,$timestamp) = split(/\-/,$loncaparev);
13469: my (%chksum,%revnum);
13470: if (ref($lines) eq 'ARRAY') {
13471: chomp(@{$lines});
1.1172.2.34 raeburn 13472: my $version = shift(@{$lines});
13473: if ($version eq $release) {
1.1172.2.17 raeburn 13474: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 13475: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 13476: if ($file =~ m{^/etc/httpd/conf}) {
13477: if ($webconfdir eq '/etc/apache2') {
13478: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13479: }
13480: }
1.1172.2.34 raeburn 13481: $chksum{$file} = $shasum;
13482: $revnum{$file} = $version;
1.1172.2.17 raeburn 13483: }
13484: if (ref($hashref) eq 'HASH') {
13485: %{$hashref} = (
13486: sums => \%chksum,
13487: versions => \%revnum,
13488: );
13489: }
13490: }
13491: }
1.869 albertel 13492: return;
1.852 albertel 13493: }
1.1172.2.17 raeburn 13494:
13495: sub fetch_dns_checksums {
13496: my %checksums;
1.1172.2.34 raeburn 13497: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 13498: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 13499: my ($release,$timestamp) = split(/\-/,$loncaparev);
13500: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 13501: \%checksums);
13502: return \%checksums;
13503: }
13504:
1.327 albertel 13505: # ------------------------------------------------------------ Read domain file
13506: {
1.852 albertel 13507: my $loaded;
1.846 albertel 13508: my %domain;
13509:
1.852 albertel 13510: sub parse_domain_tab {
13511: my ($lines) = @_;
13512: foreach my $line (@$lines) {
13513: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13514:
1.846 albertel 13515: chomp($line);
1.852 albertel 13516: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13517: my %this_domain;
13518: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13519: 'lang_def', 'city', 'longi', 'lati',
13520: 'primary') {
13521: $this_domain{$field} = shift(@elements);
13522: }
13523: $domain{$name} = \%this_domain;
1.852 albertel 13524: }
13525: }
1.864 albertel 13526:
13527: sub reset_domain_info {
13528: undef($loaded);
13529: undef(%domain);
13530: }
13531:
1.852 albertel 13532: sub load_domain_tab {
1.1172.2.70 raeburn 13533: my ($ignore_cache,$nocache) = @_;
13534: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13535: my $fh;
1.1172.2.96 raeburn 13536: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 13537: my @lines = <$fh>;
13538: &parse_domain_tab(\@lines);
1.448 albertel 13539: }
1.852 albertel 13540: close($fh);
13541: $loaded = 1;
1.327 albertel 13542: }
1.846 albertel 13543:
13544: sub domain {
1.852 albertel 13545: &load_domain_tab() if (!$loaded);
13546:
1.846 albertel 13547: my ($name,$what) = @_;
13548: return if ( !exists($domain{$name}) );
13549:
13550: if (!$what) {
13551: return $domain{$name}{'description'};
13552: }
13553: return $domain{$name}{$what};
13554: }
1.974 raeburn 13555:
13556: sub domain_info {
13557: &load_domain_tab() if (!$loaded);
13558: return %domain;
13559: }
13560:
1.327 albertel 13561: }
13562:
13563:
1.1 albertel 13564: # ------------------------------------------------------------- Read hosts file
13565: {
1.838 albertel 13566: my %hostname;
1.844 albertel 13567: my %hostdom;
1.845 albertel 13568: my %libserv;
1.852 albertel 13569: my $loaded;
1.888 albertel 13570: my %name_to_host;
1.1074 raeburn 13571: my %internetdom;
1.1107 raeburn 13572: my %LC_dns_serv;
1.852 albertel 13573:
13574: sub parse_hosts_tab {
13575: my ($file) = @_;
13576: foreach my $configline (@$file) {
13577: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13578: chomp($configline);
13579: if ($configline =~ /^\^/) {
13580: if ($configline =~ /^\^([\w.\-]+)/) {
13581: $LC_dns_serv{$1} = 1;
13582: }
13583: next;
13584: }
1.1074 raeburn 13585: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13586: $name=~s/\s//g;
13587: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 13588: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13589: my $curr = $hostname{$id};
13590: my $skip;
13591: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13592: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13593: $skip = 1;
13594: } else {
13595: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13596: }
13597: }
13598: unless ($skip) {
13599: push(@{$name_to_host{$name}},$id);
13600: }
13601: } else {
13602: push(@{$name_to_host{$name}},$id);
13603: }
1.852 albertel 13604: $hostname{$id}=$name;
13605: $hostdom{$id}=$domain;
13606: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13607: if (defined($protocol)) {
13608: if ($protocol eq 'https') {
13609: $protocol{$id} = $protocol;
13610: } else {
13611: $protocol{$id} = 'http';
13612: }
1.968 raeburn 13613: } else {
1.969 raeburn 13614: $protocol{$id} = 'http';
1.968 raeburn 13615: }
1.1074 raeburn 13616: if (defined($intdom)) {
13617: $internetdom{$id} = $intdom;
13618: }
1.852 albertel 13619: }
13620: }
13621: }
1.864 albertel 13622:
13623: sub reset_hosts_info {
1.897 albertel 13624: &purge_remembered();
1.864 albertel 13625: &reset_domain_info();
13626: &reset_hosts_ip_info();
1.892 albertel 13627: undef(%name_to_host);
1.864 albertel 13628: undef(%hostname);
13629: undef(%hostdom);
13630: undef(%libserv);
13631: undef($loaded);
13632: }
1.1 albertel 13633:
1.852 albertel 13634: sub load_hosts_tab {
1.1172.2.70 raeburn 13635: my ($ignore_cache,$nocache) = @_;
13636: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 13637: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 13638: my @config = <$config>;
13639: &parse_hosts_tab(\@config);
13640: close($config);
13641: $loaded=1;
1.1 albertel 13642: }
1.852 albertel 13643:
1.838 albertel 13644: sub hostname {
1.852 albertel 13645: &load_hosts_tab() if (!$loaded);
13646:
1.838 albertel 13647: my ($lonid) = @_;
13648: return $hostname{$lonid};
13649: }
1.845 albertel 13650:
1.838 albertel 13651: sub all_hostnames {
1.852 albertel 13652: &load_hosts_tab() if (!$loaded);
13653:
1.838 albertel 13654: return %hostname;
13655: }
1.845 albertel 13656:
1.888 albertel 13657: sub all_names {
1.1172.2.70 raeburn 13658: my ($ignore_cache,$nocache) = @_;
13659: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13660:
13661: return %name_to_host;
13662: }
13663:
1.974 raeburn 13664: sub all_host_domain {
13665: &load_hosts_tab() if (!$loaded);
13666: return %hostdom;
13667: }
13668:
1.845 albertel 13669: sub is_library {
1.852 albertel 13670: &load_hosts_tab() if (!$loaded);
13671:
1.845 albertel 13672: return exists($libserv{$_[0]});
13673: }
13674:
13675: sub all_library {
1.852 albertel 13676: &load_hosts_tab() if (!$loaded);
13677:
1.845 albertel 13678: return %libserv;
13679: }
13680:
1.1062 droeschl 13681: sub unique_library {
13682: #2x reverse removes all hostnames that appear more than once
13683: my %unique = reverse &all_library();
13684: return reverse %unique;
13685: }
13686:
1.841 albertel 13687: sub get_servers {
1.852 albertel 13688: &load_hosts_tab() if (!$loaded);
13689:
1.841 albertel 13690: my ($domain,$type) = @_;
13691: my %possible_hosts = ($type eq 'library') ? %libserv
13692: : %hostname;
13693: my %result;
1.842 albertel 13694: if (ref($domain) eq 'ARRAY') {
13695: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13696: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13697: $result{$host} = $hostname;
13698: }
13699: }
13700: } else {
13701: while ( my ($host,$hostname) = each(%possible_hosts)) {
13702: if ($hostdom{$host} eq $domain) {
13703: $result{$host} = $hostname;
13704: }
1.841 albertel 13705: }
13706: }
13707: return %result;
13708: }
1.845 albertel 13709:
1.1062 droeschl 13710: sub get_unique_servers {
13711: my %unique = reverse &get_servers(@_);
13712: return reverse %unique;
13713: }
13714:
1.844 albertel 13715: sub host_domain {
1.852 albertel 13716: &load_hosts_tab() if (!$loaded);
13717:
1.844 albertel 13718: my ($lonid) = @_;
13719: return $hostdom{$lonid};
13720: }
13721:
1.841 albertel 13722: sub all_domains {
1.852 albertel 13723: &load_hosts_tab() if (!$loaded);
13724:
1.841 albertel 13725: my %seen;
13726: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13727: return @uniq;
13728: }
1.1074 raeburn 13729:
13730: sub internet_dom {
13731: &load_hosts_tab() if (!$loaded);
13732:
13733: my ($lonid) = @_;
13734: return $internetdom{$lonid};
13735: }
1.1107 raeburn 13736:
13737: sub is_LC_dns {
13738: &load_hosts_tab() if (!$loaded);
13739:
13740: my ($hostname) = @_;
13741: return exists($LC_dns_serv{$hostname});
13742: }
13743:
1.1 albertel 13744: }
13745:
1.847 albertel 13746: {
13747: my %iphost;
1.856 albertel 13748: my %name_to_ip;
13749: my %lonid_to_ip;
1.869 albertel 13750:
1.847 albertel 13751: sub get_hosts_from_ip {
13752: my ($ip) = @_;
13753: my %iphosts = &get_iphost();
13754: if (ref($iphosts{$ip})) {
13755: return @{$iphosts{$ip}};
13756: }
13757: return;
1.839 albertel 13758: }
1.864 albertel 13759:
13760: sub reset_hosts_ip_info {
13761: undef(%iphost);
13762: undef(%name_to_ip);
13763: undef(%lonid_to_ip);
13764: }
1.856 albertel 13765:
13766: sub get_host_ip {
13767: my ($lonid) = @_;
13768: if (exists($lonid_to_ip{$lonid})) {
13769: return $lonid_to_ip{$lonid};
13770: }
13771: my $name=&hostname($lonid);
13772: my $ip = gethostbyname($name);
13773: return if (!$ip || length($ip) ne 4);
13774: $ip=inet_ntoa($ip);
13775: $name_to_ip{$name} = $ip;
13776: $lonid_to_ip{$lonid} = $ip;
13777: return $ip;
13778: }
1.847 albertel 13779:
13780: sub get_iphost {
1.1172.2.70 raeburn 13781: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13782:
1.869 albertel 13783: if (!$ignore_cache) {
13784: if (%iphost) {
13785: return %iphost;
13786: }
13787: my ($ip_info,$cached)=
13788: &Apache::lonnet::is_cached_new('iphost','iphost');
13789: if ($cached) {
13790: %iphost = %{$ip_info->[0]};
13791: %name_to_ip = %{$ip_info->[1]};
13792: %lonid_to_ip = %{$ip_info->[2]};
13793: return %iphost;
13794: }
13795: }
1.894 albertel 13796:
13797: # get yesterday's info for fallback
13798: my %old_name_to_ip;
13799: my ($ip_info,$cached)=
13800: &Apache::lonnet::is_cached_new('iphost','iphost');
13801: if ($cached) {
13802: %old_name_to_ip = %{$ip_info->[1]};
13803: }
13804:
1.1172.2.70 raeburn 13805: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13806: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13807: my $ip;
13808: if (!exists($name_to_ip{$name})) {
13809: $ip = gethostbyname($name);
13810: if (!$ip || length($ip) ne 4) {
1.894 albertel 13811: if (defined($old_name_to_ip{$name})) {
13812: $ip = $old_name_to_ip{$name};
13813: &logthis("Can't find $name defaulting to old $ip");
13814: } else {
13815: &logthis("Name $name no IP found");
13816: next;
13817: }
13818: } else {
13819: $ip=inet_ntoa($ip);
1.847 albertel 13820: }
13821: $name_to_ip{$name} = $ip;
13822: } else {
13823: $ip = $name_to_ip{$name};
1.653 albertel 13824: }
1.888 albertel 13825: foreach my $id (@{ $name_to_host{$name} }) {
13826: $lonid_to_ip{$id} = $ip;
13827: }
13828: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13829: }
1.1172.2.70 raeburn 13830: unless ($nocache) {
13831: &do_cache_new('iphost','iphost',
13832: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13833: 48*60*60);
13834: }
1.869 albertel 13835:
1.847 albertel 13836: return %iphost;
1.598 albertel 13837: }
13838:
1.992 raeburn 13839: #
13840: # Given a DNS returns the loncapa host name for that DNS
13841: #
13842: sub host_from_dns {
13843: my ($dns) = @_;
13844: my @hosts;
13845: my $ip;
13846:
1.993 raeburn 13847: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13848: $ip = $name_to_ip{$dns};
13849: }
13850: if (!$ip) {
13851: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13852: if (length($ip) == 4) {
13853: $ip = &IO::Socket::inet_ntoa($ip);
13854: }
13855: }
13856: if ($ip) {
13857: @hosts = get_hosts_from_ip($ip);
13858: return $hosts[0];
13859: }
13860: return undef;
1.986 foxr 13861: }
1.992 raeburn 13862:
1.1074 raeburn 13863: sub get_internet_names {
13864: my ($lonid) = @_;
13865: return if ($lonid eq '');
13866: my ($idnref,$cached)=
13867: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13868: if ($cached) {
13869: return $idnref;
13870: }
13871: my $ip = &get_host_ip($lonid);
13872: my @hosts = &get_hosts_from_ip($ip);
13873: my %iphost = &get_iphost();
13874: my (@idns,%seen);
13875: foreach my $id (@hosts) {
13876: my $dom = &host_domain($id);
13877: my $prim_id = &domain($dom,'primary');
13878: my $prim_ip = &get_host_ip($prim_id);
13879: next if ($seen{$prim_ip});
13880: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13881: foreach my $id (@{$iphost{$prim_ip}}) {
13882: my $intdom = &internet_dom($id);
13883: unless (grep(/^\Q$intdom\E$/,@idns)) {
13884: push(@idns,$intdom);
13885: }
13886: }
13887: }
13888: $seen{$prim_ip} = 1;
13889: }
1.1172.2.23 raeburn 13890: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13891: }
13892:
1.986 foxr 13893: }
13894:
1.1079 raeburn 13895: sub all_loncaparevs {
1.1172.2.39 raeburn 13896: 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 13897: }
13898:
1.1172.2.27 raeburn 13899: # ------------------------------------------------------- Read loncaparev table
13900: {
13901: sub load_loncaparevs {
13902: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 13903: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 13904: while (my $configline=<$config>) {
13905: chomp($configline);
13906: my ($hostid,$loncaparev)=split(/:/,$configline);
13907: $loncaparevs{$hostid}=$loncaparev;
13908: }
13909: close($config);
13910: }
13911: }
13912: }
13913: }
13914:
13915: # ----------------------------------------------------- Read serverhostID table
13916: {
13917: sub load_serverhomeIDs {
13918: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 13919: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 13920: while (my $configline=<$config>) {
13921: chomp($configline);
13922: my ($name,$id)=split(/:/,$configline);
13923: $serverhomeIDs{$name}=$id;
13924: }
13925: close($config);
13926: }
13927: }
13928: }
13929: }
13930:
13931:
1.862 albertel 13932: BEGIN {
13933:
13934: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13935: unless ($readit) {
13936: {
13937: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13938: %perlvar = (%perlvar,%{$configvars});
13939: }
13940:
13941:
1.1 albertel 13942: # ------------------------------------------------------ Read spare server file
13943: {
1.1172.2.96 raeburn 13944: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13945:
13946: while (my $configline=<$config>) {
13947: chomp($configline);
1.284 matthew 13948: if ($configline) {
1.784 albertel 13949: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13950: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13951: push(@{ $spareid{$type} }, $host);
1.1 albertel 13952: }
13953: }
1.448 albertel 13954: close($config);
1.1 albertel 13955: }
1.11 www 13956: # ------------------------------------------------------------ Read permissions
13957: {
1.1172.2.96 raeburn 13958: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13959:
13960: while (my $configline=<$config>) {
1.448 albertel 13961: chomp($configline);
13962: if ($configline) {
13963: my ($role,$perm)=split(/ /,$configline);
13964: if ($perm ne '') { $pr{$role}=$perm; }
13965: }
1.11 www 13966: }
1.448 albertel 13967: close($config);
1.11 www 13968: }
13969:
13970: # -------------------------------------------- Read plain texts for permissions
13971: {
1.1172.2.96 raeburn 13972: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13973:
13974: while (my $configline=<$config>) {
1.448 albertel 13975: chomp($configline);
13976: if ($configline) {
1.742 raeburn 13977: my ($short,@plain)=split(/:/,$configline);
13978: %{$prp{$short}} = ();
13979: if (@plain > 0) {
13980: $prp{$short}{'std'} = $plain[0];
13981: for (my $i=1; $i<@plain; $i++) {
13982: $prp{$short}{'alt'.$i} = $plain[$i];
13983: }
13984: }
1.448 albertel 13985: }
1.135 www 13986: }
1.448 albertel 13987: close($config);
1.135 www 13988: }
13989:
13990: # ---------------------------------------------------------- Read package table
13991: {
1.1172.2.96 raeburn 13992: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13993:
13994: while (my $configline=<$config>) {
1.483 albertel 13995: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13996: chomp($configline);
13997: my ($short,$plain)=split(/:/,$configline);
13998: my ($pack,$name)=split(/\&/,$short);
13999: if ($plain ne '') {
14000: $packagetab{$pack.'&'.$name.'&name'}=$name;
14001: $packagetab{$short}=$plain;
14002: }
1.11 www 14003: }
1.448 albertel 14004: close($config);
1.329 matthew 14005: }
14006:
1.1172.2.27 raeburn 14007: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 14008:
1.1172.2.27 raeburn 14009: &load_loncaparevs();
14010:
14011: # ------------------------------------------------------- Read serverhostID table
14012:
14013: &load_serverhomeIDs();
1.1074 raeburn 14014:
1.1172.2.27 raeburn 14015: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14016: {
14017: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14018: if (-e $file) {
14019: my $parser = HTML::LCParser->new($file);
14020: while (my $token = $parser->get_token()) {
14021: if ($token->[0] eq 'S') {
14022: my $item = $token->[1];
14023: my $name = $token->[2]{'name'};
14024: my $value = $token->[2]{'value'};
14025: if ($item ne '' && $name ne '' && $value ne '') {
14026: my $release = $parser->get_text();
14027: $release =~ s/(^\s*|\s*$ )//gx;
14028: $needsrelease{$item.':'.$name.':'.$value} = $release;
14029: }
14030: }
14031: }
14032: }
1.1073 raeburn 14033: }
14034:
1.1138 raeburn 14035: # ---------------------------------------------------------- Read managers table
14036: {
14037: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 14038: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14039: while (my $configline=<$config>) {
14040: chomp($configline);
14041: next if ($configline =~ /^\#/);
14042: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14043: $managerstab{$configline} = 1;
14044: }
14045: }
14046: close($config);
14047: }
14048: }
14049: }
14050:
1.329 matthew 14051: # ------------- set up temporary directory
14052: {
1.1117 foxr 14053: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14054:
1.11 www 14055: }
14056:
1.1172.2.104 raeburn 14057: # ------------- set default texengine (domain default overrides this)
14058: {
14059: $deftex = LONCAPA::texengine();
14060: }
14061:
1.1172.2.114 raeburn 14062: # ------------- set default minimum length for passwords for internal auth users
14063: {
14064: $passwdmin = LONCAPA::passwd_min();
14065: }
14066:
1.794 albertel 14067: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14068: 'compress_threshold'=> 20_000,
14069: });
1.185 www 14070:
1.281 www 14071: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14072: $dumpcount=0;
1.958 www 14073: $locknum=0;
1.22 www 14074:
1.163 harris41 14075: &logtouch();
1.672 albertel 14076: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14077: $readit=1;
1.564 albertel 14078: {
14079: use integer;
14080: my $test=(2**32)+1;
1.568 albertel 14081: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14082: &logthis(" Detected 64bit platform ($_64bit)");
14083: }
1.195 www 14084: }
1.1 albertel 14085: }
1.179 www 14086:
1.1 albertel 14087: 1;
1.191 harris41 14088: __END__
14089:
1.243 albertel 14090: =pod
14091:
1.191 harris41 14092: =head1 NAME
14093:
1.243 albertel 14094: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14095:
14096: =head1 SYNOPSIS
14097:
1.243 albertel 14098: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14099:
14100: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14101:
1.243 albertel 14102: Common parameters:
14103:
14104: =over 4
14105:
14106: =item *
14107:
14108: $uname : an internal username (if $cname expecting a course Id specifically)
14109:
14110: =item *
14111:
14112: $udom : a domain (if $cdom expecting a course's domain specifically)
14113:
14114: =item *
14115:
14116: $symb : a resource instance identifier
14117:
14118: =item *
14119:
14120: $namespace : the name of a .db file that contains the data needed or
14121: being set.
14122:
14123: =back
14124:
1.394 bowersj2 14125: =head1 OVERVIEW
1.191 harris41 14126:
1.394 bowersj2 14127: lonnet provides subroutines which interact with the
14128: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14129: about classes, users, and resources.
1.243 albertel 14130:
14131: For many of these objects you can also use this to store data about
14132: them or modify them in various ways.
1.191 harris41 14133:
1.394 bowersj2 14134: =head2 Symbs
1.191 harris41 14135:
1.394 bowersj2 14136: To identify a specific instance of a resource, LON-CAPA uses symbols
14137: or "symbs"X<symb>. These identifiers are built from the URL of the
14138: map, the resource number of the resource in the map, and the URL of
14139: the resource itself. The latter is somewhat redundant, but might help
14140: if maps change.
14141:
14142: An example is
14143:
14144: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14145:
14146: The respective map entry is
14147:
14148: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14149: title="Problem 2">
14150: </resource>
14151:
14152: Symbs are used by the random number generator, as well as to store and
14153: restore data specific to a certain instance of for example a problem.
14154:
14155: =head2 Storing And Retrieving Data
14156:
14157: X<store()>X<cstore()>X<restore()>Three of the most important functions
14158: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14159: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14160: is is the non-critical message twin of cstore. These functions are for
14161: handlers to store a perl hash to a user's permanent data space in an
14162: easy manner, and to retrieve it again on another call. It is expected
14163: that a handler would use this once at the beginning to retrieve data,
14164: and then again once at the end to send only the new data back.
14165:
14166: The data is stored in the user's data directory on the user's
14167: homeserver under the ID of the course.
14168:
14169: The hash that is returned by restore will have all of the previous
14170: value for all of the elements of the hash.
14171:
14172: Example:
14173:
14174: #creating a hash
14175: my %hash;
14176: $hash{'foo'}='bar';
14177:
14178: #storing it
14179: &Apache::lonnet::cstore(\%hash);
14180:
14181: #changing a value
14182: $hash{'foo'}='notbar';
14183:
14184: #adding a new value
14185: $hash{'bar'}='foo';
14186: &Apache::lonnet::cstore(\%hash);
14187:
14188: #retrieving the hash
14189: my %history=&Apache::lonnet::restore();
14190:
14191: #print the hash
14192: foreach my $key (sort(keys(%history))) {
14193: print("\%history{$key} = $history{$key}");
14194: }
14195:
14196: Will print out:
1.191 harris41 14197:
1.394 bowersj2 14198: %history{1:foo} = bar
14199: %history{1:keys} = foo:timestamp
14200: %history{1:timestamp} = 990455579
14201: %history{2:bar} = foo
14202: %history{2:foo} = notbar
14203: %history{2:keys} = foo:bar:timestamp
14204: %history{2:timestamp} = 990455580
14205: %history{bar} = foo
14206: %history{foo} = notbar
14207: %history{timestamp} = 990455580
14208: %history{version} = 2
14209:
14210: Note that the special hash entries C<keys>, C<version> and
14211: C<timestamp> were added to the hash. C<version> will be equal to the
14212: total number of versions of the data that have been stored. The
14213: C<timestamp> attribute will be the UNIX time the hash was
14214: stored. C<keys> is available in every historical section to list which
14215: keys were added or changed at a specific historical revision of a
14216: hash.
14217:
14218: B<Warning>: do not store the hash that restore returns directly. This
14219: will cause a mess since it will restore the historical keys as if the
14220: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14221:
1.394 bowersj2 14222: Calling convention:
1.191 harris41 14223:
1.1172.2.27 raeburn 14224: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 14225: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14226:
1.394 bowersj2 14227: For more detailed information, see lonnet specific documentation.
1.191 harris41 14228:
1.394 bowersj2 14229: =head1 RETURN MESSAGES
1.191 harris41 14230:
1.394 bowersj2 14231: =over 4
1.191 harris41 14232:
1.394 bowersj2 14233: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14234:
1.394 bowersj2 14235: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14236: when the connection is brought back up
1.191 harris41 14237:
1.394 bowersj2 14238: =item * B<con_failed>: unable to contact remote host and unable to save message
14239: for later delivery
1.191 harris41 14240:
1.967 bisitz 14241: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14242:
1.394 bowersj2 14243: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14244: that was requested
1.191 harris41 14245:
1.243 albertel 14246: =back
1.191 harris41 14247:
1.243 albertel 14248: =head1 PUBLIC SUBROUTINES
1.191 harris41 14249:
1.243 albertel 14250: =head2 Session Environment Functions
1.191 harris41 14251:
1.243 albertel 14252: =over 4
1.191 harris41 14253:
1.394 bowersj2 14254: =item *
14255: X<appenv()>
1.949 raeburn 14256: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14257: the user envirnoment file, and will be restored for each access this
1.620 albertel 14258: user makes during this session, also modifies the %env for the current
1.949 raeburn 14259: process. Optional rolesarrayref - if defined contains a reference to an array
14260: of roles which are exempt from the restriction on modifying user.role entries
14261: in the user's environment.db and in %env.
1.191 harris41 14262:
14263: =item *
1.394 bowersj2 14264: X<delenv()>
1.987 raeburn 14265: B<delenv($delthis,$regexp)>: removes all items from the session
14266: environment file that begin with $delthis. If the
14267: optional second arg - $regexp - is true, $delthis is treated as a
14268: regular expression, otherwise \Q$delthis\E is used.
14269: The values are also deleted from the current processes %env.
1.191 harris41 14270:
1.795 albertel 14271: =item * get_env_multiple($name)
14272:
14273: gets $name from the %env hash, it seemlessly handles the cases where multiple
14274: values may be defined and end up as an array ref.
14275:
14276: returns an array of values
14277:
1.243 albertel 14278: =back
14279:
14280: =head2 User Information
1.191 harris41 14281:
1.243 albertel 14282: =over 4
1.191 harris41 14283:
14284: =item *
1.394 bowersj2 14285: X<queryauthenticate()>
14286: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14287: authentication scheme
14288:
14289: =item *
1.394 bowersj2 14290: X<authenticate()>
1.1073 raeburn 14291: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14292: authenticate user from domain's lib servers (first use the current
14293: one). C<$upass> should be the users password.
1.1073 raeburn 14294: $checkdefauth is optional (value is 1 if a check should be made to
14295: authenticate user using default authentication method, and allow
14296: account creation if username does not have account in the domain).
14297: $clientcancheckhost is optional (value is 1 if checking whether the
14298: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14299:
14300: =item *
1.394 bowersj2 14301: X<homeserver()>
14302: B<homeserver($uname,$udom)>: find the server which has
14303: the user's directory and files (there must be only one), this caches
14304: the answer, and also caches if there is a borken connection.
1.191 harris41 14305:
14306: =item *
1.394 bowersj2 14307: X<idget()>
14308: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14309: (IDs are a unique resource in a domain, there must be only 1 ID per
14310: username, and only 1 username per ID in a specific domain) (returns
14311: hash: id=>name,id=>name)
1.191 harris41 14312:
14313: =item *
1.394 bowersj2 14314: X<idrget()>
14315: B<idrget($udom,@unames)>: find the IDs behind a list of
14316: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14317:
14318: =item *
1.394 bowersj2 14319: X<idput()>
14320: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 14321:
14322: =item *
1.394 bowersj2 14323: X<rolesinit()>
1.1169 droeschl 14324: B<rolesinit($udom,$username)>: get user privileges.
14325: returns user role, first access and timer interval hashes
1.243 albertel 14326:
14327: =item *
1.1171 droeschl 14328: X<privileged()>
14329: B<privileged($username,$domain)>: returns a true if user has a
14330: privileged and active role (i.e. su or dc), false otherwise.
14331:
14332: =item *
1.551 albertel 14333: X<getsection()>
14334: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14335: course $cname, return section name/number or '' for "not in course"
14336: and '-1' for "no section"
14337:
14338: =item *
1.394 bowersj2 14339: X<userenvironment()>
14340: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14341: passed in @what from the requested user's environment, returns a hash
14342:
1.858 raeburn 14343: =item *
14344: X<userlog_query()>
1.859 albertel 14345: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14346: activity.log file. %filters defines filters applied when parsing the
14347: log file. These can be start or end timestamps, or the type of action
14348: - log to look for Login or Logout events, check for Checkin or
14349: Checkout, role for role selection. The response is in the form
14350: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14351: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14352:
1.243 albertel 14353: =back
14354:
14355: =head2 User Roles
14356:
14357: =over 4
14358:
14359: =item *
14360:
1.1172.2.65 raeburn 14361: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14362: returns codes for allowed actions.
14363:
14364: The first argument is required, all others are optional.
14365:
14366: $priv is the privilege being checked.
14367: $uri contains additional information about what is being checked for access (e.g.,
14368: URL, course ID etc.).
14369: $symb is the unique resource instance identifier in a course; if needed,
14370: but not provided, it will be retrieved via a call to &symbread().
14371: $role is the role for which a priv is being checked (only used if priv is evb).
14372: $clientip is the user's IP address (only used when checking for access to portfolio
14373: files).
14374: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14375: prevents recursive calls to &allowed.
14376:
1.243 albertel 14377: F: full access
14378: U,I,K: authentication modes (cxx only)
14379: '': forbidden
14380: 1: user needs to choose course
14381: 2: browse allowed
1.766 albertel 14382: A: passphrase authentication needed
1.1172.2.65 raeburn 14383: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14384:
14385: =item *
14386:
1.1172.2.13 raeburn 14387: constructaccess($url,$setpriv) : check for access to construction space URL
14388:
14389: See if the owner domain and name in the URL match those in the
14390: expected environment. If so, return three element list
14391: ($ownername,$ownerdomain,$ownerhome).
14392:
14393: Otherwise return the null string.
14394:
14395: If second argument 'setpriv' is true, it assigns the privileges,
14396: and returns the same three element list, unless the owner has
14397: blocked "ad hoc" Domain Coordinator access to the Author Space,
14398: in which case the null string is returned.
14399:
14400: =item *
14401:
1.1172.2.84 raeburn 14402: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14403: define a custom role rolename set privileges in format of lonTabs/roles.tab
14404: for system, domain, and course level. $uname and $udom are optional (current
14405: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14406:
14407: =item *
14408:
1.988 raeburn 14409: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14410: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14411: $type is Course (default) or Community.
1.988 raeburn 14412: If $forcedefault evaluates to true, text returned will be default
14413: text for $type. Otherwise, if this is a course, the text returned
14414: will be a custom name for the role (if defined in the course's
14415: environment). If no custom name is defined the default is returned.
14416:
1.832 raeburn 14417: =item *
14418:
1.1172.2.23 raeburn 14419: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14420: All arguments are optional. Returns a hash of a roles, either for
14421: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14422: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14423: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14424: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14425: For each key, value is set to colon-separated start and end times for
14426: the role. If no username and domain are specified, will default to
1.934 raeburn 14427: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14428: of role statuses (active, future or previous), roles
14429: (e.g., cc,in, st etc.) and domains of the roles which can be used
14430: to restrict the list of roles reported. If no array ref is
14431: provided for types, will default to return only active roles.
1.834 albertel 14432:
1.1172.2.13 raeburn 14433: =item *
14434:
14435: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14436: user: $uname:$udom has a role in the course: $cdom_$cnum.
14437:
14438: Additional optional arguments are: $type (if role checking is to be restricted
14439: to certain user status types -- previous (expired roles), active (currently
14440: available roles) or future (roles available in the future), and
14441: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 14442: have active Domain Coordinator role in course's domain or in additional
14443: domains (specified in 'Domains to check for privileged users' in course
14444: environment -- set via: Course Settings -> Classlists and staff listing).
14445:
14446: =item *
14447:
14448: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14449: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14450: $possdomains and $possroles are optional array refs -- to domains to check and
14451: roles to check. If $possdomains is not specified, a dump will be done of the
14452: users' roles.db to check for a dc or su role in any domain. This can be
14453: time consuming if &privileged is called repeatedly (e.g., when displaying a
14454: classlist), so in such cases, supplying a $possdomains array is preferred, as
14455: this then allows &privileged_by_domain() to be used, which caches the identity
14456: of privileged users, eliminating the need for repeated calls to &dump().
14457:
14458: =item *
14459:
14460: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14461: where the outer hash keys are domains specified in the $possdomains array ref,
14462: next inner hash keys are privileged roles specified in the $roles array ref,
14463: and the innermost hash contains key = value pairs for username:domain = end:start
14464: for active or future "privileged" users with that role in that domain. To avoid
14465: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14466: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 14467:
1.243 albertel 14468: =back
14469:
14470: =head2 User Modification
14471:
14472: =over 4
14473:
14474: =item *
14475:
1.957 raeburn 14476: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14477: user for the level given by URL. Optional start and end dates (leave empty
14478: string or zero for "no date")
1.191 harris41 14479:
14480: =item *
14481:
1.243 albertel 14482: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14483: change a users, password, possible return values are: ok,
14484: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14485: refused
1.191 harris41 14486:
14487: =item *
14488:
1.243 albertel 14489: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14490:
14491: =item *
14492:
1.1058 raeburn 14493: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14494: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14495:
14496: will update user information (firstname,middlename,lastname,generation,
14497: permanentemail), and if forceid is true, student/employee ID also.
14498: A user's institutional affiliation(s) can also be updated.
14499: User information fields will not be overwritten with empty entries
14500: unless the field is included in the $candelete array reference.
14501: This array is included when a single user is modified via "Manage Users",
14502: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14503:
14504: =item *
14505:
1.286 matthew 14506: modifystudent
14507:
1.957 raeburn 14508: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 14509: The course id is resolved based on the current user's environment.
14510: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14511: associated with a course.
14512:
1.297 matthew 14513: This call is essentially a wrapper for lonnet::modifyuser and
14514: lonnet::modify_student_enrollment
1.286 matthew 14515:
14516: Inputs:
14517:
14518: =over 4
14519:
1.957 raeburn 14520: =item B<$udom> Student's loncapa domain
1.286 matthew 14521:
1.957 raeburn 14522: =item B<$uname> Student's loncapa login name
1.286 matthew 14523:
1.964 bisitz 14524: =item B<$uid> Student/Employee ID
1.286 matthew 14525:
1.957 raeburn 14526: =item B<$umode> Student's authentication mode
1.286 matthew 14527:
1.957 raeburn 14528: =item B<$upass> Student's password
1.286 matthew 14529:
1.957 raeburn 14530: =item B<$first> Student's first name
1.286 matthew 14531:
1.957 raeburn 14532: =item B<$middle> Student's middle name
1.286 matthew 14533:
1.957 raeburn 14534: =item B<$last> Student's last name
1.286 matthew 14535:
1.957 raeburn 14536: =item B<$gene> Student's generation
1.286 matthew 14537:
1.957 raeburn 14538: =item B<$usec> Student's section in course
1.286 matthew 14539:
14540: =item B<$end> Unix time of the roles expiration
14541:
14542: =item B<$start> Unix time of the roles start date
14543:
14544: =item B<$forceid> If defined, allow $uid to be changed
14545:
14546: =item B<$desiredhome> server to use as home server for student
14547:
1.957 raeburn 14548: =item B<$email> Student's permanent e-mail address
14549:
14550: =item B<$type> Type of enrollment (auto or manual)
14551:
1.963 raeburn 14552: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14553:
14554: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14555:
1.963 raeburn 14556: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14557:
1.963 raeburn 14558: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14559:
1.1172.2.19 raeburn 14560: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14561:
14562: =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 14563:
1.286 matthew 14564: =back
1.297 matthew 14565:
14566: =item *
14567:
14568: modify_student_enrollment
14569:
1.1172.2.31 raeburn 14570: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14571: 'role.request.course' must be defined for this function to proceed.
14572:
14573: Inputs:
14574:
14575: =over 4
14576:
1.1172.2.31 raeburn 14577: =item $udom, student's domain
1.297 matthew 14578:
1.1172.2.31 raeburn 14579: =item $uname, student's name
1.297 matthew 14580:
1.1172.2.31 raeburn 14581: =item $uid, student's user id
1.297 matthew 14582:
1.1172.2.31 raeburn 14583: =item $first, student's first name
1.297 matthew 14584:
14585: =item $middle
14586:
14587: =item $last
14588:
14589: =item $gene
14590:
14591: =item $usec
14592:
14593: =item $end
14594:
14595: =item $start
14596:
1.957 raeburn 14597: =item $type
14598:
14599: =item $locktype
14600:
14601: =item $cid
14602:
14603: =item $selfenroll
14604:
14605: =item $context
14606:
1.1172.2.19 raeburn 14607: =item $credits, number of credits student will earn from this class
14608:
1.1172.2.76 raeburn 14609: =item $instsec, institutional course section code for student
14610:
1.297 matthew 14611: =back
14612:
1.191 harris41 14613:
14614: =item *
14615:
1.243 albertel 14616: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14617: custom role; give a custom role to a user for the level given by URL. Specify
14618: name and domain of role author, and role name
1.191 harris41 14619:
14620: =item *
14621:
1.243 albertel 14622: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14623:
14624: =item *
14625:
1.243 albertel 14626: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14627:
14628: =back
14629:
14630: =head2 Course Infomation
14631:
14632: =over 4
1.191 harris41 14633:
14634: =item *
14635:
1.1118 foxr 14636: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14637: specified course id, including all environment settings for the
14638: course, the description of the course will be in the hash under the
14639: key 'description'
1.191 harris41 14640:
1.1118 foxr 14641: $options is an optional parameter that if supplied is a hash reference that controls
14642: what how this function works. It has the following key/values:
14643:
14644: =over 4
14645:
14646: =item freshen_cache
14647:
14648: If defined, and the environment cache for the course is valid, it is
14649: returned in the returned hash.
14650:
14651: =item one_time
14652:
14653: If defined, the last cache time is set to _now_
14654:
14655: =item user
14656:
14657: If defined, the supplied username is used instead of the current user.
14658:
14659:
14660: =back
14661:
1.191 harris41 14662: =item *
14663:
1.624 albertel 14664: resdata($name,$domain,$type,@which) : request for current parameter
14665: setting for a specific $type, where $type is either 'course' or 'user',
14666: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 14667: answers for 10 minutes.
1.243 albertel 14668:
1.877 foxr 14669: =item *
14670:
14671: get_courseresdata($courseid, $domain) : dump the entire course resource
14672: data base, returning a hash that is keyed by the resource name and has
14673: values that are the resource value. I believe that the timestamps and
14674: versions are also returned.
14675:
1.1172.2.31 raeburn 14676: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14677: supplemental content area. This routine caches the number of files for
14678: 10 minutes.
14679:
1.243 albertel 14680: =back
14681:
14682: =head2 Course Modification
14683:
14684: =over 4
1.191 harris41 14685:
14686: =item *
14687:
1.243 albertel 14688: writecoursepref($courseid,%prefs) : write preferences (environment
14689: database) for a course
1.191 harris41 14690:
14691: =item *
14692:
1.1011 raeburn 14693: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14694:
14695: =item *
14696:
1.1038 raeburn 14697: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14698:
1.1167 droeschl 14699: =item *
14700:
14701: is_course($courseid), is_course($cdom, $cnum)
14702:
14703: Accepts either a combined $courseid (in the form of domain_courseid) or the
14704: two component version $cdom, $cnum. It checks if the specified course exists.
14705:
14706: Returns:
14707: undef if the course doesn't exist, otherwise
14708: in scalar context the combined courseid.
14709: in list context the two components of the course identifier, domain and
14710: courseid.
14711:
1.243 albertel 14712: =back
14713:
1.1172.2.109 raeburn 14714: =head2 Bubblesheet Configuration
14715:
14716: =over 4
14717:
14718: =item *
14719:
14720: get_scantron_config($which)
14721:
14722: $which - the name of the configuration to parse from the file.
14723:
14724: Parses and returns the bubblesheet configuration line selected as a
14725: hash of configuration file fields.
14726:
14727:
14728: Returns:
14729: If the named configuration is not in the file, an empty
14730: hash is returned.
14731:
14732: a hash with the fields
14733: name - internal name for the this configuration setup
14734: description - text to display to operator that describes this config
14735: CODElocation - if 0 or the string 'none'
14736: - no CODE exists for this config
14737: if -1 || the string 'letter'
14738: - a CODE exists for this config and is
14739: a string of letters
14740: Unsupported value (but planned for future support)
14741: if a positive integer
14742: - The CODE exists as the first n items from
14743: the question section of the form
14744: if the string 'number'
14745: - The CODE exists for this config and is
14746: a string of numbers
14747: CODEstart - (only matter if a CODE exists) column in the line where
14748: the CODE starts
14749: CODElength - length of the CODE
14750: IDstart - column where the student/employee ID starts
14751: IDlength - length of the student/employee ID info
14752: Qstart - column where the information from the bubbled
14753: 'questions' start
14754: Qlength - number of columns comprising a single bubble line from
14755: the sheet. (usually either 1 or 10)
14756: Qon - either a single character representing the character used
14757: to signal a bubble was chosen in the positional setup, or
14758: the string 'letter' if the letter of the chosen bubble is
14759: in the final, or 'number' if a number representing the
14760: chosen bubble is in the file (1->A 0->J)
14761: Qoff - the character used to represent that a bubble was
14762: left blank
14763: PaperID - if the scanning process generates a unique number for each
14764: sheet scanned the column that this ID number starts in
14765: PaperIDlength - number of columns that comprise the unique ID number
14766: for the sheet of paper
14767: FirstName - column that the first name starts in
14768: FirstNameLength - number of columns that the first name spans
14769: LastName - column that the last name starts in
14770: LastNameLength - number of columns that the last name spans
14771: BubblesPerRow - number of bubbles available in each row used to
14772: bubble an answer. (If not specified, 10 assumed).
14773:
14774:
14775: =item *
14776:
14777: get_scantronformat_file($cdom)
14778:
14779: $cdom - the course's domain (optional); if not supplied, uses
14780: domain for current $env{'request.course.id'}.
14781:
14782: Returns an array containing lines from the scantron format file for
14783: the domain of the course.
14784:
14785: If a url for a custom.tab file is listed in domain's configuration.db,
14786: lines are from this file.
14787:
14788: Otherwise, if a default.tab has been published in RES space by the
14789: domainconfig user, lines are from this file.
14790:
14791: Otherwise, fall back to getting lines from the legacy file on the
14792: local server: /home/httpd/lonTabs/default_scantronformat.tab
14793:
14794: =back
14795:
1.243 albertel 14796: =head2 Resource Subroutines
14797:
14798: =over 4
1.191 harris41 14799:
14800: =item *
14801:
1.243 albertel 14802: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14803:
14804: =item *
14805:
1.243 albertel 14806: repcopy($filename) : subscribes to the requested file, and attempts to
14807: replicate from the owning library server, Might return
1.607 raeburn 14808: 'unavailable', 'not_found', 'forbidden', 'ok', or
14809: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14810: resource. Expects the local filesystem pathname
14811: (/home/httpd/html/res/....)
14812:
14813: =back
14814:
14815: =head2 Resource Information
14816:
14817: =over 4
1.191 harris41 14818:
14819: =item *
14820:
1.1172.2.28 raeburn 14821: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14822: and returns the value of a variety of different possible values,
14823: $varname should be a request string, and the other parameters can be
14824: used to specify who and what one is asking about. Ordinarily, $cid
14825: does not need to be specified, as it is retrived from
14826: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14827: within lonuserstate::loadmap() when initializing a course, before
14828: $env{'request.course.id'} has been set, so it needs to be provided
14829: in that one case.
1.243 albertel 14830:
14831: Possible values for $varname are environment.lastname (or other item
14832: from the envirnment hash), user.name (or someother aspect about the
14833: user), resource.0.maxtries (or some other part and parameter of a
14834: resource)
1.204 albertel 14835:
14836: =item *
14837:
1.243 albertel 14838: directcondval($number) : get current value of a condition; reads from a state
14839: string
1.204 albertel 14840:
14841: =item *
14842:
1.243 albertel 14843: condval($condidx) : value of condition index based on state
1.204 albertel 14844:
14845: =item *
14846:
1.243 albertel 14847: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14848: resource's metadata, $what should be either a specific key, or either
14849: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14850: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14851:
14852: this function automatically caches all requests
1.191 harris41 14853:
14854: =item *
14855:
1.243 albertel 14856: metadata_query($query,$custom,$customshow) : make a metadata query against the
14857: network of library servers; returns file handle of where SQL and regex results
14858: will be stored for query
1.191 harris41 14859:
14860: =item *
14861:
1.1172.2.66 raeburn 14862: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14863: return symbolic list entry (all arguments optional).
14864:
14865: Args: filename is the filename (including path) for the file for which a symb
14866: is required; donotrecurse, if true will prevent calls to allowed() being made
14867: to check access status if more than one resource was found in the bighash
14868: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14869: a randompick); ignorecachednull, if true will prevent a symb of '' being
14870: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14871: cause possible symbs to be checked to determine if they are subject to content
14872: blocking, if so they will not be included as possible symbs; possibles is a
14873: ref to a hash, which, as a side effect, will be populated with all possible
14874: symbs (content blocking not tested).
14875:
1.243 albertel 14876: returns the data handle
1.191 harris41 14877:
14878: =item *
14879:
1.1172.2.17 raeburn 14880: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 14881: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14882: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 14883: on failure, user must be in a course, as it assumes the existence of
14884: the course initial hash, and uses $env('request.course.id'}. The third
14885: arg is an optional reference to a scalar. If this arg is passed in the
14886: call to symbverify, it will be set to 1 if the symb has been set to be
14887: encrypted; otherwise it will be null.
1.243 albertel 14888:
1.191 harris41 14889: =item *
14890:
1.243 albertel 14891: symbclean($symb) : removes versions numbers from a symb, returns the
14892: cleaned symb
1.191 harris41 14893:
14894: =item *
14895:
1.243 albertel 14896: is_on_map($uri) : checks if the $uri is somewhere on the current
14897: course map, user must be in a course for it to work.
1.191 harris41 14898:
14899: =item *
14900:
1.243 albertel 14901: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14902:
14903: =item *
14904:
1.243 albertel 14905: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14906: a random seed, all arguments are optional, if they aren't sent it uses the
14907: environment to derive them. Note: if symb isn't sent and it can't get one
14908: from &symbread it will use the current time as its return value
1.191 harris41 14909:
14910: =item *
14911:
1.243 albertel 14912: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14913: unfakeable, receipt
1.191 harris41 14914:
14915: =item *
14916:
1.620 albertel 14917: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14918:
14919: =item *
14920:
1.243 albertel 14921: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14922:
14923: =item *
14924:
1.243 albertel 14925: 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 14926:
14927: =item *
14928:
1.243 albertel 14929: 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 14930:
14931: =item *
14932:
1.243 albertel 14933: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14934:
14935: =item *
14936:
1.243 albertel 14937: devalidate($symb) : devalidate temporary spreadsheet calculations,
14938: forcing spreadsheet to reevaluate the resource scores next time.
14939:
1.1172.2.13 raeburn 14940: =item *
14941:
14942: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14943: when viewing in course context.
14944:
14945: input: six args -- filename (decluttered), course number, course domain,
14946: url, symb (if registered) and group (if this is a
14947: group item -- e.g., bulletin board, group page etc.).
14948:
14949: output: array of five scalars --
14950: $cfile -- url for file editing if editable on current server
14951: $home -- homeserver of resource (i.e., for author if published,
14952: or course if uploaded.).
14953: $switchserver -- 1 if server switch will be needed.
14954: $forceedit -- 1 if icon/link should be to go to edit mode
14955: $forceview -- 1 if icon/link should be to go to view mode
14956:
14957: =item *
14958:
14959: is_course_upload($file,$cnum,$cdom)
14960:
14961: Used in course context to determine if current file was uploaded to
14962: the course (i.e., would be found in /userfiles/docs on the course's
14963: homeserver.
14964:
14965: input: 3 args -- filename (decluttered), course number and course domain.
14966: output: boolean -- 1 if file was uploaded.
14967:
1.243 albertel 14968: =back
14969:
14970: =head2 Storing/Retreiving Data
14971:
14972: =over 4
1.191 harris41 14973:
14974: =item *
14975:
1.1172.2.64 raeburn 14976: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14977: permanently for this url; hashref needs to be given and should be a \%hashname;
14978: the remaining args aren't required and if they aren't passed or are '' they will
14979: be derived from the env (with the exception of $laststore, which is an
14980: optional arg used when a user's submission is stored in grading).
14981: $laststore is $version=$timestamp, where $version is the most recent version
14982: number retrieved for the corresponding $symb in the $namespace db file, and
14983: $timestamp is the timestamp for that transaction (UNIX time).
14984: $laststore is currently only passed when cstore() is called by
14985: structuretags::finalize_storage().
1.191 harris41 14986:
14987: =item *
14988:
1.1172.2.64 raeburn 14989: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14990: but uses critical subroutine
1.191 harris41 14991:
14992: =item *
14993:
1.243 albertel 14994: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14995: all args are optional
1.191 harris41 14996:
14997: =item *
14998:
1.717 albertel 14999: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15000: dumps the complete (or key matching regexp) namespace into a hash
15001: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15002: normally &store()ed into
15003:
15004: $range should be either an integer '100' (give me the first 100
15005: matching records)
15006: or be two integers sperated by a - with no spaces
15007: '30-50' (give me the 30th through the 50th matching
15008: records)
15009:
15010:
15011: =item *
15012:
1.1172.2.59 raeburn 15013: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15014: replaces a &store() version of data with a replacement set of data
15015: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 15016: reference. If $tolog is true, the transaction is logged in the courselog
15017: with an action=PUTSTORE.
1.717 albertel 15018:
15019: =item *
15020:
1.243 albertel 15021: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15022: works very similar to store/cstore, but all data is stored in a
15023: temporary location and can be reset using tmpreset, $storehash should
15024: be a hash reference, returns nothing on success
1.191 harris41 15025:
15026: =item *
15027:
1.243 albertel 15028: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15029: similar to restore, but all data is stored in a temporary location and
15030: can be reset using tmpreset. Returns a hash of values on success,
15031: error string otherwise.
1.191 harris41 15032:
15033: =item *
15034:
1.243 albertel 15035: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15036: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15037:
15038: =item *
15039:
1.243 albertel 15040: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15041: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15042:
15043: =item *
15044:
1.243 albertel 15045: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15046: namesp ($udom and $uname are optional)
1.191 harris41 15047:
15048: =item *
15049:
1.702 albertel 15050: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15051: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15052: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15053:
1.702 albertel 15054: $range should be either an integer '100' (give me the first 100
15055: matching records)
15056: or be two integers sperated by a - with no spaces
15057: '30-50' (give me the 30th through the 50th matching
15058: records)
1.449 matthew 15059: =item *
15060:
15061: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15062: $store can be a scalar, an array reference, or if the amount to be
15063: incremented is > 1, a hash reference.
15064:
15065: ($udom and $uname are optional)
1.191 harris41 15066:
15067: =item *
15068:
1.243 albertel 15069: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15070: ($udom and $uname are optional)
1.191 harris41 15071:
15072: =item *
15073:
1.243 albertel 15074: cput($namespace,$storehash,$udom,$uname) : critical put
15075: ($udom and $uname are optional)
1.191 harris41 15076:
15077: =item *
15078:
1.748 albertel 15079: newput($namespace,$storehash,$udom,$uname) :
15080:
15081: Attempts to store the items in the $storehash, but only if they don't
15082: currently exist, if this succeeds you can be certain that you have
15083: successfully created a new key value pair in the $namespace db.
15084:
15085:
15086: Args:
15087: $namespace: name of database to store values to
15088: $storehash: hashref to store to the db
15089: $udom: (optional) domain of user containing the db
15090: $uname: (optional) name of user caontaining the db
15091:
15092: Returns:
15093: 'ok' -> succeeded in storing all keys of $storehash
15094: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15095: least <key> already existed in the db (other
15096: requested keys may also already exist)
1.967 bisitz 15097: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15098: 'con_lost' -> unable to contact request server
15099: 'refused' -> action was not allowed by remote machine
15100:
15101:
15102: =item *
15103:
1.243 albertel 15104: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15105: reference filled in from namesp (encrypts the return communication)
15106: ($udom and $uname are optional)
1.191 harris41 15107:
15108: =item *
15109:
1.243 albertel 15110: log($udom,$name,$home,$message) : write to permanent log for user; use
15111: critical subroutine
15112:
1.806 raeburn 15113: =item *
15114:
1.860 raeburn 15115: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15116: array reference filled in from namespace found in domain level on either
15117: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15118:
15119: =item *
15120:
1.860 raeburn 15121: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15122: domain level either on specified domain server ($uhome) or primary domain
15123: server ($udom and $uhome are optional)
1.806 raeburn 15124:
1.943 raeburn 15125: =item *
15126:
1.1172.2.35 raeburn 15127: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15128: for: authentication, language, quotas, timezone, date locale, and portal URL in
15129: the target domain.
15130:
15131: May also include additional key => value pairs for the following groups:
15132:
15133: =over
15134:
15135: =item
15136: disk quotas (MB allocated by default to portfolios and authoring spaces).
15137:
15138: =over
15139:
15140: =item defaultquota, authorquota
15141:
15142: =back
15143:
15144: =item
15145: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15146: portfolio for users).
15147:
15148: =over
15149:
15150: =item
15151: aboutme, blog, webdav, portfolio
15152:
15153: =back
15154:
15155: =item
15156: requestcourses: ability to request courses, and how requests are processed.
15157:
15158: =over
15159:
15160: =item
1.1172.2.37 raeburn 15161: official, unofficial, community, textbook
1.1172.2.35 raeburn 15162:
15163: =back
15164:
15165: =item
15166: inststatus: types of institutional affiliation, and order in which they are displayed.
15167:
15168: =over
15169:
15170: =item
1.1172.2.44 raeburn 15171: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 15172:
15173: =back
15174:
15175: =item
15176: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15177: for course's uploaded content.
15178:
15179: =over
15180:
15181: =item
1.1172.2.68 raeburn 15182: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15183: communityquota, textbookquota
1.1172.2.35 raeburn 15184:
15185: =back
15186:
15187: =item
15188: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15189: on your servers.
15190:
15191: =over
15192:
15193: =item
15194: remotesessions, hostedsessions
15195:
15196: =back
15197:
15198: =back
15199:
15200: In cases where a domain coordinator has never used the "Set Domain Configuration"
15201: utility to create a configuration.db file on a domain's primary library server
15202: only the following domain defaults: auth_def, auth_arg_def, lang_def
15203: -- corresponding values are authentication type (internal, krb4, krb5,
15204: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15205: will be available. Values are retrieved from cache (if current), unless the
15206: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15207: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15208:
15209: Typical usage:
1.943 raeburn 15210:
1.1172.2.35 raeburn 15211: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15212:
1.243 albertel 15213: =back
15214:
15215: =head2 Network Status Functions
15216:
15217: =over 4
1.191 harris41 15218:
15219: =item *
15220:
1.1137 raeburn 15221: dirlist() : return directory list based on URI (first arg).
15222:
15223: Inputs: 1 required, 5 optional.
15224:
15225: =over
15226:
15227: =item
15228: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15229:
15230: =item
15231: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15232:
15233: =item
15234: $username - username of user/course to be listed. Extracted from $uri if absent.
15235:
15236: =item
15237: $getpropath - boolean: 1 if prepend path using &propath().
15238:
15239: =item
15240: $getuserdir - boolean: 1 if prepend path for "userfiles".
15241:
15242: =item
15243: $alternateRoot - path to prepend in place of path from $uri.
15244:
15245: =back
15246:
15247: Returns: Array of up to two items.
15248:
15249: =over
15250:
15251: a reference to an array of files/subdirectories
15252:
15253: =over
15254:
15255: Each element in the array of files/subdirectories is a & separated list of
15256: item name and the result of running stat on the item. If dirlist was requested
15257: for a file instead of a directory, the item name will be ''. For a directory
15258: listing, if the item is a metadata file, the element will end &N&M
15259: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15260: default copyright set (1).
15261:
15262: =back
15263:
15264: a scalar containing error condition (if encountered).
15265:
15266: =over
15267:
15268: =item
15269: no_host (no homeserver identified for $username:$domain).
15270:
15271: =item
15272: no_such_host (server contacted for listing not identified as valid host).
15273:
15274: =item
15275: con_lost (connection to remote server failed).
15276:
15277: =item
15278: refused (invalid $username:$domain received on lond side).
15279:
15280: =item
15281: no_such_dir (directory at specified path on lond side does not exist).
15282:
15283: =item
15284: empty (directory at specified path on lond side is empty).
15285:
15286: =over
15287:
15288: This is currently not encountered because the &ls3, &ls2,
15289: &ls (_handler) routines on the lond side do not filter out
15290: . and .. from a directory listing.
15291:
15292: =back
15293:
15294: =back
15295:
15296: =back
1.191 harris41 15297:
15298: =item *
15299:
1.243 albertel 15300: spareserver() : find server with least workload from spare.tab
15301:
1.986 foxr 15302:
15303: =item *
15304:
15305: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15306: if there is no corresponding loncapa host.
15307:
1.243 albertel 15308: =back
15309:
1.986 foxr 15310:
1.243 albertel 15311: =head2 Apache Request
15312:
15313: =over 4
1.191 harris41 15314:
15315: =item *
15316:
1.243 albertel 15317: ssi($url,%hash) : server side include, does a complete request cycle on url to
15318: localhost, posts hash
15319:
15320: =back
15321:
15322: =head2 Data to String to Data
15323:
15324: =over 4
1.191 harris41 15325:
15326: =item *
15327:
1.243 albertel 15328: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15329: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15330:
15331: =item *
15332:
1.243 albertel 15333: hashref2str($hashref) : convert a hashref into a string complete with
15334: escaping and '=' and '&' separators, supports elements that are
15335: arrayrefs and hashrefs
1.191 harris41 15336:
15337: =item *
15338:
1.243 albertel 15339: arrayref2str($arrayref) : convert an arrayref into a string complete
15340: with escaping and '&' separators, supports elements that are arrayrefs
15341: and hashrefs
1.191 harris41 15342:
15343: =item *
15344:
1.243 albertel 15345: str2hash($string) : convert string to hash using unescaping and
15346: splitting on '=' and '&', supports elements that are arrayrefs and
15347: hashrefs
1.191 harris41 15348:
15349: =item *
15350:
1.243 albertel 15351: str2array($string) : convert string to hash using unescaping and
15352: splitting on '&', supports elements that are arrayrefs and hashrefs
15353:
15354: =back
15355:
15356: =head2 Logging Routines
15357:
15358:
15359: These routines allow one to make log messages in the lonnet.log and
15360: lonnet.perm logfiles.
1.191 harris41 15361:
1.1119 foxr 15362: =over 4
15363:
1.191 harris41 15364: =item *
15365:
1.243 albertel 15366: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15367:
15368: =item *
15369:
1.243 albertel 15370: logthis() : append message to the normal lonnet.log file, it gets
15371: preiodically rolled over and deleted.
1.191 harris41 15372:
15373: =item *
15374:
1.243 albertel 15375: logperm() : append a permanent message to lonnet.perm.log, this log
15376: file never gets deleted by any automated portion of the system, only
15377: messages of critical importance should go in here.
15378:
1.1119 foxr 15379:
1.243 albertel 15380: =back
15381:
15382: =head2 General File Helper Routines
15383:
15384: =over 4
1.191 harris41 15385:
15386: =item *
15387:
1.481 raeburn 15388: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15389: (a) files in /uploaded
15390: (i) If a local copy of the file exists -
15391: compares modification date of local copy with last-modified date for
15392: definitive version stored on home server for course. If local copy is
15393: stale, requests a new version from the home server and stores it.
15394: If the original has been removed from the home server, then local copy
15395: is unlinked.
15396: (ii) If local copy does not exist -
15397: requests the file from the home server and stores it.
15398:
15399: If $caller is 'uploadrep':
15400: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15401: for request for files originally uploaded via DOCS.
15402: - returns 'ok' if fresh local copy now available, -1 otherwise.
15403:
15404: Otherwise:
15405: This indicates a call from the content generation phase of the request.
15406: - returns the entire contents of the file or -1.
15407:
15408: (b) files in /res
15409: - returns the entire contents of a file or -1;
15410: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 15411:
1.712 albertel 15412:
15413: =item *
15414:
15415: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15416: reference
15417:
15418: returns either a stat() list of data about the file or an empty list
15419: if the file doesn't exist or couldn't find out about it (connection
15420: problems or user unknown)
15421:
1.191 harris41 15422: =item *
15423:
1.243 albertel 15424: filelocation($dir,$file) : returns file system location of a file
15425: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15426: directory that relative $file lookups are to looked in ($dir of /a/dir
15427: and a file of ../bob will become /a/bob)
1.191 harris41 15428:
15429: =item *
15430:
15431: hreflocation($dir,$file) : returns file system location or a URL; same as
15432: filelocation except for hrefs
15433:
15434: =item *
15435:
1.1172.2.49 raeburn 15436: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15437: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15438:
1.243 albertel 15439: =back
15440:
1.608 albertel 15441: =head2 Usererfile file routines (/uploaded*)
15442:
15443: =over 4
15444:
15445: =item *
15446:
15447: userfileupload(): main rotine for putting a file in a user or course's
15448: filespace, arguments are,
15449:
1.620 albertel 15450: formname - required - this is the name of the element in $env where the
1.608 albertel 15451: filename, and the contents of the file to create/modifed exist
1.620 albertel 15452: the filename is in $env{'form.'.$formname.'.filename'} and the
15453: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15454: context - if coursedoc, store the file in the course of the active role
15455: of the current user;
15456: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15457: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15458: subdir - required - subdirectory to put the file in under ../userfiles/
15459: if undefined, it will be placed in "unknown"
15460:
15461: (This routine calls clean_filename() to remove any dangerous
15462: characters from the filename, and then calls finuserfileupload() to
15463: complete the transaction)
15464:
15465: returns either the url of the uploaded file (/uploaded/....) if successful
15466: and /adm/notfound.html if unsuccessful
15467:
15468: =item *
15469:
15470: clean_filename(): routine for cleaing a filename up for storage in
15471: userfile space, argument is:
15472:
15473: filename - proposed filename
15474:
15475: returns: the new clean filename
15476:
15477: =item *
15478:
1.1090 raeburn 15479: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15480: userspace, probably shouldn't be called directly
15481:
15482: docuname: username or courseid of destination for the file
15483: docudom: domain of user/course of destination for the file
15484: formname: same as for userfileupload()
1.1090 raeburn 15485: fname: filename (including subdirectories) for the file
15486: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 15487: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 15488: allfiles: reference to hash used to store objects found by parser
15489: codebase: reference to hash used for codebases of java objects found by parser
15490: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15491: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15492: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15493: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15494: context: if 'overwrite', will move the uploaded file from its temporary location to
15495: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15496: mimetype: reference to scalar to accommodate mime type determined
15497: from File::MMagic if $parser = parse.
1.608 albertel 15498:
15499: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15500: and /adm/notfound.html if unsuccessful (or an error message if context
15501: was 'overwrite').
15502:
1.608 albertel 15503:
15504: =item *
15505:
15506: renameuserfile(): renames an existing userfile to a new name
15507:
15508: Args:
15509: docuname: username or courseid of destination for the file
15510: docudom: domain of user/course of destination for the file
15511: old: current file name (including any subdirs under userfiles)
15512: new: desired file name (including any subdirs under userfiles)
15513:
15514: =item *
15515:
15516: mkdiruserfile(): creates a directory is a userfiles dir
15517:
15518: Args:
15519: docuname: username or courseid of destination for the file
15520: docudom: domain of user/course of destination for the file
15521: dir: dir to create (including any subdirs under userfiles)
15522:
15523: =item *
15524:
15525: removeuserfile(): removes a file that exists in userfiles
15526:
15527: Args:
15528: docuname: username or courseid of destination for the file
15529: docudom: domain of user/course of destination for the file
15530: fname: filname to delete (including any subdirs under userfiles)
15531:
15532: =item *
15533:
15534: removeuploadedurl(): convience function for removeuserfile()
15535:
15536: Args:
15537: url: a full /uploaded/... url to delete
15538:
1.747 albertel 15539: =item *
15540:
15541: get_portfile_permissions():
15542: Args:
15543: domain: domain of user or course contain the portfolio files
15544: user: name of user or num of course contain the portfolio files
15545: Returns:
15546: hashref of a dump of the proper file_permissions.db
15547:
15548:
15549: =item *
15550:
15551: get_access_controls():
15552:
15553: Args:
15554: current_permissions: the hash ref returned from get_portfile_permissions()
15555: group: (optional) the group you want the files associated with
15556: file: (optional) the file you want access info on
15557:
15558: Returns:
1.749 raeburn 15559: a hash (keys are file names) of hashes containing
15560: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15561: values are XML containing access control settings (see below)
1.747 albertel 15562:
15563: Internal notes:
15564:
1.749 raeburn 15565: access controls are stored in file_permissions.db as key=value pairs.
15566: key -> path to file/file_name\0uniqueID:scope_end_start
15567: where scope -> public,guest,course,group,domains or users.
15568: end -> UNIX time for end of access (0 -> no end date)
15569: start -> UNIX time for start of access
15570:
15571: value -> XML description of access control
15572: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15573: <start></start>
15574: <end></end>
15575:
15576: <password></password> for scope type = guest
15577:
15578: <domain></domain> for scope type = course or group
15579: <number></number>
15580: <roles id="">
15581: <role></role>
15582: <access></access>
15583: <section></section>
15584: <group></group>
15585: </roles>
15586:
15587: <dom></dom> for scope type = domains
15588:
15589: <users> for scope type = users
15590: <user>
15591: <uname></uname>
15592: <udom></udom>
15593: </user>
15594: </users>
15595: </scope>
15596:
15597: Access data is also aggregated for each file in an additional key=value pair:
15598: key -> path to file/file_name\0accesscontrol
15599: value -> reference to hash
15600: hash contains key = value pairs
15601: where key = uniqueID:scope_end_start
15602: value = UNIX time record was last updated
15603:
15604: Used to improve speed of look-ups of access controls for each file.
15605:
15606: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15607:
1.1172.2.13 raeburn 15608: =item *
15609:
1.749 raeburn 15610: modify_access_controls():
15611:
15612: Modifies access controls for a portfolio file
15613: Args
15614: 1. file name
15615: 2. reference to hash of required changes,
15616: 3. domain
15617: 4. username
15618: where domain,username are the domain of the portfolio owner
15619: (either a user or a course)
15620:
15621: Returns:
15622: 1. result of additions or updates ('ok' or 'error', with error message).
15623: 2. result of deletions ('ok' or 'error', with error message).
15624: 3. reference to hash of any new or updated access controls.
15625: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15626: key = integer (inbound ID)
1.1172.2.13 raeburn 15627: value = uniqueID
15628:
15629: =item *
15630:
15631: get_timebased_id():
15632:
15633: Attempts to get a unique timestamp-based suffix for use with items added to a
15634: course via the Course Editor (e.g., folders, composite pages,
15635: group bulletin boards).
15636:
15637: Args: (first three required; six others optional)
15638:
15639: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15640: docssequence, or name of group
15641:
15642: 2. keyid (alphanumeric): name of temporary locking key in hash,
15643: e.g., num, boardids
15644:
15645: 3. namespace: name of gdbm file used to store suffixes already assigned;
15646: file will be named nohist_namespace.db
15647:
15648: 4. cdom: domain of course; default is current course domain from %env
15649:
15650: 5. cnum: course number; default is current course number from %env
15651:
15652: 6. idtype: set to concat if an additional digit is to be appended to the
15653: unix timestamp to form the suffix, if the plain timestamp is already
15654: in use. Default is to not do this, but simply increment the unix
15655: timestamp by 1 until a unique key is obtained.
15656:
15657: 7. who: holder of locking key; defaults to user:domain for user.
15658:
15659: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15660: retrying); default is 3.
15661:
15662: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15663:
15664: Returns:
15665:
15666: 1. suffix obtained (numeric)
15667:
15668: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15669:
15670: 3. error: contains (localized) error message if an error occurred.
15671:
1.747 albertel 15672:
1.608 albertel 15673: =back
15674:
1.243 albertel 15675: =head2 HTTP Helper Routines
15676:
15677: =over 4
15678:
1.191 harris41 15679: =item *
15680:
15681: escape() : unpack non-word characters into CGI-compatible hex codes
15682:
15683: =item *
15684:
15685: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15686:
1.243 albertel 15687: =back
15688:
15689: =head1 PRIVATE SUBROUTINES
15690:
15691: =head2 Underlying communication routines (Shouldn't call)
15692:
15693: =over 4
15694:
15695: =item *
15696:
15697: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15698:
15699: =item *
15700:
15701: reply() : uses subreply to send a message to remote machine, logs all failures
15702:
15703: =item *
15704:
15705: critical() : passes a critical message to another server; if cannot
15706: get through then place message in connection buffer directory and
15707: returns con_delayed, if incapable of saving message, returns
15708: con_failed
15709:
15710: =item *
15711:
15712: reconlonc() : tries to reconnect lonc client processes.
15713:
15714: =back
15715:
15716: =head2 Resource Access Logging
15717:
15718: =over 4
15719:
15720: =item *
15721:
15722: flushcourselogs() : flush (save) buffer logs and access logs
15723:
15724: =item *
15725:
15726: courselog($what) : save message for course in hash
15727:
15728: =item *
15729:
15730: courseacclog($what) : save message for course using &courselog(). Perform
15731: special processing for specific resource types (problems, exams, quizzes, etc).
15732:
1.191 harris41 15733: =item *
15734:
15735: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15736: as a PerlChildExitHandler
1.243 albertel 15737:
15738: =back
15739:
15740: =head2 Other
15741:
15742: =over 4
15743:
15744: =item *
15745:
15746: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15747:
15748: =back
15749:
15750: =cut
1.877 foxr 15751:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>