Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.136
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.136! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.135 2021/01/04 13:32:39 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.134 raeburn 128: my $ip = &get_requestor_ip();
1.1172.2.9 raeburn 129: my $logentry = {
130: $id => {
131: 'exe_uname' => $env{'user.name'},
132: 'exe_udom' => $env{'user.domain'},
133: 'exe_time' => $now,
1.1172.2.134 raeburn 134: 'exe_ip' => $ip,
1.1172.2.9 raeburn 135: 'delflag' => $delflag,
136: 'logentry' => $storehash,
137: 'uname' => $uname,
138: 'udom' => $udom,
139: }
140: };
141: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 142: }
143: }
1.1 albertel 144:
1.163 harris41 145: sub logtouch {
146: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 147: unless (-e "$execdir/logs/lonnet.log") {
1.1172.2.96 raeburn 148: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 149: close $fh;
150: }
151: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
152: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
153: }
154:
1.1 albertel 155: sub logthis {
156: my $message=shift;
157: my $execdir=$perlvar{'lonDaemons'};
158: my $now=time;
159: my $local=localtime($now);
1.1172.2.96 raeburn 160: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 161: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
162: print $fh $logstring;
1.448 albertel 163: close($fh);
164: }
1.1 albertel 165: return 1;
166: }
167:
168: sub logperm {
169: my $message=shift;
170: my $execdir=$perlvar{'lonDaemons'};
171: my $now=time;
172: my $local=localtime($now);
1.1172.2.96 raeburn 173: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 174: print $fh "$now:$message:$local\n";
175: close($fh);
176: }
1.1 albertel 177: return 1;
178: }
179:
1.850 albertel 180: sub create_connection {
1.853 albertel 181: my ($hostname,$lonid) = @_;
1.851 albertel 182: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 183: Type => SOCK_STREAM,
184: Timeout => 10);
185: return 0 if (!$client);
1.890 albertel 186: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 187: my $result = <$client>;
188: chomp($result);
189: return 1 if ($result eq 'done');
190: return 0;
191: }
192:
1.983 raeburn 193: sub get_server_timezone {
194: my ($cnum,$cdom) = @_;
195: my $home=&homeserver($cnum,$cdom);
196: if ($home ne 'no_host') {
197: my $cachetime = 24*3600;
198: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
199: if (defined($cached)) {
200: return $timezone;
201: } else {
202: my $timezone = &reply('servertimezone',$home);
203: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
204: }
205: }
206: }
1.850 albertel 207:
1.1106 raeburn 208: sub get_server_distarch {
209: my ($lonhost,$ignore_cache) = @_;
210: if (defined($lonhost)) {
211: if (!defined(&hostname($lonhost))) {
212: return;
213: }
214: my $cachetime = 12*3600;
215: if (!$ignore_cache) {
216: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
217: if (defined($cached)) {
218: return $distarch;
219: }
220: }
221: my $rep = &reply('serverdistarch',$lonhost);
222: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
223: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
224: $rep eq '') {
225: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
226: }
227: }
228: return;
229: }
230:
1.993 raeburn 231: sub get_server_loncaparev {
1.1073 raeburn 232: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 233: if (defined($lonhost)) {
234: if (!defined(&hostname($lonhost))) {
235: undef($lonhost);
236: }
237: }
238: if (!defined($lonhost)) {
239: if (defined(&domain($dom,'primary'))) {
240: $lonhost=&domain($dom,'primary');
241: if ($lonhost eq 'no_host') {
242: undef($lonhost);
243: }
244: }
245: }
246: if (defined($lonhost)) {
1.1073 raeburn 247: my $cachetime = 12*3600;
248: if (!$ignore_cache) {
249: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
250: if (defined($cached)) {
251: return $loncaparev;
252: }
253: }
254: my ($answer,$loncaparev);
255: my @ids=¤t_machine_ids();
256: if (grep(/^\Q$lonhost\E$/,@ids)) {
257: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 258: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 259: $loncaparev = $1;
260: }
261: } else {
262: $answer = &reply('serverloncaparev',$lonhost);
263: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
264: if ($caller eq 'loncron') {
265: my $ua=new LWP::UserAgent;
1.1082 raeburn 266: $ua->timeout(4);
1.1172.2.120 raeburn 267: my $hostname = &hostname($lonhost);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 270: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
1.1172.2.35 raeburn 359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 364: }
365:
1.1 albertel 366: # -------------------------------------------------- Non-critical communication
367: sub subreply {
368: my ($cmd,$server)=@_;
1.838 albertel 369: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 370: #
371: # With loncnew process trimming, there's a timing hole between lonc server
372: # process exit and the master server picking up the listen on the AF_UNIX
373: # socket. In that time interval, a lock file will exist:
374:
375: my $lockfile=$peerfile.".lock";
376: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 377: sleep(0.1);
1.549 foxr 378: }
379: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 380: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 381: #
1.550 foxr 382: # We'll give the connection a few tries before abandoning it. If
383: # connection is not possible, we'll con_lost back to the client.
384: #
385: my $client;
386: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
387: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
388: Type => SOCK_STREAM,
389: Timeout => 10);
1.869 albertel 390: if ($client) {
1.550 foxr 391: last; # Connected!
1.850 albertel 392: } else {
1.853 albertel 393: &create_connection(&hostname($server),$server);
1.550 foxr 394: }
1.1172.2.79 raeburn 395: sleep(0.1); # Try again later if failed connection.
1.550 foxr 396: }
397: my $answer;
398: if ($client) {
1.704 albertel 399: print $client "sethost:$server:$cmd\n";
1.550 foxr 400: $answer=<$client>;
401: if (!$answer) { $answer="con_lost"; }
402: chomp($answer);
403: } else {
404: $answer = 'con_lost'; # Failed connection.
405: }
1.1 albertel 406: return $answer;
407: }
408:
409: sub reply {
410: my ($cmd,$server)=@_;
1.838 albertel 411: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 412: my $answer=subreply($cmd,$server);
1.65 www 413: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111 raeburn 414: my $logged = $cmd;
415: if ($cmd =~ /^encrypt:([^:]+):/) {
416: my $subcmd = $1;
417: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
418: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
419: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
420: (undef,undef,my @rest) = split(/:/,$cmd);
421: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
422: splice(@rest,2,1,'Hidden');
423: } elsif ($subcmd eq 'passwd') {
424: splice(@rest,2,2,('Hidden','Hidden'));
425: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
426: ($subcmd eq 'autoexportgrades')) {
427: splice(@rest,3,1,'Hidden');
428: }
429: $logged = join(':',('encrypt:'.$subcmd,@rest));
430: }
431: }
432: &logthis("<font color=\"blue\">WARNING:".
433: " $logged to $server returned $answer</font>");
1.12 www 434: }
1.1 albertel 435: return $answer;
436: }
437:
438: # ----------------------------------------------------------- Send USR1 to lonc
439:
440: sub reconlonc {
1.891 albertel 441: my ($lonid) = @_;
442: if ($lonid) {
1.1172.2.72 raeburn 443: my $hostname = &hostname($lonid);
1.891 albertel 444: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
445: if ($hostname && -e $peerfile) {
446: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
447: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
448: Type => SOCK_STREAM,
449: Timeout => 10);
450: if ($client) {
451: print $client ("reset_retries\n");
452: my $answer=<$client>;
453: #reset just this one.
454: }
455: }
456: return;
457: }
458:
1.836 www 459: &logthis("Trying to reconnect lonc");
1.1 albertel 460: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96 raeburn 461: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 462: my $loncpid=<$fh>;
463: chomp($loncpid);
464: if (kill 0 => $loncpid) {
465: &logthis("lonc at pid $loncpid responding, sending USR1");
466: kill USR1 => $loncpid;
467: sleep 1;
1.836 www 468: } else {
1.12 www 469: &logthis(
1.672 albertel 470: "<font color=\"blue\">WARNING:".
1.12 www 471: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 472: }
473: } else {
1.836 www 474: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 475: }
476: }
477:
478: # ------------------------------------------------------ Critical communication
1.12 www 479:
1.1 albertel 480: sub critical {
481: my ($cmd,$server)=@_;
1.838 albertel 482: unless (&hostname($server)) {
1.672 albertel 483: &logthis("<font color=\"blue\">WARNING:".
1.89 www 484: " Critical message to unknown server ($server)</font>");
485: return 'no_such_host';
486: }
1.1 albertel 487: my $answer=reply($cmd,$server);
488: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 489: &reconlonc($server);
1.589 albertel 490: my $answer=reply($cmd,$server);
1.1 albertel 491: if ($answer eq 'con_lost') {
492: my $now=time;
493: my $middlename=$cmd;
1.5 www 494: $middlename=substr($middlename,0,16);
1.1 albertel 495: $middlename=~s/\W//g;
496: my $dfilename=
1.305 www 497: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
498: $dumpcount++;
1.1 albertel 499: {
1.448 albertel 500: my $dfh;
1.1172.2.96 raeburn 501: if (open($dfh,">",$dfilename)) {
1.448 albertel 502: print $dfh "$cmd\n";
503: close($dfh);
504: }
1.1 albertel 505: }
1.1172.2.79 raeburn 506: sleep 1;
1.1 albertel 507: my $wcmd='';
508: {
1.448 albertel 509: my $dfh;
1.1172.2.96 raeburn 510: if (open($dfh,"<",$dfilename)) {
1.448 albertel 511: $wcmd=<$dfh>;
512: close($dfh);
513: }
1.1 albertel 514: }
515: chomp($wcmd);
1.7 www 516: if ($wcmd eq $cmd) {
1.672 albertel 517: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 518: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 519: &logperm("D:$server:$cmd");
520: return 'con_delayed';
521: } else {
1.672 albertel 522: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 523: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 524: &logperm("F:$server:$cmd");
525: return 'con_failed';
526: }
527: }
528: }
529: return $answer;
1.405 albertel 530: }
531:
1.755 albertel 532: # ------------------------------------------- check if return value is an error
533:
534: sub error {
535: my ($result) = @_;
1.756 albertel 536: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 537: if ($2 == 2) { return undef; }
538: return $1;
539: }
540: return undef;
541: }
542:
1.783 albertel 543: sub convert_and_load_session_env {
544: my ($lonidsdir,$handle)=@_;
545: my @profile;
546: {
1.917 albertel 547: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
548: if (!$opened) {
1.915 albertel 549: return 0;
550: }
1.783 albertel 551: flock($idf,LOCK_SH);
552: @profile=<$idf>;
553: close($idf);
554: }
555: my %temp_env;
556: foreach my $line (@profile) {
1.786 albertel 557: if ($line !~ m/=/) {
558: return 0;
559: }
1.783 albertel 560: chomp($line);
561: my ($envname,$envvalue)=split(/=/,$line,2);
562: $temp_env{&unescape($envname)} = &unescape($envvalue);
563: }
564: unlink("$lonidsdir/$handle.id");
565: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
566: 0640)) {
567: %disk_env = %temp_env;
568: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
569: untie(%disk_env);
570: }
1.786 albertel 571: return 1;
1.783 albertel 572: }
573:
1.374 www 574: # ------------------------------------------- Transfer profile into environment
1.780 albertel 575: my $env_loaded;
576: sub transfer_profile_to_env {
1.788 albertel 577: my ($lonidsdir,$handle,$force_transfer) = @_;
578: if (!$force_transfer && $env_loaded) { return; }
1.374 www 579:
1.720 albertel 580: if (!defined($lonidsdir)) {
581: $lonidsdir = $perlvar{'lonIDsDir'};
582: }
583: if (!defined($handle)) {
584: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
585: }
586:
1.786 albertel 587: my $convert;
588: {
1.917 albertel 589: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
590: if (!$opened) {
1.915 albertel 591: return;
592: }
1.786 albertel 593: flock($idf,LOCK_SH);
594: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
595: &GDBM_READER(),0640)) {
596: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
597: untie(%disk_env);
598: } else {
599: $convert = 1;
600: }
601: }
602: if ($convert) {
603: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
604: &logthis("Failed to load session, or convert session.");
605: }
1.374 www 606: }
1.783 albertel 607:
1.786 albertel 608: my %remove;
1.783 albertel 609: while ( my $envname = each(%env) ) {
1.433 matthew 610: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
611: if ($time < time-300) {
1.783 albertel 612: $remove{$key}++;
1.433 matthew 613: }
614: }
615: }
1.783 albertel 616:
1.619 albertel 617: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 618: $env_loaded=1;
1.783 albertel 619: foreach my $expired_key (keys(%remove)) {
1.433 matthew 620: &delenv($expired_key);
1.374 www 621: }
1.1 albertel 622: }
623:
1.916 albertel 624: # ---------------------------------------------------- Check for valid session
625: sub check_for_valid_session {
1.1172.2.96 raeburn 626: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 627: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108 raeburn 628: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155 raeburn 629: if ($name eq 'lonDAV') {
630: $lonidsdir=$r->dir_config('lonDAVsessDir');
631: } else {
632: $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108 raeburn 633: if ($name eq '') {
634: $name = 'lonID';
635: }
636: }
637: if ($name eq 'lonID') {
638: $secure = 'lonSID';
639: $linkname = 'lonLinkID';
640: $pubname = 'lonPubID';
641: if (exists($cookies{$secure})) {
642: $lonid=$cookies{$secure};
643: } elsif (exists($cookies{$name})) {
644: $lonid=$cookies{$name};
645: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
646: $lonid=$cookies{$linkname};
647: } elsif (exists($cookies{$pubname})) {
648: $lonid=$cookies{$pubname};
649: }
650: } else {
651: $lonid=$cookies{$name};
652: }
653: return undef if (!$lonid);
654:
655: my $handle=&LONCAPA::clean_handle($lonid->value);
656: if (-l "$lonidsdir/$handle.id") {
657: my $link = readlink("$lonidsdir/$handle.id");
658: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
659: $handle = $1;
660: }
1.1155 raeburn 661: }
1.1172.2.96 raeburn 662: if (!-e "$lonidsdir/$handle.id") {
663: if ((ref($domref)) && ($name eq 'lonID') &&
664: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
665: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
666: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
667: $$domref = $possudom;
668: }
669: }
670: return undef;
671: }
1.916 albertel 672:
1.917 albertel 673: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
674: return undef if (!$opened);
1.916 albertel 675:
676: flock($idf,LOCK_SH);
677: my %disk_env;
678: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
679: &GDBM_READER(),0640)) {
680: return undef;
681: }
682:
683: if (!defined($disk_env{'user.name'})
684: || !defined($disk_env{'user.domain'})) {
1.1172.2.107 raeburn 685: untie(%disk_env);
1.916 albertel 686: return undef;
687: }
1.1172.2.18 raeburn 688:
1.1172.2.36 raeburn 689: if (ref($userhashref) eq 'HASH') {
690: $userhashref->{'name'} = $disk_env{'user.name'};
691: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 692: }
1.1172.2.107 raeburn 693: untie(%disk_env);
1.1172.2.18 raeburn 694:
1.916 albertel 695: return $handle;
696: }
697:
1.830 albertel 698: sub timed_flock {
699: my ($file,$lock_type) = @_;
700: my $failed=0;
701: eval {
702: local $SIG{__DIE__}='DEFAULT';
703: local $SIG{ALRM}=sub {
704: $failed=1;
705: die("failed lock");
706: };
707: alarm(13);
708: flock($file,$lock_type);
709: alarm(0);
710: };
711: if ($failed) {
712: return undef;
713: } else {
714: return 1;
715: }
716: }
717:
1.1172.2.107 raeburn 718: sub get_sessionfile_vars {
719: my ($handle,$lonidsdir,$storearr) = @_;
720: my %returnhash;
721: unless (ref($storearr) eq 'ARRAY') {
722: return %returnhash;
723: }
724: if (-l "$lonidsdir/$handle.id") {
725: my $link = readlink("$lonidsdir/$handle.id");
726: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
727: $handle = $1;
728: }
729: }
730: if ((-e "$lonidsdir/$handle.id") &&
731: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
732: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
733: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
734: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
735: flock($idf,LOCK_SH);
736: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
737: &GDBM_READER(),0640)) {
738: foreach my $item (@{$storearr}) {
739: $returnhash{$item} = $disk_env{$item};
740: }
741: untie(%disk_env);
742: }
743: }
744: }
745: }
746: return %returnhash;
747: }
748:
1.5 www 749: # ---------------------------------------------------------- Append Environment
750:
751: sub appenv {
1.949 raeburn 752: my ($newenv,$roles) = @_;
753: if (ref($newenv) eq 'HASH') {
754: foreach my $key (keys(%{$newenv})) {
755: my $refused = 0;
756: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
757: $refused = 1;
758: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 759: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 760: if (grep(/^\Q$role\E$/,@{$roles})) {
761: $refused = 0;
762: }
763: }
764: }
765: if ($refused) {
766: &logthis("<font color=\"blue\">WARNING: ".
767: "Attempt to modify environment ".$key." to ".$newenv->{$key}
768: .'</font>');
769: delete($newenv->{$key});
770: } else {
771: $env{$key}=$newenv->{$key};
772: }
773: }
1.1172.2.96 raeburn 774: my $lonids = $perlvar{'lonIDsDir'};
775: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
776: my $opened = open(my $env_file,'+<',$env{'user.environment'});
777: if ($opened
778: && &timed_flock($env_file,LOCK_EX)
779: &&
780: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
781: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
782: while (my ($key,$value) = each(%{$newenv})) {
783: $disk_env{$key} = $value;
784: }
785: untie(%disk_env);
786: }
1.35 www 787: }
1.191 harris41 788: }
1.56 www 789: return 'ok';
790: }
791: # ----------------------------------------------------- Delete from Environment
792:
793: sub delenv {
1.1104 raeburn 794: my ($delthis,$regexp,$roles) = @_;
795: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
796: my $refused = 1;
797: if (ref($roles) eq 'ARRAY') {
798: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
799: if (grep(/^\Q$role\E$/,@{$roles})) {
800: $refused = 0;
801: }
802: }
803: if ($refused) {
804: &logthis("<font color=\"blue\">WARNING: ".
805: "Attempt to delete from environment ".$delthis);
806: return 'error';
807: }
1.56 www 808: }
1.917 albertel 809: my $opened = open(my $env_file,'+<',$env{'user.environment'});
810: if ($opened
1.915 albertel 811: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 812: &&
813: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
814: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 815: foreach my $key (keys(%disk_env)) {
1.987 raeburn 816: if ($regexp) {
817: if ($key=~/^$delthis/) {
818: delete($env{$key});
819: delete($disk_env{$key});
820: }
821: } else {
822: if ($key=~/^\Q$delthis\E/) {
823: delete($env{$key});
824: delete($disk_env{$key});
825: }
826: }
1.448 albertel 827: }
1.783 albertel 828: untie(%disk_env);
1.5 www 829: }
830: return 'ok';
1.369 albertel 831: }
832:
1.790 albertel 833: sub get_env_multiple {
834: my ($name) = @_;
835: my @values;
836: if (defined($env{$name})) {
837: # exists is it an array
838: if (ref($env{$name})) {
839: @values=@{ $env{$name} };
840: } else {
841: $values[0]=$env{$name};
842: }
843: }
844: return(@values);
845: }
846:
1.958 www 847: # ------------------------------------------------------------------- Locking
848:
849: sub set_lock {
850: my ($text)=@_;
851: $locknum++;
852: my $id=$$.'-'.$locknum;
853: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
854: 'session.lock.'.$id => $text});
855: return $id;
856: }
857:
858: sub get_locks {
859: my $num=0;
860: my %texts=();
861: foreach my $lock (split(/\,/,$env{'session.locks'})) {
862: if ($lock=~/\w/) {
863: $num++;
864: $texts{$lock}=$env{'session.lock.'.$lock};
865: }
866: }
867: return ($num,%texts);
868: }
869:
870: sub remove_lock {
871: my ($id)=@_;
872: my $newlocks='';
873: foreach my $lock (split(/\,/,$env{'session.locks'})) {
874: if (($lock=~/\w/) && ($lock ne $id)) {
875: $newlocks.=','.$lock;
876: }
877: }
878: &appenv({'session.locks' => $newlocks});
879: &delenv('session.lock.'.$id);
880: }
881:
882: sub remove_all_locks {
883: my $activelocks=$env{'session.locks'};
884: foreach my $lock (split(/\,/,$env{'session.locks'})) {
885: if ($lock=~/\w/) {
886: &remove_lock($lock);
887: }
888: }
889: }
890:
891:
1.369 albertel 892: # ------------------------------------------ Find out current server userload
893: sub userload {
894: my $numusers=0;
895: {
896: opendir(LONIDS,$perlvar{'lonIDsDir'});
897: my $filename;
898: my $curtime=time;
899: while ($filename=readdir(LONIDS)) {
1.925 albertel 900: next if ($filename eq '.' || $filename eq '..');
901: next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112 raeburn 902: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 903: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 904: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 905: }
906: closedir(LONIDS);
907: }
908: my $userloadpercent=0;
909: my $maxuserload=$perlvar{'lonUserLoadLim'};
910: if ($maxuserload) {
1.371 albertel 911: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 912: }
1.372 albertel 913: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 914: return $userloadpercent;
1.283 www 915: }
916:
1.1 albertel 917: # ------------------------------ Find server with least workload from spare.tab
1.11 www 918:
1.1 albertel 919: sub spareserver {
1.1083 raeburn 920: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 921: my $spare_server;
1.370 albertel 922: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 923: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
924: : $userloadpercent;
1.1083 raeburn 925: my ($uint_dom,$remotesessions);
926: if (($udom ne '') && (&domain($udom) ne '')) {
927: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
928: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
929: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
930: $remotesessions = $udomdefaults{'remotesessions'};
931: }
1.1123 raeburn 932: my $spareshash = &this_host_spares($udom);
933: if (ref($spareshash) eq 'HASH') {
934: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
935: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 936: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
937: $try_server));
1.1123 raeburn 938: ($spare_server, $lowest_load) =
939: &compare_server_load($try_server, $spare_server, $lowest_load);
940: }
1.1083 raeburn 941: }
1.784 albertel 942:
1.1123 raeburn 943: my $found_server = ($spare_server ne '' && $lowest_load < 100);
944:
945: if (!$found_server) {
946: if (ref($spareshash->{'default'}) eq 'ARRAY') {
947: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 948: next unless (&spare_can_host($udom,$uint_dom,
949: $remotesessions,$try_server));
1.1123 raeburn 950: ($spare_server, $lowest_load) =
951: &compare_server_load($try_server, $spare_server, $lowest_load);
952: }
953: }
954: }
1.784 albertel 955: }
956:
957: if (!$want_server_name) {
1.1001 raeburn 958: if (defined($spare_server)) {
959: my $hostname = &hostname($spare_server);
1.1083 raeburn 960: if (defined($hostname)) {
1.1172.2.120 raeburn 961: my $protocol = 'http';
962: if ($protocol{$spare_server} eq 'https') {
963: $protocol = $protocol{$spare_server};
964: }
1.1001 raeburn 965: $spare_server = $protocol.'://'.$hostname;
966: }
967: }
1.784 albertel 968: }
969: return $spare_server;
970: }
971:
972: sub compare_server_load {
1.1172.2.41 raeburn 973: my ($try_server, $spare_server, $lowest_load, $required) = @_;
974:
975: if ($required) {
976: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
977: my $remoterev = &get_server_loncaparev(undef,$try_server);
978: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
979: if (($major eq '' && $minor eq '') ||
980: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
981: return ($spare_server,$lowest_load);
982: }
983: }
1.784 albertel 984:
985: my $loadans = &reply('load', $try_server);
986: my $userloadans = &reply('userload',$try_server);
987:
988: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 989: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 990: }
991:
992: my $load;
993: if ($loadans =~ /\d/) {
994: if ($userloadans =~ /\d/) {
995: #both are numbers, pick the bigger one
996: $load = ($loadans > $userloadans) ? $loadans
997: : $userloadans;
1.411 albertel 998: } else {
1.784 albertel 999: $load = $loadans;
1.411 albertel 1000: }
1.784 albertel 1001: } else {
1002: $load = $userloadans;
1003: }
1004:
1005: if (($load =~ /\d/) && ($load < $lowest_load)) {
1006: $spare_server = $try_server;
1007: $lowest_load = $load;
1.370 albertel 1008: }
1.784 albertel 1009: return ($spare_server,$lowest_load);
1.202 matthew 1010: }
1.914 albertel 1011:
1012: # --------------------------- ask offload servers if user already has a session
1013: sub find_existing_session {
1014: my ($udom,$uname) = @_;
1.1123 raeburn 1015: my $spareshash = &this_host_spares($udom);
1016: if (ref($spareshash) eq 'HASH') {
1017: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1018: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1019: return $try_server if (&has_user_session($try_server, $udom, $uname));
1020: }
1021: }
1022: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1023: foreach my $try_server (@{ $spareshash->{'default'} }) {
1024: return $try_server if (&has_user_session($try_server, $udom, $uname));
1025: }
1026: }
1.914 albertel 1027: }
1028: return;
1029: }
1030:
1.1172.2.107 raeburn 1031: # check if user's browser sent load balancer cookie and server still has session
1032: # and is not overloaded.
1033: sub check_for_balancer_cookie {
1034: my ($r,$update_mtime) = @_;
1035: my ($otherserver,$cookie);
1036: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1037: if (exists($cookies{'balanceID'})) {
1038: my $balid = $cookies{'balanceID'};
1039: $cookie=&LONCAPA::clean_handle($balid->value);
1040: my $balancedir=$r->dir_config('lonBalanceDir');
1041: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1042: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1043: my ($possudom,$possuname) = ($1,$2);
1044: my $has_session = 0;
1045: if ((&domain($possudom) ne '') &&
1046: (&homeserver($possuname,$possudom) ne 'no_host')) {
1047: my $try_server;
1048: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1049: if ($opened) {
1050: flock($idf,LOCK_SH);
1051: while (my $line = <$idf>) {
1052: chomp($line);
1053: if (&hostname($line) ne '') {
1054: $try_server = $line;
1055: last;
1056: }
1057: }
1058: close($idf);
1059: if (($try_server) &&
1060: (&has_user_session($try_server,$possudom,$possuname))) {
1061: my $lowest_load = 30000;
1062: ($otherserver,$lowest_load) =
1063: &compare_server_load($try_server,undef,$lowest_load);
1064: if ($otherserver ne '' && $lowest_load < 100) {
1065: $has_session = 1;
1066: } else {
1067: undef($otherserver);
1068: }
1069: }
1070: }
1071: }
1072: if ($has_session) {
1073: if ($update_mtime) {
1074: my $atime = my $mtime = time;
1075: utime($atime,$mtime,"$balancedir/$cookie.id");
1076: }
1077: } else {
1078: unlink("$balancedir/$cookie.id");
1079: }
1080: }
1081: }
1082: }
1083: return ($otherserver,$cookie);
1084: }
1085:
1.1172.2.130 raeburn 1086: sub updatebalcookie {
1087: my ($cookie,$balancer,$lastentry)=@_;
1088: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1089: my ($udom,$uname) = ($1,$2);
1090: my $uprimary_id = &domain($udom,'primary');
1091: my $uintdom = &internet_dom($uprimary_id);
1092: my $intdom = &internet_dom($balancer);
1093: my $serverhomedom = &host_domain($balancer);
1094: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1095: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1096: }
1097: }
1098: return;
1099: }
1100:
1.1172.2.107 raeburn 1101: sub delbalcookie {
1102: my ($cookie,$balancer) =@_;
1103: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1104: my ($udom,$uname) = ($1,$2);
1105: my $uprimary_id = &domain($udom,'primary');
1106: my $uintdom = &internet_dom($uprimary_id);
1107: my $intdom = &internet_dom($balancer);
1108: my $serverhomedom = &host_domain($balancer);
1109: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130 raeburn 1110: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107 raeburn 1111: }
1112: }
1113: }
1114:
1.914 albertel 1115: # -------------------------------- ask if server already has a session for user
1116: sub has_user_session {
1117: my ($lonid,$udom,$uname) = @_;
1118: my $result = &reply(join(':','userhassession',
1119: map {&escape($_)} ($udom,$uname)),$lonid);
1120: return 1 if ($result eq 'ok');
1121:
1122: return 0;
1123: }
1124:
1.1076 raeburn 1125: # --------- determine least loaded server in a user's domain which allows login
1126:
1127: sub choose_server {
1.1172.2.47 raeburn 1128: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1129: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1130: my %servers = &get_servers($udom);
1.1076 raeburn 1131: my $lowest_load = 30000;
1.1172.2.47 raeburn 1132: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1133: if ($skiploadbal) {
1134: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1135: unless (defined($cached)) {
1136: my $cachetime = 60*60*24;
1137: my %domconfig =
1138: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1139: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1140: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1141: $cachetime);
1142: }
1143: }
1144: }
1.1076 raeburn 1145: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 1146: my $loginvia;
1.1172.2.47 raeburn 1147: if ($skiploadbal) {
1148: if (ref($balancers) eq 'HASH') {
1149: next if (exists($balancers->{$lonhost}));
1150: }
1151: }
1.1115 raeburn 1152: if ($checkloginvia) {
1153: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1154: if ($loginvia) {
1155: my ($server,$path) = split(/:/,$loginvia);
1156: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1157: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1158: if ($login_host eq $server) {
1159: $portal_path = $path;
1.1151 raeburn 1160: $isredirect = 1;
1.1116 raeburn 1161: }
1162: } else {
1163: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1164: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1165: if ($login_host eq $lonhost) {
1166: $portal_path = '';
1.1151 raeburn 1167: $isredirect = '';
1.1116 raeburn 1168: }
1169: }
1170: } else {
1.1076 raeburn 1171: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1172: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1173: }
1174: }
1175: if ($login_host ne '') {
1.1116 raeburn 1176: $hostname = &hostname($login_host);
1.1076 raeburn 1177: }
1.1172.2.88 raeburn 1178: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1179: }
1180:
1.1172.2.123 raeburn 1181: sub get_course_sessions {
1182: my ($cnum,$cdom,$lastactivity) = @_;
1183: my %servers = &internet_dom_servers($cdom);
1184: my %returnhash;
1185: foreach my $server (sort(keys(%servers))) {
1186: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1187: my @pairs=split(/\&/,$rep);
1188: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1189: foreach my $item (@pairs) {
1190: my ($key,$value)=split(/=/,$item,2);
1191: $key = &unescape($key);
1192: next if ($key =~ /^error: 2 /);
1193: if (exists($returnhash{$key})) {
1194: next if ($value < $returnhash{$key});
1195: }
1196: $returnhash{$key}=$value;
1197: }
1198: }
1199: }
1200: return %returnhash;
1201: }
1202:
1.202 matthew 1203: # --------------------------------------------- Try to change a user's password
1204:
1205: sub changepass {
1.799 raeburn 1206: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1207: $currentpass = &escape($currentpass);
1208: $newpass = &escape($newpass);
1.1030 raeburn 1209: my $lonhost = $perlvar{'lonHostID'};
1210: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1211: $server);
1212: if (! $answer) {
1213: &logthis("No reply on password change request to $server ".
1214: "by $uname in domain $udom.");
1215: } elsif ($answer =~ "^ok") {
1216: &logthis("$uname in $udom successfully changed their password ".
1217: "on $server.");
1218: } elsif ($answer =~ "^pwchange_failure") {
1219: &logthis("$uname in $udom was unable to change their password ".
1220: "on $server. The action was blocked by either lcpasswd ".
1221: "or pwchange");
1222: } elsif ($answer =~ "^non_authorized") {
1223: &logthis("$uname in $udom did not get their password correct when ".
1224: "attempting to change it on $server.");
1225: } elsif ($answer =~ "^auth_mode_error") {
1226: &logthis("$uname in $udom attempted to change their password despite ".
1227: "not being locally or internally authenticated on $server.");
1228: } elsif ($answer =~ "^unknown_user") {
1229: &logthis("$uname in $udom attempted to change their password ".
1230: "on $server but were unable to because $server is not ".
1231: "their home server.");
1232: } elsif ($answer =~ "^refused") {
1233: &logthis("$server refused to change $uname in $udom password because ".
1234: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1235: } elsif ($answer =~ "invalid_client") {
1236: &logthis("$server refused to change $uname in $udom password because ".
1237: "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113 raeburn 1238: } elsif ($answer =~ "^prioruse") {
1239: &logthis("$server refused to change $uname in $udom password because ".
1240: "the password had been used before");
1.202 matthew 1241: }
1242: return $answer;
1.1 albertel 1243: }
1244:
1.169 harris41 1245: # ----------------------- Try to determine user's current authentication scheme
1246:
1247: sub queryauthenticate {
1248: my ($uname,$udom)=@_;
1.456 albertel 1249: my $uhome=&homeserver($uname,$udom);
1250: if (!$uhome) {
1251: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1252: return 'no_host';
1253: }
1254: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1255: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1256: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1257: }
1.456 albertel 1258: return $answer;
1.169 harris41 1259: }
1260:
1.1 albertel 1261: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1262:
1.1 albertel 1263: sub authenticate {
1.1073 raeburn 1264: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1265: $upass=&escape($upass);
1266: $uname= &LONCAPA::clean_username($uname);
1.836 www 1267: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1268: my $newhome;
1.836 www 1269: if ((!$uhome) || ($uhome eq 'no_host')) {
1270: # Maybe the machine was offline and only re-appeared again recently?
1271: &reconlonc();
1272: # One more
1.952 raeburn 1273: $uhome=&homeserver($uname,$udom,1);
1274: if (($uhome eq 'no_host') && $checkdefauth) {
1275: if (defined(&domain($udom,'primary'))) {
1276: $newhome=&domain($udom,'primary');
1277: }
1278: if ($newhome ne '') {
1279: $uhome = $newhome;
1280: }
1281: }
1.836 www 1282: if ((!$uhome) || ($uhome eq 'no_host')) {
1283: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1284: return 'no_host';
1285: }
1.1 albertel 1286: }
1.1073 raeburn 1287: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1288: if ($answer eq 'authorized') {
1.952 raeburn 1289: if ($newhome) {
1290: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1291: return 'no_account_on_host';
1292: } else {
1293: &logthis("User $uname at $udom authorized by $uhome");
1294: return $uhome;
1295: }
1.471 albertel 1296: }
1297: if ($answer eq 'non_authorized') {
1298: &logthis("User $uname at $udom rejected by $uhome");
1299: return 'no_host';
1.9 www 1300: }
1.471 albertel 1301: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1302: return 'no_host';
1303: }
1304:
1.1073 raeburn 1305: sub can_host_session {
1.1074 raeburn 1306: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1307: my $canhost = 1;
1.1074 raeburn 1308: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1309: if (ref($remotesessions) eq 'HASH') {
1310: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1311: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1312: $canhost = 0;
1313: } else {
1314: $canhost = 1;
1315: }
1316: }
1317: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1318: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1319: $canhost = 1;
1320: } else {
1321: $canhost = 0;
1322: }
1323: }
1324: if ($canhost) {
1325: if ($remotesessions->{'version'} ne '') {
1326: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1327: if ($reqmajor ne '' && $reqminor ne '') {
1328: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1329: my $major = $1;
1330: my $minor = $2;
1331: if (($major < $reqmajor ) ||
1332: (($major == $reqmajor) && ($minor < $reqminor))) {
1333: $canhost = 0;
1334: }
1335: } else {
1336: $canhost = 0;
1337: }
1338: }
1339: }
1340: }
1341: }
1342: if ($canhost) {
1343: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1344: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1345: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1346: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1347: if (($uint_dom ne '') &&
1348: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1349: $canhost = 0;
1350: } else {
1351: $canhost = 1;
1352: }
1353: }
1354: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1355: if (($uint_dom ne '') &&
1356: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1357: $canhost = 1;
1358: } else {
1359: $canhost = 0;
1360: }
1361: }
1362: }
1363: }
1364: return $canhost;
1365: }
1366:
1.1083 raeburn 1367: sub spare_can_host {
1368: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1369: my $canhost=1;
1.1172.2.62 raeburn 1370: my $try_server_hostname = &hostname($try_server);
1371: my $serverhomeID = &get_server_homeID($try_server_hostname);
1372: my $serverhomedom = &host_domain($serverhomeID);
1373: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1374: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1375: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1376: $canhost = 0;
1377: }
1378: }
1.1172.2.136! raeburn 1379: if ($canhost) {
! 1380: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
! 1381: if ($defdomdefaults{'offloadoth'}{$try_server}) {
! 1382: unless (&shared_institution($udom,$try_server)) {
! 1383: $canhost = 0;
! 1384: }
! 1385: }
! 1386: }
! 1387: }
1.1172.2.62 raeburn 1388: if (($canhost) && ($uint_dom)) {
1389: my @intdoms;
1390: my $internet_names = &get_internet_names($try_server);
1391: if (ref($internet_names) eq 'ARRAY') {
1392: @intdoms = @{$internet_names};
1393: }
1394: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1395: my $remoterev = &get_server_loncaparev(undef,$try_server);
1396: $canhost = &can_host_session($udom,$try_server,$remoterev,
1397: $remotesessions,
1398: $defdomdefaults{'hostedsessions'});
1399: }
1.1083 raeburn 1400: }
1401: return $canhost;
1402: }
1403:
1.1123 raeburn 1404: sub this_host_spares {
1405: my ($dom) = @_;
1.1126 raeburn 1406: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1407: my @hosts = ¤t_machine_ids();
1408: foreach my $lonhost (@hosts) {
1409: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1410: $dom_in_use = $dom;
1411: $lonhost_in_use = $lonhost;
1.1123 raeburn 1412: last;
1413: }
1414: }
1.1126 raeburn 1415: if ($dom_in_use ne '') {
1416: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1417: }
1418: if (ref($result) ne 'HASH') {
1419: $lonhost_in_use = $perlvar{'lonHostID'};
1420: $dom_in_use = &host_domain($lonhost_in_use);
1421: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1422: if (ref($result) ne 'HASH') {
1423: $result = \%spareid;
1424: }
1425: }
1426: return $result;
1427: }
1428:
1429: sub spares_for_offload {
1430: my ($dom_in_use,$lonhost_in_use) = @_;
1431: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1432: if (defined($cached)) {
1433: return $result;
1434: } else {
1.1126 raeburn 1435: my $cachetime = 60*60*24;
1436: my %domconfig =
1437: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1438: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1439: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1440: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1441: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1442: }
1443: }
1444: }
1445: }
1.1126 raeburn 1446: return;
1.1123 raeburn 1447: }
1448:
1.1129 raeburn 1449: sub get_lonbalancer_config {
1450: my ($servers) = @_;
1451: my ($currbalancer,$currtargets);
1452: if (ref($servers) eq 'HASH') {
1453: foreach my $server (keys(%{$servers})) {
1454: my %what = (
1455: spareid => 1,
1456: perlvar => 1,
1457: );
1458: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1459: if ($result eq 'ok') {
1460: if (ref($returnhash) eq 'HASH') {
1461: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1462: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1463: $currbalancer = $server;
1464: $currtargets = {};
1465: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1466: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1467: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1468: }
1469: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1470: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1471: }
1472: }
1473: last;
1474: }
1475: }
1476: }
1477: }
1478: }
1479: }
1480: return ($currbalancer,$currtargets);
1481: }
1482:
1483: sub check_loadbalancing {
1.1172.2.88 raeburn 1484: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1485: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107 raeburn 1486: $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129 raeburn 1487: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1488: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1489: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1490: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1491: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1492: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1493: my $domneedscache;
1.1129 raeburn 1494: my $cachetime = 60*60*24;
1495:
1496: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1497: $dom_in_use = $udom;
1498: $homeintdom = 1;
1499: } else {
1500: $dom_in_use = $serverhomedom;
1501: }
1502: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1503: unless (defined($cached)) {
1504: my %domconfig =
1505: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1506: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1507: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1508: } else {
1509: $domneedscache = $dom_in_use;
1.1129 raeburn 1510: }
1511: }
1512: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1513: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1514: &check_balancer_result($result,@hosts);
1.1129 raeburn 1515: if ($is_balancer) {
1516: if (ref($currrules) eq 'HASH') {
1517: if ($homeintdom) {
1518: if ($uname ne '') {
1519: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1520: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1521: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1522: $rule_in_effect = $currrules->{'_LC_author'};
1523: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1524: $rule_in_effect = $currrules->{'_LC_adv'}
1525: }
1526: }
1527: if ($rule_in_effect eq '') {
1528: my %userenv = &userenvironment($udom,$uname,'inststatus');
1529: if ($userenv{'inststatus'} ne '') {
1530: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1531: my ($othertitle,$usertypes,$types) =
1532: &Apache::loncommon::sorted_inst_types($udom);
1533: if (ref($types) eq 'ARRAY') {
1534: foreach my $type (@{$types}) {
1535: if (grep(/^\Q$type\E$/,@statuses)) {
1536: if (exists($currrules->{$type})) {
1537: $rule_in_effect = $currrules->{$type};
1538: }
1539: }
1540: }
1541: }
1542: } else {
1543: if (exists($currrules->{'default'})) {
1544: $rule_in_effect = $currrules->{'default'};
1545: }
1546: }
1547: }
1548: } else {
1549: if (exists($currrules->{'default'})) {
1550: $rule_in_effect = $currrules->{'default'};
1551: }
1552: }
1553: } else {
1554: if ($currrules->{'_LC_external'} ne '') {
1555: $rule_in_effect = $currrules->{'_LC_external'};
1556: }
1557: }
1558: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1559: $uname,$udom);
1560: }
1561: }
1562: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1563: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1564: unless (defined($cached)) {
1565: my %domconfig =
1566: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1567: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1568: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1569: } else {
1570: $domneedscache = $serverhomedom;
1.1129 raeburn 1571: }
1572: }
1573: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1574: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1575: &check_balancer_result($result,@hosts);
1576: if ($is_balancer) {
1.1129 raeburn 1577: if (ref($currrules) eq 'HASH') {
1578: if ($currrules->{'_LC_internetdom'} ne '') {
1579: $rule_in_effect = $currrules->{'_LC_internetdom'};
1580: }
1581: }
1582: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1583: $uname,$udom);
1584: }
1585: } else {
1586: if ($perlvar{'lonBalancer'} eq 'yes') {
1587: $is_balancer = 1;
1588: $offloadto = &this_host_spares($dom_in_use);
1589: }
1.1172.2.75 raeburn 1590: unless (defined($cached)) {
1591: $domneedscache = $serverhomedom;
1592: }
1.1129 raeburn 1593: }
1594: } else {
1595: if ($perlvar{'lonBalancer'} eq 'yes') {
1596: $is_balancer = 1;
1597: $offloadto = &this_host_spares($dom_in_use);
1598: }
1.1172.2.75 raeburn 1599: unless (defined($cached)) {
1600: $domneedscache = $serverhomedom;
1601: }
1602: }
1603: if ($domneedscache) {
1604: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1605: }
1.1172.2.130 raeburn 1606: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5 raeburn 1607: my $lowest_load = 30000;
1608: if (ref($offloadto) eq 'HASH') {
1609: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1610: foreach my $try_server (@{$offloadto->{'primary'}}) {
1611: ($otherserver,$lowest_load) =
1612: &compare_server_load($try_server,$otherserver,$lowest_load);
1613: }
1.1129 raeburn 1614: }
1.1172.2.5 raeburn 1615: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1616:
1.1172.2.5 raeburn 1617: if (!$found_server) {
1618: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1619: foreach my $try_server (@{$offloadto->{'default'}}) {
1620: ($otherserver,$lowest_load) =
1621: &compare_server_load($try_server,$otherserver,$lowest_load);
1622: }
1623: }
1624: }
1625: } elsif (ref($offloadto) eq 'ARRAY') {
1626: if (@{$offloadto} == 1) {
1627: $otherserver = $offloadto->[0];
1628: } elsif (@{$offloadto} > 1) {
1629: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1630: ($otherserver,$lowest_load) =
1631: &compare_server_load($try_server,$otherserver,$lowest_load);
1632: }
1633: }
1634: }
1.1172.2.88 raeburn 1635: unless ($caller eq 'login') {
1636: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1637: $is_balancer = 0;
1638: if ($uname ne '' && $udom ne '') {
1639: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1640: &appenv({'user.loadbalexempt' => $lonhost,
1641: 'user.loadbalcheck.time' => time});
1642: }
1.1172.2.5 raeburn 1643: }
1.1129 raeburn 1644: }
1645: }
1.1172.2.130 raeburn 1646: }
1647: if (($is_balancer) && (!$homeintdom)) {
1648: undef($setcookie);
1.1129 raeburn 1649: }
1.1172.2.107 raeburn 1650: return ($is_balancer,$otherserver,$setcookie);
1.1129 raeburn 1651: }
1652:
1.1172.2.12 raeburn 1653: sub check_balancer_result {
1654: my ($result,@hosts) = @_;
1.1172.2.107 raeburn 1655: my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1656: if (ref($result) eq 'HASH') {
1657: if ($result->{'lonhost'} ne '') {
1658: my $currbalancer = $result->{'lonhost'};
1659: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1660: $is_balancer = 1;
1661: $currtargets = $result->{'targets'};
1662: $currrules = $result->{'rules'};
1663: }
1664: } else {
1665: foreach my $key (keys(%{$result})) {
1666: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1667: (ref($result->{$key}) eq 'HASH')) {
1668: $is_balancer = 1;
1669: $currrules = $result->{$key}{'rules'};
1670: $currtargets = $result->{$key}{'targets'};
1.1172.2.107 raeburn 1671: $setcookie = $result->{$key}{'cookie'};
1.1172.2.12 raeburn 1672: last;
1673: }
1674: }
1675: }
1676: }
1.1172.2.107 raeburn 1677: return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1678: }
1679:
1.1129 raeburn 1680: sub get_loadbalancer_targets {
1681: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1682: my $offloadto;
1.1172.2.4 raeburn 1683: if ($rule_in_effect eq 'none') {
1684: return [$perlvar{'lonHostID'}];
1685: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1686: $offloadto = $currtargets;
1687: } else {
1688: if ($rule_in_effect eq 'homeserver') {
1689: my $homeserver = &homeserver($uname,$udom);
1690: if ($homeserver ne 'no_host') {
1691: $offloadto = [$homeserver];
1692: }
1693: } elsif ($rule_in_effect eq 'externalbalancer') {
1694: my %domconfig =
1695: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1696: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1697: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1698: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1699: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1700: }
1701: }
1702: } else {
1.1172.2.7 raeburn 1703: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1704: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1705: if (&hostname($remotebalancer) ne '') {
1706: $offloadto = [$remotebalancer];
1707: }
1708: }
1709: } elsif (&hostname($rule_in_effect) ne '') {
1710: $offloadto = [$rule_in_effect];
1711: }
1712: }
1713: return $offloadto;
1714: }
1715:
1.1127 raeburn 1716: sub internet_dom_servers {
1717: my ($dom) = @_;
1718: my (%uniqservers,%servers);
1719: my $primaryserver = &hostname(&domain($dom,'primary'));
1720: my @machinedoms = &machine_domains($primaryserver);
1721: foreach my $mdom (@machinedoms) {
1722: my %currservers = %servers;
1723: my %server = &get_servers($mdom);
1724: %servers = (%currservers,%server);
1725: }
1726: my %by_hostname;
1727: foreach my $id (keys(%servers)) {
1728: push(@{$by_hostname{$servers{$id}}},$id);
1729: }
1730: foreach my $hostname (sort(keys(%by_hostname))) {
1731: if (@{$by_hostname{$hostname}} > 1) {
1732: my $match = 0;
1733: foreach my $id (@{$by_hostname{$hostname}}) {
1734: if (&host_domain($id) eq $dom) {
1735: $uniqservers{$id} = $hostname;
1736: $match = 1;
1737: }
1738: }
1739: unless ($match) {
1740: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1741: }
1742: } else {
1743: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1744: }
1745: }
1746: return %uniqservers;
1747: }
1748:
1.1 albertel 1749: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1750:
1.599 albertel 1751: my %homecache;
1.1 albertel 1752: sub homeserver {
1.230 stredwic 1753: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1754: my $index="$uname:$udom";
1.426 albertel 1755:
1.599 albertel 1756: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1757:
1758: my %servers = &get_servers($udom,'library');
1759: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1760: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1761: exists($badServerCache{$tryserver}));
1.841 albertel 1762:
1763: my $answer=reply("home:$udom:$uname",$tryserver);
1764: if ($answer eq 'found') {
1765: delete($badServerCache{$tryserver});
1766: return $homecache{$index}=$tryserver;
1767: } elsif ($answer eq 'no_host') {
1768: $badServerCache{$tryserver}=1;
1769: }
1.1 albertel 1770: }
1771: return 'no_host';
1.70 www 1772: }
1773:
1774: # ------------------------------------- Find the usernames behind a list of IDs
1775:
1776: sub idget {
1777: my ($udom,@ids)=@_;
1778: my %returnhash=();
1779:
1.841 albertel 1780: my %servers = &get_servers($udom,'library');
1781: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1782: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1783: $idlist=~tr/A-Z/a-z/;
1784: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1785: my @answer=();
1786: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1787: @answer=split(/\&/,$reply);
1788: } ;
1789: my $i;
1790: for ($i=0;$i<=$#ids;$i++) {
1791: if ($answer[$i]) {
1.1172.2.73 raeburn 1792: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1793: }
1794: }
1795: }
1.70 www 1796: return %returnhash;
1797: }
1798:
1799: # ------------------------------------- Find the IDs behind a list of usernames
1800:
1801: sub idrget {
1802: my ($udom,@unames)=@_;
1803: my %returnhash=();
1.800 albertel 1804: foreach my $uname (@unames) {
1805: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1806: }
1.70 www 1807: return %returnhash;
1808: }
1809:
1810: # ------------------------------- Store away a list of names and associated IDs
1811:
1812: sub idput {
1813: my ($udom,%ids)=@_;
1814: my %servers=();
1.800 albertel 1815: foreach my $uname (keys(%ids)) {
1816: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1817: my $uhom=&homeserver($uname,$udom);
1.70 www 1818: if ($uhom ne 'no_host') {
1.800 albertel 1819: my $id=&escape($ids{$uname});
1.70 www 1820: $id=~tr/A-Z/a-z/;
1.800 albertel 1821: my $esc_unam=&escape($uname);
1.70 www 1822: if ($servers{$uhom}) {
1.800 albertel 1823: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1824: } else {
1.800 albertel 1825: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1826: }
1827: }
1.191 harris41 1828: }
1.800 albertel 1829: foreach my $server (keys(%servers)) {
1830: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1831: }
1.344 www 1832: }
1833:
1.1172.2.30 raeburn 1834: # ---------------------------------------- Delete unwanted IDs from ids.db file
1835:
1836: sub iddel {
1837: my ($udom,$idshashref,$uhome)=@_;
1838: my %result=();
1839: unless (ref($idshashref) eq 'HASH') {
1840: return %result;
1841: }
1842: my %servers=();
1843: while (my ($id,$uname) = each(%{$idshashref})) {
1844: my $uhom;
1845: if ($uhome) {
1846: $uhom = $uhome;
1847: } else {
1848: $uhom=&homeserver($uname,$udom);
1849: }
1850: if ($uhom ne 'no_host') {
1851: if ($servers{$uhom}) {
1852: $servers{$uhom}.='&'.&escape($id);
1853: } else {
1854: $servers{$uhom}=&escape($id);
1855: }
1856: }
1857: }
1858: foreach my $server (keys(%servers)) {
1859: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1860: }
1861: return %result;
1862: }
1863:
1.1023 raeburn 1864: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1865: sub dump_dom {
1.1165 droeschl 1866: my ($namespace, $udom, $regexp) = @_;
1867:
1868: $udom ||= $env{'user.domain'};
1869:
1870: return () unless $udom;
1871:
1872: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1873: }
1874:
1.1023 raeburn 1875: # ------------------------------------------ get items from domain db files
1.806 raeburn 1876:
1877: sub get_dom {
1.860 raeburn 1878: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1879: return if ($udom eq 'public');
1.806 raeburn 1880: my $items='';
1881: foreach my $item (@$storearr) {
1882: $items.=&escape($item).'&';
1883: }
1884: $items=~s/\&$//;
1.860 raeburn 1885: if (!$udom) {
1886: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1887: return if ($udom eq 'public');
1.860 raeburn 1888: if (defined(&domain($udom,'primary'))) {
1889: $uhome=&domain($udom,'primary');
1890: } else {
1.874 albertel 1891: undef($uhome);
1.860 raeburn 1892: }
1893: } else {
1894: if (!$uhome) {
1895: if (defined(&domain($udom,'primary'))) {
1896: $uhome=&domain($udom,'primary');
1897: }
1898: }
1899: }
1900: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1901: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1902: my %returnhash;
1.875 albertel 1903: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1904: return %returnhash;
1905: }
1.806 raeburn 1906: my @pairs=split(/\&/,$rep);
1907: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1908: return @pairs;
1909: }
1910: my $i=0;
1911: foreach my $item (@$storearr) {
1912: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1913: $i++;
1914: }
1915: return %returnhash;
1916: } else {
1.880 banghart 1917: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1918: }
1919: }
1920:
1921: # -------------------------------------------- put items in domain db files
1922:
1923: sub put_dom {
1.860 raeburn 1924: my ($namespace,$storehash,$udom,$uhome)=@_;
1925: if (!$udom) {
1926: $udom=$env{'user.domain'};
1927: if (defined(&domain($udom,'primary'))) {
1928: $uhome=&domain($udom,'primary');
1929: } else {
1.874 albertel 1930: undef($uhome);
1.860 raeburn 1931: }
1932: } else {
1933: if (!$uhome) {
1934: if (defined(&domain($udom,'primary'))) {
1935: $uhome=&domain($udom,'primary');
1936: }
1937: }
1938: }
1939: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1940: my $items='';
1941: foreach my $item (keys(%$storehash)) {
1942: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1943: }
1944: $items=~s/\&$//;
1945: return &reply("putdom:$udom:$namespace:$items",$uhome);
1946: } else {
1.860 raeburn 1947: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1948: }
1949: }
1950:
1.1023 raeburn 1951: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1952: sub newput_dom {
1.1023 raeburn 1953: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1954: my $result;
1955: if (!$udom) {
1956: $udom=$env{'user.domain'};
1957: }
1.1023 raeburn 1958: if ($udom) {
1959: my $uname = &get_domainconfiguser($udom);
1960: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1961: }
1962: return $result;
1963: }
1964:
1.1023 raeburn 1965: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1966: sub del_dom {
1.1023 raeburn 1967: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1968: if (ref($storearr) eq 'ARRAY') {
1969: if (!$udom) {
1970: $udom=$env{'user.domain'};
1971: }
1.1023 raeburn 1972: if ($udom) {
1973: my $uname = &get_domainconfiguser($udom);
1974: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1975: }
1976: }
1977: }
1978:
1.1023 raeburn 1979: # ----------------------------------construct domainconfig user for a domain
1980: sub get_domainconfiguser {
1981: my ($udom) = @_;
1982: return $udom.'-domainconfig';
1983: }
1984:
1.837 raeburn 1985: sub retrieve_inst_usertypes {
1986: my ($udom) = @_;
1987: my (%returnhash,@order);
1.989 raeburn 1988: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1989: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1990: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1991: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1992: } else {
1993: if (defined(&domain($udom,'primary'))) {
1994: my $uhome=&domain($udom,'primary');
1995: my $rep=&reply("inst_usertypes:$udom",$uhome);
1996: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1997: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1998: return (\%returnhash,\@order);
1999: }
2000: my ($hashitems,$orderitems) = split(/:/,$rep);
2001: my @pairs=split(/\&/,$hashitems);
2002: foreach my $item (@pairs) {
2003: my ($key,$value)=split(/=/,$item,2);
2004: $key = &unescape($key);
2005: next if ($key =~ /^error: 2 /);
2006: $returnhash{$key}=&thaw_unescape($value);
2007: }
2008: my @esc_order = split(/\&/,$orderitems);
2009: foreach my $item (@esc_order) {
2010: push(@order,&unescape($item));
2011: }
2012: } else {
1.1172.2.44 raeburn 2013: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2014: }
1.1172.2.44 raeburn 2015: return (\%returnhash,\@order);
1.837 raeburn 2016: }
2017: }
2018:
1.868 raeburn 2019: sub is_domainimage {
2020: my ($url) = @_;
1.1172.2.74 raeburn 2021: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 2022: if (&domain($1) ne '') {
2023: return '1';
2024: }
2025: }
2026: return;
2027: }
2028:
1.899 raeburn 2029: sub inst_directory_query {
2030: my ($srch) = @_;
2031: my $udom = $srch->{'srchdomain'};
2032: my %results;
2033: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2034: my $outcome;
1.899 raeburn 2035: if ($homeserver ne '') {
1.1172.2.116 raeburn 2036: unless ($homeserver eq $perlvar{'lonHostID'}) {
2037: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2038: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116 raeburn 2039: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
2040: if (($major eq '' && $minor eq '') || ($major < 2) ||
2041: (($major == 2) && ($minor < 11)) ||
2042: (($major == 2) && ($minor == 11) && ($subver < 3))) {
2043: return;
2044: }
2045: }
2046: }
1.904 albertel 2047: my $queryid=&reply("querysend:instdirsearch:".
2048: &escape($srch->{'srchby'}).':'.
2049: &escape($srch->{'srchterm'}).':'.
2050: &escape($srch->{'srchtype'}),$homeserver);
2051: my $host=&hostname($homeserver);
2052: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96 raeburn 2053: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2054: return;
2055: }
2056: my $response = &get_query_reply($queryid);
2057: my $maxtries = 5;
2058: my $tries = 1;
2059: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2060: $response = &get_query_reply($queryid);
2061: $tries ++;
2062: }
2063:
2064: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2065: if ($response eq 'unavailable') {
2066: $outcome = $response;
2067: } else {
2068: $outcome = 'ok';
2069: my @matches = split(/\n/,$response);
2070: foreach my $match (@matches) {
2071: my ($key,$value) = split(/=/,$match);
2072: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2073: }
1.899 raeburn 2074: }
2075: }
2076: }
1.909 raeburn 2077: return ($outcome,%results);
1.899 raeburn 2078: }
2079:
2080: sub usersearch {
2081: my ($srch) = @_;
2082: my $dom = $srch->{'srchdomain'};
2083: my %results;
2084: my %libserv = &all_library();
2085: my $query = 'usersearch';
2086: foreach my $tryserver (keys(%libserv)) {
2087: if (&host_domain($tryserver) eq $dom) {
1.1172.2.116 raeburn 2088: unless ($tryserver eq $perlvar{'lonHostID'}) {
2089: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2090: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119 raeburn 2091: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116 raeburn 2092: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2093: (($major == 2) && ($minor < 11)) ||
2094: (($major == 2) && ($minor == 11) && ($subver < 3)));
2095: }
2096: }
1.899 raeburn 2097: my $host=&hostname($tryserver);
2098: my $queryid=
1.911 raeburn 2099: &reply("querysend:".&escape($query).':'.
2100: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2101: &escape($srch->{'srchtype'}).':'.
2102: &escape($srch->{'srchterm'}),$tryserver);
2103: if ($queryid !~/^\Q$host\E\_/) {
2104: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2105: next;
1.899 raeburn 2106: }
2107: my $reply = &get_query_reply($queryid);
2108: my $maxtries = 1;
2109: my $tries = 1;
2110: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2111: $reply = &get_query_reply($queryid);
2112: $tries ++;
2113: }
2114: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2115: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2116: } else {
1.911 raeburn 2117: my @matches;
2118: if ($reply =~ /\n/) {
2119: @matches = split(/\n/,$reply);
2120: } else {
2121: @matches = split(/\&/,$reply);
2122: }
1.899 raeburn 2123: foreach my $match (@matches) {
2124: my ($uname,$udom,%userhash);
1.911 raeburn 2125: foreach my $entry (split(/:/,$match)) {
2126: my ($key,$value) =
2127: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2128: $userhash{$key} = $value;
2129: if ($key eq 'username') {
2130: $uname = $value;
2131: } elsif ($key eq 'domain') {
2132: $udom = $value;
1.911 raeburn 2133: }
1.899 raeburn 2134: }
2135: $results{$uname.':'.$udom} = \%userhash;
2136: }
2137: }
2138: }
2139: }
2140: return %results;
2141: }
2142:
1.912 raeburn 2143: sub get_instuser {
2144: my ($udom,$uname,$id) = @_;
2145: my $homeserver = &domain($udom,'primary');
2146: my ($outcome,%results);
2147: if ($homeserver ne '') {
2148: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2149: &escape($id).':'.&escape($udom),$homeserver);
2150: my $host=&hostname($homeserver);
2151: if ($queryid !~/^\Q$host\E\_/) {
2152: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2153: return;
2154: }
2155: my $response = &get_query_reply($queryid);
2156: my $maxtries = 5;
2157: my $tries = 1;
2158: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2159: $response = &get_query_reply($queryid);
2160: $tries ++;
2161: }
2162: if (!&error($response) && $response ne 'refused') {
2163: if ($response eq 'unavailable') {
2164: $outcome = $response;
2165: } else {
2166: $outcome = 'ok';
2167: my @matches = split(/\n/,$response);
2168: foreach my $match (@matches) {
2169: my ($key,$value) = split(/=/,$match);
2170: $results{&unescape($key)} = &thaw_unescape($value);
2171: }
2172: }
2173: }
2174: }
2175: my %userinfo;
2176: if (ref($results{$uname}) eq 'HASH') {
2177: %userinfo = %{$results{$uname}};
2178: }
2179: return ($outcome,%userinfo);
2180: }
2181:
1.1172.2.69 raeburn 2182: sub get_multiple_instusers {
2183: my ($udom,$users,$caller) = @_;
2184: my ($outcome,$results);
2185: if (ref($users) eq 'HASH') {
2186: my $count = keys(%{$users});
2187: my $requested = &freeze_escape($users);
2188: my $homeserver = &domain($udom,'primary');
2189: if ($homeserver ne '') {
2190: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2191: my $host=&hostname($homeserver);
2192: if ($queryid !~/^\Q$host\E\_/) {
2193: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2194: ' for host: '.$homeserver.'in domain '.$udom);
2195: return ($outcome,$results);
2196: }
2197: my $response = &get_query_reply($queryid);
2198: my $maxtries = 5;
2199: if ($count > 100) {
2200: $maxtries = 1+int($count/20);
2201: }
2202: my $tries = 1;
2203: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2204: $response = &get_query_reply($queryid);
2205: $tries ++;
2206: }
2207: if ($response eq '') {
2208: $results = {};
2209: foreach my $key (keys(%{$users})) {
2210: my ($uname,$id);
2211: if ($caller eq 'id') {
2212: $id = $key;
2213: } else {
2214: $uname = $key;
2215: }
2216: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2217: $outcome = $resp;
2218: if ($resp eq 'ok') {
2219: %{$results} = (%{$results}, %info);
2220: } else {
2221: last;
2222: }
2223: }
2224: } elsif(!&error($response) && ($response ne 'refused')) {
2225: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2226: $outcome = $response;
2227: } else {
2228: ($outcome,my $userdata) = split(/=/,$response,2);
2229: if ($outcome eq 'ok') {
2230: $results = &thaw_unescape($userdata);
2231: }
2232: }
2233: }
2234: }
2235: }
2236: return ($outcome,$results);
2237: }
2238:
1.912 raeburn 2239: sub inst_rulecheck {
1.923 raeburn 2240: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2241: my %returnhash;
2242: if ($udom ne '') {
2243: if (ref($rules) eq 'ARRAY') {
2244: @{$rules} = map {&escape($_);} (@{$rules});
2245: my $rulestr = join(':',@{$rules});
2246: my $homeserver=&domain($udom,'primary');
2247: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2248: my $response;
2249: if ($item eq 'username') {
2250: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2251: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2252: $homeserver));
1.923 raeburn 2253: } elsif ($item eq 'id') {
2254: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2255: ':'.&escape($id).':'.$rulestr,
2256: $homeserver));
1.945 raeburn 2257: } elsif ($item eq 'selfcreate') {
2258: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2259: &escape($udom).':'.&escape($uname).
2260: ':'.$rulestr,$homeserver));
1.923 raeburn 2261: }
1.912 raeburn 2262: if ($response ne 'refused') {
2263: my @pairs=split(/\&/,$response);
2264: foreach my $item (@pairs) {
2265: my ($key,$value)=split(/=/,$item,2);
2266: $key = &unescape($key);
2267: next if ($key =~ /^error: 2 /);
2268: $returnhash{$key}=&thaw_unescape($value);
2269: }
2270: }
2271: }
2272: }
2273: }
2274: return %returnhash;
2275: }
2276:
2277: sub inst_userrules {
1.923 raeburn 2278: my ($udom,$check) = @_;
1.912 raeburn 2279: my (%ruleshash,@ruleorder);
2280: if ($udom ne '') {
2281: my $homeserver=&domain($udom,'primary');
2282: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2283: my $response;
2284: if ($check eq 'id') {
2285: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2286: $homeserver);
1.943 raeburn 2287: } elsif ($check eq 'email') {
2288: $response=&reply('instemailrules:'.&escape($udom),
2289: $homeserver);
1.923 raeburn 2290: } else {
2291: $response=&reply('instuserrules:'.&escape($udom),
2292: $homeserver);
2293: }
1.912 raeburn 2294: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2295: ($response ne 'unknown_cmd') &&
1.912 raeburn 2296: ($response ne 'no_such_host')) {
2297: my ($hashitems,$orderitems) = split(/:/,$response);
2298: my @pairs=split(/\&/,$hashitems);
2299: foreach my $item (@pairs) {
2300: my ($key,$value)=split(/=/,$item,2);
2301: $key = &unescape($key);
2302: next if ($key =~ /^error: 2 /);
2303: $ruleshash{$key}=&thaw_unescape($value);
2304: }
2305: my @esc_order = split(/\&/,$orderitems);
2306: foreach my $item (@esc_order) {
2307: push(@ruleorder,&unescape($item));
2308: }
2309: }
2310: }
2311: }
2312: return (\%ruleshash,\@ruleorder);
2313: }
2314:
1.976 raeburn 2315: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2316:
2317: sub get_domain_defaults {
1.1172.2.35 raeburn 2318: my ($domain,$ignore_cache) = @_;
2319: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2320: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2321: unless ($ignore_cache) {
2322: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2323: if (defined($cached)) {
2324: if (ref($result) eq 'HASH') {
2325: return %{$result};
2326: }
1.943 raeburn 2327: }
2328: }
2329: my %domdefaults;
2330: my %domconfig =
1.989 raeburn 2331: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2332: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2333: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2334: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2335: 'coursecategories','autoenroll',
2336: 'helpsettings'],$domain);
1.1172.2.41 raeburn 2337: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2338: if (ref($domconfig{'defaults'}) eq 'HASH') {
2339: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2340: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2341: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2342: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2343: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2344: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2345: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2346: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2347: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2348: } else {
2349: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2350: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2351: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2352: }
1.976 raeburn 2353: if (ref($domconfig{'quotas'}) eq 'HASH') {
2354: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2355: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2356: } else {
2357: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2358: }
1.1172.2.6 raeburn 2359: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2360: foreach my $item (@usertools) {
2361: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2362: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2363: }
2364: }
1.1172.2.29 raeburn 2365: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2366: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2367: }
1.976 raeburn 2368: }
1.985 raeburn 2369: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2370: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2371: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2372: }
2373: }
1.1172.2.9 raeburn 2374: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2375: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2376: }
1.989 raeburn 2377: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2378: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2379: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2380: }
2381: }
1.1047 raeburn 2382: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2383: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2384: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2385: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2386: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2387: }
1.1172.2.41 raeburn 2388: foreach my $type (@coursetypes) {
2389: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2390: unless ($type eq 'community') {
2391: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2392: }
2393: }
2394: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2395: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2396: }
1.1172.2.60 raeburn 2397: if ($domdefaults{'postsubmit'} eq 'on') {
2398: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2399: $domdefaults{$type.'postsubtimeout'} =
2400: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2401: }
2402: }
1.1172.2.30 raeburn 2403: }
1.1172.2.67 raeburn 2404: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2405: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2406: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2407: if (@clonecodes) {
2408: $domdefaults{'canclone'} = join('+',@clonecodes);
2409: }
2410: }
2411: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2412: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2413: }
1.1172.2.103 raeburn 2414: if ($domconfig{'coursedefaults'}{'texengine'}) {
2415: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2416: }
1.1047 raeburn 2417: }
1.1073 raeburn 2418: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2419: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2420: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2421: }
2422: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2423: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2424: }
1.1172.2.62 raeburn 2425: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2426: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2427: }
1.1172.2.136! raeburn 2428: if (ref($domconfig{'usersessions'}{offloadoth'} eq 'HASH') {
! 2429: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
! 2430: }
1.1073 raeburn 2431: }
1.1172.2.41 raeburn 2432: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2433: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2434: my @settings = ('types','registered','enroll_dates','access_dates','section',
2435: 'approval','limit');
2436: foreach my $type (@coursetypes) {
2437: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2438: my @mgrdc = ();
2439: foreach my $item (@settings) {
2440: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2441: push(@mgrdc,$item);
2442: }
2443: }
2444: if (@mgrdc) {
2445: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2446: }
2447: }
2448: }
2449: }
2450: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2451: foreach my $type (@coursetypes) {
2452: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2453: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2454: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2455: }
2456: }
2457: }
2458: }
2459: }
1.1172.2.46 raeburn 2460: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2461: $domdefaults{'catauth'} = 'std';
2462: $domdefaults{'catunauth'} = 'std';
2463: if ($domconfig{'coursecategories'}{'auth'}) {
2464: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2465: }
2466: if ($domconfig{'coursecategories'}{'unauth'}) {
2467: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2468: }
2469: }
1.1172.2.76 raeburn 2470: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2471: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2472: }
1.1172.2.89 raeburn 2473: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2474: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2475: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2476: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2477: }
2478: }
1.1172.2.23 raeburn 2479: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2480: return %domdefaults;
2481: }
2482:
1.1172.2.106 raeburn 2483: sub get_dom_cats {
2484: my ($dom) = @_;
2485: return unless (&domain($dom));
2486: my ($cats,$cached)=&is_cached_new('cats',$dom);
2487: unless (defined($cached)) {
2488: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2489: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2490: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2491: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2492: } else {
2493: $cats = {};
2494: }
2495: } else {
2496: $cats = {};
2497: }
2498: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2499: }
2500: return $cats;
2501: }
2502:
2503: sub get_dom_instcats {
2504: my ($dom) = @_;
2505: return unless (&domain($dom));
2506: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2507: unless (defined($cached)) {
2508: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2509: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2510: if ($totcodes > 0) {
2511: my $caller = 'global';
2512: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2513: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2514: $instcats = {
2515: codes => \%codes,
2516: codetitles => \@codetitles,
2517: cat_titles => \%cat_titles,
2518: cat_order => \%cat_order,
2519: };
2520: &do_cache_new('instcats',$dom,$instcats,3600);
2521: }
2522: }
2523: }
2524: return $instcats;
2525: }
2526:
2527: sub retrieve_instcodes {
2528: my ($coursecodes,$dom) = @_;
2529: my $totcodes;
2530: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2531: foreach my $course (keys(%courses)) {
2532: if (ref($courses{$course}) eq 'HASH') {
2533: if ($courses{$course}{'inst_code'} ne '') {
2534: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2535: $totcodes ++;
2536: }
2537: }
2538: }
2539: return $totcodes;
2540: }
2541:
1.1172.2.113 raeburn 2542: # --------------------------------------------- Get domain config for passwords
2543:
2544: sub get_passwdconf {
2545: my ($dom) = @_;
2546: my (%passwdconf,$gotconf,$lookup);
2547: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2548: if (defined($cached)) {
2549: if (ref($result) eq 'HASH') {
2550: %passwdconf = %{$result};
2551: $gotconf = 1;
2552: }
2553: }
2554: unless ($gotconf) {
2555: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2556: if (ref($domconfig{'passwords'}) eq 'HASH') {
2557: %passwdconf = %{$domconfig{'passwords'}};
2558: }
2559: my $cachetime = 24*60*60;
2560: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2561: }
2562: return %passwdconf;
2563: }
2564:
1.344 www 2565: # --------------------------------------------------- Assign a key to a student
2566:
2567: sub assign_access_key {
1.364 www 2568: #
2569: # a valid key looks like uname:udom#comments
2570: # comments are being appended
2571: #
1.498 www 2572: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2573: $kdom=
1.620 albertel 2574: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2575: $knum=
1.620 albertel 2576: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2577: $cdom=
1.620 albertel 2578: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2579: $cnum=
1.620 albertel 2580: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2581: $udom=$env{'user.name'} unless (defined($udom));
2582: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2583: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2584: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2585: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2586: # assigned to this person
2587: # - this should not happen,
1.345 www 2588: # unless something went wrong
2589: # the first time around
2590: # ready to assign
1.364 www 2591: $logentry=$1.'; '.$logentry;
1.496 www 2592: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2593: $kdom,$knum) eq 'ok') {
1.345 www 2594: # key now belongs to user
1.346 www 2595: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2596: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2597: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2598: return 'ok';
2599: } else {
2600: return
2601: 'error: Count not permanently assign key, will need to be re-entered later.';
2602: }
2603: } else {
2604: return 'error: Could not assign key, try again later.';
2605: }
1.364 www 2606: } elsif (!$existing{$ckey}) {
1.345 www 2607: # the key does not exist
2608: return 'error: The key does not exist';
2609: } else {
2610: # the key is somebody else's
2611: return 'error: The key is already in use';
2612: }
1.344 www 2613: }
2614:
1.364 www 2615: # ------------------------------------------ put an additional comment on a key
2616:
2617: sub comment_access_key {
2618: #
2619: # a valid key looks like uname:udom#comments
2620: # comments are being appended
2621: #
2622: my ($ckey,$cdom,$cnum,$logentry)=@_;
2623: $cdom=
1.620 albertel 2624: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2625: $cnum=
1.620 albertel 2626: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2627: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2628: if ($existing{$ckey}) {
2629: $existing{$ckey}.='; '.$logentry;
2630: # ready to assign
1.367 www 2631: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2632: $cdom,$cnum) eq 'ok') {
2633: return 'ok';
2634: } else {
2635: return 'error: Count not store comment.';
2636: }
2637: } else {
2638: # the key does not exist
2639: return 'error: The key does not exist';
2640: }
2641: }
2642:
1.344 www 2643: # ------------------------------------------------------ Generate a set of keys
2644:
2645: sub generate_access_keys {
1.364 www 2646: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2647: $cdom=
1.620 albertel 2648: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2649: $cnum=
1.620 albertel 2650: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2651: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2652: unless (($cdom) && ($cnum)) { return 0; }
2653: if ($number>10000) { return 0; }
2654: sleep(2); # make sure don't get same seed twice
2655: srand(time()^($$+($$<<15))); # from "Programming Perl"
2656: my $total=0;
2657: for (my $i=1;$i<=$number;$i++) {
2658: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2659: sprintf("%lx",int(100000*rand)).'-'.
2660: sprintf("%lx",int(100000*rand));
2661: $newkey=~s/1/g/g; # folks mix up 1 and l
2662: $newkey=~s/0/h/g; # and also 0 and O
2663: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2664: if ($existing{$newkey}) {
2665: $i--;
2666: } else {
1.364 www 2667: if (&put('accesskeys',
2668: { $newkey => '# generated '.localtime().
1.620 albertel 2669: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2670: '; '.$logentry },
2671: $cdom,$cnum) eq 'ok') {
1.344 www 2672: $total++;
2673: }
2674: }
2675: }
1.620 albertel 2676: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2677: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2678: return $total;
2679: }
2680:
2681: # ------------------------------------------------------- Validate an accesskey
2682:
2683: sub validate_access_key {
2684: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2685: $cdom=
1.620 albertel 2686: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2687: $cnum=
1.620 albertel 2688: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2689: $udom=$env{'user.domain'} unless (defined($udom));
2690: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2691: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2692: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2693: }
2694:
2695: # ------------------------------------- Find the section of student in a course
1.652 albertel 2696: sub devalidate_getsection_cache {
2697: my ($udom,$unam,$courseid)=@_;
2698: my $hashid="$udom:$unam:$courseid";
2699: &devalidate_cache_new('getsection',$hashid);
2700: }
1.298 matthew 2701:
1.815 albertel 2702: sub courseid_to_courseurl {
2703: my ($courseid) = @_;
2704: #already url style courseid
2705: return $courseid if ($courseid =~ m{^/});
2706:
2707: if (exists($env{'course.'.$courseid.'.num'})) {
2708: my $cnum = $env{'course.'.$courseid.'.num'};
2709: my $cdom = $env{'course.'.$courseid.'.domain'};
2710: return "/$cdom/$cnum";
2711: }
2712:
2713: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2714: if (exists($courseinfo{'num'})) {
2715: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2716: }
2717:
2718: return undef;
2719: }
2720:
1.298 matthew 2721: sub getsection {
2722: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2723: my $cachetime=1800;
1.551 albertel 2724:
2725: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2726: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2727: if (defined($cached)) { return $result; }
2728:
1.298 matthew 2729: my %Pending;
2730: my %Expired;
2731: #
2732: # Each role can either have not started yet (pending), be active,
2733: # or have expired.
2734: #
2735: # If there is an active role, we are done.
2736: #
2737: # If there is more than one role which has not started yet,
2738: # choose the one which will start sooner
2739: # If there is one role which has not started yet, return it.
2740: #
2741: # If there is more than one expired role, choose the one which ended last.
2742: # If there is a role which has expired, return it.
2743: #
1.815 albertel 2744: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2745: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2746: foreach my $key (keys(%roleshash)) {
1.479 albertel 2747: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2748: my $section=$1;
2749: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2750: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2751: my $now=time;
1.548 albertel 2752: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2753: $Expired{$end}=$section;
2754: next;
2755: }
1.548 albertel 2756: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2757: $Pending{$start}=$section;
2758: next;
2759: }
1.599 albertel 2760: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2761: }
2762: #
2763: # Presumedly there will be few matching roles from the above
2764: # loop and the sorting time will be negligible.
2765: if (scalar(keys(%Pending))) {
2766: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2767: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2768: }
2769: if (scalar(keys(%Expired))) {
2770: my @sorted = sort {$a <=> $b} keys(%Expired);
2771: my $time = pop(@sorted);
1.599 albertel 2772: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2773: }
1.599 albertel 2774: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2775: }
1.70 www 2776:
1.599 albertel 2777: sub save_cache {
2778: &purge_remembered();
1.722 albertel 2779: #&Apache::loncommon::validate_page();
1.620 albertel 2780: undef(%env);
1.780 albertel 2781: undef($env_loaded);
1.599 albertel 2782: }
1.452 albertel 2783:
1.599 albertel 2784: my $to_remember=-1;
2785: my %remembered;
2786: my %accessed;
2787: my $kicks=0;
2788: my $hits=0;
1.849 albertel 2789: sub make_key {
2790: my ($name,$id) = @_;
1.872 albertel 2791: if (length($id) > 65
2792: && length(&escape($id)) > 200) {
2793: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2794: }
1.849 albertel 2795: return &escape($name.':'.$id);
2796: }
2797:
1.599 albertel 2798: sub devalidate_cache_new {
2799: my ($name,$id,$debug) = @_;
2800: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2801: my $remembered_id=$name.':'.$id;
1.849 albertel 2802: $id=&make_key($name,$id);
1.599 albertel 2803: $memcache->delete($id);
1.1172.2.81 raeburn 2804: delete($remembered{$remembered_id});
2805: delete($accessed{$remembered_id});
1.599 albertel 2806: }
2807:
2808: sub is_cached_new {
2809: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2810: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2811: # keys in %remembered hash, which persists for
2812: # duration of request (no restriction on key length).
2813: if (exists($remembered{$remembered_id})) {
2814: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2815: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2816: $hits++;
1.1172.2.81 raeburn 2817: return ($remembered{$remembered_id},1);
1.599 albertel 2818: }
1.1172.2.81 raeburn 2819: $id=&make_key($name,$id);
1.599 albertel 2820: my $value = $memcache->get($id);
2821: if (!(defined($value))) {
2822: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2823: return (undef,undef);
1.416 albertel 2824: }
1.599 albertel 2825: if ($value eq '__undef__') {
2826: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2827: $value=undef;
2828: }
1.1172.2.81 raeburn 2829: &make_room($remembered_id,$value,$debug);
1.599 albertel 2830: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2831: return ($value,1);
2832: }
2833:
2834: sub do_cache_new {
2835: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2836: my $remembered_id=$name.':'.$id;
1.849 albertel 2837: $id=&make_key($name,$id);
1.599 albertel 2838: my $setvalue=$value;
2839: if (!defined($setvalue)) {
2840: $setvalue='__undef__';
2841: }
1.623 albertel 2842: if (!defined($time) ) {
2843: $time=600;
2844: }
1.599 albertel 2845: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2846: my $result = $memcache->set($id,$setvalue,$time);
2847: if (! $result) {
1.872 albertel 2848: &logthis("caching of id -> $id failed");
1.910 albertel 2849: $memcache->disconnect_all();
1.872 albertel 2850: }
1.600 albertel 2851: # need to make a copy of $value
1.1172.2.81 raeburn 2852: &make_room($remembered_id,$value,$debug);
1.599 albertel 2853: return $value;
2854: }
2855:
2856: sub make_room {
1.1172.2.81 raeburn 2857: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2858:
1.1172.2.81 raeburn 2859: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2860: : $value;
1.599 albertel 2861: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2862: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2863: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2864: my $to_kick;
2865: my $max_time=0;
2866: foreach my $other (keys(%accessed)) {
2867: if (&tv_interval($accessed{$other}) > $max_time) {
2868: $to_kick=$other;
2869: $max_time=&tv_interval($accessed{$other});
2870: }
2871: }
2872: delete($remembered{$to_kick});
2873: delete($accessed{$to_kick});
2874: $kicks++;
2875: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2876: return;
2877: }
2878:
1.599 albertel 2879: sub purge_remembered {
1.604 albertel 2880: #&logthis("Tossing ".scalar(keys(%remembered)));
2881: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2882: undef(%remembered);
2883: undef(%accessed);
1.428 albertel 2884: }
1.70 www 2885: # ------------------------------------- Read an entry from a user's environment
2886:
2887: sub userenvironment {
2888: my ($udom,$unam,@what)=@_;
1.976 raeburn 2889: my $items;
2890: foreach my $item (@what) {
2891: $items.=&escape($item).'&';
2892: }
2893: $items=~s/\&$//;
1.70 www 2894: my %returnhash=();
1.1009 raeburn 2895: my $uhome = &homeserver($unam,$udom);
2896: unless ($uhome eq 'no_host') {
2897: my @answer=split(/\&/,
2898: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2899: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2900: return %returnhash;
2901: }
1.1009 raeburn 2902: my $i;
2903: for ($i=0;$i<=$#what;$i++) {
2904: $returnhash{$what[$i]}=&unescape($answer[$i]);
2905: }
1.70 www 2906: }
2907: return %returnhash;
1.1 albertel 2908: }
2909:
1.617 albertel 2910: # ---------------------------------------------------------- Get a studentphoto
2911: sub studentphoto {
2912: my ($udom,$unam,$ext) = @_;
2913: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2914: if (defined($env{'request.course.id'})) {
1.708 raeburn 2915: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2916: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2917: return(&retrievestudentphoto($udom,$unam,$ext));
2918: } else {
2919: my ($result,$perm_reqd)=
1.707 albertel 2920: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2921: if ($result eq 'ok') {
2922: if (!($perm_reqd eq 'yes')) {
2923: return(&retrievestudentphoto($udom,$unam,$ext));
2924: }
2925: }
2926: }
2927: }
2928: } else {
2929: my ($result,$perm_reqd) =
1.707 albertel 2930: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2931: if ($result eq 'ok') {
2932: if (!($perm_reqd eq 'yes')) {
2933: return(&retrievestudentphoto($udom,$unam,$ext));
2934: }
2935: }
2936: }
2937: return '/adm/lonKaputt/lonlogo_broken.gif';
2938: }
2939:
2940: sub retrievestudentphoto {
2941: my ($udom,$unam,$ext,$type) = @_;
2942: my $home=&Apache::lonnet::homeserver($unam,$udom);
2943: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2944: if ($ret eq 'ok') {
2945: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2946: if ($type eq 'thumbnail') {
2947: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2948: }
2949: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2950: return $tokenurl;
2951: } else {
2952: if ($type eq 'thumbnail') {
2953: return '/adm/lonKaputt/genericstudent_tn.gif';
2954: } else {
2955: return '/adm/lonKaputt/lonlogo_broken.gif';
2956: }
1.617 albertel 2957: }
2958: }
2959:
1.263 www 2960: # -------------------------------------------------------------------- New chat
2961:
2962: sub chatsend {
1.724 raeburn 2963: my ($newentry,$anon,$group)=@_;
1.620 albertel 2964: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2965: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2966: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2967: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2968: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2969: &escape($newentry)).':'.$group,$chome);
1.292 www 2970: }
2971:
2972: # ------------------------------------------ Find current version of a resource
2973:
2974: sub getversion {
2975: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2976: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2977: return ¤tversion(&filelocation('',$fname));
2978: }
2979:
2980: sub currentversion {
2981: my $fname=shift;
2982: my $author=$fname;
2983: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2984: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2985: my $home=&homeserver($uname,$udom);
1.292 www 2986: if ($home eq 'no_host') {
2987: return -1;
2988: }
1.1112 www 2989: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2990: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2991: return -1;
2992: }
1.1112 www 2993: return $answer;
1.263 www 2994: }
2995:
1.1111 www 2996: #
2997: # Return special version number of resource if set by override, empty otherwise
2998: #
2999: sub usedversion {
3000: my $fname=shift;
3001: unless ($fname) { $fname=$env{'request.uri'}; }
3002: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3003: if ($urlversion) { return $urlversion; }
3004: return '';
3005: }
3006:
1.1 albertel 3007: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3008:
1.1 albertel 3009: sub subscribe {
3010: my $fname=shift;
1.761 raeburn 3011: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3012: $fname=~s/[\n\r]//g;
1.1 albertel 3013: my $author=$fname;
3014: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3015: my ($udom,$uname)=split(/\//,$author);
3016: my $home=homeserver($uname,$udom);
1.335 albertel 3017: if ($home eq 'no_host') {
3018: return 'not_found';
1.1 albertel 3019: }
3020: my $answer=reply("sub:$fname",$home);
1.64 www 3021: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3022: $answer.=' by '.$home;
3023: }
1.1 albertel 3024: return $answer;
3025: }
3026:
1.8 www 3027: # -------------------------------------------------------------- Replicate file
3028:
3029: sub repcopy {
3030: my $filename=shift;
1.23 www 3031: $filename=~s/\/+/\//g;
1.1142 raeburn 3032: my $londocroot = $perlvar{'lonDocRoot'};
3033: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3034: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3035: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3036: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3037: return &repcopy_userfile($filename);
3038: }
1.532 albertel 3039: $filename=~s/[\n\r]//g;
1.8 www 3040: my $transname="$filename.in.transfer";
1.828 www 3041: # FIXME: this should flock
1.607 raeburn 3042: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3043: my $remoteurl=subscribe($filename);
1.64 www 3044: if ($remoteurl =~ /^con_lost by/) {
3045: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3046: return 'unavailable';
1.8 www 3047: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3048: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3049: return 'not_found';
1.64 www 3050: } elsif ($remoteurl =~ /^rejected by/) {
3051: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3052: return 'forbidden';
1.20 www 3053: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3054: return 'ok';
1.8 www 3055: } else {
1.290 www 3056: my $author=$filename;
3057: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3058: my ($udom,$uname)=split(/\//,$author);
3059: my $home=homeserver($uname,$udom);
3060: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3061: my @parts=split(/\//,$filename);
3062: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3063: if ($path ne "$londocroot/res") {
1.8 www 3064: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3065: return 'bad_request';
1.8 www 3066: }
3067: my $count;
3068: for ($count=5;$count<$#parts;$count++) {
3069: $path.="/$parts[$count]";
3070: if ((-e $path)!=1) {
3071: mkdir($path,0777);
3072: }
3073: }
3074: my $ua=new LWP::UserAgent;
3075: my $request=new HTTP::Request('GET',"$remoteurl");
3076: my $response=$ua->request($request,$transname);
3077: if ($response->is_error()) {
3078: unlink($transname);
3079: my $message=$response->status_line;
1.672 albertel 3080: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3081: ." LWP get: $message: $filename</font>");
1.607 raeburn 3082: return 'unavailable';
1.8 www 3083: } else {
1.16 www 3084: if ($remoteurl!~/\.meta$/) {
3085: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3086: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3087: if ($mresponse->is_error()) {
3088: unlink($filename.'.meta');
3089: &logthis(
1.672 albertel 3090: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3091: }
3092: }
1.8 www 3093: rename($transname,$filename);
1.607 raeburn 3094: return 'ok';
1.8 www 3095: }
1.290 www 3096: }
1.8 www 3097: }
1.330 www 3098: }
3099:
1.1172.2.124 raeburn 3100: # ------------------------------------------------- Unsubscribe from a resource
3101:
3102: sub unsubscribe {
3103: my ($fname) = @_;
3104: my $answer;
3105: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3106: $fname=~s/[\n\r]//g;
3107: my $author=$fname;
3108: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3109: my ($udom,$uname)=split(/\//,$author);
3110: my $home=homeserver($uname,$udom);
3111: if ($home eq 'no_host') {
3112: $answer = 'no_host';
3113: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3114: $answer = 'home';
3115: } else {
1.1172.2.125 raeburn 3116: $answer = reply("unsub:$fname",$home);
1.1172.2.124 raeburn 3117: }
3118: return $answer;
3119: }
3120:
1.330 www 3121: # ------------------------------------------------ Get server side include body
3122: sub ssi_body {
1.381 albertel 3123: my ($filelink,%form)=@_;
1.606 matthew 3124: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3125: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3126: }
1.953 www 3127: my $output='';
3128: my $response;
1.980 raeburn 3129: if ($filelink=~/^https?\:/) {
1.954 raeburn 3130: ($output,$response)=&externalssi($filelink);
1.953 www 3131: } else {
1.1004 droeschl 3132: $filelink .= $filelink=~/\?/ ? '&' : '?';
3133: $filelink .= 'inhibitmenu=yes';
1.953 www 3134: ($output,$response)=&ssi($filelink,%form);
3135: }
1.778 albertel 3136: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3137: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3138: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3139: if (wantarray) {
3140: return ($output, $response);
3141: } else {
3142: return $output;
3143: }
1.8 www 3144: }
3145:
1.15 www 3146: # --------------------------------------------------------- Server Side Include
3147:
1.782 albertel 3148: sub absolute_url {
3149: my ($host_name) = @_;
3150: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3151: if ($host_name eq '') {
3152: $host_name = $ENV{'SERVER_NAME'};
3153: }
3154: return $protocol.$host_name;
3155: }
3156:
1.942 foxr 3157: #
3158: # Server side include.
3159: # Parameters:
3160: # fn Possibly encrypted resource name/id.
3161: # form Hash that describes how the rendering should be done
3162: # and other things.
1.944 foxr 3163: # Returns:
1.950 raeburn 3164: # Scalar context: The content of the response.
3165: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3166: #
1.15 www 3167: sub ssi {
3168:
1.944 foxr 3169: my ($fn,%form)=@_;
1.1172.2.100 raeburn 3170: my ($request,$response);
1.711 albertel 3171:
3172: $form{'no_update_last_known'}=1;
1.895 albertel 3173: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3174: if (%form) {
1.782 albertel 3175: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 3176: $request->content(join('&',map {
3177: my $name = escape($_);
3178: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3179: ? join("&$name=", map {escape($_) } @{$form{$_}})
3180: : &escape($form{$_}) );
3181: } keys(%form)));
1.23 www 3182: } else {
1.782 albertel 3183: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3184: }
3185:
1.15 www 3186: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100 raeburn 3187:
1.1172.2.101 raeburn 3188: if (($env{'request.course.id'}) &&
3189: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3190: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3191: ($form{'grade_symb'} ne '') &&
3192: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3193: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100 raeburn 3194: if (LWP::UserAgent->VERSION >= 5.834) {
3195: my $ua=new LWP::UserAgent;
3196: $ua->local_address('127.0.0.1');
3197: $response = $ua->request($request);
3198: } else {
3199: {
3200: require LWP::Protocol::http;
3201: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3202: my $ua=new LWP::UserAgent;
3203: $response = $ua->request($request);
3204: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3205: }
3206: }
3207: } else {
3208: my $ua=new LWP::UserAgent;
3209: $response = $ua->request($request);
3210: }
1.944 foxr 3211: if (wantarray) {
1.1172.2.3 raeburn 3212: return ($response->content, $response);
1.944 foxr 3213: } else {
1.1172.2.3 raeburn 3214: return $response->content;
1.942 foxr 3215: }
1.324 www 3216: }
3217:
3218: sub externalssi {
3219: my ($url)=@_;
3220: my $ua=new LWP::UserAgent;
3221: my $request=new HTTP::Request('GET',$url);
3222: my $response=$ua->request($request);
1.954 raeburn 3223: if (wantarray) {
3224: return ($response->content, $response);
3225: } else {
3226: return $response->content;
3227: }
1.15 www 3228: }
1.254 www 3229:
1.1172.2.98 raeburn 3230: # If the local copy of a replicated resource is outdated, trigger a
3231: # connection from the homeserver to flush the delayed queue. If no update
3232: # happens, remove local copies of outdated resource (and corresponding
3233: # metadata file).
3234:
3235: sub remove_stale_resfile {
3236: my ($url) = @_;
3237: my $removed;
3238: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3239: my $audom = $1;
3240: my $auname = $2;
3241: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3242: my $homeserver = &homeserver($auname,$audom);
3243: unless (($homeserver eq 'no_host') ||
3244: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3245: my $fname = &filelocation('',$url);
3246: if (-e $fname) {
3247: my $hostname = &hostname($homeserver);
3248: if ($hostname) {
1.1172.2.120 raeburn 3249: my $protocol = $protocol{$homeserver};
3250: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98 raeburn 3251: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120 raeburn 3252: my $ua=new LWP::UserAgent;
3253: $ua->timeout(5);
1.1172.2.98 raeburn 3254: my $request=new HTTP::Request('HEAD',$uri);
3255: my $response=$ua->request($request);
3256: if ($response->is_success()) {
3257: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3258: my $locmodtime = (stat($fname))[9];
3259: if ($locmodtime < $remmodtime) {
3260: my $stale;
3261: my $answer = &reply('pong',$homeserver);
3262: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3263: sleep(0.2);
3264: $locmodtime = (stat($fname))[9];
3265: if ($locmodtime < $remmodtime) {
3266: my $posstransfer = $fname.'.in.transfer';
3267: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3268: $removed = 1;
3269: } else {
3270: $stale = 1;
3271: }
3272: } else {
3273: $removed = 1;
3274: }
3275: } else {
3276: $stale = 1;
3277: }
3278: if ($stale) {
1.1172.2.124 raeburn 3279: if (unlink($fname)) {
3280: if ($uri!~/\.meta$/) {
3281: if (-e $fname.'.meta') {
3282: unlink($fname.'.meta');
3283: }
3284: }
3285: my $unsubresult = &unsubscribe($fname);
3286: unless ($unsubresult eq 'ok') {
3287: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3288: }
3289: $removed = 1;
1.1172.2.98 raeburn 3290: }
3291: }
3292: }
3293: }
3294: }
3295: }
3296: }
3297: }
3298: }
3299: return $removed;
3300: }
3301:
1.492 albertel 3302: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3303:
3304: sub allowuploaded {
3305: my ($srcurl,$url)=@_;
3306: $url=&clutter(&declutter($url));
3307: my $dir=$url;
3308: $dir=~s/\/[^\/]+$//;
3309: my %httpref=();
3310: my $httpurl=&hreflocation('',$url);
3311: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3312: &Apache::lonnet::appenv(\%httpref);
1.254 www 3313: }
1.477 raeburn 3314:
1.1172.2.13 raeburn 3315: #
3316: # Determine if the current user should be able to edit a particular resource,
3317: # when viewing in course context.
3318: # (a) When viewing resource used to determine if "Edit" item is included in
3319: # Functions.
3320: # (b) When displaying folder contents in course editor, used to determine if
3321: # "Edit" link will be displayed alongside resource.
3322: #
3323: # input: six args -- filename (decluttered), course number, course domain,
3324: # url, symb (if registered) and group (if this is a group
3325: # item -- e.g., bulletin board, group page etc.).
3326: # output: array of five scalars --
3327: # $cfile -- url for file editing if editable on current server
3328: # $home -- homeserver of resource (i.e., for author if published,
3329: # or course if uploaded.).
3330: # $switchserver -- 1 if server switch will be needed.
3331: # $forceedit -- 1 if icon/link should be to go to edit mode
3332: # $forceview -- 1 if icon/link should be to go to view mode
3333: #
3334:
3335: sub can_edit_resource {
3336: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3337: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3338: #
3339: # For aboutme pages user can only edit his/her own.
3340: #
3341: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3342: my ($sdom,$sname) = ($1,$2);
3343: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3344: $home = $env{'user.home'};
3345: $cfile = $resurl;
3346: if ($env{'form.forceedit'}) {
3347: $forceview = 1;
3348: } else {
3349: $forceedit = 1;
3350: }
3351: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3352: } else {
3353: return;
3354: }
3355: }
3356:
3357: if ($env{'request.course.id'}) {
3358: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3359: if ($group ne '') {
3360: # if this is a group homepage or group bulletin board, check group privs
3361: my $allowed = 0;
3362: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3363: if ((&allowed('mdg',$env{'request.course.id'}.
3364: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3365: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3366: $allowed = 1;
3367: }
3368: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3369: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3370: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3371: $allowed = 1;
3372: }
3373: }
3374: if ($allowed) {
3375: $home=&homeserver($cnum,$cdom);
3376: if ($env{'form.forceedit'}) {
3377: $forceview = 1;
3378: } else {
3379: $forceedit = 1;
3380: }
3381: $cfile = $resurl;
3382: } else {
3383: return;
3384: }
3385: } else {
1.1172.2.15 raeburn 3386: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3387: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3388: return;
3389: }
3390: } elsif (!$crsedit) {
1.1172.2.13 raeburn 3391: #
3392: # No edit allowed where CC has switched to student role.
3393: #
3394: return;
3395: }
3396: }
3397: }
3398:
3399: if ($file ne '') {
3400: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3401: if (&is_course_upload($file,$cnum,$cdom)) {
3402: $uploaded = 1;
3403: $incourse = 1;
3404: if ($file =~/\.(htm|html|css|js|txt)$/) {
3405: $cfile = &hreflocation('',$file);
3406: if ($env{'form.forceedit'}) {
3407: $forceview = 1;
3408: } else {
3409: $forceedit = 1;
3410: }
3411: }
3412: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3413: $incourse = 1;
3414: if ($env{'form.forceedit'}) {
3415: $forceview = 1;
3416: } else {
3417: $forceedit = 1;
3418: }
3419: $cfile = $resurl;
3420: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3421: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3422: $incourse = 1;
3423: if ($env{'form.forceedit'}) {
3424: $forceview = 1;
3425: } else {
3426: $forceedit = 1;
3427: }
3428: $cfile = $resurl;
3429: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3430: $incourse = 1;
3431: $cfile = $resurl.'/smpedit';
3432: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3433: $incourse = 1;
3434: if ($env{'form.forceedit'}) {
3435: $forceview = 1;
3436: } else {
3437: $forceedit = 1;
3438: }
3439: $cfile = $resurl;
1.1172.2.122 raeburn 3440: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3441: my ($map,$id,$res) = &decode_symb($symb);
3442: if ($map =~ /\.page$/) {
3443: $incourse = 1;
3444: if ($env{'form.forceedit'}) {
3445: $forceview = 1;
3446: $cfile = $map;
3447: } else {
3448: $forceedit = 1;
3449: $cfile = '/adm/wrapper'.$resurl;
3450: }
3451: }
1.1172.2.15 raeburn 3452: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3453: $incourse = 1;
3454: if ($env{'form.forceedit'}) {
3455: $forceview = 1;
3456: } else {
3457: $forceedit = 1;
3458: }
3459: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3460: }
3461: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3462: my $template = '/res/lib/templates/simpleproblem.problem';
3463: if (&is_on_map($template)) {
3464: $incourse = 1;
3465: $forceview = 1;
3466: $cfile = $template;
3467: }
3468: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118 raeburn 3469: $incourse = 1;
3470: if ($env{'form.forceedit'}) {
3471: $forceview = 1;
3472: } else {
3473: $forceedit = 1;
3474: }
3475: $cfile = $resurl;
1.1172.2.13 raeburn 3476: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3477: $incourse = 1;
3478: $forceview = 1;
3479: if ($symb) {
3480: my ($map,$id,$res)=&decode_symb($symb);
3481: $env{'request.symb'} = $symb;
3482: $cfile = &clutter($res);
3483: } else {
3484: $cfile = $env{'form.suppurl'};
3485: $cfile =~ s{^http://}{};
3486: $cfile = '/adm/wrapper/ext/'.$cfile;
3487: }
1.1172.2.31 raeburn 3488: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3489: if ($env{'form.forceedit'}) {
3490: $forceview = 1;
3491: } else {
3492: $forceedit = 1;
3493: }
3494: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3495: }
3496: }
3497: if ($uploaded || $incourse) {
3498: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3499: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3500: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3501: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3502: # Check that the user has permission to edit this resource
3503: my $setpriv = 1;
3504: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3505: if (defined($cfudom)) {
3506: $home=&homeserver($cfuname,$cfudom);
3507: $cfile=$file;
3508: }
3509: }
3510: if (($cfile ne '') && (!$incourse || $uploaded) &&
3511: (($home ne '') && ($home ne 'no_host'))) {
3512: my @ids=¤t_machine_ids();
3513: unless (grep(/^\Q$home\E$/,@ids)) {
3514: $switchserver=1;
3515: }
3516: }
3517: }
3518: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3519: }
3520:
3521: sub is_course_upload {
3522: my ($file,$cnum,$cdom) = @_;
3523: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3524: $uploadpath =~ s{^\/}{};
3525: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3526: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3527: return 1;
3528: }
3529: return;
3530: }
3531:
3532: sub in_course {
3533: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3534: if ($hideprivileged) {
3535: my $skipuser;
1.1172.2.23 raeburn 3536: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3537: my @possdoms = ($cdom);
3538: if ($coursehash{'checkforpriv'}) {
3539: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3540: }
3541: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3542: $skipuser = 1;
3543: if ($coursehash{'nothideprivileged'}) {
3544: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3545: my $user;
3546: if ($item =~ /:/) {
3547: $user = $item;
3548: } else {
3549: $user = join(':',split(/[\@]/,$item));
3550: }
3551: if ($user eq $uname.':'.$udom) {
3552: undef($skipuser);
3553: last;
3554: }
3555: }
3556: }
3557: if ($skipuser) {
3558: return 0;
3559: }
3560: }
3561: }
3562: $type ||= 'any';
3563: if (!defined($cdom) || !defined($cnum)) {
3564: my $cid = $env{'request.course.id'};
3565: $cdom = $env{'course.'.$cid.'.domain'};
3566: $cnum = $env{'course.'.$cid.'.num'};
3567: }
3568: my $typesref;
3569: if (($type eq 'any') || ($type eq 'all')) {
3570: $typesref = ['active','previous','future'];
3571: } elsif ($type eq 'previous' || $type eq 'future') {
3572: $typesref = [$type];
3573: }
3574: my %roles = &get_my_roles($uname,$udom,'userroles',
3575: $typesref,undef,[$cdom]);
3576: my ($tmp) = keys(%roles);
3577: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3578: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3579: if (@course_roles > 0) {
3580: return 1;
3581: }
3582: return 0;
3583: }
3584:
1.478 albertel 3585: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3586: # input: action, courseID, current domain, intended
1.637 raeburn 3587: # path to file, source of file, instruction to parse file for objects,
3588: # ref to hash for embedded objects,
3589: # ref to hash for codebase of java objects.
1.1095 raeburn 3590: # reference to scalar to accommodate mime type determined
3591: # from File::MMagic if $parser = parse.
1.637 raeburn 3592: #
1.485 raeburn 3593: # output: url to file (if action was uploaddoc),
3594: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3595: #
1.478 albertel 3596: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3597: # course.
1.477 raeburn 3598: #
1.478 albertel 3599: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3600: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3601: # course's home server.
1.477 raeburn 3602: #
1.478 albertel 3603: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3604: # be copied from $source (current location) to
3605: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3606: # and will then be copied to
3607: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3608: # course's home server.
1.485 raeburn 3609: #
1.481 raeburn 3610: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3611: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3612: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3613: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3614: # in course's home server.
1.637 raeburn 3615: #
1.477 raeburn 3616:
3617: sub process_coursefile {
1.1095 raeburn 3618: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3619: $mimetype)=@_;
1.477 raeburn 3620: my $fetchresult;
1.638 albertel 3621: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3622: if ($action eq 'propagate') {
1.638 albertel 3623: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3624: $home);
1.481 raeburn 3625: } else {
1.477 raeburn 3626: my $fpath = '';
3627: my $fname = $file;
1.478 albertel 3628: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3629: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3630: my $filepath = &build_filepath($fpath);
1.481 raeburn 3631: if ($action eq 'copy') {
3632: if ($source eq '') {
3633: $fetchresult = 'no source file';
3634: return $fetchresult;
3635: } else {
3636: my $destination = $filepath.'/'.$fname;
3637: rename($source,$destination);
3638: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3639: $home);
1.481 raeburn 3640: }
3641: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3642: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3643: print $fh $env{'form.'.$source};
1.481 raeburn 3644: close($fh);
1.637 raeburn 3645: if ($parser eq 'parse') {
1.1024 raeburn 3646: my $mm = new File::MMagic;
1.1095 raeburn 3647: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3648: if ($type eq 'text/html') {
1.1024 raeburn 3649: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3650: unless ($parse_result eq 'ok') {
3651: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3652: }
1.637 raeburn 3653: }
1.1095 raeburn 3654: if (ref($mimetype)) {
3655: $$mimetype = $type;
3656: }
1.637 raeburn 3657: }
1.477 raeburn 3658: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3659: $home);
1.481 raeburn 3660: if ($fetchresult eq 'ok') {
3661: return '/uploaded/'.$fpath.'/'.$fname;
3662: } else {
3663: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3664: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3665: return '/adm/notfound.html';
3666: }
1.477 raeburn 3667: }
3668: }
1.485 raeburn 3669: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3670: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3671: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3672: }
3673: return $fetchresult;
3674: }
3675:
1.637 raeburn 3676: sub build_filepath {
3677: my ($fpath) = @_;
3678: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3679: unless ($fpath eq '') {
3680: my @parts=split('/',$fpath);
3681: foreach my $part (@parts) {
3682: $filepath.= '/'.$part;
3683: if ((-e $filepath)!=1) {
3684: mkdir($filepath,0777);
3685: }
3686: }
3687: }
3688: return $filepath;
3689: }
3690:
3691: sub store_edited_file {
1.638 albertel 3692: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3693: my $file = $primary_url;
3694: $file =~ s#^/uploaded/$docudom/$docuname/##;
3695: my $fpath = '';
3696: my $fname = $file;
3697: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3698: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3699: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 3700: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3701: print $fh $content;
3702: close($fh);
1.638 albertel 3703: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3704: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3705: $home);
1.637 raeburn 3706: if ($$fetchresult eq 'ok') {
3707: return '/uploaded/'.$fpath.'/'.$fname;
3708: } else {
1.638 albertel 3709: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3710: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3711: return '/adm/notfound.html';
3712: }
3713: }
3714:
1.531 albertel 3715: sub clean_filename {
1.831 albertel 3716: my ($fname,$args)=@_;
1.315 www 3717: # Replace Windows backslashes by forward slashes
1.257 www 3718: $fname=~s/\\/\//g;
1.831 albertel 3719: if (!$args->{'keep_path'}) {
3720: # Get rid of everything but the actual filename
3721: $fname=~s/^.*\/([^\/]+)$/$1/;
3722: }
1.315 www 3723: # Replace spaces by underscores
3724: $fname=~s/\s+/\_/g;
1.1172.2.110 raeburn 3725: # Transliterate non-ascii text to ascii
3726: my $lang = &Apache::lonlocal::current_language();
3727: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3728: # Replace all other weird characters by nothing
1.831 albertel 3729: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3730: # Replace all .\d. sequences with _\d. so they no longer look like version
3731: # numbers
3732: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3733: return $fname;
3734: }
1.1172.2.110 raeburn 3735:
1.1051 raeburn 3736: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3737: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3738: # image with the same aspect ratio as the original, but with dimensions which do
3739: # not exceed $resizewidth and $resizeheight.
3740:
1.984 neumanie 3741: sub resizeImage {
1.1051 raeburn 3742: my ($img_path,$resizewidth,$resizeheight) = @_;
3743: my $ima = Image::Magick->new;
3744: my $resized;
3745: if (-e $img_path) {
3746: $ima->Read($img_path);
3747: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3748: my $width = $ima->Get('width');
3749: my $height = $ima->Get('height');
3750: if ($width > $resizewidth) {
3751: my $factor = $width/$resizewidth;
3752: my $newheight = $height/$factor;
3753: $ima->Scale(width=>$resizewidth,height=>$newheight);
3754: $resized = 1;
3755: }
3756: }
3757: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3758: my $width = $ima->Get('width');
3759: my $height = $ima->Get('height');
3760: if ($height > $resizeheight) {
3761: my $factor = $height/$resizeheight;
3762: my $newwidth = $width/$factor;
3763: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3764: $resized = 1;
3765: }
3766: }
3767: if ($resized) {
3768: $ima->Write($img_path);
3769: }
3770: }
3771: return;
1.977 amueller 3772: }
3773:
1.608 albertel 3774: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3775: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3776: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3777: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.109 raeburn 3778: # canceloverwrite, scantron or ''.
1.1090 raeburn 3779: # if 'coursedoc': upload to the current course
3780: # if 'existingfile': write file to tmp/overwrites directory
3781: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3782: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3783: # $subdir - directory in userfile to store the file into
1.1172.2.109 raeburn 3784: # $parser - instruction to parse file for objects ($parser = parse) or
3785: # if context is 'scantron', $parser is hashref of csv column mapping
3786: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3787: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3788: # $allfiles - reference to hash for embedded objects
3789: # $codebase - reference to hash for codebase of java objects
3790: # $desuname - username for permanent storage of uploaded file
3791: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3792: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3793: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3794: # $resizewidth - width (pixels) to which to resize uploaded image
3795: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3796: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3797: # from File::MMagic.
1.858 raeburn 3798: #
1.686 albertel 3799: # output: url of file in userspace, or error: <message>
3800: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3801:
1.531 albertel 3802: sub userfileupload {
1.1090 raeburn 3803: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3804: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3805: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3806: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3807: $fname=&clean_filename($fname);
1.1090 raeburn 3808: # See if there is anything left
1.257 www 3809: unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110 raeburn 3810: # If filename now begins with a . prepend unix timestamp _ milliseconds
3811: if ($fname =~ /^\./) {
3812: my ($s,$usec) = &gettimeofday();
3813: while (length($usec) < 6) {
3814: $usec = '0'.$usec;
3815: }
3816: $fname = $s.'_'.substr($usec,0,3).$fname;
3817: }
1.1090 raeburn 3818: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3819: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3820: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3821: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3822: my $now = time;
1.1090 raeburn 3823: my $filepath;
1.1095 raeburn 3824: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3825: $filepath = 'tmp/helprequests/'.$now;
3826: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3827: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3828: '_'.$env{'user.domain'}.'/pending';
3829: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3830: my ($docuname,$docudom);
1.1172.2.96 raeburn 3831: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3832: $docudom = $destudom;
3833: } else {
3834: $docudom = $env{'user.domain'};
3835: }
1.1172.2.96 raeburn 3836: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3837: $docuname = $destuname;
3838: } else {
3839: $docuname = $env{'user.name'};
3840: }
3841: if (exists($env{'form.group'})) {
3842: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3843: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3844: }
3845: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3846: if ($context eq 'canceloverwrite') {
3847: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3848: if (-e $tempfile) {
3849: my @info = stat($tempfile);
3850: if ($info[9] eq $env{'form.timestamp'}) {
3851: unlink($tempfile);
3852: }
3853: }
3854: return;
1.523 raeburn 3855: }
3856: }
1.1090 raeburn 3857: # Create the directory if not present
1.741 raeburn 3858: my @parts=split(/\//,$filepath);
3859: my $fullpath = $perlvar{'lonDaemons'};
3860: for (my $i=0;$i<@parts;$i++) {
3861: $fullpath .= '/'.$parts[$i];
3862: if ((-e $fullpath)!=1) {
3863: mkdir($fullpath,0777);
3864: }
3865: }
1.1172.2.96 raeburn 3866: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3867: print $fh $env{'form.'.$formname};
3868: close($fh);
1.1090 raeburn 3869: if ($context eq 'existingfile') {
3870: my @info = stat($fullpath.'/'.$fname);
3871: return ($fullpath.'/'.$fname,$info[9]);
3872: } else {
3873: return $fullpath.'/'.$fname;
3874: }
1.523 raeburn 3875: }
1.995 raeburn 3876: if ($subdir eq 'scantron') {
3877: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3878: } else {
1.995 raeburn 3879: $fname="$subdir/$fname";
3880: }
1.1090 raeburn 3881: if ($context eq 'coursedoc') {
1.638 albertel 3882: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3883: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3884: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3885: return &finishuserfileupload($docuname,$docudom,
3886: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3887: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3888: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3889: } else {
1.1172.2.21 raeburn 3890: if ($env{'form.folder'}) {
3891: $fname=$env{'form.folder'}.'/'.$fname;
3892: }
1.638 albertel 3893: return &process_coursefile('uploaddoc',$docuname,$docudom,
3894: $fname,$formname,$parser,
1.1095 raeburn 3895: $allfiles,$codebase,$mimetype);
1.481 raeburn 3896: }
1.719 banghart 3897: } elsif (defined($destuname)) {
3898: my $docuname=$destuname;
3899: my $docudom=$destudom;
1.860 raeburn 3900: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3901: $parser,$allfiles,$codebase,
1.1051 raeburn 3902: $thumbwidth,$thumbheight,
1.1095 raeburn 3903: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3904: } else {
1.638 albertel 3905: my $docuname=$env{'user.name'};
3906: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3907: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3908: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3909: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3910: }
1.860 raeburn 3911: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3912: $parser,$allfiles,$codebase,
1.1051 raeburn 3913: $thumbwidth,$thumbheight,
1.1095 raeburn 3914: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3915: }
1.271 www 3916: }
3917:
3918: sub finishuserfileupload {
1.860 raeburn 3919: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3920: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3921: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3922: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3923:
1.860 raeburn 3924: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3925: $file=$fname;
3926: if ($fname=~m|/|) {
3927: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3928: $path.=$fnamepath.'/';
3929: }
1.259 www 3930: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3931: my $count;
3932: for ($count=4;$count<=$#parts;$count++) {
3933: $filepath.="/$parts[$count]";
3934: if ((-e $filepath)!=1) {
3935: mkdir($filepath,0777);
3936: }
3937: }
1.984 neumanie 3938:
1.258 www 3939: # Save the file
3940: {
1.1172.2.96 raeburn 3941: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 3942: &logthis('Failed to create '.$filepath.'/'.$file);
3943: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3944: return '/adm/notfound.html';
3945: }
1.1090 raeburn 3946: if ($context eq 'overwrite') {
1.1117 foxr 3947: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3948: my $target = $filepath.'/'.$file;
3949: if (-e $source) {
3950: my @info = stat($source);
3951: if ($info[9] eq $env{'form.timestamp'}) {
3952: unless (&File::Copy::move($source,$target)) {
3953: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3954: return "Moving from $source failed";
3955: }
3956: } else {
3957: return "Temporary file: $source had unexpected date/time for last modification";
3958: }
3959: } else {
3960: return "Temporary file: $source missing";
3961: }
3962: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3963: &logthis('Failed to write to '.$filepath.'/'.$file);
3964: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3965: return '/adm/notfound.html';
3966: }
1.570 albertel 3967: close(FH);
1.1051 raeburn 3968: if ($resizewidth && $resizeheight) {
3969: my $mm = new File::MMagic;
3970: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3971: if ($mime_type =~ m{^image/}) {
3972: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3973: }
1.977 amueller 3974: }
1.258 www 3975: }
1.1152 raeburn 3976: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3977: if (ref($mimetype)) {
3978: if ($$mimetype eq '') {
3979: my $mm = new File::MMagic;
3980: my $type = $mm->checktype_filename($filepath.'/'.$file);
3981: $$mimetype = $type;
3982: }
3983: }
3984: }
1.1172.2.109 raeburn 3985: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 3986: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3987: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3988: $allfiles,$codebase);
3989: unless ($parse_result eq 'ok') {
3990: &logthis('Failed to parse '.$filepath.$file.
3991: ' for embedded media: '.$parse_result);
3992: }
1.637 raeburn 3993: }
1.1172.2.109 raeburn 3994: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
3995: my $format = $env{'form.scantron_format'};
3996: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 3997: }
1.860 raeburn 3998: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3999: my $input = $filepath.'/'.$file;
4000: my $output = $filepath.'/'.'tn-'.$file;
4001: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96 raeburn 4002: my @args = ('convert','-sample',$thumbsize,$input,$output);
4003: system({$args[0]} @args);
1.860 raeburn 4004: if (-e $filepath.'/'.'tn-'.$file) {
4005: $fetchthumb = 1;
4006: }
4007: }
1.858 raeburn 4008:
1.259 www 4009: # Notify homeserver to grep it
4010: #
1.984 neumanie 4011: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4012: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4013: if ($fetchresult eq 'ok') {
1.860 raeburn 4014: if ($fetchthumb) {
4015: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4016: if ($thumbresult ne 'ok') {
4017: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4018: $docuhome.': '.$thumbresult);
4019: }
4020: }
1.259 www 4021: #
1.258 www 4022: # Return the URL to it
1.494 albertel 4023: return '/uploaded/'.$path.$file;
1.263 www 4024: } else {
1.494 albertel 4025: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4026: ': '.$fetchresult);
1.263 www 4027: return '/adm/notfound.html';
1.858 raeburn 4028: }
1.493 albertel 4029: }
4030:
1.637 raeburn 4031: sub extract_embedded_items {
1.961 raeburn 4032: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4033: my @state = ();
1.1164 raeburn 4034: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4035: my %javafiles = (
4036: codebase => '',
4037: code => '',
4038: archive => ''
4039: );
4040: my %mediafiles = (
4041: src => '',
4042: movie => '',
4043: );
1.648 raeburn 4044: my $p;
4045: if ($content) {
4046: $p = HTML::LCParser->new($content);
4047: } else {
1.961 raeburn 4048: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4049: }
1.641 albertel 4050: while (my $t=$p->get_token()) {
1.640 albertel 4051: if ($t->[0] eq 'S') {
4052: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4053: push(@state, $tagname);
1.648 raeburn 4054: if (lc($tagname) eq 'allow') {
4055: &add_filetype($allfiles,$attr->{'src'},'src');
4056: }
1.640 albertel 4057: if (lc($tagname) eq 'img') {
4058: &add_filetype($allfiles,$attr->{'src'},'src');
4059: }
1.886 albertel 4060: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 4061: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4062: &add_filetype($allfiles,$attr->{'href'},'href');
4063: }
1.886 albertel 4064: }
1.645 raeburn 4065: if (lc($tagname) eq 'script') {
1.1164 raeburn 4066: my $src;
1.645 raeburn 4067: if ($attr->{'archive'} =~ /\.jar$/i) {
4068: &add_filetype($allfiles,$attr->{'archive'},'archive');
4069: } else {
1.1164 raeburn 4070: if ($attr->{'src'} ne '') {
4071: $src = $attr->{'src'};
4072: &add_filetype($allfiles,$src,'src');
4073: }
4074: }
4075: my $text = $p->get_trimmed_text();
4076: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4077: my @swfargs = split(/,/,$1);
4078: foreach my $item (@swfargs) {
4079: $item =~ s/["']//g;
4080: $item =~ s/^\s+//;
4081: $item =~ s/\s+$//;
4082: }
4083: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4084: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4085: push(@{$related{$swfargs[0]}},$swfargs[2]);
4086: } else {
4087: $related{$swfargs[0]} = [$swfargs[2]];
4088: }
4089: }
1.645 raeburn 4090: }
4091: }
4092: if (lc($tagname) eq 'link') {
4093: if (lc($attr->{'rel'}) eq 'stylesheet') {
4094: &add_filetype($allfiles,$attr->{'href'},'href');
4095: }
4096: }
1.640 albertel 4097: if (lc($tagname) eq 'object' ||
4098: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4099: foreach my $item (keys(%javafiles)) {
4100: $javafiles{$item} = '';
4101: }
1.1164 raeburn 4102: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4103: $lastids{lc($tagname)} = $attr->{'id'};
4104: }
1.640 albertel 4105: }
4106: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4107: my $name = lc($attr->{'name'});
4108: foreach my $item (keys(%javafiles)) {
4109: if ($name eq $item) {
4110: $javafiles{$item} = $attr->{'value'};
4111: last;
4112: }
4113: }
1.1164 raeburn 4114: my $pathfrom;
1.640 albertel 4115: foreach my $item (keys(%mediafiles)) {
4116: if ($name eq $item) {
1.1164 raeburn 4117: $pathfrom = $attr->{'value'};
4118: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4119: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4120: last;
4121: }
4122: }
1.1164 raeburn 4123: if ($name eq 'flashvars') {
4124: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4125: }
4126: if ($pathfrom ne '') {
4127: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4128: $pathfrom);
4129: }
1.640 albertel 4130: }
4131: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4132: foreach my $item (keys(%javafiles)) {
4133: if ($attr->{$item}) {
4134: $javafiles{$item} = $attr->{$item};
4135: last;
4136: }
4137: }
4138: foreach my $item (keys(%mediafiles)) {
4139: if ($attr->{$item}) {
4140: &add_filetype($allfiles,$attr->{$item},$item);
4141: last;
4142: }
4143: }
1.1164 raeburn 4144: if (lc($tagname) eq 'embed') {
4145: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4146: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4147: $attr->{'src'});
4148: }
4149: }
1.640 albertel 4150: }
1.1172.2.35 raeburn 4151: if (lc($tagname) eq 'iframe') {
4152: my $src = $attr->{'src'} ;
4153: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4154: &add_filetype($allfiles,$src,'src');
4155: } elsif ($src =~ m{^/}) {
4156: if ($env{'request.course.id'}) {
4157: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4158: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4159: my $url = &hreflocation('',$fullpath);
4160: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4161: my $relpath = $1;
4162: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4163: &add_filetype($allfiles,$1,'src');
4164: }
4165: }
4166: }
4167: }
4168: }
1.1164 raeburn 4169: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 4170: pop(@state);
1.1164 raeburn 4171: }
1.640 albertel 4172: } elsif ($t->[0] eq 'E') {
4173: my ($tagname) = ($t->[1]);
4174: if ($javafiles{'codebase'} ne '') {
4175: $javafiles{'codebase'} .= '/';
4176: }
4177: if (lc($tagname) eq 'applet' ||
4178: lc($tagname) eq 'object' ||
4179: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4180: ) {
4181: foreach my $item (keys(%javafiles)) {
4182: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4183: my $file=$javafiles{'codebase'}.$javafiles{$item};
4184: &add_filetype($allfiles,$file,$item);
4185: }
4186: }
4187: }
4188: pop @state;
4189: }
4190: }
1.1164 raeburn 4191: foreach my $id (sort(keys(%flashvars))) {
4192: if ($shockwave{$id} ne '') {
4193: my @pairs = split(/\&/,$flashvars{$id});
4194: foreach my $pair (@pairs) {
4195: my ($key,$value) = split(/\=/,$pair);
4196: if ($key eq 'thumb') {
4197: &add_filetype($allfiles,$value,$key);
4198: } elsif ($key eq 'content') {
4199: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4200: my ($ext) = ($value =~ /\.([^.]+)$/);
4201: if ($ext ne '') {
4202: &add_filetype($allfiles,$path.$value,$ext);
4203: }
4204: }
4205: }
4206: }
4207: }
1.637 raeburn 4208: return 'ok';
4209: }
4210:
1.639 albertel 4211: sub add_filetype {
4212: my ($allfiles,$file,$type)=@_;
4213: if (exists($allfiles->{$file})) {
4214: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4215: push(@{$allfiles->{$file}}, &escape($type));
4216: }
4217: } else {
4218: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4219: }
4220: }
4221:
1.1164 raeburn 4222: sub embedded_dependency {
4223: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4224: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4225: if (($identifier ne '') &&
4226: (ref($related->{$identifier}) eq 'ARRAY') &&
4227: ($pathfrom ne '')) {
4228: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4229: foreach my $dep (@{$related->{$identifier}}) {
4230: &add_filetype($allfiles,$path.$dep,'object');
4231: }
4232: }
4233: }
4234: return;
4235: }
4236:
1.1172.2.109 raeburn 4237: sub bubblesheet_converter {
4238: my ($cdom,$fullpath,$config,$format) = @_;
4239: if ((&domain($cdom) ne '') &&
4240: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4241: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4242: my (%csvcols,%csvoptions);
4243: if (ref($config->{'fields'}) eq 'HASH') {
4244: %csvcols = %{$config->{'fields'}};
4245: }
4246: if (ref($config->{'options'}) eq 'HASH') {
4247: %csvoptions = %{$config->{'options'}};
4248: }
4249: my %csvbynum = reverse(%csvcols);
4250: my %scantronconf = &get_scantron_config($format,$cdom);
4251: if (keys(%scantronconf)) {
4252: my %bynum = (
4253: $scantronconf{CODEstart} => 'CODEstart',
4254: $scantronconf{IDstart} => 'IDstart',
4255: $scantronconf{PaperID} => 'PaperID',
4256: $scantronconf{FirstName} => 'FirstName',
4257: $scantronconf{LastName} => 'LastName',
4258: $scantronconf{Qstart} => 'Qstart',
4259: );
4260: my @ordered;
4261: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4262: push(@ordered,$bynum{$item});
4263: }
4264: my %mapstart = (
4265: CODEstart => 'CODE',
4266: IDstart => 'ID',
4267: PaperID => 'PaperID',
4268: FirstName => 'FirstName',
4269: LastName => 'LastName',
4270: Qstart => 'FirstQuestion',
4271: );
4272: my %maplength = (
4273: CODEstart => 'CODElength',
4274: IDstart => 'IDlength',
4275: PaperID => 'PaperIDlength',
4276: FirstName => 'FirstNamelength',
4277: LastName => 'LastNamelength',
4278: );
4279: if (open(my $fh,'<',$fullpath)) {
4280: my $output;
4281: my %lettdig = &letter_to_digits();
4282: my %diglett = reverse(%lettdig);
4283: my $numletts = scalar(keys(%lettdig));
4284: my $num = 0;
4285: while (my $line=<$fh>) {
4286: $num ++;
4287: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4288: $line =~ s{[\r\n]+$}{};
4289: my %found;
4290: my @values = split(/,/,$line);
4291: my ($qstart,$record);
4292: for (my $i=0; $i<@values; $i++) {
4293: if ((($qstart ne '') && ($i > $qstart)) ||
4294: ($csvbynum{$i} eq 'FirstQuestion')) {
4295: if ($values[$i] eq '') {
4296: $values[$i] = $scantronconf{'Qoff'};
4297: } elsif ($scantronconf{'Qon'} eq 'number') {
4298: if ($values[$i] =~ /^[A-Ja-j]$/) {
4299: $values[$i] = $lettdig{uc($values[$i])};
4300: }
4301: } elsif ($scantronconf{'Qon'} eq 'letter') {
4302: if ($values[$i] =~ /^[0-9]$/) {
4303: $values[$i] = $diglett{$values[$i]};
4304: }
4305: } else {
4306: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4307: my $digit;
4308: if ($values[$i] =~ /^[A-Ja-j]$/) {
4309: $digit = $lettdig{uc($values[$i])}-1;
4310: if ($values[$i] eq 'J') {
4311: $digit += $numletts;
4312: }
4313: } elsif ($values[$i] =~ /^[0-9]$/) {
4314: $digit = $values[$i]-1;
4315: if ($values[$i] eq '0') {
4316: $digit += $numletts;
4317: }
4318: }
4319: my $qval='';
4320: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4321: if ($j == $digit) {
4322: $qval .= $scantronconf{'Qon'};
4323: } else {
4324: $qval .= $scantronconf{'Qoff'};
4325: }
4326: }
4327: $values[$i] = $qval;
4328: }
4329: }
4330: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4331: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4332: }
4333: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4334: if ($numblank > 0) {
4335: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4336: }
4337: if ($csvbynum{$i} eq 'FirstQuestion') {
4338: $qstart = $i;
4339: $found{$csvbynum{$i}} = $values[$i];
4340: } else {
4341: $found{'FirstQuestion'} .= $values[$i];
4342: }
4343: } elsif (exists($csvbynum{$i})) {
4344: if ($csvoptions{'rem'}) {
4345: $values[$i] =~ s/^\s+//;
4346: }
4347: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4348: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4349: $values[$i] = '0'.$values[$i];
4350: }
4351: }
4352: $found{$csvbynum{$i}} = $values[$i];
4353: }
4354: }
4355: foreach my $item (@ordered) {
4356: my $currlength = 1+length($record);
4357: my $numspaces = $scantronconf{$item} - $currlength;
4358: if ($numspaces > 0) {
4359: $record .= (' ' x $numspaces);
4360: }
4361: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4362: unless ($item eq 'Qstart') {
4363: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4364: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4365: }
4366: }
4367: $record .= $found{$mapstart{$item}};
4368: }
4369: }
4370: $output .= "$record\n";
4371: }
4372: close($fh);
4373: if ($output) {
4374: if (open(my $fh,'>',$fullpath)) {
4375: print $fh $output;
4376: close($fh);
4377: }
4378: }
4379: }
4380: }
4381: return;
4382: }
4383: }
4384:
4385: sub letter_to_digits {
4386: my %lettdig = (
4387: A => 1,
4388: B => 2,
4389: C => 3,
4390: D => 4,
4391: E => 5,
4392: F => 6,
4393: G => 7,
4394: H => 8,
4395: I => 9,
4396: J => 0,
4397: );
4398: return %lettdig;
4399: }
4400:
4401: sub get_scantron_config {
4402: my ($which,$cdom) = @_;
4403: my @lines = &get_scantronformat_file($cdom);
4404: my %config;
4405: #FIXME probably should move to XML it has already gotten a bit much now
4406: foreach my $line (@lines) {
4407: my ($name,$descrip)=split(/:/,$line);
4408: if ($name ne $which ) { next; }
4409: chomp($line);
4410: my @config=split(/:/,$line);
4411: $config{'name'}=$config[0];
4412: $config{'description'}=$config[1];
4413: $config{'CODElocation'}=$config[2];
4414: $config{'CODEstart'}=$config[3];
4415: $config{'CODElength'}=$config[4];
4416: $config{'IDstart'}=$config[5];
4417: $config{'IDlength'}=$config[6];
4418: $config{'Qstart'}=$config[7];
4419: $config{'Qlength'}=$config[8];
4420: $config{'Qoff'}=$config[9];
4421: $config{'Qon'}=$config[10];
4422: $config{'PaperID'}=$config[11];
4423: $config{'PaperIDlength'}=$config[12];
4424: $config{'FirstName'}=$config[13];
4425: $config{'FirstNamelength'}=$config[14];
4426: $config{'LastName'}=$config[15];
4427: $config{'LastNamelength'}=$config[16];
4428: $config{'BubblesPerRow'}=$config[17];
4429: last;
4430: }
4431: return %config;
4432: }
4433:
4434: sub get_scantronformat_file {
4435: my ($cdom) = @_;
4436: if ($cdom eq '') {
4437: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4438: }
4439: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4440: my $gottab = 0;
4441: my @lines;
4442: if (ref($domconfig{'scantron'}) eq 'HASH') {
4443: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4444: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4445: if ($formatfile ne '-1') {
4446: @lines = split("\n",$formatfile,-1);
4447: $gottab = 1;
4448: }
4449: }
4450: }
4451: if (!$gottab) {
4452: my $confname = $cdom.'-domainconfig';
4453: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4454: my $formatfile = &getfile($default);
4455: if ($formatfile ne '-1') {
4456: @lines = split("\n",$formatfile,-1);
4457: $gottab = 1;
4458: }
4459: }
4460: if (!$gottab) {
4461: my @domains = ¤t_machine_domains();
4462: if (grep(/^\Q$cdom\E$/,@domains)) {
4463: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4464: @lines = <$fh>;
4465: close($fh);
4466: }
4467: } else {
4468: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4469: @lines = <$fh>;
4470: close($fh);
4471: }
4472: }
4473: }
4474: return @lines;
4475: }
4476:
1.493 albertel 4477: sub removeuploadedurl {
1.984 neumanie 4478: my ($url)=@_;
4479: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4480: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4481: }
4482:
4483: sub removeuserfile {
4484: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4485: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4486: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4487: if ($result eq 'ok') {
1.798 raeburn 4488: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4489: my $metafile = $fname.'.meta';
4490: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4491: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4492: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4493: my $sqlresult =
1.823 albertel 4494: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4495: 'portfolio_metadata',$group,
4496: 'delete');
1.798 raeburn 4497: }
4498: }
4499: return $result;
1.257 www 4500: }
1.15 www 4501:
1.530 albertel 4502: sub mkdiruserfile {
4503: my ($docuname,$docudom,$dir)=@_;
4504: my $home=&homeserver($docuname,$docudom);
4505: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4506: }
4507:
1.531 albertel 4508: sub renameuserfile {
4509: my ($docuname,$docudom,$old,$new)=@_;
4510: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4511: my $result = &reply("renameuserfile:$docudom:$docuname:".
4512: &escape("$old").':'.&escape("$new"),$home);
4513: if ($result eq 'ok') {
4514: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4515: my $oldmeta = $old.'.meta';
4516: my $newmeta = $new.'.meta';
4517: my $metaresult =
4518: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4519: my $url = "/uploaded/$docudom/$docuname/$old";
4520: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4521: my $sqlresult =
1.823 albertel 4522: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4523: 'portfolio_metadata',$group,
4524: 'delete');
1.798 raeburn 4525: }
4526: }
4527: return $result;
1.531 albertel 4528: }
4529:
1.14 www 4530: # ------------------------------------------------------------------------- Log
4531:
4532: sub log {
4533: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4534: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4535: }
4536:
4537: # ------------------------------------------------------------------ Course Log
1.352 www 4538: #
4539: # This routine flushes several buffers of non-mission-critical nature
4540: #
1.157 www 4541:
4542: sub flushcourselogs {
1.352 www 4543: &logthis('Flushing log buffers');
4544: #
4545: # course logs
4546: # This is a log of all transactions in a course, which can be used
4547: # for data mining purposes
4548: #
4549: # It also collects the courseid database, which lists last transaction
4550: # times and course titles for all courseids
4551: #
4552: my %courseidbuffer=();
1.921 raeburn 4553: foreach my $crsid (keys(%courselogs)) {
1.352 www 4554: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4555: &escape($courselogs{$crsid}),
4556: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4557: delete $courselogs{$crsid};
4558: } else {
4559: &logthis('Failed to flush log buffer for '.$crsid);
4560: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4561: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4562: " exceeded maximum size, deleting.</font>");
4563: delete $courselogs{$crsid};
4564: }
1.352 www 4565: }
1.920 raeburn 4566: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4567: 'description' => $coursedescrbuf{$crsid},
4568: 'inst_code' => $courseinstcodebuf{$crsid},
4569: 'type' => $coursetypebuf{$crsid},
4570: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4571: };
1.191 harris41 4572: }
1.352 www 4573: #
4574: # Write course id database (reverse lookup) to homeserver of courses
4575: # Is used in pickcourse
4576: #
1.840 albertel 4577: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4578: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4579: $courseidbuffer{$crs_home},
4580: $crs_home,'timeonly');
1.352 www 4581: }
4582: #
4583: # File accesses
4584: # Writes to the dynamic metadata of resources to get hit counts, etc.
4585: #
1.449 matthew 4586: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4587: if ($entry =~ /___count$/) {
4588: my ($dom,$name);
1.807 albertel 4589: ($dom,$name,undef)=
1.811 albertel 4590: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4591: if (! defined($dom) || $dom eq '' ||
4592: ! defined($name) || $name eq '') {
1.620 albertel 4593: my $cid = $env{'request.course.id'};
4594: $dom = $env{'request.'.$cid.'.domain'};
4595: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4596: }
1.450 matthew 4597: my $value = $accesshash{$entry};
4598: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4599: my %temphash=($url => $value);
1.449 matthew 4600: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4601: if ($result eq 'ok') {
4602: delete $accesshash{$entry};
4603: }
4604: } else {
1.811 albertel 4605: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4606: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4607: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4608: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4609: delete $accesshash{$entry};
4610: }
1.185 www 4611: }
1.191 harris41 4612: }
1.352 www 4613: #
4614: # Roles
4615: # Reverse lookup of user roles for course faculty/staff and co-authorship
4616: #
1.800 albertel 4617: foreach my $entry (keys(%userrolehash)) {
1.351 www 4618: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4619: split(/\:/,$entry);
4620: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4621: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4622: $rudom,$runame) eq 'ok') {
4623: delete $userrolehash{$entry};
4624: }
4625: }
1.662 raeburn 4626: #
1.1172.2.90 raeburn 4627: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4628: #
4629: my %domrolebuffer = ();
1.1000 raeburn 4630: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4631: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4632: if ($domrolebuffer{$rudom}) {
4633: $domrolebuffer{$rudom}.='&'.&escape($entry).
4634: '='.&escape($domainrolehash{$entry});
4635: } else {
4636: $domrolebuffer{$rudom}.=&escape($entry).
4637: '='.&escape($domainrolehash{$entry});
4638: }
4639: delete $domainrolehash{$entry};
4640: }
4641: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4642: my %servers;
4643: if (defined(&domain($dom,'primary'))) {
4644: my $primary=&domain($dom,'primary');
4645: my $hostname=&hostname($primary);
4646: $servers{$primary} = $hostname;
4647: } else {
4648: %servers = &get_servers($dom,'library');
4649: }
1.841 albertel 4650: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4651: if (&reply('domroleput:'.$dom.':'.
4652: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4653: last;
4654: } else {
1.841 albertel 4655: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4656: }
1.662 raeburn 4657: }
4658: }
1.186 www 4659: $dumpcount++;
1.157 www 4660: }
4661:
4662: sub courselog {
4663: my $what=shift;
1.158 www 4664: $what=time.':'.$what;
1.620 albertel 4665: unless ($env{'request.course.id'}) { return ''; }
4666: $coursedombuf{$env{'request.course.id'}}=
4667: $env{'course.'.$env{'request.course.id'}.'.domain'};
4668: $coursenumbuf{$env{'request.course.id'}}=
4669: $env{'course.'.$env{'request.course.id'}.'.num'};
4670: $coursehombuf{$env{'request.course.id'}}=
4671: $env{'course.'.$env{'request.course.id'}.'.home'};
4672: $coursedescrbuf{$env{'request.course.id'}}=
4673: $env{'course.'.$env{'request.course.id'}.'.description'};
4674: $courseinstcodebuf{$env{'request.course.id'}}=
4675: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4676: $courseownerbuf{$env{'request.course.id'}}=
4677: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4678: $coursetypebuf{$env{'request.course.id'}}=
4679: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4680: if (defined $courselogs{$env{'request.course.id'}}) {
4681: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4682: } else {
1.620 albertel 4683: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4684: }
1.620 albertel 4685: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4686: &flushcourselogs();
4687: }
1.158 www 4688: }
4689:
4690: sub courseacclog {
4691: my $fnsymb=shift;
1.620 albertel 4692: unless ($env{'request.course.id'}) { return ''; }
4693: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4694: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4695: $what.=':POST';
1.583 matthew 4696: # FIXME: Probably ought to escape things....
1.800 albertel 4697: foreach my $key (keys(%env)) {
4698: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4699: my $formitem = $1;
4700: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4701: $what.=':'.$formitem.'='.$env{$key};
4702: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131 raeburn 4703: if ($formitem eq 'proctorpassword') {
1.1172.2.132 raeburn 4704: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131 raeburn 4705: } else {
4706: $what.=':'.$formitem.'='.$env{$key};
4707: }
1.975 raeburn 4708: }
1.158 www 4709: }
1.191 harris41 4710: }
1.583 matthew 4711: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4712: # FIXME: We should not be depending on a form parameter that someone
4713: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4714: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4715: $what.= ':POST';
4716: # FIXME: Probably ought to escape things....
4717: foreach my $element ('courseexp','crsfulltext','crsrelated',
4718: 'crsdiscuss') {
1.620 albertel 4719: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4720: }
4721: }
1.158 www 4722: }
4723: &courselog($what);
1.149 www 4724: }
4725:
1.185 www 4726: sub countacc {
4727: my $url=&declutter(shift);
1.458 matthew 4728: return if (! defined($url) || $url eq '');
1.620 albertel 4729: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4730: #
4731: # Mark that this url was used in this course
4732: #
1.620 albertel 4733: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4734: #
4735: # Increase the access count for this resource in this child process
4736: #
1.281 www 4737: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4738: $accesshash{$key}++;
1.185 www 4739: }
1.349 www 4740:
1.361 www 4741: sub linklog {
4742: my ($from,$to)=@_;
4743: $from=&declutter($from);
4744: $to=&declutter($to);
4745: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4746: $accesshash{$to.'___'.$from.'___goto'}=1;
4747: }
1.1160 www 4748:
4749: sub statslog {
4750: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4751: if ($users<2) { return; }
4752: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4753: 'course' => $env{'request.course.id'},
4754: 'sections' => '"all"',
4755: 'num_students' => $users,
4756: 'part' => $part,
4757: 'symb' => $symb,
4758: 'mean_tries' => $av_attempts,
4759: 'deg_of_diff' => $degdiff});
4760: foreach my $key (keys(%dynstore)) {
4761: $accesshash{$key}=$dynstore{$key};
4762: }
4763: }
1.361 www 4764:
1.349 www 4765: sub userrolelog {
4766: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4767: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4768: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4769: $userrolehash
4770: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4771: =$tend.':'.$tstart;
1.662 raeburn 4772: }
1.1169 droeschl 4773: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4774: $userrolehash
4775: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4776: =$tend.':'.$tstart;
4777: }
1.1172.2.90 raeburn 4778: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4779: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4780: $domainrolehash
4781: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4782: = $tend.':'.$tstart;
4783: }
1.351 www 4784: }
4785:
1.957 raeburn 4786: sub courserolelog {
4787: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4788: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4789: my $cdom = $1;
4790: my $cnum = $2;
4791: my $sec = $3;
4792: my $namespace = 'rolelog';
4793: my %storehash = (
4794: role => $trole,
4795: start => $tstart,
4796: end => $tend,
4797: selfenroll => $selfenroll,
4798: context => $context,
4799: );
4800: if ($trole eq 'gr') {
4801: $namespace = 'groupslog';
4802: $storehash{'group'} = $sec;
4803: } else {
4804: $storehash{'section'} = $sec;
4805: }
4806: &write_log('course',$namespace,\%storehash,$delflag,$username,
4807: $domain,$cnum,$cdom);
4808: if (($trole ne 'st') || ($sec ne '')) {
4809: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4810: }
4811: }
4812: return;
4813: }
4814:
1.1172.2.9 raeburn 4815: sub domainrolelog {
4816: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4817: if ($area =~ m{^/($match_domain)/$}) {
4818: my $cdom = $1;
4819: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4820: my $namespace = 'rolelog';
4821: my %storehash = (
4822: role => $trole,
4823: start => $tstart,
4824: end => $tend,
4825: context => $context,
4826: );
4827: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4828: $domain,$domconfiguser,$cdom);
4829: }
4830: return;
4831:
4832: }
4833:
4834: sub coauthorrolelog {
4835: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4836: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4837: my $audom = $1;
4838: my $auname = $2;
4839: my $namespace = 'rolelog';
4840: my %storehash = (
4841: role => $trole,
4842: start => $tstart,
4843: end => $tend,
4844: context => $context,
4845: );
4846: &write_log('author',$namespace,\%storehash,$delflag,$username,
4847: $domain,$auname,$audom);
4848: }
4849: return;
4850: }
4851:
1.351 www 4852: sub get_course_adv_roles {
1.948 raeburn 4853: my ($cid,$codes) = @_;
1.620 albertel 4854: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4855: my %coursehash=&coursedescription($cid);
1.988 raeburn 4856: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4857: my %nothide=();
1.800 albertel 4858: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4859: if ($user !~ /:/) {
4860: $nothide{join(':',split(/[\@]/,$user))}=1;
4861: } else {
4862: $nothide{$user}=1;
4863: }
1.470 www 4864: }
1.1172.2.23 raeburn 4865: my @possdoms = ($coursehash{'domain'});
4866: if ($coursehash{'checkforpriv'}) {
4867: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4868: }
1.351 www 4869: my %returnhash=();
4870: my %dumphash=
4871: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4872: my $now=time;
1.997 raeburn 4873: my %privileged;
1.1000 raeburn 4874: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4875: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4876: if (($tstart) && ($tstart<0)) { next; }
4877: if (($tend) && ($tend<$now)) { next; }
4878: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4879: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4880: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4881: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4882: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4883: if ($role eq 'cr') { next; }
1.948 raeburn 4884: if ($codes) {
4885: if ($section) { $role .= ':'.$section; }
4886: if ($returnhash{$role}) {
4887: $returnhash{$role}.=','.$username.':'.$domain;
4888: } else {
4889: $returnhash{$role}=$username.':'.$domain;
4890: }
1.351 www 4891: } else {
1.988 raeburn 4892: my $key=&plaintext($role,$crstype);
1.973 bisitz 4893: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4894: if ($returnhash{$key}) {
4895: $returnhash{$key}.=','.$username.':'.$domain;
4896: } else {
4897: $returnhash{$key}=$username.':'.$domain;
4898: }
1.351 www 4899: }
1.948 raeburn 4900: }
1.400 www 4901: return %returnhash;
4902: }
4903:
4904: sub get_my_roles {
1.937 raeburn 4905: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4906: unless (defined($uname)) { $uname=$env{'user.name'}; }
4907: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4908: my (%dumphash,%nothide);
1.1086 raeburn 4909: if ($context eq 'userroles') {
1.1166 raeburn 4910: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4911: } else {
1.1172.2.23 raeburn 4912: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4913: if ($hidepriv) {
4914: my %coursehash=&coursedescription($udom.'_'.$uname);
4915: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4916: if ($user !~ /:/) {
4917: $nothide{join(':',split(/[\@]/,$user))} = 1;
4918: } else {
4919: $nothide{$user} = 1;
4920: }
4921: }
4922: }
1.858 raeburn 4923: }
1.400 www 4924: my %returnhash=();
4925: my $now=time;
1.999 raeburn 4926: my %privileged;
1.800 albertel 4927: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4928: my ($role,$tend,$tstart);
4929: if ($context eq 'userroles') {
1.1149 raeburn 4930: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4931: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4932: } else {
4933: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4934: }
1.400 www 4935: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4936: my $status = 'active';
1.939 raeburn 4937: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4938: $status = 'previous';
4939: }
4940: if (($tstart) && ($now<$tstart)) {
4941: $status = 'future';
4942: }
4943: if (ref($types) eq 'ARRAY') {
4944: if (!grep(/^\Q$status\E$/,@{$types})) {
4945: next;
4946: }
4947: } else {
4948: if ($status ne 'active') {
4949: next;
4950: }
4951: }
1.867 raeburn 4952: my ($rolecode,$username,$domain,$section,$area);
4953: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4954: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4955: (undef,$domain,$username,$section) = split(/\//,$area);
4956: } else {
4957: ($role,$username,$domain,$section) = split(/\:/,$entry);
4958: }
1.832 raeburn 4959: if (ref($roledoms) eq 'ARRAY') {
4960: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4961: next;
4962: }
4963: }
4964: if (ref($roles) eq 'ARRAY') {
4965: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4966: if ($role =~ /^cr\//) {
4967: if (!grep(/^cr$/,@{$roles})) {
4968: next;
4969: }
1.1104 raeburn 4970: } elsif ($role =~ /^gr\//) {
4971: if (!grep(/^gr$/,@{$roles})) {
4972: next;
4973: }
1.922 raeburn 4974: } else {
4975: next;
4976: }
1.832 raeburn 4977: }
1.867 raeburn 4978: }
1.937 raeburn 4979: if ($hidepriv) {
1.1172.2.23 raeburn 4980: my @privroles = ('dc','su');
1.999 raeburn 4981: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4982: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4983: } else {
1.1172.2.23 raeburn 4984: my $possdoms = [$domain];
4985: if (ref($roledoms) eq 'ARRAY') {
4986: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4987: }
1.1172.2.23 raeburn 4988: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4989: if (!$nothide{$username.':'.$domain}) {
4990: next;
4991: }
4992: }
1.937 raeburn 4993: }
4994: }
1.933 raeburn 4995: if ($withsec) {
4996: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4997: $tstart.':'.$tend;
4998: } else {
4999: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5000: }
1.832 raeburn 5001: }
1.373 www 5002: return %returnhash;
1.399 www 5003: }
5004:
1.1172.2.89 raeburn 5005: sub get_all_adhocroles {
5006: my ($dom) = @_;
5007: my @roles_by_num = ();
5008: my %domdefaults = &get_domain_defaults($dom);
5009: my (%description,%access_in_dom,%access_info);
5010: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5011: my $count = 0;
5012: my %domcurrent = %{$domdefaults{'adhocroles'}};
5013: my %ordered;
5014: foreach my $role (sort(keys(%domcurrent))) {
5015: my ($order,$desc,$access_in_dom);
5016: if (ref($domcurrent{$role}) eq 'HASH') {
5017: $order = $domcurrent{$role}{'order'};
5018: $desc = $domcurrent{$role}{'desc'};
5019: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5020: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5021: }
5022: if ($order eq '') {
5023: $order = $count;
5024: }
5025: $ordered{$order} = $role;
5026: if ($desc ne '') {
5027: $description{$role} = $desc;
5028: } else {
5029: $description{$role}= $role;
5030: }
5031: $count++;
5032: }
5033: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5034: push(@roles_by_num,$ordered{$item});
5035: }
5036: }
5037: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5038: }
5039:
5040: sub get_my_adhocroles {
5041: my ($cid,$checkreg) = @_;
5042: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5043: if ($env{'request.course.id'} eq $cid) {
5044: $cdom = $env{'course.'.$cid.'.domain'};
5045: $cnum = $env{'course.'.$cid.'.num'};
5046: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5047: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5048: $cdom = $1;
5049: $cnum = $2;
5050: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5051: $cdom,$cnum);
5052: }
5053: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5054: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5055: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5056: if ($rosterhash{$user} ne '') {
5057: my $type = (split(/:/,$rosterhash{$user}))[5];
5058: return ([],{}) if ($type eq 'auto');
5059: }
5060: }
5061: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 5062: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 5063: my $then=$env{'user.login.time'};
5064: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 5065: if (!$update) {
5066: $update = $then;
5067: }
5068: my @liveroles;
5069: foreach my $role ('dh','da') {
5070: if ($env{"user.role.$role./$cdom/"}) {
5071: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5072: my $limit = $update;
5073: if ($env{'request.role'} eq "$role./$cdom/") {
5074: $limit = $then;
5075: }
5076: my $activerole = 1;
5077: if ($tstart && $tstart>$limit) { $activerole = 0; }
5078: if ($tend && $tend <$limit) { $activerole = 0; }
5079: if ($activerole) {
5080: push(@liveroles,$role);
5081: }
5082: }
5083: }
5084: if (@liveroles) {
1.1172.2.89 raeburn 5085: if (&homeserver($cnum,$cdom) ne 'no_host') {
5086: my ($accessref,$accessinfo,%access_in_dom);
5087: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5088: if (ref($roles_by_num) eq 'ARRAY') {
5089: if (@{$roles_by_num}) {
5090: my %settings;
5091: if ($env{'request.course.id'} eq $cid) {
5092: foreach my $envkey (keys(%env)) {
5093: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5094: $settings{$1} = $env{$envkey};
5095: }
5096: }
5097: } else {
5098: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5099: }
5100: my %setincrs;
5101: if ($settings{'internal.adhocaccess'}) {
5102: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5103: }
5104: my @statuses;
5105: if ($env{'environment.inststatus'}) {
5106: @statuses = split(/,/,$env{'environment.inststatus'});
5107: }
5108: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5109: if (ref($accessref) eq 'HASH') {
5110: %access_in_dom = %{$accessref};
5111: }
5112: foreach my $role (@{$roles_by_num}) {
5113: my ($curraccess,@okstatus,@personnel);
5114: if ($setincrs{$role}) {
5115: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5116: if ($curraccess eq 'status') {
5117: @okstatus = split(/\&/,$rest);
5118: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5119: @personnel = split(/\&/,$rest);
5120: }
5121: } else {
5122: $curraccess = $access_in_dom{$role};
5123: if (ref($accessinfo) eq 'HASH') {
5124: if ($curraccess eq 'status') {
5125: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5126: @okstatus = @{$accessinfo->{$role}};
5127: }
5128: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5129: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5130: @personnel = @{$accessinfo->{$role}};
5131: }
5132: }
5133: }
5134: }
5135: if ($curraccess eq 'none') {
5136: next;
5137: } elsif ($curraccess eq 'all') {
5138: push(@possroles,$role);
1.1172.2.90 raeburn 5139: } elsif ($curraccess eq 'dh') {
5140: if (grep(/^dh$/,@liveroles)) {
5141: push(@possroles,$role);
5142: } else {
5143: next;
5144: }
5145: } elsif ($curraccess eq 'da') {
5146: if (grep(/^da$/,@liveroles)) {
5147: push(@possroles,$role);
5148: } else {
5149: next;
5150: }
1.1172.2.89 raeburn 5151: } elsif ($curraccess eq 'status') {
5152: if (@okstatus) {
5153: if (!@statuses) {
5154: if (grep(/^default$/,@okstatus)) {
5155: push(@possroles,$role);
5156: }
5157: } else {
5158: foreach my $status (@okstatus) {
5159: if (grep(/^\Q$status\E$/,@statuses)) {
5160: push(@possroles,$role);
5161: last;
5162: }
5163: }
5164: }
5165: }
5166: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5167: if (grep(/^\Q$user\E$/,@personnel)) {
5168: if ($curraccess eq 'exc') {
5169: push(@possroles,$role);
5170: }
5171: } elsif ($curraccess eq 'inc') {
5172: push(@possroles,$role);
5173: }
5174: }
5175: }
5176: }
5177: }
5178: }
5179: }
5180: }
5181: }
5182: unless (ref($description) eq 'HASH') {
5183: if (ref($roles_by_num) eq 'ARRAY') {
5184: my %desc;
5185: map { $desc{$_} = $_; } (@{$roles_by_num});
5186: $description = \%desc;
5187: } else {
5188: $description = {};
5189: }
5190: }
5191: return (\@possroles,$description);
5192: }
5193:
1.399 www 5194: # ----------------------------------------------------- Frontpage Announcements
5195: #
5196: #
5197:
5198: sub postannounce {
5199: my ($server,$text)=@_;
1.844 albertel 5200: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5201: unless ($text=~/\w/) { $text=''; }
5202: return &reply('setannounce:'.&escape($text),$server);
5203: }
5204:
5205: sub getannounce {
1.448 albertel 5206:
1.1172.2.96 raeburn 5207: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5208: my $announcement='';
1.800 albertel 5209: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5210: close($fh);
1.399 www 5211: if ($announcement=~/\w/) {
5212: return
5213: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5214: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5215: } else {
5216: return '';
5217: }
5218: } else {
5219: return '';
5220: }
1.351 www 5221: }
1.353 www 5222:
5223: # ---------------------------------------------------------- Course ID routines
5224: # Deal with domain's nohist_courseid.db files
5225: #
5226:
5227: sub courseidput {
1.921 raeburn 5228: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5229: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5230: my $outcome;
5231: if ($caller eq 'timeonly') {
5232: my $cids = '';
5233: foreach my $item (keys(%$storehash)) {
5234: $cids.=&escape($item).'&';
5235: }
5236: $cids=~s/\&$//;
5237: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5238: $coursehome);
5239: } else {
5240: my $items = '';
5241: foreach my $item (keys(%$storehash)) {
5242: $items.= &escape($item).'='.
5243: &freeze_escape($$storehash{$item}).'&';
5244: }
5245: $items=~s/\&$//;
5246: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5247: $coursehome);
1.918 raeburn 5248: }
5249: if ($outcome eq 'unknown_cmd') {
5250: my $what;
5251: foreach my $cid (keys(%$storehash)) {
5252: $what .= &escape($cid).'=';
1.921 raeburn 5253: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5254: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5255: }
5256: $what =~ s/\:$/&/;
5257: }
5258: $what =~ s/\&$//;
5259: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5260: } else {
5261: return $outcome;
5262: }
1.353 www 5263: }
5264:
5265: sub courseiddump {
1.921 raeburn 5266: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5267: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5268: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5269: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5270: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5271: my $as_hash = 1;
5272: my %returnhash;
5273: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5274: my %libserv = &all_library();
5275: foreach my $tryserver (keys(%libserv)) {
5276: if ( ( $hostidflag == 1
5277: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5278: || (!defined($hostidflag)) ) {
5279:
1.918 raeburn 5280: if (($domfilter eq '') ||
5281: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5282: my $rep;
5283: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5284: $rep = &LONCAPA::Lond::dump_course_id_handler(
5285: join(":", (&host_domain($tryserver), $sincefilter,
5286: &escape($descfilter), &escape($instcodefilter),
5287: &escape($ownerfilter), &escape($coursefilter),
5288: &escape($typefilter), &escape($regexp_ok),
5289: $as_hash, &escape($selfenrollonly),
5290: &escape($catfilter), $showhidden, $caller,
5291: &escape($cloner), &escape($cc_clone), $cloneonly,
5292: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5293: &escape($creationcontext),$domcloner,$hasuniquecode,
5294: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5295: } else {
5296: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5297: $sincefilter.':'.&escape($descfilter).':'.
5298: &escape($instcodefilter).':'.&escape($ownerfilter).
5299: ':'.&escape($coursefilter).':'.&escape($typefilter).
5300: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5301: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5302: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5303: &escape($cc_clone).':'.$cloneonly.':'.
5304: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5305: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5306: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5307: }
5308:
1.918 raeburn 5309: my @pairs=split(/\&/,$rep);
5310: foreach my $item (@pairs) {
5311: my ($key,$value)=split(/\=/,$item,2);
5312: $key = &unescape($key);
5313: next if ($key =~ /^error: 2 /);
5314: my $result = &thaw_unescape($value);
5315: if (ref($result) eq 'HASH') {
5316: $returnhash{$key}=$result;
5317: } else {
1.921 raeburn 5318: my @responses = split(/:/,$value);
5319: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5320: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5321: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5322: }
1.1008 raeburn 5323: }
1.353 www 5324: }
5325: }
5326: }
5327: }
5328: return %returnhash;
5329: }
5330:
1.1055 raeburn 5331: sub courselastaccess {
5332: my ($cdom,$cnum,$hostidref) = @_;
5333: my %returnhash;
5334: if ($cdom && $cnum) {
5335: my $chome = &homeserver($cnum,$cdom);
5336: if ($chome ne 'no_host') {
5337: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5338: &extract_lastaccess(\%returnhash,$rep);
5339: }
5340: } else {
5341: if (!$cdom) { $cdom=''; }
5342: my %libserv = &all_library();
5343: foreach my $tryserver (keys(%libserv)) {
5344: if (ref($hostidref) eq 'ARRAY') {
5345: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5346: }
5347: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5348: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5349: &extract_lastaccess(\%returnhash,$rep);
5350: }
5351: }
5352: }
5353: return %returnhash;
5354: }
5355:
5356: sub extract_lastaccess {
5357: my ($returnhash,$rep) = @_;
5358: if (ref($returnhash) eq 'HASH') {
5359: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5360: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5361: $rep eq '') {
5362: my @pairs=split(/\&/,$rep);
5363: foreach my $item (@pairs) {
5364: my ($key,$value)=split(/\=/,$item,2);
5365: $key = &unescape($key);
5366: next if ($key =~ /^error: 2 /);
5367: $returnhash->{$key} = &thaw_unescape($value);
5368: }
5369: }
5370: }
5371: return;
5372: }
5373:
1.658 raeburn 5374: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5375:
5376: sub dcmailput {
1.685 raeburn 5377: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5378: my $status = &Apache::lonnet::critical(
1.740 www 5379: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5380: &escape($message),$server);
1.662 raeburn 5381: return $status;
5382: }
5383:
1.658 raeburn 5384: sub dcmaildump {
5385: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5386: my %returnhash=();
1.846 albertel 5387:
5388: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5389: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5390: &escape($enddate).':';
5391: my @esc_senders=map { &escape($_)} @$senders;
5392: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5393: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5394: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5395: if (($key) && ($value)) {
5396: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5397: }
5398: }
5399: }
5400: return %returnhash;
5401: }
1.662 raeburn 5402: # ---------------------------------------------------------- Domain roles
5403:
5404: sub get_domain_roles {
5405: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5406: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5407: $startdate = '.';
5408: }
1.1018 raeburn 5409: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5410: $enddate = '.';
5411: }
1.922 raeburn 5412: my $rolelist;
5413: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5414: $rolelist = join('&',@{$roles});
1.922 raeburn 5415: }
1.662 raeburn 5416: my %personnel = ();
1.841 albertel 5417:
5418: my %servers = &get_servers($dom,'library');
5419: foreach my $tryserver (keys(%servers)) {
5420: %{$personnel{$tryserver}}=();
5421: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5422: &escape($startdate).':'.
5423: &escape($enddate).':'.
5424: &escape($rolelist), $tryserver))) {
5425: my ($key,$value) = split(/\=/,$line,2);
5426: if (($key) && ($value)) {
5427: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5428: }
5429: }
1.662 raeburn 5430: }
5431: return %personnel;
5432: }
1.658 raeburn 5433:
1.1172.2.89 raeburn 5434: sub get_active_domroles {
5435: my ($dom,$roles) = @_;
5436: return () unless (ref($roles) eq 'ARRAY');
5437: my $now = time;
5438: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5439: my %domroles;
5440: foreach my $server (keys(%dompersonnel)) {
5441: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5442: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5443: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5444: }
5445: }
5446: return %domroles;
5447: }
5448:
1.1057 www 5449: # ----------------------------------------------------------- Interval timing
1.149 www 5450:
1.1153 www 5451: {
5452: # Caches needed for speedup of navmaps
5453: # We don't want to cache this for very long at all (5 seconds at most)
5454: #
5455: # The user for whom we cache
5456: my $cachedkey='';
5457: # The cached times for this user
5458: my %cachedtimes=();
5459: # When this was last done
1.1172.2.66 raeburn 5460: my $cachedtime='';
1.1153 www 5461:
5462: sub load_all_first_access {
1.1154 raeburn 5463: my ($uname,$udom)=@_;
1.1156 www 5464: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 5465: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 5466: return;
5467: }
5468: $cachedtime=time;
5469: $cachedkey=$uname.':'.$udom;
5470: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5471: }
5472:
1.504 albertel 5473: sub get_first_access {
1.1162 raeburn 5474: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 5475: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5476: if ($argsymb) { $symb=$argsymb; }
5477: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5478: if ($argmap) { $map = $argmap; }
1.926 albertel 5479: if ($type eq 'course') {
5480: $res='course';
5481: } elsif ($type eq 'map') {
1.588 albertel 5482: $res=&symbread($map);
5483: } else {
5484: $res=$symb;
5485: }
1.1153 www 5486: &load_all_first_access($uname,$udom);
5487: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5488: }
5489:
5490: sub set_first_access {
1.1162 raeburn 5491: my ($type,$interval)=@_;
1.790 albertel 5492: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5493: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5494: if ($type eq 'course') {
5495: $res='course';
5496: } elsif ($type eq 'map') {
1.588 albertel 5497: $res=&symbread($map);
5498: } else {
5499: $res=$symb;
5500: }
1.1153 www 5501: $cachedkey='';
1.1162 raeburn 5502: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5503: if ($firstaccess) {
5504: &logthis("First access time already set ($firstaccess) when attempting ".
5505: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5506: "in $courseid");
5507: return 'already_set';
5508: } else {
1.1162 raeburn 5509: my $start = time;
5510: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5511: $udom,$uname);
5512: if ($putres eq 'ok') {
5513: &put('timerinterval',{"$courseid\0$res"=>$interval},
5514: $udom,$uname);
5515: &appenv(
5516: {
5517: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5518: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5519: }
5520: );
1.1172.2.97 raeburn 5521: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5522: $cachedtimes{"$courseid\0$res"} = $start;
5523: }
1.1172.2.102 raeburn 5524: } elsif ($putres ne 'refused') {
5525: &logthis("Result: $putres when attempting to set first access time ".
5526: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5527: }
5528: return $putres;
1.505 albertel 5529: }
5530: return 'already_set';
1.504 albertel 5531: }
1.1153 www 5532: }
1.1172.2.32 raeburn 5533:
5534: sub checkout {
5535: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5536: my $now=time;
5537: my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134 raeburn 5538: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5539: my $infostr=&escape(
5540: 'CHECKOUTTOKEN&'.
5541: $tuname.'&'.
5542: $tudom.'&'.
5543: $tcrsid.'&'.
5544: $symb.'&'.
1.1172.2.134 raeburn 5545: $now.'&'.$ip);
1.1172.2.32 raeburn 5546: my $token=&reply('tmpput:'.$infostr,$lonhost);
5547: if ($token=~/^error\:/) {
5548: &logthis("<font color=\"blue\">WARNING: ".
5549: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5550: "</font>");
5551: return '';
5552: }
5553:
5554: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5555: $token=~tr/a-z/A-Z/;
5556:
5557: my %infohash=('resource.0.outtoken' => $token,
5558: 'resource.0.checkouttime' => $now,
1.1172.2.134 raeburn 5559: 'resource.0.outremote' => $ip);
1.1172.2.32 raeburn 5560:
5561: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5562: return '';
5563: } else {
5564: &logthis("<font color=\"blue\">WARNING: ".
5565: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5566: "</font>");
5567: }
5568:
5569: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5570: &escape('Checkout '.$infostr.' - '.
5571: $token)) ne 'ok') {
5572: return '';
5573: } else {
5574: &logthis("<font color=\"blue\">WARNING: ".
5575: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5576: "</font>");
5577: }
5578: return $token;
5579: }
5580:
5581: # ------------------------------------------------------------ Check in an item
5582:
5583: sub checkin {
5584: my $token=shift;
5585: my $now=time;
5586: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5587: $lonhost=~tr/A-Z/a-z/;
5588: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5589: $dtoken=~s/\W/\_/g;
1.1172.2.134 raeburn 5590: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5591: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5592: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5593:
5594: unless (($tuname) && ($tudom)) {
5595: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5596: return '';
5597: }
5598:
5599: unless (&allowed('mgr',$tcrsid)) {
5600: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5601: $env{'user.name'}.' - '.$env{'user.domain'});
5602: return '';
5603: }
5604:
5605: my %infohash=('resource.0.intoken' => $token,
5606: 'resource.0.checkintime' => $now,
1.1172.2.134 raeburn 5607: 'resource.0.inremote' => $ip);
1.1172.2.32 raeburn 5608:
5609: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5610: return '';
5611: }
5612:
5613: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5614: &escape('Checkin - '.$token)) ne 'ok') {
5615: return '';
5616: }
5617:
5618: return ($symb,$tuname,$tudom,$tcrsid);
5619: }
5620:
1.110 www 5621: # --------------------------------------------- Set Expire Date for Spreadsheet
5622:
5623: sub expirespread {
5624: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5625: my $cid=$env{'request.course.id'};
1.110 www 5626: if ($cid) {
5627: my $now=time;
5628: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5629: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5630: $env{'course.'.$cid.'.num'}.
1.110 www 5631: ':nohist_expirationdates:'.
5632: &escape($key).'='.$now,
1.620 albertel 5633: $env{'course.'.$cid.'.home'})
1.110 www 5634: }
5635: return 'ok';
1.14 www 5636: }
5637:
1.109 www 5638: # ----------------------------------------------------- Devalidate Spreadsheets
5639:
5640: sub devalidate {
1.325 www 5641: my ($symb,$uname,$udom)=@_;
1.620 albertel 5642: my $cid=$env{'request.course.id'};
1.109 www 5643: if ($cid) {
1.391 matthew 5644: # delete the stored spreadsheets for
5645: # - the student level sheet of this user in course's homespace
5646: # - the assessment level sheet for this resource
5647: # for this user in user's homespace
1.553 albertel 5648: # - current conditional state info
1.325 www 5649: my $key=$uname.':'.$udom.':';
1.109 www 5650: my $status=
1.299 matthew 5651: &del('nohist_calculatedsheets',
1.391 matthew 5652: [$key.'studentcalc:'],
1.620 albertel 5653: $env{'course.'.$cid.'.domain'},
5654: $env{'course.'.$cid.'.num'})
1.133 albertel 5655: .' '.
5656: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5657: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5658: unless ($status eq 'ok ok') {
5659: &logthis('Could not devalidate spreadsheet '.
1.325 www 5660: $uname.' at '.$udom.' for '.
1.109 www 5661: $symb.': '.$status);
1.133 albertel 5662: }
1.553 albertel 5663: &delenv('user.state.'.$cid);
1.109 www 5664: }
5665: }
5666:
1.265 albertel 5667: sub get_scalar {
5668: my ($string,$end) = @_;
5669: my $value;
5670: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5671: $value = $1;
5672: } elsif ($$string =~ s/^([^&]*?)&//) {
5673: $value = $1;
5674: }
5675: return &unescape($value);
5676: }
5677:
5678: sub array2str {
5679: my (@array) = @_;
5680: my $result=&arrayref2str(\@array);
5681: $result=~s/^__ARRAY_REF__//;
5682: $result=~s/__END_ARRAY_REF__$//;
5683: return $result;
5684: }
5685:
1.204 albertel 5686: sub arrayref2str {
5687: my ($arrayref) = @_;
1.265 albertel 5688: my $result='__ARRAY_REF__';
1.204 albertel 5689: foreach my $elem (@$arrayref) {
1.265 albertel 5690: if(ref($elem) eq 'ARRAY') {
5691: $result.=&arrayref2str($elem).'&';
5692: } elsif(ref($elem) eq 'HASH') {
5693: $result.=&hashref2str($elem).'&';
5694: } elsif(ref($elem)) {
5695: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5696: } else {
5697: $result.=&escape($elem).'&';
5698: }
5699: }
5700: $result=~s/\&$//;
1.265 albertel 5701: $result .= '__END_ARRAY_REF__';
1.204 albertel 5702: return $result;
5703: }
5704:
1.168 albertel 5705: sub hash2str {
1.204 albertel 5706: my (%hash) = @_;
5707: my $result=&hashref2str(\%hash);
1.265 albertel 5708: $result=~s/^__HASH_REF__//;
5709: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5710: return $result;
5711: }
5712:
5713: sub hashref2str {
5714: my ($hashref)=@_;
1.265 albertel 5715: my $result='__HASH_REF__';
1.800 albertel 5716: foreach my $key (sort(keys(%$hashref))) {
5717: if (ref($key) eq 'ARRAY') {
5718: $result.=&arrayref2str($key).'=';
5719: } elsif (ref($key) eq 'HASH') {
5720: $result.=&hashref2str($key).'=';
5721: } elsif (ref($key)) {
1.265 albertel 5722: $result.='=';
1.800 albertel 5723: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5724: } else {
1.1132 raeburn 5725: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5726: }
5727:
1.800 albertel 5728: if(ref($hashref->{$key}) eq 'ARRAY') {
5729: $result.=&arrayref2str($hashref->{$key}).'&';
5730: } elsif(ref($hashref->{$key}) eq 'HASH') {
5731: $result.=&hashref2str($hashref->{$key}).'&';
5732: } elsif(ref($hashref->{$key})) {
1.265 albertel 5733: $result.='&';
1.800 albertel 5734: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5735: } else {
1.800 albertel 5736: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5737: }
5738: }
1.168 albertel 5739: $result=~s/\&$//;
1.265 albertel 5740: $result .= '__END_HASH_REF__';
1.168 albertel 5741: return $result;
5742: }
5743:
5744: sub str2hash {
1.265 albertel 5745: my ($string)=@_;
5746: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5747: return %$hash;
5748: }
5749:
5750: sub str2hashref {
1.168 albertel 5751: my ($string) = @_;
1.265 albertel 5752:
5753: my %hash;
5754:
5755: if($string !~ /^__HASH_REF__/) {
5756: if (! ($string eq '' || !defined($string))) {
5757: $hash{'error'}='Not hash reference';
5758: }
5759: return (\%hash, $string);
5760: }
5761:
5762: $string =~ s/^__HASH_REF__//;
5763:
5764: while($string !~ /^__END_HASH_REF__/) {
5765: #key
5766: my $key='';
5767: if($string =~ /^__HASH_REF__/) {
5768: ($key, $string)=&str2hashref($string);
5769: if(defined($key->{'error'})) {
5770: $hash{'error'}='Bad data';
5771: return (\%hash, $string);
5772: }
5773: } elsif($string =~ /^__ARRAY_REF__/) {
5774: ($key, $string)=&str2arrayref($string);
5775: if($key->[0] eq 'Array reference error') {
5776: $hash{'error'}='Bad data';
5777: return (\%hash, $string);
5778: }
5779: } else {
5780: $string =~ s/^(.*?)=//;
1.267 albertel 5781: $key=&unescape($1);
1.265 albertel 5782: }
5783: $string =~ s/^=//;
5784:
5785: #value
5786: my $value='';
5787: if($string =~ /^__HASH_REF__/) {
5788: ($value, $string)=&str2hashref($string);
5789: if(defined($value->{'error'})) {
5790: $hash{'error'}='Bad data';
5791: return (\%hash, $string);
5792: }
5793: } elsif($string =~ /^__ARRAY_REF__/) {
5794: ($value, $string)=&str2arrayref($string);
5795: if($value->[0] eq 'Array reference error') {
5796: $hash{'error'}='Bad data';
5797: return (\%hash, $string);
5798: }
5799: } else {
5800: $value=&get_scalar(\$string,'__END_HASH_REF__');
5801: }
5802: $string =~ s/^&//;
5803:
5804: $hash{$key}=$value;
1.204 albertel 5805: }
1.265 albertel 5806:
5807: $string =~ s/^__END_HASH_REF__//;
5808:
5809: return (\%hash, $string);
1.204 albertel 5810: }
5811:
5812: sub str2array {
1.265 albertel 5813: my ($string)=@_;
5814: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5815: return @$array;
5816: }
5817:
5818: sub str2arrayref {
1.204 albertel 5819: my ($string) = @_;
1.265 albertel 5820: my @array;
5821:
5822: if($string !~ /^__ARRAY_REF__/) {
5823: if (! ($string eq '' || !defined($string))) {
5824: $array[0]='Array reference error';
5825: }
5826: return (\@array, $string);
5827: }
5828:
5829: $string =~ s/^__ARRAY_REF__//;
5830:
5831: while($string !~ /^__END_ARRAY_REF__/) {
5832: my $value='';
5833: if($string =~ /^__HASH_REF__/) {
5834: ($value, $string)=&str2hashref($string);
5835: if(defined($value->{'error'})) {
5836: $array[0] ='Array reference error';
5837: return (\@array, $string);
5838: }
5839: } elsif($string =~ /^__ARRAY_REF__/) {
5840: ($value, $string)=&str2arrayref($string);
5841: if($value->[0] eq 'Array reference error') {
5842: $array[0] ='Array reference error';
5843: return (\@array, $string);
5844: }
5845: } else {
5846: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5847: }
5848: $string =~ s/^&//;
5849:
5850: push(@array, $value);
1.191 harris41 5851: }
1.265 albertel 5852:
5853: $string =~ s/^__END_ARRAY_REF__//;
5854:
5855: return (\@array, $string);
1.168 albertel 5856: }
5857:
1.167 albertel 5858: # -------------------------------------------------------------------Temp Store
5859:
1.168 albertel 5860: sub tmpreset {
5861: my ($symb,$namespace,$domain,$stuname) = @_;
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.168 albertel 5869: $namespace=~s/\//\_/g;
5870: $namespace=~s/\W//g;
5871:
1.620 albertel 5872: if (!$domain) { $domain=$env{'user.domain'}; }
5873: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5874: if ($domain eq 'public' && $stuname eq 'public') {
5875: $stuname=$ENV{'REMOTE_ADDR'};
5876: }
1.1117 foxr 5877: my $path=LONCAPA::tempdir();
1.168 albertel 5878: my %hash;
5879: if (tie(%hash,'GDBM_File',
5880: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5881: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5882: foreach my $key (keys(%hash)) {
1.180 albertel 5883: if ($key=~ /:$symb/) {
1.168 albertel 5884: delete($hash{$key});
5885: }
5886: }
5887: }
5888: }
5889:
1.167 albertel 5890: sub tmpstore {
1.168 albertel 5891: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5892:
5893: if (!$symb) {
5894: $symb=&symbread();
1.620 albertel 5895: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5896: }
5897: $symb=escape($symb);
5898:
5899: if (!$namespace) {
5900: # I don't think we would ever want to store this for a course.
5901: # it seems this will only be used if we don't have a course.
1.620 albertel 5902: #$namespace=$env{'request.course.id'};
1.168 albertel 5903: #if (!$namespace) {
1.620 albertel 5904: $namespace=$env{'request.state'};
1.168 albertel 5905: #}
5906: }
5907: $namespace=~s/\//\_/g;
5908: $namespace=~s/\W//g;
1.620 albertel 5909: if (!$domain) { $domain=$env{'user.domain'}; }
5910: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5911: if ($domain eq 'public' && $stuname eq 'public') {
5912: $stuname=$ENV{'REMOTE_ADDR'};
5913: }
1.168 albertel 5914: my $now=time;
5915: my %hash;
1.1117 foxr 5916: my $path=LONCAPA::tempdir();
1.168 albertel 5917: if (tie(%hash,'GDBM_File',
5918: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5919: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5920: $hash{"version:$symb"}++;
5921: my $version=$hash{"version:$symb"};
5922: my $allkeys='';
5923: foreach my $key (keys(%$storehash)) {
5924: $allkeys.=$key.':';
1.591 albertel 5925: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5926: }
5927: $hash{"$version:$symb:timestamp"}=$now;
5928: $allkeys.='timestamp';
5929: $hash{"$version:keys:$symb"}=$allkeys;
5930: if (untie(%hash)) {
5931: return 'ok';
5932: } else {
5933: return "error:$!";
5934: }
5935: } else {
5936: return "error:$!";
5937: }
5938: }
1.167 albertel 5939:
1.168 albertel 5940: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5941:
1.168 albertel 5942: sub tmprestore {
5943: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5944:
1.168 albertel 5945: if (!$symb) {
5946: $symb=&symbread();
1.620 albertel 5947: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5948: }
5949: $symb=escape($symb);
5950:
1.620 albertel 5951: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5952:
1.620 albertel 5953: if (!$domain) { $domain=$env{'user.domain'}; }
5954: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5955: if ($domain eq 'public' && $stuname eq 'public') {
5956: $stuname=$ENV{'REMOTE_ADDR'};
5957: }
1.168 albertel 5958: my %returnhash;
5959: $namespace=~s/\//\_/g;
5960: $namespace=~s/\W//g;
5961: my %hash;
1.1117 foxr 5962: my $path=LONCAPA::tempdir();
1.168 albertel 5963: if (tie(%hash,'GDBM_File',
5964: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5965: &GDBM_READER(),0640)) {
1.168 albertel 5966: my $version=$hash{"version:$symb"};
5967: $returnhash{'version'}=$version;
5968: my $scope;
5969: for ($scope=1;$scope<=$version;$scope++) {
5970: my $vkeys=$hash{"$scope:keys:$symb"};
5971: my @keys=split(/:/,$vkeys);
5972: my $key;
5973: $returnhash{"$scope:keys"}=$vkeys;
5974: foreach $key (@keys) {
1.591 albertel 5975: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5976: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5977: }
5978: }
1.168 albertel 5979: if (!(untie(%hash))) {
5980: return "error:$!";
5981: }
5982: } else {
5983: return "error:$!";
5984: }
5985: return %returnhash;
1.167 albertel 5986: }
5987:
1.9 www 5988: # ----------------------------------------------------------------------- Store
5989:
5990: sub store {
1.1172.2.64 raeburn 5991: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5992: my $home='';
5993:
1.168 albertel 5994: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5995:
1.213 www 5996: $symb=&symbclean($symb);
1.122 albertel 5997: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5998:
1.620 albertel 5999: if (!$domain) { $domain=$env{'user.domain'}; }
6000: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6001:
6002: &devalidate($symb,$stuname,$domain);
1.109 www 6003:
6004: $symb=escape($symb);
1.187 www 6005: if (!$namespace) {
1.620 albertel 6006: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6007: return '';
6008: }
6009: }
1.620 albertel 6010: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6011:
6012: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6013: $$storehash{'host'}=$perlvar{'lonHostID'};
6014:
1.12 www 6015: my $namevalue='';
1.800 albertel 6016: foreach my $key (keys(%$storehash)) {
6017: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6018: }
1.12 www 6019: $namevalue=~s/\&$//;
1.187 www 6020: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 6021: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6022: }
6023:
1.47 www 6024: # -------------------------------------------------------------- Critical Store
6025:
6026: sub cstore {
1.1172.2.64 raeburn 6027: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6028: my $home='';
6029:
1.168 albertel 6030: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6031:
1.213 www 6032: $symb=&symbclean($symb);
1.122 albertel 6033: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6034:
1.620 albertel 6035: if (!$domain) { $domain=$env{'user.domain'}; }
6036: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6037:
6038: &devalidate($symb,$stuname,$domain);
1.109 www 6039:
6040: $symb=escape($symb);
1.187 www 6041: if (!$namespace) {
1.620 albertel 6042: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6043: return '';
6044: }
6045: }
1.620 albertel 6046: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6047:
6048: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6049: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6050:
1.47 www 6051: my $namevalue='';
1.800 albertel 6052: foreach my $key (keys(%$storehash)) {
6053: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6054: }
1.47 www 6055: $namevalue=~s/\&$//;
1.187 www 6056: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6057: return critical
1.1172.2.64 raeburn 6058: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6059: }
6060:
1.9 www 6061: # --------------------------------------------------------------------- Restore
6062:
6063: sub restore {
1.124 www 6064: my ($symb,$namespace,$domain,$stuname) = @_;
6065: my $home='';
6066:
1.168 albertel 6067: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6068:
1.122 albertel 6069: if (!$symb) {
1.1172.2.26 raeburn 6070: return if ($namespace eq 'courserequests');
6071: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6072: } else {
1.1172.2.26 raeburn 6073: unless ($namespace eq 'courserequests') {
6074: $symb=&escape(&symbclean($symb));
6075: }
1.122 albertel 6076: }
1.188 www 6077: if (!$namespace) {
1.620 albertel 6078: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6079: return '';
6080: }
6081: }
1.620 albertel 6082: if (!$domain) { $domain=$env{'user.domain'}; }
6083: if (!$stuname) { $stuname=$env{'user.name'}; }
6084: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6085: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6086:
1.12 www 6087: my %returnhash=();
1.800 albertel 6088: foreach my $line (split(/\&/,$answer)) {
6089: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6090: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6091: }
1.75 www 6092: my $version;
6093: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6094: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6095: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6096: }
1.75 www 6097: }
1.13 www 6098: return %returnhash;
1.34 www 6099: }
6100:
6101: # ---------------------------------------------------------- Course Description
1.1118 foxr 6102: #
6103: #
1.34 www 6104:
6105: sub coursedescription {
1.731 albertel 6106: my ($courseid,$args)=@_;
1.34 www 6107: $courseid=~s/^\///;
1.49 www 6108: $courseid=~s/\_/\//g;
1.34 www 6109: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6110: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6111: my $normalid=$cdomain.'_'.$cnum;
6112: # need to always cache even if we get errors otherwise we keep
6113: # trying and trying and trying to get the course description.
6114: my %envhash=();
6115: my %returnhash=();
1.731 albertel 6116:
6117: my $expiretime=600;
6118: if ($env{'request.course.id'} eq $normalid) {
6119: $expiretime=120;
6120: }
6121:
6122: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6123: if (!$args->{'freshen_cache'}
6124: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6125: foreach my $key (keys(%env)) {
6126: next if ($key !~ /^\Q$prefix\E(.*)/);
6127: my ($setting) = $1;
6128: $returnhash{$setting} = $env{$key};
6129: }
6130: return %returnhash;
6131: }
6132:
1.1118 foxr 6133: # get the data again
6134:
1.731 albertel 6135: if (!$args->{'one_time'}) {
6136: $envhash{'course.'.$normalid.'.last_cache'}=time;
6137: }
1.811 albertel 6138:
1.34 www 6139: if ($chome ne 'no_host') {
1.302 albertel 6140: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6141: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6142: my $username = $env{'user.name'}; # Defult username
6143: if(defined $args->{'user'}) {
6144: $username = $args->{'user'};
6145: }
1.129 albertel 6146: $returnhash{'home'}= $chome;
6147: $returnhash{'domain'} = $cdomain;
6148: $returnhash{'num'} = $cnum;
1.741 raeburn 6149: if (!defined($returnhash{'type'})) {
6150: $returnhash{'type'} = 'Course';
6151: }
1.130 albertel 6152: while (my ($name,$value) = each %returnhash) {
1.53 www 6153: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6154: }
1.270 www 6155: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6156: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6157: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6158: $envhash{'course.'.$normalid.'.home'}=$chome;
6159: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6160: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6161: }
6162: }
1.731 albertel 6163: if (!$args->{'one_time'}) {
1.949 raeburn 6164: &appenv(\%envhash);
1.731 albertel 6165: }
1.302 albertel 6166: return %returnhash;
1.461 www 6167: }
6168:
1.1080 raeburn 6169: sub update_released_required {
6170: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6171: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6172: $cid = $env{'request.course.id'};
6173: $cdom = $env{'course.'.$cid.'.domain'};
6174: $cnum = $env{'course.'.$cid.'.num'};
6175: $chome = $env{'course.'.$cid.'.home'};
6176: }
6177: if ($needsrelease) {
6178: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6179: my $needsupdate;
6180: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6181: $needsupdate = 1;
6182: } else {
6183: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6184: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6185: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6186: $needsupdate = 1;
6187: }
6188: }
6189: if ($needsupdate) {
6190: my %needshash = (
6191: 'internal.releaserequired' => $needsrelease,
6192: );
6193: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6194: if ($putresult eq 'ok') {
6195: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6196: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6197: if (ref($crsinfo{$cid}) eq 'HASH') {
6198: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6199: &courseidput($cdom,\%crsinfo,$chome,'notime');
6200: }
6201: }
6202: }
6203: }
6204: return;
6205: }
6206:
1.461 www 6207: # -------------------------------------------------See if a user is privileged
6208:
6209: sub privileged {
1.1172.2.23 raeburn 6210: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6211: my $now = time;
1.1172.2.23 raeburn 6212: my $roles;
6213: if (ref($possroles) eq 'ARRAY') {
6214: $roles = $possroles;
6215: } else {
6216: $roles = ['dc','su'];
6217: }
6218: if (ref($possdomains) eq 'ARRAY') {
6219: my %privileged = &privileged_by_domain($possdomains,$roles);
6220: foreach my $dom (@{$possdomains}) {
6221: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6222: (ref($privileged{$dom}) eq 'HASH')) {
6223: foreach my $role (@{$roles}) {
6224: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6225: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6226: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6227: return 1 unless (($end && $end < $now) ||
6228: ($start && $start > $now));
6229: }
6230: }
6231: }
6232: }
6233: }
6234: } else {
6235: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6236: my $now = time;
1.1170 droeschl 6237:
1.1172.2.58 raeburn 6238: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6239: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6240: if (grep(/^\Q$trole\E$/,@{$roles})) {
6241: return 1 unless ($tend && $tend < $now)
6242: or ($tstart && $tstart > $now);
1.1170 droeschl 6243: }
1.1172.2.23 raeburn 6244: }
6245: }
1.461 www 6246: return 0;
1.9 www 6247: }
1.1 albertel 6248:
1.1172.2.23 raeburn 6249: sub privileged_by_domain {
6250: my ($domains,$roles) = @_;
6251: my %privileged = ();
6252: my $cachetime = 60*60*24;
6253: my $now = time;
6254: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6255: return %privileged;
6256: }
6257: foreach my $dom (@{$domains}) {
6258: next if (ref($privileged{$dom}) eq 'HASH');
6259: my $needroles;
6260: foreach my $role (@{$roles}) {
6261: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6262: if (defined($cached)) {
6263: if (ref($result) eq 'HASH') {
6264: $privileged{$dom}{$role} = $result;
6265: }
6266: } else {
6267: $needroles = 1;
6268: }
6269: }
6270: if ($needroles) {
6271: my %dompersonnel = &get_domain_roles($dom,$roles);
6272: $privileged{$dom} = {};
6273: foreach my $server (keys(%dompersonnel)) {
6274: if (ref($dompersonnel{$server}) eq 'HASH') {
6275: foreach my $item (keys(%{$dompersonnel{$server}})) {
6276: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6277: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6278: next if ($end && $end < $now);
6279: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6280: $dompersonnel{$server}{$item};
6281: }
6282: }
6283: }
6284: if (ref($privileged{$dom}) eq 'HASH') {
6285: foreach my $role (@{$roles}) {
6286: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6287: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6288: } else {
6289: my %hash = ();
6290: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6291: }
6292: }
6293: }
6294: }
6295: }
6296: return %privileged;
6297: }
6298:
1.103 harris41 6299: # -------------------------------------------------------- Get user privileges
1.11 www 6300:
6301: sub rolesinit {
1.1169 droeschl 6302: my ($domain, $username) = @_;
6303: my %userroles = ('user.login.time' => time);
6304: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6305:
6306: # firstaccess and timerinterval are related to timed maps/resources.
6307: # also, blocking can be triggered by an activating timer
6308: # it's saved in the user's %env.
6309: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6310: my %timerinterval = &dump('timerinterval', $domain, $username);
6311: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6312: %timerintchk, %timerintenv);
6313:
1.1162 raeburn 6314: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6315: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6316: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6317: }
1.1169 droeschl 6318:
1.1162 raeburn 6319: foreach my $key (keys(%timerinterval)) {
6320: my ($cid,$rest) = split(/\0/,$key);
6321: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6322: }
1.1169 droeschl 6323:
1.11 www 6324: my %allroles=();
1.1162 raeburn 6325: my %allgroups=();
1.11 www 6326:
1.1172.2.58 raeburn 6327: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6328: my $role = $rolesdump{$area};
6329: $area =~ s/\_\w\w$//;
6330:
6331: my ($trole, $tend, $tstart, $group_privs);
6332:
6333: if ($role =~ /^cr/) {
6334: # Custom role, defined by a user
6335: # e.g., user.role.cr/msu/smith/mynewrole
6336: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6337: $trole = $1;
6338: ($tend, $tstart) = split('_', $2);
6339: } else {
6340: $trole = $role;
6341: }
6342: } elsif ($role =~ m|^gr/|) {
6343: # Role of member in a group, defined within a course/community
6344: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6345: ($trole, $tend, $tstart) = split(/_/, $role);
6346: next if $tstart eq '-1';
6347: ($trole, $group_privs) = split(/\//, $trole);
6348: $group_privs = &unescape($group_privs);
6349: } else {
6350: # Just a normal role, defined in roles.tab
6351: ($trole, $tend, $tstart) = split(/_/,$role);
6352: }
6353:
6354: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6355: $username);
6356: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6357:
6358: # role expired or not available yet?
6359: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6360: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6361:
6362: next if $area eq '' or $trole eq '';
6363:
6364: my $spec = "$trole.$area";
6365: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6366:
6367: if ($trole =~ /^cr\//) {
6368: # Custom role, defined by a user
6369: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6370: } elsif ($trole eq 'gr') {
6371: # Role of a member in a group, defined within a course/community
6372: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6373: next;
6374: } else {
6375: # Normal role, defined in roles.tab
6376: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6377: }
6378:
6379: my $cid = $tdomain.'_'.$trest;
6380: unless ($firstaccchk{$cid}) {
6381: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6382: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6383: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6384: $coursetimerstarts{$cid}{$item};
6385: }
6386: }
6387: $firstaccchk{$cid} = 1;
6388: }
6389: unless ($timerintchk{$cid}) {
6390: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6391: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6392: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6393: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6394: }
1.12 www 6395: }
1.1169 droeschl 6396: $timerintchk{$cid} = 1;
1.191 harris41 6397: }
1.11 www 6398: }
1.1169 droeschl 6399:
1.1172.2.91 raeburn 6400: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6401: \%allroles, \%allgroups);
1.1169 droeschl 6402: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6403: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6404:
1.1162 raeburn 6405: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6406: }
6407:
1.567 raeburn 6408: sub set_arearole {
1.1172.2.19 raeburn 6409: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6410: unless ($nolog) {
1.567 raeburn 6411: # log the associated role with the area
1.1172.2.19 raeburn 6412: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6413: }
1.743 albertel 6414: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6415: }
6416:
6417: sub custom_roleprivs {
6418: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6419: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6420: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6421: if (&hostname($homsvr) ne '') {
1.567 raeburn 6422: my ($rdummy,$roledef)=
6423: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6424: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6425: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6426: if (defined($syspriv)) {
1.1043 raeburn 6427: if ($trest =~ /^$match_community$/) {
6428: $syspriv =~ s/bre\&S//;
6429: }
1.567 raeburn 6430: $$allroles{'cm./'}.=':'.$syspriv;
6431: $$allroles{$spec.'./'}.=':'.$syspriv;
6432: }
6433: if ($tdomain ne '') {
6434: if (defined($dompriv)) {
6435: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6436: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6437: }
6438: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6439: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6440: my $rolename = $1;
6441: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6442: }
1.567 raeburn 6443: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6444: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6445: }
6446: }
6447: }
6448: }
6449: }
6450:
1.1172.2.89 raeburn 6451: sub course_adhocrole_privs {
6452: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6453: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6454: if ($overrides{"internal.adhocpriv.$rolename"}) {
6455: my (%currprivs,%storeprivs);
6456: foreach my $item (split(/:/,$coursepriv)) {
6457: my ($priv,$restrict) = split(/\&/,$item);
6458: $currprivs{$priv} = $restrict;
6459: }
6460: my (%possadd,%possremove,%full);
6461: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6462: my ($priv,$restrict)=split(/\&/,$item);
6463: $full{$priv} = $restrict;
6464: }
6465: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6466: next if ($item eq '');
6467: my ($rule,$rest) = split(/=/,$item);
6468: next unless (($rule eq 'off') || ($rule eq 'on'));
6469: foreach my $priv (split(/:/,$rest)) {
6470: if ($priv ne '') {
6471: if ($rule eq 'off') {
6472: $possremove{$priv} = 1;
6473: } else {
6474: $possadd{$priv} = 1;
6475: }
6476: }
6477: }
6478: }
6479: foreach my $priv (sort(keys(%full))) {
6480: if (exists($currprivs{$priv})) {
6481: unless (exists($possremove{$priv})) {
6482: $storeprivs{$priv} = $currprivs{$priv};
6483: }
6484: } elsif (exists($possadd{$priv})) {
6485: $storeprivs{$priv} = $full{$priv};
6486: }
6487: }
6488: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6489: }
6490: return $coursepriv;
6491: }
6492:
1.678 raeburn 6493: sub group_roleprivs {
6494: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6495: my $access = 1;
6496: my $now = time;
6497: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6498: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6499: if ($access) {
1.811 albertel 6500: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6501: $$allgroups{$course}{$group} .=':'.$group_privs;
6502: }
6503: }
1.567 raeburn 6504:
6505: sub standard_roleprivs {
6506: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6507: if (defined($pr{$trole.':s'})) {
6508: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6509: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6510: }
6511: if ($tdomain ne '') {
6512: if (defined($pr{$trole.':d'})) {
6513: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6514: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6515: }
6516: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6517: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6518: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6519: }
6520: }
6521: }
6522:
6523: sub set_userprivs {
1.1064 raeburn 6524: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6525: my $author=0;
6526: my $adv=0;
1.1172.2.91 raeburn 6527: my $rar=0;
1.678 raeburn 6528: my %grouproles = ();
6529: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6530: my @groupkeys;
1.1000 raeburn 6531: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6532: push(@groupkeys,$role);
6533: }
6534: if (ref($groups_roles) eq 'HASH') {
6535: foreach my $key (keys(%{$groups_roles})) {
6536: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6537: push(@groupkeys,$key);
6538: }
6539: }
6540: }
6541: if (@groupkeys > 0) {
6542: foreach my $role (@groupkeys) {
6543: my ($trole,$area,$sec,$extendedarea);
6544: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6545: $trole = $1;
6546: $area = $2;
6547: $sec = $3;
6548: $extendedarea = $area.$sec;
6549: if (exists($$allgroups{$area})) {
6550: foreach my $group (keys(%{$$allgroups{$area}})) {
6551: my $spec = $trole.'.'.$extendedarea;
6552: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6553: $$allgroups{$area}{$group};
1.1064 raeburn 6554: }
1.678 raeburn 6555: }
6556: }
6557: }
6558: }
6559: }
1.800 albertel 6560: foreach my $group (keys(%grouproles)) {
6561: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6562: }
1.800 albertel 6563: foreach my $role (keys(%{$allroles})) {
6564: my %thesepriv;
1.941 raeburn 6565: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6566: foreach my $item (split(/:/,$$allroles{$role})) {
6567: if ($item ne '') {
6568: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6569: if ($restrictions eq '') {
6570: $thesepriv{$privilege}='F';
6571: } elsif ($thesepriv{$privilege} ne 'F') {
6572: $thesepriv{$privilege}.=$restrictions;
6573: }
6574: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 6575: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6576: }
6577: }
6578: my $thesestr='';
1.1104 raeburn 6579: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6580: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6581: }
6582: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6583: }
1.1172.2.91 raeburn 6584: return ($author,$adv,$rar);
1.567 raeburn 6585: }
6586:
1.994 raeburn 6587: sub role_status {
1.1104 raeburn 6588: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6589: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 6590: my ($one,$two) = split(m{\./},$rolekey,2);
6591: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6592: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 6593: $$where = '/'.$two;
1.994 raeburn 6594: $$trolecode=$$role.'.'.$$where;
6595: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6596: $$tstatus='is';
1.1104 raeburn 6597: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6598: $$tstatus='future';
1.1034 raeburn 6599: if ($$tstart<$now) {
6600: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6601: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6602: my (%allroles,%allgroups,$group_privs,
6603: %groups_roles,@rolecodes);
1.1002 raeburn 6604: my %userroles = (
6605: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6606: );
1.1064 raeburn 6607: @rolecodes = ('cm');
1.1002 raeburn 6608: my $spec=$$role.'.'.$$where;
6609: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6610: if ($$role =~ /^cr\//) {
6611: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6612: push(@rolecodes,'cr');
1.1002 raeburn 6613: } elsif ($$role eq 'gr') {
1.1064 raeburn 6614: push(@rolecodes,$$role);
1.1002 raeburn 6615: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6616: $env{'user.name'});
1.1064 raeburn 6617: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6618: (undef,my $group_privs) = split(/\//,$trole);
6619: $group_privs = &unescape($group_privs);
6620: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6621: 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 6622: &get_groups_roles($tdomain,$trest,
6623: \%course_roles,\@rolecodes,
6624: \%groups_roles);
1.1002 raeburn 6625: } else {
1.1064 raeburn 6626: push(@rolecodes,$$role);
1.1002 raeburn 6627: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6628: }
1.1172.2.91 raeburn 6629: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6630: \%groups_roles);
1.1064 raeburn 6631: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6632: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6633: }
6634: }
1.1034 raeburn 6635: $$tstatus = 'is';
1.1002 raeburn 6636: }
1.994 raeburn 6637: }
6638: if ($$tend) {
1.1104 raeburn 6639: if ($$tend<$update) {
1.994 raeburn 6640: $$tstatus='expired';
6641: } elsif ($$tend<$now) {
6642: $$tstatus='will_not';
6643: }
6644: }
6645: }
6646: }
6647: }
6648:
1.1104 raeburn 6649: sub get_groups_roles {
6650: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6651: return unless((ref($cdom_courseroles) eq 'HASH') &&
6652: (ref($rolecodes) eq 'ARRAY') &&
6653: (ref($groups_roles) eq 'HASH'));
6654: if (keys(%{$cdom_courseroles}) > 0) {
6655: my ($cnum) = ($rest =~ /^($match_courseid)/);
6656: if ($cdom ne '' && $cnum ne '') {
6657: foreach my $key (keys(%{$cdom_courseroles})) {
6658: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6659: my $crsrole = $1;
6660: my $crssec = $2;
6661: if ($crsrole =~ /^cr/) {
6662: unless (grep(/^cr$/,@{$rolecodes})) {
6663: push(@{$rolecodes},'cr');
6664: }
6665: } else {
6666: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6667: push(@{$rolecodes},$crsrole);
6668: }
6669: }
6670: my $rolekey = "$crsrole./$cdom/$cnum";
6671: if ($crssec ne '') {
6672: $rolekey .= "/$crssec";
6673: }
6674: $rolekey .= './';
6675: $groups_roles->{$rolekey} = $rolecodes;
6676: }
6677: }
6678: }
6679: }
6680: return;
6681: }
6682:
6683: sub delete_env_groupprivs {
6684: my ($where,$courseroles,$possroles) = @_;
6685: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6686: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6687: unless (ref($courseroles->{$udom}) eq 'HASH') {
6688: %{$courseroles->{$udom}} =
6689: &get_my_roles('','','userroles',['active'],
6690: $possroles,[$udom],1);
6691: }
6692: if (ref($courseroles->{$udom}) eq 'HASH') {
6693: foreach my $item (keys(%{$courseroles->{$udom}})) {
6694: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6695: my $area = '/'.$cdom.'/'.$cnum;
6696: my $privkey = "user.priv.$crsrole.$area";
6697: if ($crssec ne '') {
6698: $privkey .= '/'.$crssec;
6699: }
6700: $privkey .= ".$area/$group";
6701: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6702: }
6703: }
6704: return;
6705: }
6706:
1.994 raeburn 6707: sub check_adhoc_privs {
1.1172.2.86 raeburn 6708: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6709: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6710: if ($sec) {
6711: $cckey .= '/'.$sec;
6712: }
1.1172.2.9 raeburn 6713: my $setprivs;
1.994 raeburn 6714: if ($env{$cckey}) {
6715: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6716: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6717: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6718: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6719: $setprivs = 1;
1.994 raeburn 6720: }
6721: } else {
1.1172.2.87 raeburn 6722: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6723: $setprivs = 1;
1.994 raeburn 6724: }
1.1172.2.9 raeburn 6725: return $setprivs;
1.994 raeburn 6726: }
6727:
6728: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6729: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6730: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6731: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6732: if ($sec ne '') {
6733: $area .= '/'.$sec;
6734: }
1.994 raeburn 6735: my $spec = $role.'.'.$area;
6736: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6737: $env{'user.name'},1);
1.1172.2.84 raeburn 6738: my %rolehash = ();
1.1172.2.89 raeburn 6739: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6740: my $rolename = $1;
1.1172.2.84 raeburn 6741: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6742: my %domdef = &get_domain_defaults($dcdom);
6743: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6744: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6745: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6746: }
6747: }
1.1172.2.84 raeburn 6748: } else {
6749: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6750: }
1.1172.2.91 raeburn 6751: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6752: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6753: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6754: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6755: &appenv( {'request.role' => $spec,
6756: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6757: 'request.course.sec' => $sec,
1.1088 raeburn 6758: }
6759: );
6760: my $tadv=0;
6761: if (&allowed('adv') eq 'F') { $tadv=1; }
6762: &appenv({'request.role.adv' => $tadv});
6763: }
1.994 raeburn 6764: }
6765:
1.12 www 6766: # --------------------------------------------------------------- get interface
6767:
6768: sub get {
1.131 albertel 6769: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6770: my $items='';
1.800 albertel 6771: foreach my $item (@$storearr) {
6772: $items.=&escape($item).'&';
1.191 harris41 6773: }
1.12 www 6774: $items=~s/\&$//;
1.620 albertel 6775: if (!$udomain) { $udomain=$env{'user.domain'}; }
6776: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6777: my $uhome=&homeserver($uname,$udomain);
6778:
1.133 albertel 6779: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6780: my @pairs=split(/\&/,$rep);
1.273 albertel 6781: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6782: return @pairs;
6783: }
1.15 www 6784: my %returnhash=();
1.42 www 6785: my $i=0;
1.800 albertel 6786: foreach my $item (@$storearr) {
6787: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6788: $i++;
1.191 harris41 6789: }
1.15 www 6790: return %returnhash;
1.27 www 6791: }
6792:
6793: # --------------------------------------------------------------- del interface
6794:
6795: sub del {
1.133 albertel 6796: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6797: my $items='';
1.800 albertel 6798: foreach my $item (@$storearr) {
6799: $items.=&escape($item).'&';
1.191 harris41 6800: }
1.984 neumanie 6801:
1.27 www 6802: $items=~s/\&$//;
1.620 albertel 6803: if (!$udomain) { $udomain=$env{'user.domain'}; }
6804: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6805: my $uhome=&homeserver($uname,$udomain);
6806: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6807: }
6808:
6809: # -------------------------------------------------------------- dump interface
6810:
1.1172.2.22 raeburn 6811: sub unserialize {
6812: my ($rep, $escapedkeys) = @_;
6813:
6814: return {} if $rep =~ /^error/;
6815:
6816: my %returnhash=();
6817: foreach my $item (split(/\&/,$rep)) {
6818: my ($key, $value) = split(/=/, $item, 2);
6819: $key = unescape($key) unless $escapedkeys;
6820: next if $key =~ /^error: 2 /;
6821: $returnhash{$key} = &thaw_unescape($value);
6822: }
6823: return \%returnhash;
6824: }
6825:
6826: # see Lond::dump_with_regexp
6827: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6828: sub dump {
1.1172.2.22 raeburn 6829: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6830: if (!$udomain) { $udomain=$env{'user.domain'}; }
6831: if (!$uname) { $uname=$env{'user.name'}; }
6832: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6833:
1.1172.2.55 raeburn 6834: if ($regexp) {
6835: $regexp=&escape($regexp);
6836: } else {
6837: $regexp='.';
6838: }
1.1172.2.22 raeburn 6839: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6840: # user is hosted on this machine
1.1172.2.55 raeburn 6841: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6842: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6843: return %{&unserialize($reply, $escapedkeys)};
6844: }
1.1166 raeburn 6845: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6846: my @pairs=split(/\&/,$rep);
6847: my %returnhash=();
1.1098 foxr 6848: if (!($rep =~ /^error/ )) {
6849: foreach my $item (@pairs) {
6850: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6851: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6852: next if ($key =~ /^error: 2 /);
6853: $returnhash{$key}=&thaw_unescape($value);
6854: }
1.755 albertel 6855: }
6856: return %returnhash;
1.407 www 6857: }
6858:
1.1098 foxr 6859:
1.717 albertel 6860: # --------------------------------------------------------- dumpstore interface
6861:
6862: sub dumpstore {
6863: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6864: # same as dump but keys must be escaped. They may contain colon separated
6865: # lists of values that may themself contain colons (e.g. symbs).
6866: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6867: }
6868:
1.407 www 6869: # -------------------------------------------------------------- keys interface
6870:
6871: sub getkeys {
6872: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6873: if (!$udomain) { $udomain=$env{'user.domain'}; }
6874: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6875: my $uhome=&homeserver($uname,$udomain);
6876: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6877: my @keyarray=();
1.800 albertel 6878: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6879: next if ($key =~ /^error: 2 /);
1.800 albertel 6880: push(@keyarray,&unescape($key));
1.407 www 6881: }
6882: return @keyarray;
1.318 matthew 6883: }
6884:
1.319 matthew 6885: # --------------------------------------------------------------- currentdump
6886: sub currentdump {
1.328 matthew 6887: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6888: $courseid = $env{'request.course.id'} if (! defined($courseid));
6889: $sdom = $env{'user.domain'} if (! defined($sdom));
6890: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6891: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6892: my $rep;
6893:
6894: if (grep { $_ eq $uhome } current_machine_ids()) {
6895: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6896: $courseid)));
6897: } else {
6898: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6899: }
6900:
1.318 matthew 6901: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6902: #
1.318 matthew 6903: my %returnhash=();
1.319 matthew 6904: #
6905: if ($rep eq "unknown_cmd") {
6906: # an old lond will not know currentdump
6907: # Do a dump and make it look like a currentdump
1.822 albertel 6908: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6909: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6910: my %hash = @tmp;
6911: @tmp=();
1.424 matthew 6912: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6913: } else {
6914: my @pairs=split(/\&/,$rep);
1.800 albertel 6915: foreach my $pair (@pairs) {
6916: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6917: my ($symb,$param) = split(/:/,$key);
6918: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6919: &thaw_unescape($value);
1.319 matthew 6920: }
1.191 harris41 6921: }
1.12 www 6922: return %returnhash;
1.424 matthew 6923: }
6924:
6925: sub convert_dump_to_currentdump{
6926: my %hash = %{shift()};
6927: my %returnhash;
6928: # Code ripped from lond, essentially. The only difference
6929: # here is the unescaping done by lonnet::dump(). Conceivably
6930: # we might run in to problems with parameter names =~ /^v\./
6931: while (my ($key,$value) = each(%hash)) {
6932: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6933: $symb = &unescape($symb);
6934: $param = &unescape($param);
1.424 matthew 6935: next if ($v eq 'version' || $symb eq 'keys');
6936: next if (exists($returnhash{$symb}) &&
6937: exists($returnhash{$symb}->{$param}) &&
6938: $returnhash{$symb}->{'v.'.$param} > $v);
6939: $returnhash{$symb}->{$param}=$value;
6940: $returnhash{$symb}->{'v.'.$param}=$v;
6941: }
6942: #
6943: # Remove all of the keys in the hashes which keep track of
6944: # the version of the parameter.
6945: while (my ($symb,$param_hash) = each(%returnhash)) {
6946: # use a foreach because we are going to delete from the hash.
6947: foreach my $key (keys(%$param_hash)) {
6948: delete($param_hash->{$key}) if ($key =~ /^v\./);
6949: }
6950: }
6951: return \%returnhash;
1.12 www 6952: }
6953:
1.627 albertel 6954: # ------------------------------------------------------ critical inc interface
6955:
6956: sub cinc {
6957: return &inc(@_,'critical');
6958: }
6959:
1.449 matthew 6960: # --------------------------------------------------------------- inc interface
6961:
6962: sub inc {
1.627 albertel 6963: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6964: if (!$udomain) { $udomain=$env{'user.domain'}; }
6965: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6966: my $uhome=&homeserver($uname,$udomain);
6967: my $items='';
6968: if (! ref($store)) {
6969: # got a single value, so use that instead
6970: $items = &escape($store).'=&';
6971: } elsif (ref($store) eq 'SCALAR') {
6972: $items = &escape($$store).'=&';
6973: } elsif (ref($store) eq 'ARRAY') {
6974: $items = join('=&',map {&escape($_);} @{$store});
6975: } elsif (ref($store) eq 'HASH') {
6976: while (my($key,$value) = each(%{$store})) {
6977: $items.= &escape($key).'='.&escape($value).'&';
6978: }
6979: }
6980: $items=~s/\&$//;
1.627 albertel 6981: if ($critical) {
6982: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6983: } else {
6984: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6985: }
1.449 matthew 6986: }
6987:
1.12 www 6988: # --------------------------------------------------------------- put interface
6989:
6990: sub put {
1.134 albertel 6991: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6992: if (!$udomain) { $udomain=$env{'user.domain'}; }
6993: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6994: my $uhome=&homeserver($uname,$udomain);
1.12 www 6995: my $items='';
1.800 albertel 6996: foreach my $item (keys(%$storehash)) {
6997: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6998: }
1.12 www 6999: $items=~s/\&$//;
1.134 albertel 7000: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7001: }
7002:
1.631 albertel 7003: # ------------------------------------------------------------ newput interface
7004:
7005: sub newput {
7006: my ($namespace,$storehash,$udomain,$uname)=@_;
7007: if (!$udomain) { $udomain=$env{'user.domain'}; }
7008: if (!$uname) { $uname=$env{'user.name'}; }
7009: my $uhome=&homeserver($uname,$udomain);
7010: my $items='';
7011: foreach my $key (keys(%$storehash)) {
7012: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7013: }
7014: $items=~s/\&$//;
7015: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7016: }
7017:
7018: # --------------------------------------------------------- putstore interface
7019:
1.524 raeburn 7020: sub putstore {
1.1172.2.59 raeburn 7021: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7022: if (!$udomain) { $udomain=$env{'user.domain'}; }
7023: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7024: my $uhome=&homeserver($uname,$udomain);
7025: my $items='';
1.715 albertel 7026: foreach my $key (keys(%$storehash)) {
7027: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7028: }
1.715 albertel 7029: $items=~s/\&$//;
1.716 albertel 7030: my $esc_symb=&escape($symb);
7031: my $esc_v=&escape($version);
1.715 albertel 7032: my $reply =
1.716 albertel 7033: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7034: $uhome);
1.1172.2.59 raeburn 7035: if (($tolog) && ($reply eq 'ok')) {
7036: my $namevalue='';
7037: foreach my $key (keys(%{$storehash})) {
7038: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7039: }
1.1172.2.134 raeburn 7040: my $ip = &get_requestor_ip();
1.1172.2.135 raeburn 7041: $namevalue .= 'ip='.&escape($ip).
1.1172.2.59 raeburn 7042: '&host='.&escape($perlvar{'lonHostID'}).
7043: '&version='.$esc_v.
7044: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7045: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7046: }
1.715 albertel 7047: if ($reply eq 'unknown_cmd') {
1.716 albertel 7048: # gfall back to way things use to be done
1.715 albertel 7049: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7050: $uname);
1.524 raeburn 7051: }
1.715 albertel 7052: return $reply;
7053: }
7054:
7055: sub old_putstore {
1.716 albertel 7056: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7057: if (!$udomain) { $udomain=$env{'user.domain'}; }
7058: if (!$uname) { $uname=$env{'user.name'}; }
7059: my $uhome=&homeserver($uname,$udomain);
7060: my %newstorehash;
1.800 albertel 7061: foreach my $item (keys(%$storehash)) {
7062: my $key = $version.':'.&escape($symb).':'.$item;
7063: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7064: }
7065: my $items='';
7066: my %allitems = ();
1.800 albertel 7067: foreach my $item (keys(%newstorehash)) {
7068: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7069: my $key = $1.':keys:'.$2;
7070: $allitems{$key} .= $3.':';
7071: }
1.800 albertel 7072: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7073: }
1.800 albertel 7074: foreach my $item (keys(%allitems)) {
7075: $allitems{$item} =~ s/\:$//;
7076: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7077: }
7078: $items=~s/\&$//;
7079: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7080: }
7081:
1.47 www 7082: # ------------------------------------------------------ critical put interface
7083:
7084: sub cput {
1.134 albertel 7085: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7086: if (!$udomain) { $udomain=$env{'user.domain'}; }
7087: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7088: my $uhome=&homeserver($uname,$udomain);
1.47 www 7089: my $items='';
1.800 albertel 7090: foreach my $item (keys(%$storehash)) {
7091: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7092: }
1.47 www 7093: $items=~s/\&$//;
1.134 albertel 7094: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7095: }
7096:
7097: # -------------------------------------------------------------- eget interface
7098:
7099: sub eget {
1.133 albertel 7100: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7101: my $items='';
1.800 albertel 7102: foreach my $item (@$storearr) {
7103: $items.=&escape($item).'&';
1.191 harris41 7104: }
1.12 www 7105: $items=~s/\&$//;
1.620 albertel 7106: if (!$udomain) { $udomain=$env{'user.domain'}; }
7107: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7108: my $uhome=&homeserver($uname,$udomain);
7109: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7110: my @pairs=split(/\&/,$rep);
7111: my %returnhash=();
1.42 www 7112: my $i=0;
1.800 albertel 7113: foreach my $item (@$storearr) {
7114: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7115: $i++;
1.191 harris41 7116: }
1.12 www 7117: return %returnhash;
7118: }
7119:
1.667 albertel 7120: # ------------------------------------------------------------ tmpput interface
7121: sub tmpput {
1.802 raeburn 7122: my ($storehash,$server,$context)=@_;
1.667 albertel 7123: my $items='';
1.800 albertel 7124: foreach my $item (keys(%$storehash)) {
7125: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7126: }
7127: $items=~s/\&$//;
1.802 raeburn 7128: if (defined($context)) {
7129: $items .= ':'.&escape($context);
7130: }
1.667 albertel 7131: return &reply("tmpput:$items",$server);
7132: }
7133:
7134: # ------------------------------------------------------------ tmpget interface
7135: sub tmpget {
1.688 albertel 7136: my ($token,$server)=@_;
7137: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7138: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7139: my %returnhash;
1.1172.2.85 raeburn 7140: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7141: return %returnhash;
7142: }
1.667 albertel 7143: foreach my $item (split(/\&/,$rep)) {
7144: my ($key,$value)=split(/=/,$item);
7145: $returnhash{&unescape($key)}=&thaw_unescape($value);
7146: }
7147: return %returnhash;
7148: }
7149:
1.1113 raeburn 7150: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7151: sub tmpdel {
7152: my ($token,$server)=@_;
7153: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7154: return &reply("tmpdel:$token",$server);
7155: }
7156:
1.1172.2.13 raeburn 7157: # ------------------------------------------------------------ get_timebased_id
7158:
7159: sub get_timebased_id {
7160: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7161: $maxtries) = @_;
7162: my ($newid,$error,$dellock);
7163: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7164: return ('','ok','invalid call to get suffix');
7165: }
7166:
7167: # set defaults for any optional args for which values were not supplied
7168: if ($who eq '') {
7169: $who = $env{'user.name'}.':'.$env{'user.domain'};
7170: }
7171: if (!$locktries) {
7172: $locktries = 3;
7173: }
7174: if (!$maxtries) {
7175: $maxtries = 10;
7176: }
7177:
7178: if (($cdom eq '') || ($cnum eq '')) {
7179: if ($env{'request.course.id'}) {
7180: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7181: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7182: }
7183: if (($cdom eq '') || ($cnum eq '')) {
7184: return ('','ok','call to get suffix not in course context');
7185: }
7186: }
7187:
7188: # construct locking item
7189: my $lockhash = {
7190: $prefix."\0".'locked_'.$keyid => $who,
7191: };
7192: my $tries = 0;
7193:
7194: # attempt to get lock on nohist_$namespace file
7195: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7196: while (($gotlock ne 'ok') && $tries <$locktries) {
7197: $tries ++;
7198: sleep 1;
7199: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7200: }
7201:
7202: # attempt to get unique identifier, based on current timestamp
7203: if ($gotlock eq 'ok') {
7204: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7205: my $id = time;
7206: $newid = $id;
1.1172.2.56 raeburn 7207: if ($idtype eq 'addcode') {
7208: $newid .= &sixnum_code();
7209: }
1.1172.2.13 raeburn 7210: my $idtries = 0;
7211: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7212: if ($idtype eq 'concat') {
7213: $newid = $id.$idtries;
1.1172.2.56 raeburn 7214: } elsif ($idtype eq 'addcode') {
7215: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7216: } else {
7217: $newid ++;
7218: }
7219: $idtries ++;
7220: }
7221: if (!exists($inuse{$prefix."\0".$newid})) {
7222: my %new_item = (
7223: $prefix."\0".$newid => $who,
7224: );
7225: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7226: $cdom,$cnum);
7227: if ($putresult ne 'ok') {
7228: undef($newid);
7229: $error = 'error saving new item: '.$putresult;
7230: }
7231: } else {
1.1172.2.56 raeburn 7232: undef($newid);
1.1172.2.13 raeburn 7233: $error = ('error: no unique suffix available for the new item ');
7234: }
7235: # remove lock
7236: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7237: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7238: } else {
7239: $error = "error: could not obtain lockfile\n";
7240: $dellock = 'ok';
1.1172.2.58 raeburn 7241: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7242: $dellock = 'nolock';
7243: }
1.1172.2.13 raeburn 7244: }
7245: return ($newid,$dellock,$error);
7246: }
7247:
1.1172.2.56 raeburn 7248: sub sixnum_code {
7249: my $code;
7250: for (0..6) {
7251: $code .= int( rand(9) );
7252: }
7253: return $code;
7254: }
7255:
1.765 albertel 7256: # -------------------------------------------------- portfolio access checking
7257:
7258: sub portfolio_access {
1.1172.2.77 raeburn 7259: my ($requrl,$clientip) = @_;
1.765 albertel 7260: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7261: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7262: if ($result) {
7263: my %setters;
7264: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7265: my ($startblock,$endblock) =
7266: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7267: if ($startblock && $endblock) {
7268: return 'B';
7269: }
7270: } else {
7271: my ($startblock,$endblock) =
7272: &Apache::loncommon::blockcheck(\%setters,'port');
7273: if ($startblock && $endblock) {
7274: return 'B';
7275: }
7276: }
7277: }
1.765 albertel 7278: if ($result eq 'ok') {
1.766 albertel 7279: return 'F';
1.765 albertel 7280: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7281: return 'A';
1.765 albertel 7282: }
1.766 albertel 7283: return '';
1.765 albertel 7284: }
7285:
7286: sub get_portfolio_access {
1.1172.2.77 raeburn 7287: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7288:
7289: if (!ref($access_hash)) {
7290: my $current_perms = &get_portfile_permissions($udom,$unum);
7291: my %access_controls = &get_access_controls($current_perms,$group,
7292: $file_name);
7293: $access_hash = $access_controls{$file_name};
7294: }
7295:
1.1172.2.77 raeburn 7296: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7297: my $now = time;
7298: if (ref($access_hash) eq 'HASH') {
7299: foreach my $key (keys(%{$access_hash})) {
7300: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7301: if ($start > $now) {
7302: next;
7303: }
7304: if ($end && $end<$now) {
7305: next;
7306: }
7307: if ($scope eq 'public') {
7308: $public = $key;
7309: last;
7310: } elsif ($scope eq 'guest') {
7311: $guest = $key;
7312: } elsif ($scope eq 'domains') {
7313: push(@domains,$key);
7314: } elsif ($scope eq 'users') {
7315: push(@users,$key);
7316: } elsif ($scope eq 'course') {
7317: push(@courses,$key);
7318: } elsif ($scope eq 'group') {
7319: push(@groups,$key);
1.1172.2.77 raeburn 7320: } elsif ($scope eq 'ip') {
7321: push(@ips,$key);
1.765 albertel 7322: }
7323: }
7324: if ($public) {
7325: return 'ok';
1.1172.2.77 raeburn 7326: } elsif (@ips > 0) {
7327: my $allowed;
7328: foreach my $ipkey (@ips) {
7329: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7330: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7331: $allowed = 1;
7332: last;
7333: }
7334: }
7335: }
7336: if ($allowed) {
7337: return 'ok';
7338: }
1.765 albertel 7339: }
7340: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7341: if ($guest) {
7342: return $guest;
7343: }
7344: } else {
7345: if (@domains > 0) {
7346: foreach my $domkey (@domains) {
7347: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7348: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7349: return 'ok';
7350: }
7351: }
7352: }
7353: }
7354: if (@users > 0) {
7355: foreach my $userkey (@users) {
1.865 raeburn 7356: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7357: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7358: if (ref($item) eq 'HASH') {
7359: if (($item->{'uname'} eq $env{'user.name'}) &&
7360: ($item->{'udom'} eq $env{'user.domain'})) {
7361: return 'ok';
7362: }
7363: }
7364: }
7365: }
1.765 albertel 7366: }
7367: }
7368: my %roleshash;
7369: my @courses_and_groups = @courses;
7370: push(@courses_and_groups,@groups);
7371: if (@courses_and_groups > 0) {
7372: my (%allgroups,%allroles);
7373: my ($start,$end,$role,$sec,$group);
7374: foreach my $envkey (%env) {
1.1060 raeburn 7375: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7376: my $cid = $2.'_'.$3;
7377: if ($1 eq 'gr') {
7378: $group = $4;
7379: $allgroups{$cid}{$group} = $env{$envkey};
7380: } else {
7381: if ($4 eq '') {
7382: $sec = 'none';
7383: } else {
7384: $sec = $4;
7385: }
7386: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7387: }
1.811 albertel 7388: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7389: my $cid = $2.'_'.$3;
7390: if ($4 eq '') {
7391: $sec = 'none';
7392: } else {
7393: $sec = $4;
7394: }
7395: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7396: }
7397: }
7398: if (keys(%allroles) == 0) {
7399: return;
7400: }
7401: foreach my $key (@courses_and_groups) {
7402: my %content = %{$$access_hash{$key}};
7403: my $cnum = $content{'number'};
7404: my $cdom = $content{'domain'};
7405: my $cid = $cdom.'_'.$cnum;
7406: if (!exists($allroles{$cid})) {
7407: next;
7408: }
7409: foreach my $role_id (keys(%{$content{'roles'}})) {
7410: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7411: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7412: my @status = @{$content{'roles'}{$role_id}{'access'}};
7413: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7414: foreach my $role (keys(%{$allroles{$cid}})) {
7415: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7416: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7417: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7418: if (grep/^all$/,@sections) {
7419: return 'ok';
7420: } else {
7421: if (grep/^$sec$/,@sections) {
7422: return 'ok';
7423: }
7424: }
7425: }
7426: }
7427: if (keys(%{$allgroups{$cid}}) == 0) {
7428: if (grep/^none$/,@groups) {
7429: return 'ok';
7430: }
7431: } else {
7432: if (grep/^all$/,@groups) {
7433: return 'ok';
7434: }
7435: foreach my $group (keys(%{$allgroups{$cid}})) {
7436: if (grep/^$group$/,@groups) {
7437: return 'ok';
7438: }
7439: }
7440: }
7441: }
7442: }
7443: }
7444: }
7445: }
7446: if ($guest) {
7447: return $guest;
7448: }
7449: }
7450: }
7451: return;
7452: }
7453:
7454: sub course_group_datechecker {
7455: my ($dates,$now,$status) = @_;
7456: my ($start,$end) = split(/\./,$dates);
7457: if (!$start && !$end) {
7458: return 'ok';
7459: }
7460: if (grep/^active$/,@{$status}) {
7461: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7462: return 'ok';
7463: }
7464: }
7465: if (grep/^previous$/,@{$status}) {
7466: if ($end > $now ) {
7467: return 'ok';
7468: }
7469: }
7470: if (grep/^future$/,@{$status}) {
7471: if ($start > $now) {
7472: return 'ok';
7473: }
7474: }
7475: return;
7476: }
7477:
7478: sub parse_portfolio_url {
7479: my ($url) = @_;
7480:
7481: my ($type,$udom,$unum,$group,$file_name);
7482:
1.823 albertel 7483: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7484: $type = 1;
7485: $udom = $1;
7486: $unum = $2;
7487: $file_name = $3;
1.823 albertel 7488: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7489: $type = 2;
7490: $udom = $1;
7491: $unum = $2;
7492: $group = $3;
7493: $file_name = $3.'/'.$4;
7494: }
7495: if (wantarray) {
7496: return ($type,$udom,$unum,$file_name,$group);
7497: }
7498: return $type;
7499: }
7500:
7501: sub is_portfolio_url {
7502: my ($url) = @_;
7503: return scalar(&parse_portfolio_url($url));
7504: }
7505:
1.798 raeburn 7506: sub is_portfolio_file {
7507: my ($file) = @_;
1.820 raeburn 7508: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7509: return 1;
7510: }
7511: return;
7512: }
7513:
1.976 raeburn 7514: sub usertools_access {
1.1084 raeburn 7515: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7516: my ($access,%tools);
7517: if ($context eq '') {
7518: $context = 'tools';
7519: }
7520: if ($context eq 'requestcourses') {
7521: %tools = (
7522: official => 1,
7523: unofficial => 1,
1.1006 raeburn 7524: community => 1,
1.1172.2.37 raeburn 7525: textbook => 1,
1.985 raeburn 7526: );
1.1172.2.9 raeburn 7527: } elsif ($context eq 'requestauthor') {
7528: %tools = (
7529: requestauthor => 1,
7530: );
1.985 raeburn 7531: } else {
7532: %tools = (
7533: aboutme => 1,
7534: blog => 1,
1.1172.2.6 raeburn 7535: webdav => 1,
1.985 raeburn 7536: portfolio => 1,
7537: );
7538: }
1.976 raeburn 7539: return if (!defined($tools{$tool}));
7540:
1.1172.2.35 raeburn 7541: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7542: $udom = $env{'user.domain'};
7543: $uname = $env{'user.name'};
7544: }
7545:
1.978 raeburn 7546: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7547: if ($action ne 'reload') {
1.985 raeburn 7548: if ($context eq 'requestcourses') {
7549: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 7550: } elsif ($context eq 'requestauthor') {
7551: return $env{'environment.canrequest.author'};
1.985 raeburn 7552: } else {
7553: return $env{'environment.availabletools.'.$tool};
7554: }
7555: }
1.976 raeburn 7556: }
7557:
1.1172.2.9 raeburn 7558: my ($toolstatus,$inststatus,$envkey);
7559: if ($context eq 'requestauthor') {
7560: $envkey = $context;
7561: } else {
7562: $envkey = $context.'.'.$tool;
7563: }
1.976 raeburn 7564:
1.985 raeburn 7565: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7566: ($action ne 'reload')) {
1.1172.2.9 raeburn 7567: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7568: $inststatus = $env{'environment.inststatus'};
7569: } else {
1.1084 raeburn 7570: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 7571: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7572: $inststatus = $userenvref->{'inststatus'};
7573: } else {
1.1172.2.9 raeburn 7574: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7575: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7576: $inststatus = $userenv{'inststatus'};
7577: }
1.976 raeburn 7578: }
7579:
7580: if ($toolstatus ne '') {
7581: if ($toolstatus) {
7582: $access = 1;
7583: } else {
7584: $access = 0;
7585: }
7586: return $access;
7587: }
7588:
1.1084 raeburn 7589: my ($is_adv,%domdef);
7590: if (ref($is_advref) eq 'HASH') {
7591: $is_adv = $is_advref->{'is_adv'};
7592: } else {
7593: $is_adv = &is_advanced_user($udom,$uname);
7594: }
7595: if (ref($domdefref) eq 'HASH') {
7596: %domdef = %{$domdefref};
7597: } else {
7598: %domdef = &get_domain_defaults($udom);
7599: }
1.976 raeburn 7600: if (ref($domdef{$tool}) eq 'HASH') {
7601: if ($is_adv) {
7602: if ($domdef{$tool}{'_LC_adv'} ne '') {
7603: if ($domdef{$tool}{'_LC_adv'}) {
7604: $access = 1;
7605: } else {
7606: $access = 0;
7607: }
7608: return $access;
7609: }
7610: }
7611: if ($inststatus ne '') {
7612: my ($hasaccess,$hasnoaccess);
7613: foreach my $affiliation (split(/:/,$inststatus)) {
7614: if ($domdef{$tool}{$affiliation} ne '') {
7615: if ($domdef{$tool}{$affiliation}) {
7616: $hasaccess = 1;
7617: } else {
7618: $hasnoaccess = 1;
7619: }
7620: }
7621: }
7622: if ($hasaccess || $hasnoaccess) {
7623: if ($hasaccess) {
7624: $access = 1;
7625: } elsif ($hasnoaccess) {
7626: $access = 0;
7627: }
7628: return $access;
7629: }
7630: } else {
7631: if ($domdef{$tool}{'default'} ne '') {
7632: if ($domdef{$tool}{'default'}) {
7633: $access = 1;
7634: } elsif ($domdef{$tool}{'default'} == 0) {
7635: $access = 0;
7636: }
7637: return $access;
7638: }
7639: }
7640: } else {
1.1172.2.6 raeburn 7641: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7642: $access = 1;
7643: } else {
7644: $access = 0;
7645: }
1.976 raeburn 7646: return $access;
7647: }
7648: }
7649:
1.1050 raeburn 7650: sub is_course_owner {
7651: my ($cdom,$cnum,$udom,$uname) = @_;
7652: if (($udom eq '') || ($uname eq '')) {
7653: $udom = $env{'user.domain'};
7654: $uname = $env{'user.name'};
7655: }
7656: unless (($udom eq '') || ($uname eq '')) {
7657: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7658: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7659: return 1;
7660: } else {
7661: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7662: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7663: return 1;
7664: }
7665: }
7666: }
7667: }
7668: return;
7669: }
7670:
1.976 raeburn 7671: sub is_advanced_user {
7672: my ($udom,$uname) = @_;
1.1085 raeburn 7673: if ($udom ne '' && $uname ne '') {
7674: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7675: if (wantarray) {
7676: return ($env{'user.adv'},$env{'user.author'});
7677: } else {
7678: return $env{'user.adv'};
7679: }
1.1085 raeburn 7680: }
7681: }
1.976 raeburn 7682: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7683: my %allroles;
1.1128 raeburn 7684: my ($is_adv,$is_author);
1.976 raeburn 7685: foreach my $role (keys(%roleshash)) {
7686: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7687: my $area = '/'.$tdomain.'/'.$trest;
7688: if ($sec ne '') {
7689: $area .= '/'.$sec;
7690: }
7691: if (($area ne '') && ($trole ne '')) {
7692: my $spec=$trole.'.'.$area;
7693: if ($trole =~ /^cr\//) {
7694: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7695: } elsif ($trole ne 'gr') {
7696: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7697: }
1.1128 raeburn 7698: if ($trole eq 'au') {
7699: $is_author = 1;
7700: }
1.976 raeburn 7701: }
7702: }
7703: foreach my $role (keys(%allroles)) {
7704: last if ($is_adv);
7705: foreach my $item (split(/:/,$allroles{$role})) {
7706: if ($item ne '') {
7707: my ($privilege,$restrictions)=split(/&/,$item);
7708: if ($privilege eq 'adv') {
7709: $is_adv = 1;
7710: last;
7711: }
7712: }
7713: }
7714: }
1.1128 raeburn 7715: if (wantarray) {
7716: return ($is_adv,$is_author);
7717: }
1.976 raeburn 7718: return $is_adv;
7719: }
1.798 raeburn 7720:
1.1035 raeburn 7721: sub check_can_request {
1.1036 raeburn 7722: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7723: my $canreq = 0;
7724: my ($types,$typename) = &Apache::loncommon::course_types();
7725: my @options = ('approval','validate','autolimit');
7726: my $optregex = join('|',@options);
7727: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7728: foreach my $type (@{$types}) {
7729: if (&usertools_access($env{'user.name'},
7730: $env{'user.domain'},
7731: $type,undef,'requestcourses')) {
7732: $canreq ++;
1.1036 raeburn 7733: if (ref($request_domains) eq 'HASH') {
7734: push(@{$request_domains->{$type}},$env{'user.domain'});
7735: }
1.1035 raeburn 7736: if ($dom eq $env{'user.domain'}) {
7737: $can_request->{$type} = 1;
7738: }
7739: }
7740: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7741: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7742: if (@curr > 0) {
1.1036 raeburn 7743: foreach my $item (@curr) {
7744: if (ref($request_domains) eq 'HASH') {
7745: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7746: if ($otherdom ne '') {
7747: if (ref($request_domains->{$type}) eq 'ARRAY') {
7748: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7749: push(@{$request_domains->{$type}},$otherdom);
7750: }
7751: } else {
7752: push(@{$request_domains->{$type}},$otherdom);
7753: }
7754: }
7755: }
7756: }
7757: unless($dom eq $env{'user.domain'}) {
7758: $canreq ++;
1.1035 raeburn 7759: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7760: $can_request->{$type} = 1;
7761: }
7762: }
7763: }
7764: }
7765: }
7766: }
7767: return $canreq;
7768: }
7769:
1.341 www 7770: # ---------------------------------------------- Custom access rule evaluation
7771:
7772: sub customaccess {
7773: my ($priv,$uri)=@_;
1.807 albertel 7774: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7775: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7776: $udom = &LONCAPA::clean_domain($udom);
7777: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7778: my $access=0;
1.800 albertel 7779: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7780: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7781: if ($type eq 'user') {
7782: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7783: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7784: if ($tdom) {
7785: if ($tdom ne $env{'user.domain'}) { next; }
7786: }
1.896 albertel 7787: if ($tuname) {
7788: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7789: }
7790: $access=($effect eq 'allow');
7791: last;
7792: }
7793: } else {
7794: if ($role) {
7795: if ($role ne $urole) { next; }
7796: }
7797: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7798: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7799: if ($tdom) {
7800: if ($tdom ne $udom) { next; }
7801: }
7802: if ($tcrs) {
7803: if ($tcrs ne $ucrs) { next; }
7804: }
7805: if ($tsec) {
7806: if ($tsec ne $usec) { next; }
7807: }
7808: $access=($effect eq 'allow');
7809: last;
7810: }
7811: if ($realm eq '' && $role eq '') {
7812: $access=($effect eq 'allow');
7813: }
1.402 bowersj2 7814: }
1.341 www 7815: }
7816: return $access;
7817: }
7818:
1.103 harris41 7819: # ------------------------------------------------- Check for a user privilege
1.12 www 7820:
7821: sub allowed {
1.1172.2.126 raeburn 7822: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705 albertel 7823: my $ver_orguri=$uri;
1.439 www 7824: $uri=&deversion($uri);
1.152 www 7825: my $orguri=$uri;
1.52 www 7826: $uri=&declutter($uri);
1.809 raeburn 7827:
1.810 raeburn 7828: if ($priv eq 'evb') {
7829: # Evade communication block restrictions for specified role in a course
7830: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7831: return $1;
7832: } else {
7833: return;
7834: }
7835: }
7836:
1.620 albertel 7837: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7838: # Free bre access to adm and meta resources
1.1172.2.133 raeburn 7839: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$}))
1.769 albertel 7840: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7841: && ($priv eq 'bre')) {
1.14 www 7842: return 'F';
1.159 www 7843: }
7844:
1.545 banghart 7845: # Free bre access to user's own portfolio contents
1.714 raeburn 7846: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7847: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7848: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7849: my %setters;
7850: my ($startblock,$endblock) =
7851: &Apache::loncommon::blockcheck(\%setters,'port');
7852: if ($startblock && $endblock) {
7853: return 'B';
7854: } else {
7855: return 'F';
7856: }
1.545 banghart 7857: }
7858:
1.762 raeburn 7859: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7860: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7861: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7862: if (exists($env{'request.course.id'})) {
7863: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7864: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7865: if (($domain eq $cdom) && ($name eq $cnum)) {
7866: my $courseprivid=$env{'request.course.id'};
7867: $courseprivid=~s/\_/\//;
7868: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7869: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7870: return $1;
1.762 raeburn 7871: } else {
7872: if ($env{'request.course.sec'}) {
7873: $courseprivid.='/'.$env{'request.course.sec'};
7874: }
7875: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7876: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7877: return $2;
7878: }
1.714 raeburn 7879: }
7880: }
7881: }
7882: }
7883:
1.159 www 7884: # Free bre to public access
7885:
7886: if ($priv eq 'bre') {
1.238 www 7887: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7888: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7889: return 'F';
7890: }
1.238 www 7891: if ($copyright eq 'priv') {
7892: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7893: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7894: return '';
7895: }
7896: }
7897: if ($copyright eq 'domain') {
7898: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7899: unless (($env{'user.domain'} eq $1) ||
7900: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7901: return '';
7902: }
1.262 matthew 7903: }
1.620 albertel 7904: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7905: # Library role, so allow browsing of resources in this domain.
7906: return 'F';
1.238 www 7907: }
1.341 www 7908: if ($copyright eq 'custom') {
7909: unless (&customaccess($priv,$uri)) { return ''; }
7910: }
1.14 www 7911: }
1.264 matthew 7912: # Domain coordinator is trying to create a course
1.620 albertel 7913: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7914: # uri is the requested domain in this case.
7915: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7916: # a role of dc for the domain in question.
1.620 albertel 7917: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7918: }
1.29 www 7919:
1.52 www 7920: my $thisallowed='';
7921: my $statecond=0;
7922: my $courseprivid='';
7923:
1.1039 raeburn 7924: my $ownaccess;
1.1043 raeburn 7925: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7926: if (($priv eq 'bro') && ($env{'user.author'})) {
7927: if ($uri eq '') {
7928: $ownaccess = 1;
7929: } else {
7930: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7931: my $udom = $env{'user.domain'};
7932: my $uname = $env{'user.name'};
7933: if ($uri =~ m{^\Q$udom\E/?$}) {
7934: $ownaccess = 1;
1.1040 raeburn 7935: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7936: unless ($uri =~ m{\.\./}) {
7937: $ownaccess = 1;
7938: }
7939: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7940: my $now = time;
7941: if ($uri =~ m{^([^/]+)/?$}) {
7942: my $adom = $1;
7943: foreach my $key (keys(%env)) {
1.1042 raeburn 7944: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7945: my ($start,$end) = split('.',$env{$key});
7946: if (($now >= $start) && (!$end || $end < $now)) {
7947: $ownaccess = 1;
7948: last;
7949: }
7950: }
7951: }
7952: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7953: my $adom = $1;
7954: my $aname = $2;
1.1042 raeburn 7955: foreach my $role ('ca','aa') {
7956: if ($env{"user.role.$role./$adom/$aname"}) {
7957: my ($start,$end) =
7958: split('.',$env{"user.role.$role./$adom/$aname"});
7959: if (($now >= $start) && (!$end || $end < $now)) {
7960: $ownaccess = 1;
7961: last;
7962: }
1.1039 raeburn 7963: }
7964: }
7965: }
7966: }
7967: }
7968: }
7969: }
7970:
1.52 www 7971: # Course
7972:
1.620 albertel 7973: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7974: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7975: $thisallowed.=$1;
7976: }
1.52 www 7977: }
1.29 www 7978:
1.52 www 7979: # Domain
7980:
1.620 albertel 7981: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7982: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7983: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7984: $thisallowed.=$1;
7985: }
1.12 www 7986: }
1.52 www 7987:
1.1141 raeburn 7988: # User who is not author or co-author might still be able to edit
7989: # resource of an author in the domain (e.g., if Domain Coordinator).
7990: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7991: (&allowed('mdc',$env{'request.course.id'}))) {
7992: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7993: $thisallowed.=$1;
7994: }
7995: }
7996:
1.52 www 7997: # Course: uri itself is a course
1.66 www 7998: my $courseuri=$uri;
7999: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8000: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8001:
1.620 albertel 8002: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8003: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 8004: if ($priv eq 'mip') {
8005: my $rem = $1;
8006: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8007: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8008: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8009: if ($cdom ne '') {
8010: my %passwdconf = &get_passwdconf($cdom);
8011: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8012: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8013: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8014: my @inststatuses = split(':',$env{'environment.inststatus'});
8015: unless (@inststatuses) {
8016: @inststatuses = ('default');
8017: }
8018: foreach my $status (@inststatuses) {
8019: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8020: $thisallowed.=$rem;
8021: }
8022: }
8023: }
8024: }
8025: }
8026: }
8027: }
8028: } else {
8029: unless (($priv eq 'bro') && (!$ownaccess)) {
8030: $thisallowed.=$1;
8031: }
1.1039 raeburn 8032: }
1.12 www 8033: }
1.29 www 8034:
1.665 albertel 8035: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8036: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8037: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8038: $thisallowed='';
1.671 raeburn 8039: my ($match)=&is_on_map($uri);
8040: if ($match) {
8041: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8042: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 8043: my $value = $1;
8044: if ($noblockcheck) {
8045: $thisallowed.=$value;
1.1162 raeburn 8046: } else {
1.1172.2.126 raeburn 8047: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8048: if (@blockers > 0) {
8049: $thisallowed = 'B';
8050: } else {
8051: $thisallowed.=$value;
8052: }
1.1162 raeburn 8053: }
1.671 raeburn 8054: }
8055: } else {
1.705 albertel 8056: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8057: if ($refuri) {
8058: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8059: $thisallowed='F';
1.671 raeburn 8060: } else {
8061: $refuri=&declutter($refuri);
8062: my ($match) = &is_on_map($refuri);
8063: if ($match) {
1.1172.2.65 raeburn 8064: if ($noblockcheck) {
1.1162 raeburn 8065: $thisallowed='F';
1.1172.2.65 raeburn 8066: } else {
1.1172.2.127 raeburn 8067: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8068: if (@blockers > 0) {
8069: $thisallowed = 'B';
8070: } else {
8071: $thisallowed='F';
8072: }
1.1162 raeburn 8073: }
1.671 raeburn 8074: }
1.669 raeburn 8075: }
1.671 raeburn 8076: }
8077: }
1.314 www 8078: }
1.492 albertel 8079:
1.766 albertel 8080: if ($priv eq 'bre'
8081: && $thisallowed ne 'F'
8082: && $thisallowed ne '2'
8083: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8084: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8085: }
8086:
1.52 www 8087: # Full access at system, domain or course-wide level? Exit.
1.29 www 8088: if ($thisallowed=~/F/) {
8089: return 'F';
8090: }
8091:
1.52 www 8092: # If this is generating or modifying users, exit with special codes
1.29 www 8093:
1.643 www 8094: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8095: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8096: my ($audom,$auname)=split('/',$uri);
1.643 www 8097: # no author name given, so this just checks on the general right to make a co-author in this domain
8098: unless ($auname) { return $thisallowed; }
8099: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8100: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8101: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8102: ($audom ne $env{'request.role.domain'}))) { return ''; }
8103: }
1.52 www 8104: return $thisallowed;
8105: }
8106: #
1.103 harris41 8107: # Gathered so far: system, domain and course wide privileges
1.52 www 8108: #
8109: # Course: See if uri or referer is an individual resource that is part of
8110: # the course
8111:
1.620 albertel 8112: if ($env{'request.course.id'}) {
1.232 www 8113:
1.1172.2.115 raeburn 8114: # If this is modifying password (internal auth) domains must match for user and user's role.
8115:
8116: if ($priv eq 'mip') {
8117: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8118: return $thisallowed;
8119: } else {
8120: return '';
8121: }
8122: }
8123:
1.620 albertel 8124: $courseprivid=$env{'request.course.id'};
8125: if ($env{'request.course.sec'}) {
8126: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8127: }
8128: $courseprivid=~s/\_/\//;
8129: my $checkreferer=1;
1.232 www 8130: my ($match,$cond)=&is_on_map($uri);
8131: if ($match) {
8132: $statecond=$cond;
1.620 albertel 8133: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8134: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8135: my $value = $1;
8136: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8137: if ($noblockcheck) {
1.1162 raeburn 8138: $thisallowed.=$value;
1.1172.2.65 raeburn 8139: } else {
1.1172.2.126 raeburn 8140: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8141: if (@blockers > 0) {
8142: $thisallowed = 'B';
8143: } else {
8144: $thisallowed.=$value;
8145: }
1.1162 raeburn 8146: }
8147: } else {
8148: $thisallowed.=$value;
8149: }
1.52 www 8150: $checkreferer=0;
8151: }
1.29 www 8152: }
1.1172.2.126 raeburn 8153:
1.148 www 8154: if ($checkreferer) {
1.620 albertel 8155: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8156: unless ($refuri) {
1.800 albertel 8157: foreach my $key (keys(%env)) {
8158: if ($key=~/^httpref\..*\*/) {
8159: my $pattern=$key;
1.156 www 8160: $pattern=~s/^httpref\.\/res\///;
1.148 www 8161: $pattern=~s/\*/\[\^\/\]\+/g;
8162: $pattern=~s/\//\\\//g;
1.152 www 8163: if ($orguri=~/$pattern/) {
1.800 albertel 8164: $refuri=$env{$key};
1.148 www 8165: }
8166: }
1.191 harris41 8167: }
1.148 www 8168: }
1.232 www 8169:
1.148 www 8170: if ($refuri) {
1.152 www 8171: $refuri=&declutter($refuri);
1.232 www 8172: my ($match,$cond)=&is_on_map($refuri);
8173: if ($match) {
8174: my $refstatecond=$cond;
1.620 albertel 8175: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8176: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8177: my $value = $1;
8178: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8179: if ($noblockcheck) {
1.1162 raeburn 8180: $thisallowed.=$value;
1.1172.2.65 raeburn 8181: } else {
1.1172.2.127 raeburn 8182: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8183: if (@blockers > 0) {
8184: $thisallowed = 'B';
8185: } else {
8186: $thisallowed.=$value;
8187: }
1.1162 raeburn 8188: }
8189: } else {
8190: $thisallowed.=$value;
8191: }
1.53 www 8192: $uri=$refuri;
8193: $statecond=$refstatecond;
1.52 www 8194: }
8195: }
1.148 www 8196: }
1.29 www 8197: }
1.52 www 8198: }
1.29 www 8199:
1.52 www 8200: #
1.103 harris41 8201: # Gathered now: all privileges that could apply, and condition number
1.52 www 8202: #
8203: #
8204: # Full or no access?
8205: #
1.29 www 8206:
1.52 www 8207: if ($thisallowed=~/F/) {
8208: return 'F';
8209: }
1.29 www 8210:
1.52 www 8211: unless ($thisallowed) {
8212: return '';
8213: }
1.29 www 8214:
1.52 www 8215: # Restrictions exist, deal with them
8216: #
8217: # C:according to course preferences
8218: # R:according to resource settings
8219: # L:unless locked
8220: # X:according to user session state
8221: #
8222:
8223: # Possibly locked functionality, check all courses
1.54 www 8224: # Locks might take effect only after 10 minutes cache expiration for other
8225: # courses, and 2 minutes for current course
1.52 www 8226:
8227: my $envkey;
8228: if ($thisallowed=~/L/) {
1.1000 raeburn 8229: foreach $envkey (keys(%env)) {
1.54 www 8230: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8231: my $courseid=$2;
8232: my $roleid=$1.'.'.$2;
1.92 www 8233: $courseid=~s/^\///;
1.54 www 8234: my $expiretime=600;
1.620 albertel 8235: if ($env{'request.role'} eq $roleid) {
1.54 www 8236: $expiretime=120;
8237: }
8238: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8239: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8240: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8241: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8242: }
1.620 albertel 8243: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8244: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8245: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8246: &log($env{'user.domain'},$env{'user.name'},
8247: $env{'user.home'},
1.57 www 8248: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8249: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8250: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8251: return '';
8252: }
8253: }
1.620 albertel 8254: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8255: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8256: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8257: &log($env{'user.domain'},$env{'user.name'},
8258: $env{'user.home'},
1.57 www 8259: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8260: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8261: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8262: return '';
8263: }
8264: }
8265: }
1.29 www 8266: }
1.52 www 8267: }
1.1172.2.126 raeburn 8268:
1.52 www 8269: #
8270: # Rest of the restrictions depend on selected course
8271: #
8272:
1.620 albertel 8273: unless ($env{'request.course.id'}) {
1.766 albertel 8274: if ($thisallowed eq 'A') {
8275: return 'A';
1.814 raeburn 8276: } elsif ($thisallowed eq 'B') {
8277: return 'B';
1.766 albertel 8278: } else {
8279: return '1';
8280: }
1.52 www 8281: }
1.29 www 8282:
1.52 www 8283: #
8284: # Now user is definitely in a course
8285: #
1.53 www 8286:
8287:
8288: # Course preferences
8289:
8290: if ($thisallowed=~/C/) {
1.620 albertel 8291: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8292: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8293: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8294: =~/\Q$rolecode\E/) {
1.1103 raeburn 8295: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8296: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8297: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8298: $env{'request.course.id'});
8299: }
1.237 www 8300: return '';
8301: }
8302:
1.620 albertel 8303: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8304: =~/\Q$unamedom\E/) {
1.1103 raeburn 8305: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8306: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8307: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8308: $env{'request.course.id'});
8309: }
1.54 www 8310: return '';
8311: }
1.53 www 8312: }
8313:
8314: # Resource preferences
8315:
8316: if ($thisallowed=~/R/) {
1.620 albertel 8317: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8318: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8319: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8320: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8321: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8322: }
8323: return '';
1.54 www 8324: }
1.53 www 8325: }
1.30 www 8326:
1.246 www 8327: # Restricted by state or randomout?
1.30 www 8328:
1.52 www 8329: if ($thisallowed=~/X/) {
1.620 albertel 8330: if ($env{'acc.randomout'}) {
1.579 albertel 8331: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8332: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8333: return '';
8334: }
1.247 www 8335: }
8336: if (&condval($statecond)) {
1.52 www 8337: return '2';
8338: } else {
8339: return '';
8340: }
8341: }
1.30 www 8342:
1.766 albertel 8343: if ($thisallowed eq 'A') {
8344: return 'A';
1.814 raeburn 8345: } elsif ($thisallowed eq 'B') {
8346: return 'B';
1.766 albertel 8347: }
1.52 www 8348: return 'F';
1.232 www 8349: }
1.1162 raeburn 8350:
1.1172.2.13 raeburn 8351: # ------------------------------------------- Check construction space access
8352:
8353: sub constructaccess {
8354: my ($url,$setpriv)=@_;
8355:
8356: # We do not allow editing of previous versions of files
8357: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8358:
8359: # Get username and domain from URL
8360: my ($ownername,$ownerdomain,$ownerhome);
8361:
8362: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 8363: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8364:
8365: # The URL does not really point to any authorspace, forget it
8366: unless (($ownername) && ($ownerdomain)) { return ''; }
8367:
8368: # Now we need to see if the user has access to the authorspace of
8369: # $ownername at $ownerdomain
8370:
8371: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8372: # Real author for this?
8373: $ownerhome = $env{'user.home'};
8374: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8375: return ($ownername,$ownerdomain,$ownerhome);
8376: }
8377: } else {
8378: # Co-author for this?
8379: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8380: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8381: $ownerhome = &homeserver($ownername,$ownerdomain);
8382: return ($ownername,$ownerdomain,$ownerhome);
8383: }
8384: }
8385:
8386: # We don't have any access right now. If we are not possibly going to do anything about this,
8387: # we might as well leave
8388: unless ($setpriv) { return ''; }
8389:
8390: # Backdoor access?
8391: my $allowed=&allowed('eco',$ownerdomain);
8392: # Nope
8393: unless ($allowed) { return ''; }
8394: # Looks like we may have access, but could be locked by the owner of the construction space
8395: if ($allowed eq 'U') {
8396: my %blocked=&get('environment',['domcoord.author'],
8397: $ownerdomain,$ownername);
8398: # Is blocked by owner
8399: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8400: }
8401: if (($allowed eq 'F') || ($allowed eq 'U')) {
8402: # Grant temporary access
8403: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 8404: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 8405: if (!$update) { $update = $then; }
8406: my $refresh=$env{'user.refresh.time'};
8407: if (!$refresh) { $refresh = $update; }
8408: my $now = time;
8409: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8410: $now,'ca','constructaccess');
8411: $ownerhome = &homeserver($ownername,$ownerdomain);
8412: return($ownername,$ownerdomain,$ownerhome);
8413: }
8414: # No business here
8415: return '';
8416: }
8417:
1.1172.2.66 raeburn 8418: # ----------------------------------------------------------- Content Blocking
8419:
8420: {
8421: # Caches for faster Course Contents display where content blocking
8422: # is in operation (i.e., interval param set) for timed quiz.
8423: #
8424: # User for whom data are being temporarily cached.
8425: my $cacheduser='';
1.1172.2.126 raeburn 8426: # Course for which data are being temporarily cached.
8427: my $cachedcid='';
1.1172.2.66 raeburn 8428: # Cached blockers for this user (a hash of blocking items).
8429: my %cachedblockers=();
8430: # When the data were last cached.
8431: my $cachedlast='';
8432:
8433: sub load_all_blockers {
1.1172.2.128 raeburn 8434: my ($uname,$udom)=@_;
1.1172.2.66 raeburn 8435: if (($uname ne '') && ($udom ne '')) {
8436: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126 raeburn 8437: ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128 raeburn 8438: (abs($cachedlast-time)<5)) {
1.1172.2.66 raeburn 8439: return;
8440: }
8441: }
8442: $cachedlast=time;
8443: $cacheduser=$uname.':'.$udom;
1.1172.2.126 raeburn 8444: $cachedcid=$env{'request.course.id'};
1.1172.2.128 raeburn 8445: %cachedblockers = &get_commblock_resources();
1.1172.2.126 raeburn 8446: return;
1.1172.2.66 raeburn 8447: }
8448:
1.1162 raeburn 8449: sub get_comm_blocks {
8450: my ($cdom,$cnum) = @_;
8451: if ($cdom eq '' || $cnum eq '') {
8452: return unless ($env{'request.course.id'});
8453: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8454: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8455: }
8456: my %commblocks;
8457: my $hashid=$cdom.'_'.$cnum;
8458: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8459: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8460: %commblocks = %{$blocksref};
8461: } else {
8462: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8463: my $cachetime = 600;
8464: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8465: }
8466: return %commblocks;
8467: }
8468:
1.1172.2.66 raeburn 8469: sub get_commblock_resources {
8470: my ($blocks) = @_;
8471: my %blockers = ();
8472: return %blockers unless ($env{'request.course.id'});
8473: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8474: my %commblocks;
8475: if (ref($blocks) eq 'HASH') {
8476: %commblocks = %{$blocks};
8477: } else {
8478: %commblocks = &get_comm_blocks();
8479: }
1.1172.2.66 raeburn 8480: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8481: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8482: return %blockers unless (ref($navmap));
8483: my $now = time;
1.1162 raeburn 8484: foreach my $block (keys(%commblocks)) {
8485: if ($block =~ /^(\d+)____(\d+)$/) {
8486: my ($start,$end) = ($1,$2);
8487: if ($start <= $now && $end >= $now) {
8488: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8489: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8490: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8491: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8492: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8493: }
8494: }
8495: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8496: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8497: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8498: }
8499: }
8500: }
8501: }
8502: }
8503: } elsif ($block =~ /^firstaccess____(.+)$/) {
8504: my $item = $1;
1.1163 raeburn 8505: my @to_test;
1.1162 raeburn 8506: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8507: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 8508: my @interval;
8509: my $type = 'map';
8510: if ($item eq 'course') {
8511: $type = 'course';
8512: @interval=&EXT("resource.0.interval");
8513: } else {
8514: if ($item =~ /___\d+___/) {
8515: $type = 'resource';
8516: @interval=&EXT("resource.0.interval",$item);
8517: if (ref($navmap)) {
8518: my $res = $navmap->getBySymb($item);
8519: push(@to_test,$res);
8520: }
1.1162 raeburn 8521: } else {
1.1172.2.66 raeburn 8522: my $mapsymb = &symbread($item,1);
8523: if ($mapsymb) {
8524: if (ref($navmap)) {
8525: my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.129 raeburn 8526: if (ref($mapres)) {
8527: my $first = $mapres->map_start();
8528: my $finish = $mapres->map_finish();
8529: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8530: if (ref($it)) {
8531: my $res;
8532: while ($res = $it->next(undef,1)) {
8533: next unless (ref($res));
8534: my $symb = $res->symb();
8535: next if (($symb eq $mapsymb) || ($symb eq ''));
8536: @interval=&EXT("resource.0.interval",$symb);
8537: if ($interval[1] eq 'map') {
8538: if ($res->answerable()) {
8539: push(@to_test,$res);
8540: last;
8541: }
8542: }
1.1162 raeburn 8543: }
8544: }
8545: }
8546: }
8547: }
8548: }
1.1172.2.66 raeburn 8549: }
8550: if ($interval[0] =~ /^\d+$/) {
8551: my $first_access;
8552: if ($type eq 'resource') {
8553: $first_access=&get_first_access($interval[1],$item);
8554: } elsif ($type eq 'map') {
8555: $first_access=&get_first_access($interval[1],undef,$item);
8556: } else {
8557: $first_access=&get_first_access($interval[1]);
8558: }
8559: if ($first_access) {
8560: my $timesup = $first_access+$interval[0];
8561: if ($timesup > $now) {
8562: my $activeblock;
8563: foreach my $res (@to_test) {
8564: if ($res->answerable()) {
8565: $activeblock = 1;
8566: last;
8567: }
8568: }
8569: if ($activeblock) {
8570: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8571: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8572: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8573: }
8574: }
8575: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8576: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8577: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8578: }
1.1162 raeburn 8579: }
8580: }
8581: }
8582: }
8583: }
8584: }
8585: }
8586: }
8587: }
1.1172.2.66 raeburn 8588: return %blockers;
1.1162 raeburn 8589: }
8590:
1.1172.2.66 raeburn 8591: sub has_comm_blocking {
1.1172.2.128 raeburn 8592: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 8593: my @blockers;
8594: return unless ($env{'request.course.id'});
8595: return unless ($priv eq 'bre');
8596: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8597: return if ($env{'request.state'} eq 'construct');
1.1172.2.128 raeburn 8598: my %blockinfo;
8599: if (ref($blocks) eq 'HASH') {
8600: %blockinfo = &get_commblock_resources($blocks);
8601: } else {
8602: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8603: %blockinfo = %cachedblockers;
8604: }
8605: return unless (keys(%blockinfo) > 0);
1.1172.2.66 raeburn 8606: my (%possibles,@symbs);
8607: if (!$symb) {
1.1172.2.128 raeburn 8608: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 8609: }
1.1172.2.66 raeburn 8610: if ($symb) {
8611: @symbs = ($symb);
8612: } elsif (keys(%possibles)) {
8613: @symbs = keys(%possibles);
8614: }
8615: my $noblock;
8616: foreach my $symb (@symbs) {
8617: last if ($noblock);
8618: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128 raeburn 8619: foreach my $block (keys(%blockinfo)) {
1.1172.2.66 raeburn 8620: if ($block =~ /^firstaccess____(.+)$/) {
8621: my $item = $1;
1.1172.2.126 raeburn 8622: unless ($blocked) {
8623: if (($item eq $map) || ($item eq $symb)) {
8624: $noblock = 1;
8625: last;
8626: }
1.1172.2.66 raeburn 8627: }
1.1162 raeburn 8628: }
1.1172.2.128 raeburn 8629: if (ref($blockinfo{$block}) eq 'HASH') {
8630: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8631: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66 raeburn 8632: unless (grep(/^\Q$block\E$/,@blockers)) {
8633: push(@blockers,$block);
8634: }
8635: }
8636: }
1.1172.2.128 raeburn 8637: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8638: if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126 raeburn 8639: unless (grep(/^\Q$block\E$/,@blockers)) {
8640: push(@blockers,$block);
8641: }
1.1172.2.66 raeburn 8642: }
8643: }
1.1162 raeburn 8644: }
8645: }
8646: }
1.1172.2.126 raeburn 8647: unless ($noblock) {
8648: return @blockers;
8649: }
8650: return;
1.1172.2.66 raeburn 8651: }
1.1162 raeburn 8652: }
8653:
1.1172.2.66 raeburn 8654: # -------------------------------- Deversion and split uri into path an filename
8655:
1.1133 foxr 8656: #
1.1172.2.66 raeburn 8657: # Removes the version from a URI and
1.1133 foxr 8658: # splits it in to its filename and path to the filename.
8659: # Seems like File::Basename could have done this more clearly.
8660: # Parameters:
8661: # $uri - input URI
8662: # Returns:
8663: # Two element list consisting of
8664: # $pathname - the URI up to and excluding the trailing /
8665: # $filename - The part of the URI following the last /
8666: # NOTE:
8667: # Another realization of this is simply:
8668: # use File::Basename;
8669: # ...
8670: # $uri = shift;
8671: # $filename = basename($uri);
8672: # $path = dirname($uri);
8673: # return ($filename, $path);
8674: #
8675: # The implementation below is probably faster however.
8676: #
1.710 albertel 8677: sub split_uri_for_cond {
8678: my $uri=&deversion(&declutter(shift));
8679: my @uriparts=split(/\//,$uri);
8680: my $filename=pop(@uriparts);
8681: my $pathname=join('/',@uriparts);
8682: return ($pathname,$filename);
8683: }
1.232 www 8684: # --------------------------------------------------- Is a resource on the map?
8685:
8686: sub is_on_map {
1.710 albertel 8687: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8688: #Trying to find the conditional for the file
1.620 albertel 8689: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8690: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8691: if ($match) {
1.289 bowersj2 8692: return (1,$1);
8693: } else {
1.434 www 8694: return (0,0);
1.289 bowersj2 8695: }
1.12 www 8696: }
8697:
1.427 www 8698: # --------------------------------------------------------- Get symb from alias
8699:
8700: sub get_symb_from_alias {
8701: my $symb=shift;
8702: my ($map,$resid,$url)=&decode_symb($symb);
8703: # Already is a symb
8704: if ($url) { return $symb; }
8705: # Must be an alias
8706: my $aliassymb='';
8707: my %bighash;
1.620 albertel 8708: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8709: &GDBM_READER(),0640)) {
8710: my $rid=$bighash{'mapalias_'.$symb};
8711: if ($rid) {
8712: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8713: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8714: $resid,$bighash{'src_'.$rid});
1.427 www 8715: }
8716: untie %bighash;
8717: }
8718: return $aliassymb;
8719: }
8720:
1.12 www 8721: # ----------------------------------------------------------------- Define Role
8722:
8723: sub definerole {
8724: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8725: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8726: foreach my $role (split(':',$sysrole)) {
8727: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8728: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8729: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8730: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8731: return "refused:s:$crole&$cqual";
8732: }
8733: }
1.191 harris41 8734: }
1.800 albertel 8735: foreach my $role (split(':',$domrole)) {
8736: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8737: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8738: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8739: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8740: return "refused:d:$crole&$cqual";
8741: }
8742: }
1.191 harris41 8743: }
1.800 albertel 8744: foreach my $role (split(':',$courole)) {
8745: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8746: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8747: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8748: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8749: return "refused:c:$crole&$cqual";
8750: }
8751: }
1.191 harris41 8752: }
1.1172.2.84 raeburn 8753: my $uhome;
8754: if (($uname ne '') && ($udom ne '')) {
8755: $uhome = &homeserver($uname,$udom);
8756: return $uhome if ($uhome eq 'no_host');
8757: } else {
8758: $uname = $env{'user.name'};
8759: $udom = $env{'user.domain'};
8760: $uhome = $env{'user.home'};
8761: }
1.620 albertel 8762: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8763: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8764: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8765: return reply($command,$uhome);
1.12 www 8766: } else {
8767: return 'refused';
8768: }
1.105 harris41 8769: }
8770:
8771: # ---------------- Make a metadata query against the network of library servers
8772:
8773: sub metadata_query {
1.1172.2.33 raeburn 8774: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8775: my %rhash;
1.845 albertel 8776: my %libserv = &all_library();
1.244 matthew 8777: my @server_list = (defined($server_array) ? @$server_array
8778: : keys(%libserv) );
8779: for my $server (@server_list) {
1.1172.2.33 raeburn 8780: my $domains = '';
8781: if (ref($domains_hash) eq 'HASH') {
8782: $domains = $domains_hash->{$server};
8783: }
1.118 harris41 8784: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8785: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8786: $rhash{$server}=$reply;
8787: }
8788: else {
8789: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8790: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8791: $server);
8792: $rhash{$server}=$reply;
8793: }
1.112 harris41 8794: }
1.118 harris41 8795: return \%rhash;
1.240 www 8796: }
8797:
8798: # ----------------------------------------- Send log queries and wait for reply
8799:
8800: sub log_query {
8801: my ($uname,$udom,$query,%filters)=@_;
8802: my $uhome=&homeserver($uname,$udom);
8803: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8804: my $uhost=&hostname($uhome);
1.800 albertel 8805: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8806: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8807: $uhome);
1.479 albertel 8808: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8809: return get_query_reply($queryid);
8810: }
8811:
1.818 raeburn 8812: # -------------------------- Update MySQL table for portfolio file
8813:
8814: sub update_portfolio_table {
1.821 raeburn 8815: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8816: if ($group ne '') {
8817: $file_name =~s /^\Q$group\E//;
8818: }
1.818 raeburn 8819: my $homeserver = &homeserver($uname,$udom);
8820: my $queryid=
1.821 raeburn 8821: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8822: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8823: my $reply = &get_query_reply($queryid);
8824: return $reply;
8825: }
8826:
1.899 raeburn 8827: # -------------------------- Update MySQL allusers table
8828:
8829: sub update_allusers_table {
8830: my ($uname,$udom,$names) = @_;
8831: my $homeserver = &homeserver($uname,$udom);
8832: my $queryid=
8833: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8834: 'lastname='.&escape($names->{'lastname'}).'%%'.
8835: 'firstname='.&escape($names->{'firstname'}).'%%'.
8836: 'middlename='.&escape($names->{'middlename'}).'%%'.
8837: 'generation='.&escape($names->{'generation'}).'%%'.
8838: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8839: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8840: return;
1.899 raeburn 8841: }
8842:
1.508 raeburn 8843: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8844:
8845: sub fetch_enrollment_query {
1.511 raeburn 8846: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8847: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8848: my $maxtries = 1;
1.508 raeburn 8849: if ($context eq 'automated') {
8850: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8851: $sleep = 2;
8852: $loopmax = 100;
1.547 raeburn 8853: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8854: } else {
8855: $homeserver = &homeserver($cnum,$dom);
8856: }
1.838 albertel 8857: my $host=&hostname($homeserver);
1.506 raeburn 8858: my $cmd = '';
1.1000 raeburn 8859: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8860: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8861: }
8862: $cmd =~ s/%%$//;
8863: $cmd = &escape($cmd);
8864: my $query = 'fetchenrollment';
1.620 albertel 8865: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8866: unless ($queryid=~/^\Q$host\E\_/) {
8867: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8868: return 'error: '.$queryid;
8869: }
1.1172.2.93 raeburn 8870: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8871: my $tries = 1;
8872: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8873: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8874: $tries ++;
8875: }
1.526 raeburn 8876: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8877: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8878: } else {
1.901 albertel 8879: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8880: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8881: foreach my $line (@responses) {
8882: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8883: $$replyref{$key} = $value;
8884: }
8885: } else {
1.1117 foxr 8886: my $pathname = LONCAPA::tempdir();
1.800 albertel 8887: foreach my $line (@responses) {
8888: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8889: $$replyref{$key} = $value;
8890: if ($value > 0) {
1.800 albertel 8891: foreach my $item (@{$$affiliatesref{$key}}) {
8892: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8893: my $destname = $pathname.'/'.$filename;
8894: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8895: if ($xml_classlist =~ /^error/) {
8896: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8897: } else {
1.1172.2.96 raeburn 8898: if ( open(FILE,">",$destname) ) {
1.506 raeburn 8899: print FILE &unescape($xml_classlist);
8900: close(FILE);
1.526 raeburn 8901: } else {
8902: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8903: }
8904: }
8905: }
8906: }
8907: }
8908: }
8909: return 'ok';
8910: }
8911: return 'error';
8912: }
8913:
1.242 www 8914: sub get_query_reply {
1.1172.2.79 raeburn 8915: my ($queryid,$sleep,$loopmax) = @_;
8916: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8917: $sleep = 0.2;
8918: }
8919: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8920: $loopmax = 100;
8921: }
1.1117 foxr 8922: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8923: my $reply='';
1.1172.2.79 raeburn 8924: for (1..$loopmax) {
8925: sleep($sleep);
1.240 www 8926: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 8927: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 8928: $reply = join('',<$fh>);
8929: close($fh);
1.240 www 8930: } else { return 'error: reply_file_error'; }
1.242 www 8931: return &unescape($reply);
8932: }
1.240 www 8933: }
1.242 www 8934: return 'timeout:'.$queryid;
1.240 www 8935: }
8936:
8937: sub courselog_query {
1.241 www 8938: #
8939: # possible filters:
8940: # url: url or symb
8941: # username
8942: # domain
8943: # action: view, submit, grade
8944: # start: timestamp
8945: # end: timestamp
8946: #
1.240 www 8947: my (%filters)=@_;
1.620 albertel 8948: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8949: if ($filters{'url'}) {
8950: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8951: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8952: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8953: }
1.620 albertel 8954: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8955: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8956: return &log_query($cname,$cdom,'courselog',%filters);
8957: }
8958:
8959: sub userlog_query {
1.858 raeburn 8960: #
8961: # possible filters:
8962: # action: log check role
8963: # start: timestamp
8964: # end: timestamp
8965: #
1.240 www 8966: my ($uname,$udom,%filters)=@_;
8967: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8968: }
8969:
1.506 raeburn 8970: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8971:
8972: sub auto_run {
1.508 raeburn 8973: my ($cnum,$cdom) = @_;
1.876 raeburn 8974: my $response = 0;
8975: my $settings;
8976: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8977: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8978: $settings = $domconfig{'autoenroll'};
8979: if ($settings->{'run'} eq '1') {
8980: $response = 1;
8981: }
8982: } else {
1.934 raeburn 8983: my $homeserver;
8984: if (&is_course($cdom,$cnum)) {
8985: $homeserver = &homeserver($cnum,$cdom);
8986: } else {
8987: $homeserver = &domain($cdom,'primary');
8988: }
8989: if ($homeserver ne 'no_host') {
8990: $response = &reply('autorun:'.$cdom,$homeserver);
8991: }
1.876 raeburn 8992: }
1.506 raeburn 8993: return $response;
8994: }
1.776 albertel 8995:
1.506 raeburn 8996: sub auto_get_sections {
1.508 raeburn 8997: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8998: my $homeserver;
8999: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9000: $homeserver = &homeserver($cnum,$cdom);
9001: }
9002: if (!defined($homeserver)) {
9003: if ($cdom =~ /^$match_domain$/) {
9004: $homeserver = &domain($cdom,'primary');
9005: }
9006: }
9007: my @secs;
9008: if (defined($homeserver)) {
9009: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9010: unless ($response eq 'refused') {
9011: @secs = split(/:/,$response);
9012: }
1.506 raeburn 9013: }
9014: return @secs;
9015: }
1.776 albertel 9016:
1.506 raeburn 9017: sub auto_new_course {
1.1099 raeburn 9018: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9019: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9020: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9021: return $response;
9022: }
1.776 albertel 9023:
1.506 raeburn 9024: sub auto_validate_courseID {
1.508 raeburn 9025: my ($cnum,$cdom,$inst_course_id) = @_;
9026: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9027: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9028: return $response;
9029: }
1.776 albertel 9030:
1.1007 raeburn 9031: sub auto_validate_instcode {
1.1020 raeburn 9032: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9033: my ($homeserver,$response);
9034: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9035: $homeserver = &homeserver($cnum,$cdom);
9036: }
9037: if (!defined($homeserver)) {
9038: if ($cdom =~ /^$match_domain$/) {
9039: $homeserver = &domain($cdom,'primary');
9040: }
9041: }
1.1065 raeburn 9042: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9043: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9044: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9045: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9046: }
9047:
1.506 raeburn 9048: sub auto_create_password {
1.873 raeburn 9049: my ($cnum,$cdom,$authparam,$udom) = @_;
9050: my ($homeserver,$response);
1.506 raeburn 9051: my $create_passwd = 0;
9052: my $authchk = '';
1.873 raeburn 9053: if ($udom =~ /^$match_domain$/) {
9054: $homeserver = &domain($udom,'primary');
9055: }
9056: if ($homeserver eq '') {
9057: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9058: $homeserver = &homeserver($cnum,$cdom);
9059: }
9060: }
9061: if ($homeserver eq '') {
9062: $authchk = 'nodomain';
1.506 raeburn 9063: } else {
1.873 raeburn 9064: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9065: if ($response eq 'refused') {
9066: $authchk = 'refused';
9067: } else {
1.901 albertel 9068: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9069: }
1.506 raeburn 9070: }
9071: return ($authparam,$create_passwd,$authchk);
9072: }
9073:
1.706 raeburn 9074: sub auto_photo_permission {
9075: my ($cnum,$cdom,$students) = @_;
9076: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9077: my ($outcome,$perm_reqd,$conditions) =
9078: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9079: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9080: return (undef,undef);
9081: }
1.706 raeburn 9082: return ($outcome,$perm_reqd,$conditions);
9083: }
9084:
9085: sub auto_checkphotos {
9086: my ($uname,$udom,$pid) = @_;
9087: my $homeserver = &homeserver($uname,$udom);
9088: my ($result,$resulttype);
9089: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9090: &escape($uname).':'.&escape($pid),
9091: $homeserver));
1.709 albertel 9092: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9093: return (undef,undef);
9094: }
1.706 raeburn 9095: if ($outcome) {
9096: ($result,$resulttype) = split(/:/,$outcome);
9097: }
9098: return ($result,$resulttype);
9099: }
9100:
9101: sub auto_photochoice {
9102: my ($cnum,$cdom) = @_;
9103: my $homeserver = &homeserver($cnum,$cdom);
9104: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9105: &escape($cdom),
9106: $homeserver)));
1.709 albertel 9107: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9108: return (undef,undef);
9109: }
1.706 raeburn 9110: return ($update,$comment);
9111: }
9112:
9113: sub auto_photoupdate {
9114: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9115: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9116: my $host=&hostname($homeserver);
1.706 raeburn 9117: my $cmd = '';
9118: my $maxtries = 1;
1.800 albertel 9119: foreach my $affiliate (keys(%{$affiliatesref})) {
9120: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9121: }
9122: $cmd =~ s/%%$//;
9123: $cmd = &escape($cmd);
9124: my $query = 'institutionalphotos';
9125: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9126: unless ($queryid=~/^\Q$host\E\_/) {
9127: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9128: return 'error: '.$queryid;
9129: }
9130: my $reply = &get_query_reply($queryid);
9131: my $tries = 1;
9132: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9133: $reply = &get_query_reply($queryid);
9134: $tries ++;
9135: }
9136: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9137: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9138: } else {
9139: my @responses = split(/:/,$reply);
9140: my $outcome = shift(@responses);
9141: foreach my $item (@responses) {
9142: my ($key,$value) = split(/=/,$item);
9143: $$photo{$key} = $value;
9144: }
9145: return $outcome;
9146: }
9147: return 'error';
9148: }
9149:
1.521 raeburn 9150: sub auto_instcode_format {
1.793 albertel 9151: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9152: $cat_order) = @_;
1.521 raeburn 9153: my $courses = '';
1.772 raeburn 9154: my @homeservers;
1.521 raeburn 9155: if ($caller eq 'global') {
1.841 albertel 9156: my %servers = &get_servers($codedom,'library');
9157: foreach my $tryserver (keys(%servers)) {
9158: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9159: push(@homeservers,$tryserver);
9160: }
1.584 raeburn 9161: }
1.1022 raeburn 9162: } elsif ($caller eq 'requests') {
9163: if ($codedom =~ /^$match_domain$/) {
9164: my $chome = &domain($codedom,'primary');
9165: unless ($chome eq 'no_host') {
9166: push(@homeservers,$chome);
9167: }
9168: }
1.521 raeburn 9169: } else {
1.772 raeburn 9170: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9171: }
1.793 albertel 9172: foreach my $code (keys(%{$instcodes})) {
9173: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9174: }
9175: chop($courses);
1.772 raeburn 9176: my $ok_response = 0;
9177: my $response;
9178: while (@homeservers > 0 && $ok_response == 0) {
9179: my $server = shift(@homeservers);
9180: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9181: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9182: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9183: split(/:/,$response);
1.772 raeburn 9184: %{$codes} = (%{$codes},&str2hash($codes_str));
9185: push(@{$codetitles},&str2array($codetitles_str));
9186: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9187: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9188: $ok_response = 1;
9189: }
9190: }
9191: if ($ok_response) {
1.521 raeburn 9192: return 'ok';
1.772 raeburn 9193: } else {
9194: return $response;
1.521 raeburn 9195: }
9196: }
9197:
1.792 raeburn 9198: sub auto_instcode_defaults {
9199: my ($domain,$returnhash,$code_order) = @_;
9200: my @homeservers;
1.841 albertel 9201:
9202: my %servers = &get_servers($domain,'library');
9203: foreach my $tryserver (keys(%servers)) {
9204: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9205: push(@homeservers,$tryserver);
9206: }
1.792 raeburn 9207: }
1.841 albertel 9208:
1.792 raeburn 9209: my $response;
1.841 albertel 9210: foreach my $server (@homeservers) {
1.792 raeburn 9211: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9212: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9213:
9214: foreach my $pair (split(/\&/,$response)) {
9215: my ($name,$value)=split(/\=/,$pair);
9216: if ($name eq 'code_order') {
9217: @{$code_order} = split(/\&/,&unescape($value));
9218: } else {
9219: $returnhash->{&unescape($name)}=&unescape($value);
9220: }
9221: }
9222: return 'ok';
1.792 raeburn 9223: }
1.841 albertel 9224:
9225: return $response;
1.1003 raeburn 9226: }
9227:
9228: sub auto_possible_instcodes {
1.1007 raeburn 9229: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9230: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9231: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9232: return;
9233: }
1.1003 raeburn 9234: my (@homeservers,$uhome);
9235: if (defined(&domain($domain,'primary'))) {
9236: $uhome=&domain($domain,'primary');
9237: push(@homeservers,&domain($domain,'primary'));
9238: } else {
9239: my %servers = &get_servers($domain,'library');
9240: foreach my $tryserver (keys(%servers)) {
9241: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9242: push(@homeservers,$tryserver);
9243: }
9244: }
9245: }
9246: my $response;
9247: foreach my $server (@homeservers) {
9248: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9249: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9250: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9251: split(':',$response);
9252: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9253: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9254: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9255: my ($name,$value)=split('=',$item);
9256: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9257: }
9258: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9259: my ($name,$value)=split('=',$item);
9260: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9261: }
9262: return 'ok';
9263: }
9264: return $response;
9265: }
1.792 raeburn 9266:
1.1010 raeburn 9267: sub auto_courserequest_checks {
9268: my ($dom) = @_;
1.1020 raeburn 9269: my ($homeserver,%validations);
9270: if ($dom =~ /^$match_domain$/) {
9271: $homeserver = &domain($dom,'primary');
9272: }
9273: unless ($homeserver eq 'no_host') {
9274: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9275: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9276: my @items = split(/&/,$response);
9277: foreach my $item (@items) {
9278: my ($key,$value) = split('=',$item);
9279: $validations{&unescape($key)} = &thaw_unescape($value);
9280: }
9281: }
9282: }
1.1010 raeburn 9283: return %validations;
9284: }
9285:
1.1020 raeburn 9286: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9287: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9288: my ($homeserver,$response);
9289: if ($dom =~ /^$match_domain$/) {
9290: $homeserver = &domain($dom,'primary');
9291: }
1.1172.2.43 raeburn 9292: unless ($homeserver eq 'no_host') {
9293: my $customdata;
9294: if (ref($custominfo) eq 'HASH') {
9295: $customdata = &freeze_escape($custominfo);
9296: }
1.1020 raeburn 9297: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9298: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9299: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9300: $customdata,$homeserver));
1.1020 raeburn 9301: }
9302: return $response;
9303: }
9304:
1.777 albertel 9305: sub auto_validate_class_sec {
1.918 raeburn 9306: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9307: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9308: my $ownerlist;
9309: if (ref($owners) eq 'ARRAY') {
9310: $ownerlist = join(',',@{$owners});
9311: } else {
9312: $ownerlist = $owners;
9313: }
1.773 raeburn 9314: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9315: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9316: return $response;
9317: }
9318:
1.1172.2.94 raeburn 9319: sub auto_validate_instclasses {
9320: my ($cdom,$cnum,$owners,$classesref) = @_;
9321: my ($homeserver,%validations);
9322: $homeserver = &homeserver($cnum,$cdom);
9323: unless ($homeserver eq 'no_host') {
9324: my $ownerlist;
9325: if (ref($owners) eq 'ARRAY') {
9326: $ownerlist = join(',',@{$owners});
9327: } else {
9328: $ownerlist = $owners;
9329: }
9330: if (ref($classesref) eq 'HASH') {
9331: my $classes = &freeze_escape($classesref);
9332: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9333: ':'.$cdom.':'.$classes,$homeserver);
9334: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9335: my @items = split(/&/,$response);
9336: foreach my $item (@items) {
9337: my ($key,$value) = split('=',$item);
9338: $validations{&unescape($key)} = &thaw_unescape($value);
9339: }
9340: }
9341: }
9342: }
9343: return %validations;
9344: }
9345:
1.1172.2.38 raeburn 9346: sub auto_crsreq_update {
9347: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 9348: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 9349: my ($homeserver,%crsreqresponse);
9350: if ($cdom =~ /^$match_domain$/) {
9351: $homeserver = &domain($cdom,'primary');
9352: }
9353: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9354: my $info;
9355: if (ref($inbound) eq 'HASH') {
9356: $info = &freeze_escape($inbound);
9357: }
9358: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9359: ':'.&escape($action).':'.&escape($ownername).':'.
9360: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 9361: &escape($title).':'.&escape($code).':'.
9362: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 9363: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9364: my @items = split(/&/,$response);
9365: foreach my $item (@items) {
9366: my ($key,$value) = split('=',$item);
9367: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9368: }
9369: }
9370: }
9371: return \%crsreqresponse;
9372: }
9373:
1.1172.2.78 raeburn 9374: sub auto_export_grades {
9375: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9376: my ($homeserver,%exportresponse);
9377: if ($cdom =~ /^$match_domain$/) {
9378: $homeserver = &domain($cdom,'primary');
9379: }
9380: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9381: my $info;
9382: if (ref($inforef) eq 'HASH') {
9383: $info = &freeze_escape($inforef);
9384: }
9385: if (ref($gradesref) eq 'HASH') {
9386: my $grades = &freeze_escape($gradesref);
9387: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9388: $info.':'.$grades,$homeserver);
9389: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9390: my @items = split(/&/,$response);
9391: foreach my $item (@items) {
9392: my ($key,$value) = split('=',$item);
9393: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9394: }
9395: }
9396: }
9397: }
9398: return \%exportresponse;
9399: }
9400:
1.1172.2.68 raeburn 9401: sub check_instcode_cloning {
9402: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9403: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9404: return;
9405: }
9406: my $canclone;
9407: if (@{$code_order} > 0) {
9408: my $instcoderegexp ='^';
9409: my @clonecodes = split(/\&/,$cloner);
9410: foreach my $item (@{$code_order}) {
9411: if (grep(/^\Q$item\E=/,@clonecodes)) {
9412: foreach my $pair (@clonecodes) {
9413: my ($key,$val) = split(/\=/,$pair,2);
9414: $val = &unescape($val);
9415: if ($key eq $item) {
9416: $instcoderegexp .= '('.$val.')';
9417: last;
9418: }
9419: }
9420: } else {
9421: $instcoderegexp .= $codedefaults->{$item};
9422: }
9423: }
9424: $instcoderegexp .= '$';
9425: my (@from,@to);
9426: eval {
9427: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9428: (@to) = ($clonetocode =~ /$instcoderegexp/);
9429: };
9430: if ((@from > 0) && (@to > 0)) {
9431: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9432: if (!@diffs) {
9433: $canclone = 1;
9434: }
9435: }
9436: }
9437: return $canclone;
9438: }
9439:
9440: sub default_instcode_cloning {
9441: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9442: my (%codedefaults,@code_order,$canclone);
9443: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9444: %codedefaults = %{$codedefaultsref};
9445: @code_order = @{$codeorderref};
9446: } elsif ($clonedom) {
9447: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9448: }
9449: if (($domdefclone) && (@code_order)) {
9450: my @clonecodes = split(/\+/,$domdefclone);
9451: my $instcoderegexp ='^';
9452: foreach my $item (@code_order) {
9453: if (grep(/^\Q$item\E$/,@clonecodes)) {
9454: $instcoderegexp .= '('.$codedefaults{$item}.')';
9455: } else {
9456: $instcoderegexp .= $codedefaults{$item};
9457: }
9458: }
9459: $instcoderegexp .= '$';
9460: my (@from,@to);
9461: eval {
9462: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9463: (@to) = ($clonetocode =~ /$instcoderegexp/);
9464: };
9465: if ((@from > 0) && (@to > 0)) {
9466: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9467: if (!@diffs) {
9468: $canclone = 1;
9469: }
9470: }
9471: }
9472: return $canclone;
9473: }
9474:
1.679 raeburn 9475: # ------------------------------------------------------- Course Group routines
9476:
9477: sub get_coursegroups {
1.809 raeburn 9478: my ($cdom,$cnum,$group,$namespace) = @_;
9479: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9480: }
9481:
1.679 raeburn 9482: sub modify_coursegroup {
9483: my ($cdom,$cnum,$groupsettings) = @_;
9484: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9485: }
9486:
1.809 raeburn 9487: sub toggle_coursegroup_status {
9488: my ($cdom,$cnum,$group,$action) = @_;
9489: my ($from_namespace,$to_namespace);
9490: if ($action eq 'delete') {
9491: $from_namespace = 'coursegroups';
9492: $to_namespace = 'deleted_groups';
9493: } else {
9494: $from_namespace = 'deleted_groups';
9495: $to_namespace = 'coursegroups';
9496: }
9497: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9498: if (my $tmp = &error(%curr_group)) {
9499: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9500: return ('read error',$tmp);
9501: } else {
9502: my %savedsettings = %curr_group;
1.809 raeburn 9503: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9504: my $deloutcome;
9505: if ($result eq 'ok') {
1.809 raeburn 9506: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9507: } else {
9508: return ('write error',$result);
9509: }
9510: if ($deloutcome eq 'ok') {
9511: return 'ok';
9512: } else {
9513: return ('delete error',$deloutcome);
9514: }
9515: }
9516: }
9517:
1.679 raeburn 9518: sub modify_group_roles {
1.957 raeburn 9519: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9520: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9521: my $role = 'gr/'.&escape($userprivs);
9522: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9523: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9524: if ($result eq 'ok') {
9525: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9526: }
1.679 raeburn 9527: return $result;
9528: }
9529:
9530: sub modify_coursegroup_membership {
9531: my ($cdom,$cnum,$membership) = @_;
9532: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9533: return $result;
9534: }
9535:
1.682 raeburn 9536: sub get_active_groups {
9537: my ($udom,$uname,$cdom,$cnum) = @_;
9538: my $now = time;
9539: my %groups = ();
9540: foreach my $key (keys(%env)) {
1.811 albertel 9541: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9542: my ($start,$end) = split(/\./,$env{$key});
9543: if (($end!=0) && ($end<$now)) { next; }
9544: if (($start!=0) && ($start>$now)) { next; }
9545: if ($1 eq $cdom && $2 eq $cnum) {
9546: $groups{$3} = $env{$key} ;
9547: }
9548: }
9549: }
9550: return %groups;
9551: }
9552:
1.683 raeburn 9553: sub get_group_membership {
9554: my ($cdom,$cnum,$group) = @_;
9555: return(&dump('groupmembership',$cdom,$cnum,$group));
9556: }
9557:
9558: sub get_users_groups {
9559: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9560: my @usersgroups;
1.683 raeburn 9561: my $cachetime=1800;
9562:
9563: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9564: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9565: if (defined($cached)) {
1.734 albertel 9566: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9567: } else {
9568: $grouplist = '';
1.816 raeburn 9569: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9570: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9571: my $access_end = $env{'course.'.$courseid.
9572: '.default_enrollment_end_date'};
9573: my $now = time;
9574: foreach my $key (keys(%roleshash)) {
9575: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9576: my $group = $1;
9577: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9578: my $start = $2;
9579: my $end = $1;
9580: if ($start == -1) { next; } # deleted from group
9581: if (($start!=0) && ($start>$now)) { next; }
9582: if (($end!=0) && ($end<$now)) {
9583: if ($access_end && $access_end < $now) {
9584: if ($access_end - $end < 86400) {
9585: push(@usersgroups,$group);
1.733 raeburn 9586: }
9587: }
1.817 raeburn 9588: next;
1.733 raeburn 9589: }
1.817 raeburn 9590: push(@usersgroups,$group);
1.683 raeburn 9591: }
9592: }
9593: }
1.817 raeburn 9594: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9595: $grouplist = join(':',@usersgroups);
9596: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9597: }
1.733 raeburn 9598: return @usersgroups;
1.683 raeburn 9599: }
9600:
9601: sub devalidate_getgroups_cache {
9602: my ($udom,$uname,$cdom,$cnum)=@_;
9603: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9604:
1.683 raeburn 9605: my $hashid="$udom:$uname:$courseid";
9606: &devalidate_cache_new('getgroups',$hashid);
9607: }
9608:
1.12 www 9609: # ------------------------------------------------------------------ Plain Text
9610:
9611: sub plaintext {
1.988 raeburn 9612: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9613: if ($short =~ m{^cr/}) {
1.758 albertel 9614: return (split('/',$short))[-1];
9615: }
1.742 raeburn 9616: if (!defined($cid)) {
9617: $cid = $env{'request.course.id'};
9618: }
9619: my %rolenames = (
1.1008 raeburn 9620: Course => 'std',
9621: Community => 'alt1',
1.742 raeburn 9622: );
1.1037 raeburn 9623: if ($cid ne '') {
9624: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9625: unless ($forcedefault) {
9626: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9627: &Apache::lonlocal::mt_escape(\$roletext);
9628: return &Apache::lonlocal::mt($roletext);
9629: }
9630: }
9631: }
9632: if ((defined($type)) && (defined($rolenames{$type})) &&
9633: (defined($rolenames{$type})) &&
9634: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9635: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9636: } elsif ($cid ne '') {
9637: my $crstype = $env{'course.'.$cid.'.type'};
9638: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9639: (defined($prp{$short}{$rolenames{$crstype}}))) {
9640: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9641: }
1.742 raeburn 9642: }
1.1037 raeburn 9643: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9644: }
9645:
9646: # ----------------------------------------------------------------- Assign Role
9647:
9648: sub assignrole {
1.957 raeburn 9649: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9650: $context)=@_;
1.21 www 9651: my $mrole;
9652: if ($role =~ /^cr\//) {
1.393 www 9653: my $cwosec=$url;
1.811 albertel 9654: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9655: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9656: my $refused = 1;
9657: if ($context eq 'requestcourses') {
9658: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9659: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9660: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9661: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9662: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9663: if ($crsenv{'internal.courseowner'} eq
9664: $env{'user.name'}.':'.$env{'user.domain'}) {
9665: $refused = '';
9666: }
9667: }
9668: }
9669: }
9670: }
9671: if ($refused) {
9672: &logthis('Refused custom assignrole: '.
9673: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9674: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9675: return 'refused';
9676: }
1.104 www 9677: }
1.21 www 9678: $mrole='cr';
1.678 raeburn 9679: } elsif ($role =~ /^gr\//) {
9680: my $cwogrp=$url;
1.811 albertel 9681: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9682: unless (&allowed('mdg',$cwogrp)) {
9683: &logthis('Refused group assignrole: '.
9684: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9685: $env{'user.name'}.' at '.$env{'user.domain'});
9686: return 'refused';
9687: }
9688: $mrole='gr';
1.21 www 9689: } else {
1.82 www 9690: my $cwosec=$url;
1.811 albertel 9691: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9692: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9693: my $refused;
9694: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9695: if (!(&allowed('c'.$role,$url))) {
9696: $refused = 1;
9697: }
9698: } else {
9699: $refused = 1;
9700: }
1.947 raeburn 9701: if ($refused) {
1.1045 raeburn 9702: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9703: if (!$selfenroll && $context eq 'course') {
9704: my %crsenv;
9705: if ($role eq 'cc' || $role eq 'co') {
9706: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9707: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9708: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9709: if ($crsenv{'internal.courseowner'} eq
9710: $env{'user.name'}.':'.$env{'user.domain'}) {
9711: $refused = '';
9712: }
9713: }
9714: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9715: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9716: if ($crsenv{'internal.courseowner'} eq
9717: $env{'user.name'}.':'.$env{'user.domain'}) {
9718: $refused = '';
9719: }
9720: }
9721: }
9722: }
9723: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9724: $refused = '';
1.1017 raeburn 9725: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9726: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9727: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9728: my $wrongcc;
9729: if ($cnum =~ /^$match_community$/) {
9730: $wrongcc = 1 if ($role eq 'cc');
9731: } else {
9732: $wrongcc = 1 if ($role eq 'co');
9733: }
9734: unless ($wrongcc) {
9735: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9736: if ($crsenv{'internal.courseowner'} eq
9737: $env{'user.name'}.':'.$env{'user.domain'}) {
9738: $refused = '';
9739: }
1.1017 raeburn 9740: }
9741: }
1.1172.2.9 raeburn 9742: } elsif ($context eq 'requestauthor') {
9743: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9744: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9745: if ($env{'environment.requestauthor'} eq 'automatic') {
9746: $refused = '';
9747: } else {
9748: my %domdefaults = &get_domain_defaults($udom);
9749: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9750: my $checkbystatus;
9751: if ($env{'user.adv'}) {
9752: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9753: if ($disposition eq 'automatic') {
9754: $refused = '';
9755: } elsif ($disposition eq '') {
9756: $checkbystatus = 1;
9757: }
9758: } else {
9759: $checkbystatus = 1;
9760: }
9761: if ($checkbystatus) {
9762: if ($env{'environment.inststatus'}) {
9763: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9764: foreach my $type (@inststatuses) {
9765: if (($type ne '') &&
9766: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9767: $refused = '';
9768: }
9769: }
9770: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9771: $refused = '';
9772: }
9773: }
9774: }
9775: }
9776: }
1.1017 raeburn 9777: }
9778: if ($refused) {
1.947 raeburn 9779: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9780: ' '.$role.' '.$end.' '.$start.' by '.
9781: $env{'user.name'}.' at '.$env{'user.domain'});
9782: return 'refused';
9783: }
1.932 raeburn 9784: }
1.1131 raeburn 9785: } elsif ($role eq 'au') {
9786: if ($url ne '/'.$udom.'/') {
9787: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9788: ' to assign author role for '.$uname.':'.$udom.
9789: ' in domain: '.$url.' refused (wrong domain).');
9790: return 'refused';
9791: }
1.104 www 9792: }
1.21 www 9793: $mrole=$role;
9794: }
1.620 albertel 9795: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9796: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9797: if ($end) { $command.='_'.$end; }
1.21 www 9798: if ($start) {
9799: if ($end) {
1.81 www 9800: $command.='_'.$start;
1.21 www 9801: } else {
1.81 www 9802: $command.='_0_'.$start;
1.21 www 9803: }
9804: }
1.739 raeburn 9805: my $origstart = $start;
9806: my $origend = $end;
1.957 raeburn 9807: my $delflag;
1.357 www 9808: # actually delete
9809: if ($deleteflag) {
1.373 www 9810: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9811: # modify command to delete the role
1.620 albertel 9812: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9813: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9814: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9815: # set start and finish to negative values for userrolelog
9816: $start=-1;
9817: $end=-1;
1.957 raeburn 9818: $delflag = 1;
1.357 www 9819: }
9820: }
9821: # send command
1.349 www 9822: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9823: # log new user role if status is ok
1.349 www 9824: if ($answer eq 'ok') {
1.663 raeburn 9825: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9826: if (($role eq 'cc') || ($role eq 'in') ||
9827: ($role eq 'ep') || ($role eq 'ad') ||
9828: ($role eq 'ta') || ($role eq 'st') ||
9829: ($role=~/^cr/) || ($role eq 'gr') ||
9830: ($role eq 'co')) {
1.1172.2.13 raeburn 9831: # for course roles, perform group memberships changes triggered by role change.
9832: unless ($role =~ /^gr/) {
9833: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9834: $origstart,$selfenroll,$context);
9835: }
1.1172.2.9 raeburn 9836: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9837: $selfenroll,$context);
9838: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9839: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9840: ($role eq 'da')) {
1.1172.2.9 raeburn 9841: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9842: $context);
9843: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9844: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9845: $context);
9846: }
1.1053 raeburn 9847: if ($role eq 'cc') {
9848: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9849: }
1.349 www 9850: }
9851: return $answer;
1.169 harris41 9852: }
9853:
1.1053 raeburn 9854: sub autoupdate_coowners {
9855: my ($url,$end,$start,$uname,$udom) = @_;
9856: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9857: if (($cdom ne '') && ($cnum ne '')) {
9858: my $now = time;
9859: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9860: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9861: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9862: my $instcode = $coursehash{'internal.coursecode'};
9863: if ($instcode ne '') {
1.1056 raeburn 9864: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9865: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9866: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9867: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9868: if ($result eq 'valid') {
9869: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9870: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9871: push(@newcoowners,$coowner);
9872: }
9873: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9874: push(@newcoowners,$uname.':'.$udom);
9875: }
9876: @newcoowners = sort(@newcoowners);
9877: } else {
9878: push(@newcoowners,$uname.':'.$udom);
9879: }
9880: } else {
9881: if ($coursehash{'internal.co-owners'}) {
9882: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9883: unless ($coowner eq $uname.':'.$udom) {
9884: push(@newcoowners,$coowner);
9885: }
9886: }
9887: unless (@newcoowners > 0) {
9888: $delcoowners = 1;
9889: $coowners = '';
9890: }
9891: }
9892: }
9893: if (@newcoowners || $delcoowners) {
9894: &store_coowners($cdom,$cnum,$coursehash{'home'},
9895: $delcoowners,@newcoowners);
9896: }
9897: }
9898: }
9899: }
9900: }
9901: }
9902: }
9903:
9904: sub store_coowners {
9905: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9906: my $cid = $cdom.'_'.$cnum;
9907: my ($coowners,$delresult,$putresult);
9908: if (@newcoowners) {
9909: $coowners = join(',',@newcoowners);
9910: my %coownershash = (
9911: 'internal.co-owners' => $coowners,
9912: );
9913: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9914: if ($putresult eq 'ok') {
9915: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9916: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9917: }
9918: }
9919: }
9920: if ($delcoowners) {
9921: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9922: if ($delresult eq 'ok') {
9923: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9924: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9925: }
9926: }
9927: }
9928: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9929: my %crsinfo =
9930: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9931: if (ref($crsinfo{$cid}) eq 'HASH') {
9932: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9933: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9934: }
9935: }
9936: }
9937:
1.169 harris41 9938: # -------------------------------------------------- Modify user authentication
1.197 www 9939: # Overrides without validation
9940:
1.169 harris41 9941: sub modifyuserauth {
9942: my ($udom,$uname,$umode,$upass)=@_;
9943: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 9944: my $allowed;
9945: if (&allowed('mau',$udom)) {
9946: $allowed = 1;
9947: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
9948: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
9949: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
9950: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9951: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9952: if (($cdom ne '') && ($cnum ne '')) {
9953: my $is_owner = &is_course_owner($cdom,$cnum);
9954: if ($is_owner) {
9955: $allowed = 1;
9956: }
9957: }
9958: }
9959: unless ($allowed) { return 'refused'; }
1.197 www 9960: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9961: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9962: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9963: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9964: &escape($upass),$uhome);
1.1172.2.134 raeburn 9965: my $ip = &get_requestor_ip();
1.620 albertel 9966: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9967: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134 raeburn 9968: '(Remote '.$ip.'): '.$reply);
1.197 www 9969: &log($udom,,$uname,$uhome,
1.620 albertel 9970: 'Authentication changed by '.$env{'user.domain'}.', '.
9971: $env{'user.name'}.', '.$umode.
1.1172.2.134 raeburn 9972: '(Remote '.$ip.'): '.$reply);
1.169 harris41 9973: unless ($reply eq 'ok') {
1.197 www 9974: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9975: return 'error: '.$reply;
9976: }
1.170 harris41 9977: return 'ok';
1.80 www 9978: }
9979:
1.81 www 9980: # --------------------------------------------------------------- Modify a user
1.80 www 9981:
1.81 www 9982: sub modifyuser {
1.206 matthew 9983: my ($udom, $uname, $uid,
9984: $umode, $upass, $first,
9985: $middle, $last, $gene,
1.1058 raeburn 9986: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9987: $udom= &LONCAPA::clean_domain($udom);
9988: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9989: my $showcandelete = 'none';
9990: if (ref($candelete) eq 'ARRAY') {
9991: if (@{$candelete} > 0) {
9992: $showcandelete = join(', ',@{$candelete});
9993: }
9994: }
1.81 www 9995: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9996: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9997: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9998: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9999: ' desiredhome not specified').
1.620 albertel 10000: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10001: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10002: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10003: my $newuser;
10004: if ($uhome eq 'no_host') {
10005: $newuser = 1;
10006: }
1.80 www 10007: # ----------------------------------------------------------------- Create User
1.406 albertel 10008: if (($uhome eq 'no_host') &&
10009: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 10010: my $unhome='';
1.844 albertel 10011: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10012: $unhome = $desiredhome;
1.620 albertel 10013: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10014: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10015: } else { # load balancing routine for determining $unhome
1.81 www 10016: my $loadm=10000000;
1.841 albertel 10017: my %servers = &get_servers($udom,'library');
10018: foreach my $tryserver (keys(%servers)) {
10019: my $answer=reply('load',$tryserver);
10020: if (($answer=~/\d+/) && ($answer<$loadm)) {
10021: $loadm=$answer;
10022: $unhome=$tryserver;
10023: }
1.80 www 10024: }
10025: }
10026: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10027: return 'error: unable to find a home server for '.$uname.
10028: ' in domain '.$udom;
1.80 www 10029: }
10030: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10031: &escape($upass),$unhome);
10032: unless ($reply eq 'ok') {
10033: return 'error: '.$reply;
10034: }
1.230 stredwic 10035: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10036: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10037: return 'error: unable verify users home machine.';
1.80 www 10038: }
1.209 matthew 10039: } # End of creation of new user
1.80 www 10040: # ---------------------------------------------------------------------- Add ID
10041: if ($uid) {
10042: $uid=~tr/A-Z/a-z/;
10043: my %uidhash=&idrget($udom,$uname);
1.196 www 10044: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10045: && (!$forceid)) {
1.80 www 10046: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10047: return 'error: user id "'.$uid.'" does not match '.
10048: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10049: }
10050: } else {
10051: &idput($udom,($uname => $uid));
10052: }
10053: }
10054: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10055: my @tmp=&get('environment',
1.899 raeburn 10056: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10057: 'permanentemail','inststatus'],
1.134 albertel 10058: $udom,$uname);
1.1075 raeburn 10059: my (%names,%oldnames);
1.313 matthew 10060: if ($tmp[0] =~ m/^error:.*/) {
10061: %names=();
10062: } else {
10063: %names = @tmp;
1.1075 raeburn 10064: %oldnames = %names;
1.313 matthew 10065: }
1.388 www 10066: #
1.1058 raeburn 10067: # If name, email and/or uid are blank (e.g., because an uploaded file
10068: # of users did not contain them), do not overwrite existing values
10069: # unless field is in $candelete array ref.
10070: #
10071:
10072: my @fields = ('firstname','middlename','lastname','generation',
10073: 'permanentemail','id');
10074: my %newvalues;
10075: if (ref($candelete) eq 'ARRAY') {
10076: foreach my $field (@fields) {
10077: if (grep(/^\Q$field\E$/,@{$candelete})) {
10078: if ($field eq 'firstname') {
10079: $names{$field} = $first;
10080: } elsif ($field eq 'middlename') {
10081: $names{$field} = $middle;
10082: } elsif ($field eq 'lastname') {
10083: $names{$field} = $last;
10084: } elsif ($field eq 'generation') {
10085: $names{$field} = $gene;
10086: } elsif ($field eq 'permanentemail') {
10087: $names{$field} = $email;
10088: } elsif ($field eq 'id') {
10089: $names{$field} = $uid;
10090: }
10091: }
10092: }
10093: }
1.388 www 10094: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10095: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10096: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10097: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10098: if ($email) {
10099: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10100: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10101: }
1.899 raeburn 10102: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10103: if (defined($inststatus)) {
10104: $names{'inststatus'} = '';
10105: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10106: if (ref($usertypes) eq 'HASH') {
10107: my @okstatuses;
10108: foreach my $item (split(/:/,$inststatus)) {
10109: if (defined($usertypes->{$item})) {
10110: push(@okstatuses,$item);
10111: }
10112: }
10113: if (@okstatuses) {
10114: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10115: }
10116: }
10117: }
1.1075 raeburn 10118: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10119: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10120: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10121: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10122: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10123: } else {
10124: $logmsg .= ' during self creation';
10125: }
1.1075 raeburn 10126: my $changed;
10127: if ($newuser) {
10128: $changed = 1;
10129: } else {
10130: foreach my $field (@fields) {
10131: if ($names{$field} ne $oldnames{$field}) {
10132: $changed = 1;
10133: last;
10134: }
10135: }
10136: }
10137: unless ($changed) {
10138: $logmsg = 'No changes in user information needed for: '.$logmsg;
10139: &logthis($logmsg);
10140: return 'ok';
10141: }
10142: my $reply = &put('environment', \%names, $udom,$uname);
10143: if ($reply ne 'ok') {
10144: return 'error: '.$reply;
10145: }
1.1087 raeburn 10146: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10147: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10148: }
1.1075 raeburn 10149: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10150: &devalidate_cache_new('namescache',$uname.':'.$udom);
10151: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10152: &logthis($logmsg);
1.134 albertel 10153: return 'ok';
1.80 www 10154: }
10155:
1.81 www 10156: # -------------------------------------------------------------- Modify student
1.80 www 10157:
1.81 www 10158: sub modifystudent {
10159: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10160: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10161: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10162: if (!$cid) {
1.620 albertel 10163: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10164: return 'not_in_class';
10165: }
1.80 www 10166: }
10167: # --------------------------------------------------------------- Make the user
1.81 www 10168: my $reply=&modifyuser
1.209 matthew 10169: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10170: $desiredhome,$email,$inststatus);
1.80 www 10171: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10172: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10173: # student's environment
1.297 matthew 10174: $uid = undef if (!$forceid);
1.455 albertel 10175: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10176: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10177: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10178: return $reply;
10179: }
10180:
10181: sub modify_student_enrollment {
1.1172.2.23 raeburn 10182: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10183: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10184: my ($cdom,$cnum,$chome);
10185: if (!$cid) {
1.620 albertel 10186: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10187: return 'not_in_class';
10188: }
1.620 albertel 10189: $cdom=$env{'course.'.$cid.'.domain'};
10190: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10191: } else {
10192: ($cdom,$cnum)=split(/_/,$cid);
10193: }
1.620 albertel 10194: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10195: if (!$chome) {
1.457 raeburn 10196: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10197: }
1.455 albertel 10198: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10199: # Make sure the user exists
1.81 www 10200: my $uhome=&homeserver($uname,$udom);
10201: if (($uhome eq '') || ($uhome eq 'no_host')) {
10202: return 'error: no such user';
10203: }
1.297 matthew 10204: # Get student data if we were not given enough information
10205: if (!defined($first) || $first eq '' ||
10206: !defined($last) || $last eq '' ||
10207: !defined($uid) || $uid eq '' ||
10208: !defined($middle) || $middle eq '' ||
10209: !defined($gene) || $gene eq '') {
1.294 matthew 10210: # They did not supply us with enough data to enroll the student, so
10211: # we need to pick up more information.
1.297 matthew 10212: my %tmp = &get('environment',
1.294 matthew 10213: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10214: ,$udom,$uname);
10215:
1.800 albertel 10216: #foreach my $key (keys(%tmp)) {
10217: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10218: #}
1.294 matthew 10219: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10220: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10221: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10222: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10223: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10224: }
1.556 albertel 10225: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10226: my $user = "$uname:$udom";
10227: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10228: my $reply=cput('classlist',
1.1148 raeburn 10229: {$user =>
1.1172.2.76 raeburn 10230: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10231: $cdom,$cnum);
1.1148 raeburn 10232: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10233: &devalidate_getsection_cache($udom,$uname,$cid);
10234: } else {
1.81 www 10235: return 'error: '.$reply;
10236: }
1.297 matthew 10237: # Add student role to user
1.83 www 10238: my $uurl='/'.$cid;
1.81 www 10239: $uurl=~s/\_/\//g;
10240: if ($usec) {
10241: $uurl.='/'.$usec;
10242: }
1.1148 raeburn 10243: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10244: $selfenroll,$context);
10245: if ($result ne 'ok') {
10246: if ($old_entry{$user} ne '') {
10247: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10248: } else {
10249: $reply = &del('classlist',[$user],$cdom,$cnum);
10250: }
10251: }
10252: return $result;
1.21 www 10253: }
10254:
1.556 albertel 10255: sub format_name {
10256: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10257: my $name;
10258: if ($first ne 'lastname') {
10259: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10260: } else {
10261: if ($lastname=~/\S/) {
10262: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10263: $name=~s/\s+,/,/;
10264: } else {
10265: $name.= $firstname.' '.$middlename.' '.$generation;
10266: }
10267: }
10268: $name=~s/^\s+//;
10269: $name=~s/\s+$//;
10270: $name=~s/\s+/ /g;
10271: return $name;
10272: }
10273:
1.84 www 10274: # ------------------------------------------------- Write to course preferences
10275:
10276: sub writecoursepref {
10277: my ($courseid,%prefs)=@_;
10278: $courseid=~s/^\///;
10279: $courseid=~s/\_/\//g;
10280: my ($cdomain,$cnum)=split(/\//,$courseid);
10281: my $chome=homeserver($cnum,$cdomain);
10282: if (($chome eq '') || ($chome eq 'no_host')) {
10283: return 'error: no such course';
10284: }
10285: my $cstring='';
1.800 albertel 10286: foreach my $pref (keys(%prefs)) {
10287: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10288: }
1.84 www 10289: $cstring=~s/\&$//;
10290: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10291: }
10292:
10293: # ---------------------------------------------------------- Make/modify course
10294:
10295: sub createcourse {
1.741 raeburn 10296: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10297: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10298: $url=&declutter($url);
10299: my $cid='';
1.1028 raeburn 10300: if ($context eq 'requestcourses') {
10301: my $can_create = 0;
10302: my ($ownername,$ownerdom) = split(':',$course_owner);
10303: if ($udom eq $ownerdom) {
10304: if (&usertools_access($ownername,$ownerdom,$category,undef,
10305: $context)) {
10306: $can_create = 1;
10307: }
10308: } else {
10309: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10310: $category);
10311: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10312: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10313: if (@curr > 0) {
10314: my @options = qw(approval validate autolimit);
10315: my $optregex = join('|',@options);
10316: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10317: $can_create = 1;
10318: }
10319: }
10320: }
10321: }
10322: if ($can_create) {
10323: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10324: unless (&allowed('ccc',$udom)) {
10325: return 'refused';
10326: }
1.1017 raeburn 10327: }
10328: } else {
10329: return 'refused';
10330: }
1.1028 raeburn 10331: } elsif (!&allowed('ccc',$udom)) {
10332: return 'refused';
1.84 www 10333: }
1.1011 raeburn 10334: # --------------------------------------------------------------- Get Unique ID
10335: my $uname;
10336: if ($cnum =~ /^$match_courseid$/) {
10337: my $chome=&homeserver($cnum,$udom,'true');
10338: if (($chome eq '') || ($chome eq 'no_host')) {
10339: $uname = $cnum;
10340: } else {
1.1038 raeburn 10341: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10342: }
10343: } else {
1.1038 raeburn 10344: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10345: }
10346: return $uname if ($uname =~ /^error/);
10347: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10348: if (!defined($course_server)) {
10349: if (defined(&domain($udom,'primary'))) {
10350: $course_server = &domain($udom,'primary');
10351: } else {
10352: $course_server = $env{'user.home'};
10353: }
10354: }
10355: my %host_servers =
10356: &Apache::lonnet::get_servers($udom,'library');
10357: unless ($host_servers{$course_server}) {
10358: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10359: }
1.84 www 10360: # ------------------------------------------------------------- Make the course
10361: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10362: $course_server);
1.84 www 10363: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10364: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10365: if (($uhome eq '') || ($uhome eq 'no_host')) {
10366: return 'error: no such course';
10367: }
1.271 www 10368: # ----------------------------------------------------------------- Course made
1.516 raeburn 10369: # log existence
1.1029 raeburn 10370: my $now = time;
1.918 raeburn 10371: my $newcourse = {
10372: $udom.'_'.$uname => {
1.921 raeburn 10373: description => $description,
10374: inst_code => $inst_code,
10375: owner => $course_owner,
10376: type => $crstype,
1.1029 raeburn 10377: creator => $env{'user.name'}.':'.
10378: $env{'user.domain'},
10379: created => $now,
10380: context => $context,
1.918 raeburn 10381: },
10382: };
1.921 raeburn 10383: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10384: # set toplevel url
1.271 www 10385: my $topurl=$url;
10386: unless ($nonstandard) {
10387: # ------------------------------------------ For standard courses, make top url
10388: my $mapurl=&clutter($url);
1.278 www 10389: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10390: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10391: <map>
10392: <resource id="1" type="start"></resource>
10393: <resource id="2" src="$mapurl"></resource>
10394: <resource id="3" type="finish"></resource>
10395: <link index="1" from="1" to="2"></link>
10396: <link index="2" from="2" to="3"></link>
10397: </map>
10398: ENDINITMAP
10399: $topurl=&declutter(
1.638 albertel 10400: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10401: );
10402: }
10403: # ----------------------------------------------------------- Write preferences
1.84 www 10404: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10405: ('description' => $description,
10406: 'url' => $topurl,
10407: 'internal.creator' => $env{'user.name'}.':'.
10408: $env{'user.domain'},
10409: 'internal.created' => $now,
10410: 'internal.creationcontext' => $context)
10411: );
1.84 www 10412: return '/'.$udom.'/'.$uname;
10413: }
10414:
1.1011 raeburn 10415: # ------------------------------------------------------------------- Create ID
10416: sub generate_coursenum {
1.1038 raeburn 10417: my ($udom,$crstype) = @_;
1.1011 raeburn 10418: my $domdesc = &domain($udom);
10419: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10420: my $first;
10421: if ($crstype eq 'Community') {
10422: $first = '0';
10423: } else {
10424: $first = int(1+rand(9));
10425: }
10426: my $uname=$first.
1.1011 raeburn 10427: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10428: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10429: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10430: # ----------------------------------------------- Make sure that does not exist
10431: my $uhome=&homeserver($uname,$udom,'true');
10432: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10433: if ($crstype eq 'Community') {
10434: $first = '0';
10435: } else {
10436: $first = int(1+rand(9));
10437: }
10438: $uname=$first.
1.1011 raeburn 10439: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10440: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10441: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10442: $uhome=&homeserver($uname,$udom,'true');
10443: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10444: return 'error: unable to generate unique course-ID';
10445: }
10446: }
10447: return $uname;
10448: }
10449:
1.813 albertel 10450: sub is_course {
1.1167 droeschl 10451: my ($cdom, $cnum) = scalar(@_) == 1 ?
10452: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 10453: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10454: my $uhome=&homeserver($cnum,$cdom);
10455: my $iscourse;
10456: if (grep { $_ eq $uhome } current_machine_ids()) {
10457: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10458: } else {
10459: my $hashid = $cdom.':'.$cnum;
10460: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10461: unless (defined($cached)) {
10462: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10463: $cnum,undef,undef,'.');
10464: $iscourse = 0;
10465: if (exists($courses{$cdom.'_'.$cnum})) {
10466: $iscourse = 1;
10467: }
10468: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10469: }
10470: }
10471: return unless($iscourse);
1.1167 droeschl 10472: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10473: }
10474:
1.1015 raeburn 10475: sub store_userdata {
10476: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10477: my $result;
1.1016 raeburn 10478: if ($datakey ne '') {
1.1013 raeburn 10479: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10480: if ($udom eq '' || $uname eq '') {
10481: $udom = $env{'user.domain'};
10482: $uname = $env{'user.name'};
10483: }
10484: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10485: if (($uhome eq '') || ($uhome eq 'no_host')) {
10486: $result = 'error: no_host';
10487: } else {
10488: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10489: $storehash->{'host'} = $perlvar{'lonHostID'};
10490:
10491: my $namevalue='';
10492: foreach my $key (keys(%{$storehash})) {
10493: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10494: }
10495: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10496: unless ($namespace eq 'courserequests') {
10497: $datakey = &escape($datakey);
10498: }
1.1105 raeburn 10499: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10500: $namevalue,$uhome);
1.1013 raeburn 10501: }
10502: } else {
10503: $result = 'error: data to store was not a hash reference';
10504: }
10505: } else {
10506: $result= 'error: invalid requestkey';
10507: }
10508: return $result;
10509: }
10510:
1.21 www 10511: # ---------------------------------------------------------- Assign Custom Role
10512:
10513: sub assigncustomrole {
1.957 raeburn 10514: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10515: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10516: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10517: }
10518:
10519: # ----------------------------------------------------------------- Revoke Role
10520:
10521: sub revokerole {
1.957 raeburn 10522: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10523: my $now=time;
1.965 raeburn 10524: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10525: }
10526:
10527: # ---------------------------------------------------------- Revoke Custom Role
10528:
10529: sub revokecustomrole {
1.957 raeburn 10530: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10531: my $now=time;
1.357 www 10532: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10533: $deleteflag,$selfenroll,$context);
1.17 www 10534: }
10535:
1.533 banghart 10536: # ------------------------------------------------------------ Disk usage
1.535 albertel 10537: sub diskusage {
1.955 raeburn 10538: my ($udom,$uname,$directorypath,$getpropath)=@_;
10539: $directorypath =~ s/\/$//;
10540: my $listing=&reply('du2:'.&escape($directorypath).':'
10541: .&escape($getpropath).':'.&escape($uname).':'
10542: .&escape($udom),homeserver($uname,$udom));
10543: if ($listing eq 'unknown_cmd') {
10544: if ($getpropath) {
10545: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10546: }
10547: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10548: }
1.514 albertel 10549: return $listing;
1.512 banghart 10550: }
10551:
1.566 banghart 10552: sub is_locked {
1.1096 raeburn 10553: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10554: my @check;
10555: my $is_locked;
1.1093 raeburn 10556: push (@check,$file_name);
1.613 albertel 10557: my %locked = &get('file_permissions',\@check,
1.620 albertel 10558: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10559: my ($tmp)=keys(%locked);
10560: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10561:
1.566 banghart 10562: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10563: $is_locked = 'false';
10564: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10565: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10566: $is_locked = 'true';
1.1096 raeburn 10567: if (ref($which) eq 'ARRAY') {
10568: push(@{$which},$entry);
10569: } else {
10570: last;
10571: }
1.745 raeburn 10572: }
10573: }
1.566 banghart 10574: } else {
10575: $is_locked = 'false';
10576: }
1.1093 raeburn 10577: return $is_locked;
1.566 banghart 10578: }
10579:
1.759 albertel 10580: sub declutter_portfile {
10581: my ($file) = @_;
1.833 albertel 10582: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10583: return $file;
10584: }
10585:
1.559 banghart 10586: # ------------------------------------------------------------- Mark as Read Only
10587:
10588: sub mark_as_readonly {
10589: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10590: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10591: my ($tmp)=keys(%current_permissions);
10592: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10593: foreach my $file (@{$files}) {
1.759 albertel 10594: $file = &declutter_portfile($file);
1.561 banghart 10595: push(@{$current_permissions{$file}},$what);
1.559 banghart 10596: }
1.613 albertel 10597: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10598: return;
10599: }
10600:
1.572 banghart 10601: # ------------------------------------------------------------Save Selected Files
10602:
10603: sub save_selected_files {
10604: my ($user, $path, @files) = @_;
10605: my $filename = $user."savedfiles";
1.573 banghart 10606: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 10607: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10608: foreach my $file (@files) {
1.620 albertel 10609: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10610: }
10611: foreach my $file (@other_files) {
1.574 banghart 10612: print (OUT $file."\n");
1.572 banghart 10613: }
1.574 banghart 10614: close (OUT);
1.572 banghart 10615: return 'ok';
10616: }
10617:
1.574 banghart 10618: sub clear_selected_files {
10619: my ($user) = @_;
10620: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 10621: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10622: print (OUT undef);
10623: close (OUT);
10624: return ("ok");
10625: }
10626:
1.572 banghart 10627: sub files_in_path {
10628: my ($user, $path) = @_;
10629: my $filename = $user."savedfiles";
10630: my %return_files;
1.1172.2.96 raeburn 10631: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10632: while (my $line_in = <IN>) {
1.574 banghart 10633: chomp ($line_in);
10634: my @paths_and_file = split (m!/!, $line_in);
10635: my $file_part = pop (@paths_and_file);
10636: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10637: $path_part.='/';
10638: my $path_and_file = $path_part.$file_part;
10639: if ($path_part eq $path) {
10640: $return_files{$file_part}= 'selected';
10641: }
10642: }
1.574 banghart 10643: close (IN);
10644: return (\%return_files);
1.572 banghart 10645: }
10646:
10647: # called in portfolio select mode, to show files selected NOT in current directory
10648: sub files_not_in_path {
10649: my ($user, $path) = @_;
10650: my $filename = $user."savedfiles";
10651: my @return_files;
10652: my $path_part;
1.1172.2.96 raeburn 10653: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10654: while (my $line = <IN>) {
1.572 banghart 10655: #ok, I know it's clunky, but I want it to work
1.800 albertel 10656: my @paths_and_file = split(m|/|, $line);
10657: my $file_part = pop(@paths_and_file);
10658: chomp($file_part);
10659: my $path_part = join('/', @paths_and_file);
1.572 banghart 10660: $path_part .= '/';
10661: my $path_and_file = $path_part.$file_part;
10662: if ($path_part ne $path) {
1.800 albertel 10663: push(@return_files, ($path_and_file));
1.572 banghart 10664: }
10665: }
1.800 albertel 10666: close(OUT);
1.574 banghart 10667: return (@return_files);
1.572 banghart 10668: }
10669:
1.745 raeburn 10670: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10671:
1.745 raeburn 10672: sub get_portfile_permissions {
10673: my ($domain,$user) = @_;
1.613 albertel 10674: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10675: my ($tmp)=keys(%current_permissions);
10676: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10677: return \%current_permissions;
10678: }
10679:
10680: #---------------------------------------------Get portfolio file access controls
10681:
1.749 raeburn 10682: sub get_access_controls {
1.745 raeburn 10683: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10684: my %access;
10685: my $real_file = $file;
10686: $file =~ s/\.meta$//;
1.745 raeburn 10687: if (defined($file)) {
1.749 raeburn 10688: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10689: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10690: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10691: }
10692: }
1.745 raeburn 10693: } else {
1.749 raeburn 10694: foreach my $key (keys(%{$current_permissions})) {
10695: if ($key =~ /\0accesscontrol$/) {
10696: if (defined($group)) {
10697: if ($key !~ m-^\Q$group\E/-) {
10698: next;
10699: }
10700: }
10701: my ($fullpath) = split(/\0/,$key);
10702: if (ref($$current_permissions{$key}) eq 'HASH') {
10703: foreach my $control (keys(%{$$current_permissions{$key}})) {
10704: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10705: }
10706: }
10707: }
10708: }
10709: }
10710: return %access;
10711: }
10712:
10713: sub modify_access_controls {
10714: my ($file_name,$changes,$domain,$user)=@_;
10715: my ($outcome,$deloutcome);
10716: my %store_permissions;
10717: my %new_values;
10718: my %new_control;
10719: my %translation;
10720: my @deletions = ();
10721: my $now = time;
10722: if (exists($$changes{'activate'})) {
10723: if (ref($$changes{'activate'}) eq 'HASH') {
10724: my @newitems = sort(keys(%{$$changes{'activate'}}));
10725: my $numnew = scalar(@newitems);
10726: for (my $i=0; $i<$numnew; $i++) {
10727: my $newkey = $newitems[$i];
10728: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10729: if ($newkey =~ /^\d+:/) {
10730: $newkey =~ s/^(\d+)/$newid/;
10731: $translation{$1} = $newid;
10732: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10733: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10734: $translation{$1} = $newid;
10735: }
1.749 raeburn 10736: $new_values{$file_name."\0".$newkey} =
10737: $$changes{'activate'}{$newitems[$i]};
10738: $new_control{$newkey} = $now;
10739: }
10740: }
10741: }
10742: my %todelete;
10743: my %changed_items;
10744: foreach my $action ('delete','update') {
10745: if (exists($$changes{$action})) {
10746: if (ref($$changes{$action}) eq 'HASH') {
10747: foreach my $key (keys(%{$$changes{$action}})) {
10748: my ($itemnum) = ($key =~ /^([^:]+):/);
10749: if ($action eq 'delete') {
10750: $todelete{$itemnum} = 1;
10751: } else {
10752: $changed_items{$itemnum} = $key;
10753: }
10754: }
1.745 raeburn 10755: }
10756: }
1.749 raeburn 10757: }
10758: # get lock on access controls for file.
10759: my $lockhash = {
10760: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10761: ':'.$env{'user.domain'},
10762: };
10763: my $tries = 0;
10764: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10765:
1.1172.2.79 raeburn 10766: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10767: $tries ++;
1.1172.2.79 raeburn 10768: sleep(0.1);
1.749 raeburn 10769: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10770: }
10771: if ($gotlock eq 'ok') {
10772: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10773: my ($tmp)=keys(%curr_permissions);
10774: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10775: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10776: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10777: if (ref($curr_controls) eq 'HASH') {
10778: foreach my $control_item (keys(%{$curr_controls})) {
10779: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10780: if (defined($todelete{$itemnum})) {
10781: push(@deletions,$file_name."\0".$control_item);
10782: } else {
10783: if (defined($changed_items{$itemnum})) {
10784: $new_control{$changed_items{$itemnum}} = $now;
10785: push(@deletions,$file_name."\0".$control_item);
10786: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10787: } else {
10788: $new_control{$control_item} = $$curr_controls{$control_item};
10789: }
10790: }
1.745 raeburn 10791: }
10792: }
10793: }
1.970 raeburn 10794: my ($group);
10795: if (&is_course($domain,$user)) {
10796: ($group,my $file) = split(/\//,$file_name,2);
10797: }
1.749 raeburn 10798: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10799: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10800: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10801: # remove lock
10802: my @del_lock = ($file_name."\0".'locked_access_records');
10803: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10804: my $sqlresult =
1.970 raeburn 10805: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10806: $group);
1.749 raeburn 10807: } else {
10808: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10809: }
1.749 raeburn 10810: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10811: }
10812:
1.827 raeburn 10813: sub make_public_indefinitely {
10814: my ($requrl) = @_;
10815: my $now = time;
10816: my $action = 'activate';
10817: my $aclnum = 0;
10818: if (&is_portfolio_url($requrl)) {
10819: my (undef,$udom,$unum,$file_name,$group) =
10820: &parse_portfolio_url($requrl);
10821: my $current_perms = &get_portfile_permissions($udom,$unum);
10822: my %access_controls = &get_access_controls($current_perms,
10823: $group,$file_name);
10824: foreach my $key (keys(%{$access_controls{$file_name}})) {
10825: my ($num,$scope,$end,$start) =
10826: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10827: if ($scope eq 'public') {
10828: if ($start <= $now && $end == 0) {
10829: $action = 'none';
10830: } else {
10831: $action = 'update';
10832: $aclnum = $num;
10833: }
10834: last;
10835: }
10836: }
10837: if ($action eq 'none') {
10838: return 'ok';
10839: } else {
10840: my %changes;
10841: my $newend = 0;
10842: my $newstart = $now;
10843: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10844: $changes{$action}{$newkey} = {
10845: type => 'public',
10846: time => {
10847: start => $newstart,
10848: end => $newend,
10849: },
10850: };
10851: my ($outcome,$deloutcome,$new_values,$translation) =
10852: &modify_access_controls($file_name,\%changes,$udom,$unum);
10853: return $outcome;
10854: }
10855: } else {
10856: return 'invalid';
10857: }
10858: }
10859:
1.745 raeburn 10860: #------------------------------------------------------Get Marked as Read Only
10861:
10862: sub get_marked_as_readonly {
10863: my ($domain,$user,$what,$group) = @_;
10864: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10865: my @readonly_files;
1.629 banghart 10866: my $cmp1=$what;
10867: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10868: while (my ($file_name,$value) = each(%{$current_permissions})) {
10869: if (defined($group)) {
10870: if ($file_name !~ m-^\Q$group\E/-) {
10871: next;
10872: }
10873: }
1.561 banghart 10874: if (ref($value) eq "ARRAY"){
10875: foreach my $stored_what (@{$value}) {
1.629 banghart 10876: my $cmp2=$stored_what;
1.759 albertel 10877: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10878: $cmp2=join('',@{$stored_what});
1.745 raeburn 10879: }
1.629 banghart 10880: if ($cmp1 eq $cmp2) {
1.561 banghart 10881: push(@readonly_files, $file_name);
1.745 raeburn 10882: last;
1.563 banghart 10883: } elsif (!defined($what)) {
10884: push(@readonly_files, $file_name);
1.745 raeburn 10885: last;
1.561 banghart 10886: }
10887: }
1.745 raeburn 10888: }
1.561 banghart 10889: }
10890: return @readonly_files;
10891: }
1.577 banghart 10892: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10893:
1.577 banghart 10894: sub get_marked_as_readonly_hash {
1.745 raeburn 10895: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10896: my %readonly_files;
1.745 raeburn 10897: while (my ($file_name,$value) = each(%{$current_permissions})) {
10898: if (defined($group)) {
10899: if ($file_name !~ m-^\Q$group\E/-) {
10900: next;
10901: }
10902: }
1.577 banghart 10903: if (ref($value) eq "ARRAY"){
10904: foreach my $stored_what (@{$value}) {
1.745 raeburn 10905: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10906: foreach my $lock_descriptor(@{$stored_what}) {
10907: if ($lock_descriptor eq 'graded') {
10908: $readonly_files{$file_name} = 'graded';
10909: } elsif ($lock_descriptor eq 'handback') {
10910: $readonly_files{$file_name} = 'handback';
10911: } else {
10912: if (!exists($readonly_files{$file_name})) {
10913: $readonly_files{$file_name} = 'locked';
10914: }
10915: }
1.745 raeburn 10916: }
1.750 banghart 10917: }
1.577 banghart 10918: }
10919: }
10920: }
10921: return %readonly_files;
10922: }
1.559 banghart 10923: # ------------------------------------------------------------ Unmark as Read Only
10924:
10925: sub unmark_as_readonly {
1.629 banghart 10926: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10927: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10928: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10929: $file_name = &declutter_portfile($file_name);
1.634 albertel 10930: my $symb_crs = $what;
10931: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10932: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10933: my ($tmp)=keys(%current_permissions);
10934: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10935: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10936: foreach my $file (@readonly_files) {
1.759 albertel 10937: my $clean_file = &declutter_portfile($file);
10938: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10939: my $current_locks = $current_permissions{$file};
1.563 banghart 10940: my @new_locks;
10941: my @del_keys;
10942: if (ref($current_locks) eq "ARRAY"){
10943: foreach my $locker (@{$current_locks}) {
1.632 albertel 10944: my $compare=$locker;
1.749 raeburn 10945: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10946: $compare=join('',@{$locker});
1.746 raeburn 10947: if ($compare ne $symb_crs) {
10948: push(@new_locks, $locker);
10949: }
1.563 banghart 10950: }
10951: }
1.650 albertel 10952: if (scalar(@new_locks) > 0) {
1.563 banghart 10953: $current_permissions{$file} = \@new_locks;
10954: } else {
10955: push(@del_keys, $file);
1.613 albertel 10956: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10957: delete($current_permissions{$file});
1.563 banghart 10958: }
10959: }
1.561 banghart 10960: }
1.613 albertel 10961: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10962: return;
10963: }
1.512 banghart 10964:
1.17 www 10965: # ------------------------------------------------------------ Directory lister
10966:
10967: sub dirlist {
1.955 raeburn 10968: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10969: $uri=~s/^\///;
10970: $uri=~s/\/$//;
1.253 stredwic 10971: my ($udom, $uname);
1.955 raeburn 10972: if ($getuserdir) {
1.253 stredwic 10973: $udom = $userdomain;
10974: $uname = $username;
1.955 raeburn 10975: } else {
10976: (undef,$udom,$uname)=split(/\//,$uri);
10977: if(defined($userdomain)) {
10978: $udom = $userdomain;
10979: }
10980: if(defined($username)) {
10981: $uname = $username;
10982: }
1.253 stredwic 10983: }
1.955 raeburn 10984: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10985:
1.955 raeburn 10986: $dirRoot = $perlvar{'lonDocRoot'};
10987: if (defined($getpropath)) {
10988: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10989: $dirRoot =~ s/\/$//;
1.955 raeburn 10990: } elsif (defined($getuserdir)) {
10991: my $subdir=$uname.'__';
10992: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10993: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10994: ."/$udom/$subdir/$uname";
10995: } elsif (defined($alternateRoot)) {
10996: $dirRoot = $alternateRoot;
1.751 banghart 10997: }
1.253 stredwic 10998:
10999: if($udom) {
11000: if($uname) {
1.1135 raeburn 11001: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11002: if ($uhome eq 'no_host') {
11003: return ([],'no_host');
11004: }
1.955 raeburn 11005: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11006: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11007: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11008: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11009: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11010: } else {
11011: @listing_results = map { &unescape($_); } split(/:/,$listing);
11012: }
1.605 matthew 11013: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11014: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11015: @listing_results = split(/:/,$listing);
11016: } else {
11017: @listing_results = map { &unescape($_); } split(/:/,$listing);
11018: }
1.1135 raeburn 11019: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11020: ($listing eq 'rejected') || ($listing eq 'refused') ||
11021: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11022: return ([],$listing);
11023: } else {
11024: return (\@listing_results);
1.1135 raeburn 11025: }
1.955 raeburn 11026: } elsif(!$alternateRoot) {
1.1136 raeburn 11027: my (%allusers,%listerror);
1.841 albertel 11028: my %servers = &get_servers($udom,'library');
1.955 raeburn 11029: foreach my $tryserver (keys(%servers)) {
11030: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11031: &escape($udom),$tryserver);
11032: if ($listing eq 'unknown_cmd') {
11033: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11034: $udom, $tryserver);
11035: } else {
11036: @listing_results = map { &unescape($_); } split(/:/,$listing);
11037: }
1.841 albertel 11038: if ($listing eq 'unknown_cmd') {
11039: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11040: $udom, $tryserver);
11041: @listing_results = split(/:/,$listing);
11042: } else {
11043: @listing_results =
11044: map { &unescape($_); } split(/:/,$listing);
11045: }
1.1136 raeburn 11046: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11047: ($listing eq 'rejected') || ($listing eq 'refused') ||
11048: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11049: $listerror{$tryserver} = $listing;
11050: } else {
1.841 albertel 11051: foreach my $line (@listing_results) {
11052: my ($entry) = split(/&/,$line,2);
11053: $allusers{$entry} = 1;
11054: }
11055: }
1.253 stredwic 11056: }
1.1136 raeburn 11057: my @alluserslist=();
1.800 albertel 11058: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11059: push(@alluserslist,$user.'&user');
1.253 stredwic 11060: }
1.1172.2.80 raeburn 11061: if (!%listerror) {
11062: # no errors
11063: return (\@alluserslist);
11064: } elsif (scalar(keys(%servers)) == 1) {
11065: # one library server, one error
11066: my ($key) = keys(%listerror);
11067: return (\@alluserslist, $listerror{$key});
11068: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11069: # con_lost indicates that we might miss data from at least one
11070: # library server
11071: return (\@alluserslist, 'con_lost');
11072: } else {
11073: # multiple library servers and no con_lost -> data should be
11074: # complete.
11075: return (\@alluserslist);
11076: }
11077:
1.253 stredwic 11078: } else {
1.1136 raeburn 11079: return ([],'missing username');
1.253 stredwic 11080: }
1.955 raeburn 11081: } elsif(!defined($getpropath)) {
1.1136 raeburn 11082: my $path = $perlvar{'lonDocRoot'}.'/res/';
11083: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11084: return (\@all_domains);
1.955 raeburn 11085: } else {
1.1136 raeburn 11086: return ([],'missing domain');
1.275 stredwic 11087: }
11088: }
11089:
11090: # --------------------------------------------- GetFileTimestamp
11091: # This function utilizes dirlist and returns the date stamp for
11092: # when it was last modified. It will also return an error of -1
11093: # if an error occurs
11094:
11095: sub GetFileTimestamp {
1.955 raeburn 11096: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11097: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11098: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11099: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11100: undef,$getuserdir);
11101: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11102: return -1;
11103: }
11104: if (ref($fileref) eq 'ARRAY') {
11105: my @stats = split('&',$fileref->[0]);
1.375 matthew 11106: # @stats contains first the filename, then the stat output
11107: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11108: } else {
11109: return -1;
1.253 stredwic 11110: }
1.26 www 11111: }
11112:
1.712 albertel 11113: sub stat_file {
11114: my ($uri) = @_;
1.787 albertel 11115: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11116:
1.955 raeburn 11117: my ($udom,$uname,$file);
1.712 albertel 11118: if ($uri =~ m-^/(uploaded|editupload)/-) {
11119: ($udom,$uname,$file) =
1.811 albertel 11120: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11121: $file = 'userfiles/'.$file;
11122: }
11123: if ($uri =~ m-^/res/-) {
11124: ($udom,$uname) =
1.807 albertel 11125: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11126: $file = $uri;
11127: }
11128:
11129: if (!$udom || !$uname || !$file) {
11130: # unable to handle the uri
11131: return ();
11132: }
1.956 raeburn 11133: my $getpropath;
11134: if ($file =~ /^userfiles\//) {
11135: $getpropath = 1;
11136: }
1.1136 raeburn 11137: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11138: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11139: return ();
11140: } else {
11141: if (ref($listref) eq 'ARRAY') {
11142: my @stats = split('&',$listref->[0]);
11143: shift(@stats); #filename is first
11144: return @stats;
11145: }
1.712 albertel 11146: }
11147: return ();
11148: }
11149:
1.26 www 11150: # -------------------------------------------------------- Value of a Condition
11151:
1.713 albertel 11152: # gets the value of a specific preevaluated condition
11153: # stored in the string $env{user.state.<cid>}
11154: # or looks up a condition reference in the bighash and if if hasn't
11155: # already been evaluated recurses into docondval to get the value of
11156: # the condition, then memoizing it to
11157: # $env{user.state.<cid>.<condition>}
1.40 www 11158: sub directcondval {
11159: my $number=shift;
1.620 albertel 11160: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11161: &Apache::lonuserstate::evalstate();
11162: }
1.713 albertel 11163: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11164: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11165: } elsif ($number =~ /^_/) {
11166: my $sub_condition;
11167: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11168: &GDBM_READER(),0640)) {
11169: $sub_condition=$bighash{'conditions'.$number};
11170: untie(%bighash);
11171: }
11172: my $value = &docondval($sub_condition);
1.949 raeburn 11173: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11174: return $value;
11175: }
1.620 albertel 11176: if ($env{'user.state.'.$env{'request.course.id'}}) {
11177: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11178: } else {
11179: return 2;
11180: }
11181: }
11182:
1.713 albertel 11183: # get the collection of conditions for this resource
1.26 www 11184: sub condval {
11185: my $condidx=shift;
1.54 www 11186: my $allpathcond='';
1.713 albertel 11187: foreach my $cond (split(/\|/,$condidx)) {
11188: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11189: $allpathcond.=
11190: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11191: }
1.191 harris41 11192: }
1.54 www 11193: $allpathcond=~s/\|$//;
1.713 albertel 11194: return &docondval($allpathcond);
11195: }
11196:
11197: #evaluates an expression of conditions
11198: sub docondval {
11199: my ($allpathcond) = @_;
11200: my $result=0;
11201: if ($env{'request.course.id'}
11202: && defined($allpathcond)) {
11203: my $operand='|';
11204: my @stack;
11205: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11206: if ($chunk eq '(') {
11207: push @stack,($operand,$result);
11208: } elsif ($chunk eq ')') {
11209: my $before=pop @stack;
11210: if (pop @stack eq '&') {
11211: $result=$result>$before?$before:$result;
11212: } else {
11213: $result=$result>$before?$result:$before;
11214: }
11215: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11216: $operand=$chunk;
11217: } else {
11218: my $new=directcondval($chunk);
11219: if ($operand eq '&') {
11220: $result=$result>$new?$new:$result;
11221: } else {
11222: $result=$result>$new?$result:$new;
11223: }
11224: }
11225: }
1.26 www 11226: }
11227: return $result;
1.421 albertel 11228: }
11229:
11230: # ---------------------------------------------------- Devalidate courseresdata
11231:
11232: sub devalidatecourseresdata {
11233: my ($coursenum,$coursedomain)=@_;
11234: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11235: &devalidate_cache_new('courseres',$hashid);
1.28 www 11236: }
11237:
1.763 www 11238:
1.200 www 11239: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11240: #
11241: # Parameters:
11242: # $coursenum - Number of the course.
11243: # $coursedomain - Domain at which the course was created.
11244: # Returns:
11245: # A hash of the course parameters along (I think) with timestamps
11246: # and version info.
1.877 foxr 11247:
1.624 albertel 11248: sub get_courseresdata {
11249: my ($coursenum,$coursedomain)=@_;
1.200 www 11250: my $coursehom=&homeserver($coursenum,$coursedomain);
11251: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11252: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11253: my %dumpreply;
1.417 albertel 11254: unless (defined($cached)) {
1.624 albertel 11255: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11256: $result=\%dumpreply;
1.251 albertel 11257: my ($tmp) = keys(%dumpreply);
11258: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11259: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11260: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11261: return $tmp;
1.416 albertel 11262: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11263: $result=undef;
1.599 albertel 11264: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11265: }
11266: }
1.624 albertel 11267: return $result;
11268: }
11269:
1.633 albertel 11270: sub devalidateuserresdata {
11271: my ($uname,$udom)=@_;
11272: my $hashid="$udom:$uname";
11273: &devalidate_cache_new('userres',$hashid);
11274: }
11275:
1.624 albertel 11276: sub get_userresdata {
11277: my ($uname,$udom)=@_;
11278: #most student don\'t have any data set, check if there is some data
11279: if (&EXT_cache_status($udom,$uname)) { return undef; }
11280:
11281: my $hashid="$udom:$uname";
11282: my ($result,$cached)=&is_cached_new('userres',$hashid);
11283: if (!defined($cached)) {
11284: my %resourcedata=&dump('resourcedata',$udom,$uname);
11285: $result=\%resourcedata;
11286: &do_cache_new('userres',$hashid,$result,600);
11287: }
11288: my ($tmp)=keys(%$result);
11289: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11290: return $result;
11291: }
11292: #error 2 occurs when the .db doesn't exist
11293: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 11294: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11295: &logthis("<font color=\"blue\">WARNING:".
11296: " Trying to get resource data for ".
11297: $uname." at ".$udom.": ".
11298: $tmp."</font>");
11299: }
1.624 albertel 11300: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11301: #&EXT_cache_set($udom,$uname);
11302: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11303: undef($tmp); # not really an error so don't send it back
1.624 albertel 11304: }
11305: return $tmp;
11306: }
1.879 foxr 11307: #----------------------------------------------- resdata - return resource data
11308: # Purpose:
11309: # Return resource data for either users or for a course.
11310: # Parameters:
11311: # $name - Course/user name.
11312: # $domain - Name of the domain the user/course is registered on.
11313: # $type - Type of thing $name is (must be 'course' or 'user'
11314: # @which - Array of names of resources desired.
11315: # Returns:
11316: # The value of the first reasource in @which that is found in the
11317: # resource hash.
11318: # Exceptional Conditions:
11319: # If the $type passed in is not valid (not the string 'course' or
11320: # 'user', an undefined reference is returned.
11321: # If none of the resources are found, an undef is returned
1.624 albertel 11322: sub resdata {
11323: my ($name,$domain,$type,@which)=@_;
11324: my $result;
11325: if ($type eq 'course') {
11326: $result=&get_courseresdata($name,$domain);
11327: } elsif ($type eq 'user') {
11328: $result=&get_userresdata($name,$domain);
11329: }
11330: if (!ref($result)) { return $result; }
1.251 albertel 11331: foreach my $item (@which) {
1.927 albertel 11332: if (defined($result->{$item->[0]})) {
11333: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11334: }
1.250 albertel 11335: }
1.291 albertel 11336: return undef;
1.200 www 11337: }
11338:
1.1172.2.31 raeburn 11339: sub get_numsuppfiles {
11340: my ($cnum,$cdom,$ignorecache)=@_;
11341: my $hashid=$cnum.':'.$cdom;
11342: my ($suppcount,$cached);
11343: unless ($ignorecache) {
11344: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11345: }
11346: unless (defined($cached)) {
11347: my $chome=&homeserver($cnum,$cdom);
11348: unless ($chome eq 'no_host') {
11349: ($suppcount,my $errors) = (0,0);
11350: my $suppmap = 'supplemental.sequence';
11351: ($suppcount,$errors) =
11352: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11353: }
11354: &do_cache_new('suppcount',$hashid,$suppcount,600);
11355: }
11356: return $suppcount;
11357: }
11358:
1.379 matthew 11359: #
11360: # EXT resource caching routines
11361: #
11362:
11363: sub clear_EXT_cache_status {
1.383 albertel 11364: &delenv('cache.EXT.');
1.379 matthew 11365: }
11366:
11367: sub EXT_cache_status {
11368: my ($target_domain,$target_user) = @_;
1.383 albertel 11369: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11370: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11371: # We know already the user has no data
11372: return 1;
11373: } else {
11374: return 0;
11375: }
11376: }
11377:
11378: sub EXT_cache_set {
11379: my ($target_domain,$target_user) = @_;
1.383 albertel 11380: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11381: #&appenv({$cachename => time});
1.379 matthew 11382: }
11383:
1.28 www 11384: # --------------------------------------------------------- Value of a Variable
1.58 www 11385: sub EXT {
1.715 albertel 11386:
1.1172.2.28 raeburn 11387: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11388: unless ($varname) { return ''; }
1.218 albertel 11389: #get real user name/domain, courseid and symb
11390: my $courseid;
1.359 albertel 11391: my $publicuser;
1.427 www 11392: if ($symbparm) {
11393: $symbparm=&get_symb_from_alias($symbparm);
11394: }
1.218 albertel 11395: if (!($uname && $udom)) {
1.790 albertel 11396: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11397: if (!$symbparm) { $symbparm=$cursymb; }
11398: } else {
1.620 albertel 11399: $courseid=$env{'request.course.id'};
1.218 albertel 11400: }
1.48 www 11401: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11402: my $rest;
1.320 albertel 11403: if (defined($therest[0])) {
1.48 www 11404: $rest=join('.',@therest);
11405: } else {
11406: $rest='';
11407: }
1.320 albertel 11408:
1.57 www 11409: my $qualifierrest=$qualifier;
11410: if ($rest) { $qualifierrest.='.'.$rest; }
11411: my $spacequalifierrest=$space;
11412: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11413: if ($realm eq 'user') {
1.48 www 11414: # --------------------------------------------------------------- user.resource
11415: if ($space eq 'resource') {
1.651 albertel 11416: if ( (defined($Apache::lonhomework::parsing_a_problem)
11417: || defined($Apache::lonhomework::parsing_a_task))
11418: &&
1.744 albertel 11419: ($symbparm eq &symbread()) ) {
11420: # if we are in the middle of processing the resource the
11421: # get the value we are planning on committing
11422: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11423: return $Apache::lonhomework::results{$qualifierrest};
11424: } else {
11425: return $Apache::lonhomework::history{$qualifierrest};
11426: }
1.335 albertel 11427: } else {
1.359 albertel 11428: my %restored;
1.620 albertel 11429: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11430: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11431: } else {
11432: %restored=&restore($symbparm,$courseid,$udom,$uname);
11433: }
1.335 albertel 11434: return $restored{$qualifierrest};
11435: }
1.48 www 11436: # ----------------------------------------------------------------- user.access
11437: } elsif ($space eq 'access') {
1.218 albertel 11438: # FIXME - not supporting calls for a specific user
1.48 www 11439: return &allowed($qualifier,$rest);
11440: # ------------------------------------------ user.preferences, user.environment
11441: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11442: if (($uname eq $env{'user.name'}) &&
11443: ($udom eq $env{'user.domain'})) {
11444: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11445: } else {
1.359 albertel 11446: my %returnhash;
11447: if (!$publicuser) {
11448: %returnhash=&userenvironment($udom,$uname,
11449: $qualifierrest);
11450: }
1.218 albertel 11451: return $returnhash{$qualifierrest};
11452: }
1.48 www 11453: # ----------------------------------------------------------------- user.course
11454: } elsif ($space eq 'course') {
1.218 albertel 11455: # FIXME - not supporting calls for a specific user
1.620 albertel 11456: return $env{join('.',('request.course',$qualifier))};
1.48 www 11457: # ------------------------------------------------------------------- user.role
11458: } elsif ($space eq 'role') {
1.218 albertel 11459: # FIXME - not supporting calls for a specific user
1.620 albertel 11460: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11461: if ($qualifier eq 'value') {
11462: return $role;
11463: } elsif ($qualifier eq 'extent') {
11464: return $where;
11465: }
11466: # ----------------------------------------------------------------- user.domain
11467: } elsif ($space eq 'domain') {
1.218 albertel 11468: return $udom;
1.48 www 11469: # ------------------------------------------------------------------- user.name
11470: } elsif ($space eq 'name') {
1.218 albertel 11471: return $uname;
1.48 www 11472: # ---------------------------------------------------- Any other user namespace
1.29 www 11473: } else {
1.359 albertel 11474: my %reply;
11475: if (!$publicuser) {
11476: %reply=&get($space,[$qualifierrest],$udom,$uname);
11477: }
11478: return $reply{$qualifierrest};
1.48 www 11479: }
1.236 www 11480: } elsif ($realm eq 'query') {
11481: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11482: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11483: [$spacequalifierrest]);
1.620 albertel 11484: return $env{'form.'.$spacequalifierrest};
1.236 www 11485: } elsif ($realm eq 'request') {
1.48 www 11486: # ------------------------------------------------------------- request.browser
11487: if ($space eq 'browser') {
1.1145 bisitz 11488: return $env{'browser.'.$qualifier};
1.57 www 11489: # ------------------------------------------------------------ request.filename
11490: } else {
1.620 albertel 11491: return $env{'request.'.$spacequalifierrest};
1.29 www 11492: }
1.28 www 11493: } elsif ($realm eq 'course') {
1.48 www 11494: # ---------------------------------------------------------- course.description
1.620 albertel 11495: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11496: } elsif ($realm eq 'resource') {
1.165 www 11497:
1.620 albertel 11498: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11499: if (!$symbparm) { $symbparm=&symbread(); }
11500: }
1.693 albertel 11501:
1.1172.2.30 raeburn 11502: if ($qualifier eq '') {
11503: if ($space eq 'title') {
11504: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11505: return &gettitle($symbparm);
11506: }
1.693 albertel 11507:
1.1172.2.30 raeburn 11508: if ($space eq 'map') {
11509: my ($map) = &decode_symb($symbparm);
11510: return &symbread($map);
11511: }
11512: if ($space eq 'maptitle') {
11513: my ($map) = &decode_symb($symbparm);
11514: return &gettitle($map);
11515: }
11516: if ($space eq 'filename') {
11517: if ($symbparm) {
11518: return &clutter((&decode_symb($symbparm))[2]);
11519: }
11520: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11521: }
1.1172.2.30 raeburn 11522:
11523: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11524: if ($space eq 'visibleparts') {
11525: my $navmap = Apache::lonnavmaps::navmap->new();
11526: my $item;
11527: if (ref($navmap)) {
11528: my $res = $navmap->getBySymb($symbparm);
11529: my $parts = $res->parts();
11530: if (ref($parts) eq 'ARRAY') {
11531: $item = join(',',@{$parts});
11532: }
11533: undef($navmap);
11534: }
11535: return $item;
11536: }
11537: }
11538: }
1.693 albertel 11539:
11540: my ($section, $group, @groups);
1.593 albertel 11541: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11542: if (($courseid eq '') && ($cid)) {
11543: $courseid = $cid;
11544: }
11545: if (($symbparm && $courseid) &&
11546: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11547:
1.218 albertel 11548: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11549:
1.60 www 11550: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11551: my $symbp=$symbparm;
1.735 albertel 11552: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11553:
11554: my $symbparm=$symbp.'.'.$spacequalifierrest;
11555: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11556:
1.620 albertel 11557: if (($env{'user.name'} eq $uname) &&
11558: ($env{'user.domain'} eq $udom)) {
11559: $section=$env{'request.course.sec'};
1.733 raeburn 11560: @groups = split(/:/,$env{'request.course.groups'});
11561: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11562: } else {
1.539 albertel 11563: if (! defined($usection)) {
1.551 albertel 11564: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11565: } else {
11566: $section = $usection;
11567: }
1.733 raeburn 11568: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11569: }
11570:
11571: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11572: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11573: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11574:
1.593 albertel 11575: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11576: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11577: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11578:
1.60 www 11579: # ----------------------------------------------------------- first, check user
1.624 albertel 11580:
11581: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11582: ([$courselevelr,'resource'],
11583: [$courselevelm,'map' ],
11584: [$courselevel, 'course' ]));
1.931 albertel 11585: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11586:
1.594 albertel 11587: # ------------------------------------------------ second, check some of course
1.684 raeburn 11588: my $coursereply;
1.691 raeburn 11589: if (@groups > 0) {
11590: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11591: $mapparm,$spacequalifierrest);
1.927 albertel 11592: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11593: }
1.96 www 11594:
1.684 raeburn 11595: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11596: $env{'course.'.$courseid.'.domain'},
11597: 'course',
11598: ([$seclevelr, 'resource'],
11599: [$seclevelm, 'map' ],
11600: [$seclevel, 'course' ],
11601: [$courselevelr,'resource']));
11602: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11603:
1.60 www 11604: # ------------------------------------------------------ third, check map parms
1.218 albertel 11605: my %parmhash=();
11606: my $thisparm='';
11607: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11608: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11609: &GDBM_READER(),0640)) {
1.218 albertel 11610: $thisparm=$parmhash{$symbparm};
11611: untie(%parmhash);
11612: }
1.927 albertel 11613: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11614: }
1.594 albertel 11615: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11616:
1.218 albertel 11617: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11618: my $filename;
11619: if (!$symbparm) { $symbparm=&symbread(); }
11620: if ($symbparm) {
1.409 www 11621: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11622: } else {
1.620 albertel 11623: $filename=$env{'request.filename'};
1.282 albertel 11624: }
11625: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11626: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11627: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11628: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11629:
1.927 albertel 11630: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11631: if ($symbparm && defined($courseid) &&
1.620 albertel 11632: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11633: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11634: $env{'course.'.$courseid.'.domain'},
11635: 'course',
1.927 albertel 11636: ([$courselevelm,'map' ],
11637: [$courselevel, 'course']));
11638: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11639: }
1.145 www 11640: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11641: unless ($space eq '0') {
1.336 albertel 11642: my @parts=split(/_/,$space);
11643: my $id=pop(@parts);
11644: my $part=join('_',@parts);
11645: if ($part eq '') { $part='0'; }
1.927 albertel 11646: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11647: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11648: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11649: }
1.395 albertel 11650: if ($recurse) { return undef; }
11651: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11652: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11653: # ---------------------------------------------------- Any other user namespace
11654: } elsif ($realm eq 'environment') {
11655: # ----------------------------------------------------------------- environment
1.620 albertel 11656: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11657: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11658: } else {
1.770 albertel 11659: if ($uname eq 'anonymous' && $udom eq '') {
11660: return '';
11661: }
1.219 albertel 11662: my %returnhash=&userenvironment($udom,$uname,
11663: $spacequalifierrest);
11664: return $returnhash{$spacequalifierrest};
11665: }
1.28 www 11666: } elsif ($realm eq 'system') {
1.48 www 11667: # ----------------------------------------------------------------- system.time
11668: if ($space eq 'time') {
11669: return time;
11670: }
1.696 albertel 11671: } elsif ($realm eq 'server') {
11672: # ----------------------------------------------------------------- system.time
11673: if ($space eq 'name') {
11674: return $ENV{'SERVER_NAME'};
11675: }
1.28 www 11676: }
1.48 www 11677: return '';
1.61 www 11678: }
11679:
1.927 albertel 11680: sub get_reply {
11681: my ($reply_value) = @_;
1.940 raeburn 11682: if (ref($reply_value) eq 'ARRAY') {
11683: if (wantarray) {
11684: return @$reply_value;
11685: }
11686: return $reply_value->[0];
11687: } else {
11688: return $reply_value;
1.927 albertel 11689: }
11690: }
11691:
1.691 raeburn 11692: sub check_group_parms {
11693: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11694: my @groupitems = ();
11695: my $resultitem;
1.927 albertel 11696: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11697: foreach my $group (@{$groups}) {
11698: foreach my $level (@levels) {
1.927 albertel 11699: my $item = $courseid.'.['.$group.'].'.$level->[0];
11700: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11701: }
11702: }
11703: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11704: $env{'course.'.$courseid.'.domain'},
11705: 'course',@groupitems);
11706: return $coursereply;
11707: }
11708:
11709: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11710: my ($courseid,@groups) = @_;
11711: @groups = sort(@groups);
1.691 raeburn 11712: return @groups;
11713: }
11714:
1.395 albertel 11715: sub packages_tab_default {
11716: my ($uri,$varname)=@_;
11717: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11718:
11719: my (@extension,@specifics,$do_default);
11720: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11721: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11722: if ($pack_type eq 'default') {
11723: $do_default=1;
11724: } elsif ($pack_type eq 'extension') {
11725: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11726: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11727: # only look at packages defaults for packages that this id is
1.738 albertel 11728: push(@specifics,[$package,$pack_type,$pack_part]);
11729: }
11730: }
11731: # first look for a package that matches the requested part id
11732: foreach my $package (@specifics) {
11733: my (undef,$pack_type,$pack_part)=@{$package};
11734: next if ($pack_part ne $part);
11735: if (defined($packagetab{"$pack_type&$name&default"})) {
11736: return $packagetab{"$pack_type&$name&default"};
11737: }
11738: }
11739: # look for any possible matching non extension_ package
11740: foreach my $package (@specifics) {
11741: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11742: if (defined($packagetab{"$pack_type&$name&default"})) {
11743: return $packagetab{"$pack_type&$name&default"};
11744: }
1.585 albertel 11745: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11746: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11747: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11748: }
11749: }
1.738 albertel 11750: # look for any posible extension_ match
11751: foreach my $package (@extension) {
11752: my ($package,$pack_type)=@{$package};
11753: if (defined($packagetab{"$pack_type&$name&default"})) {
11754: return $packagetab{"$pack_type&$name&default"};
11755: }
11756: if (defined($packagetab{$package."&$name&default"})) {
11757: return $packagetab{$package."&$name&default"};
11758: }
11759: }
11760: # look for a global default setting
11761: if ($do_default && defined($packagetab{"default&$name&default"})) {
11762: return $packagetab{"default&$name&default"};
11763: }
1.395 albertel 11764: return undef;
11765: }
11766:
1.334 albertel 11767: sub add_prefix_and_part {
11768: my ($prefix,$part)=@_;
11769: my $keyroot;
11770: if (defined($prefix) && $prefix !~ /^__/) {
11771: # prefix that has a part already
11772: $keyroot=$prefix;
11773: } elsif (defined($prefix)) {
11774: # prefix that is missing a part
11775: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11776: } else {
11777: # no prefix at all
11778: if (defined($part)) { $keyroot='_'.$part; }
11779: }
11780: return $keyroot;
11781: }
11782:
1.71 www 11783: # ---------------------------------------------------------------- Get metadata
11784:
1.599 albertel 11785: my %metaentry;
1.1070 www 11786: my %importedpartids;
1.1172.2.99 raeburn 11787: my %importedrespids;
1.71 www 11788: sub metadata {
1.176 www 11789: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11790: $uri=&declutter($uri);
1.288 albertel 11791: # if it is a non metadata possible uri return quickly
1.529 albertel 11792: if (($uri eq '') ||
11793: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 11794: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 11795: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11796: return undef;
11797: }
1.1172.2.49 raeburn 11798: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11799: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11800: return undef;
1.288 albertel 11801: }
1.73 www 11802: my $filename=$uri;
11803: $uri=~s/\.meta$//;
1.172 www 11804: #
11805: # Is the metadata already cached?
1.177 www 11806: # Look at timestamp of caching
1.172 www 11807: # Everything is cached by the main uri, libraries are never directly cached
11808: #
1.428 albertel 11809: if (!defined($liburi)) {
1.599 albertel 11810: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11811: if (defined($cached)) { return $result->{':'.$what}; }
11812: }
11813: {
1.1069 www 11814: # Imported parts would go here
1.1172.2.99 raeburn 11815: my @origfiletagids=();
1.1069 www 11816: my $importedparts=0;
1.1172.2.99 raeburn 11817:
11818: # Imported responseids would go here
11819: my $importedresponses=0;
1.172 www 11820: #
11821: # Is this a recursive call for a library?
11822: #
1.599 albertel 11823: # if (! exists($metacache{$uri})) {
11824: # $metacache{$uri}={};
11825: # }
1.924 albertel 11826: my $cachetime = 60*60;
1.171 www 11827: if ($liburi) {
11828: $liburi=&declutter($liburi);
11829: $filename=$liburi;
1.401 bowersj2 11830: } else {
1.599 albertel 11831: &devalidate_cache_new('meta',$uri);
11832: undef(%metaentry);
1.401 bowersj2 11833: }
1.140 www 11834: my %metathesekeys=();
1.73 www 11835: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11836: my $metastring;
1.1140 www 11837: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11838: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11839: $metastring =
1.929 albertel 11840: &Apache::lonnet::ssi_body($which,
1.924 albertel 11841: ('grade_target' => 'meta'));
11842: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11843: } elsif (($uri !~ m -^(editupload)/-) &&
11844: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11845: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11846: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11847: $metastring=&getfile($file);
1.489 albertel 11848: }
1.208 albertel 11849: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11850: my $token;
1.140 www 11851: undef %metathesekeys;
1.71 www 11852: while ($token=$parser->get_token) {
1.339 albertel 11853: if ($token->[0] eq 'S') {
11854: if (defined($token->[2]->{'package'})) {
1.172 www 11855: #
11856: # This is a package - get package info
11857: #
1.339 albertel 11858: my $package=$token->[2]->{'package'};
11859: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11860: if (defined($token->[2]->{'id'})) {
11861: $keyroot.='_'.$token->[2]->{'id'};
11862: }
1.599 albertel 11863: if ($metaentry{':packages'}) {
11864: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11865: } else {
1.599 albertel 11866: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11867: }
1.736 albertel 11868: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11869: my $part=$keyroot;
11870: $part=~s/^\_//;
1.736 albertel 11871: if ($pack_entry=~/^\Q$package\E\&/ ||
11872: $pack_entry=~/^\Q$package\E_0\&/) {
11873: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11874: # ignore package.tab specified default values
11875: # here &package_tab_default() will fetch those
11876: if ($subp eq 'default') { next; }
1.736 albertel 11877: my $value=$packagetab{$pack_entry};
1.432 albertel 11878: my $unikey;
11879: if ($pack =~ /_0$/) {
11880: $unikey='parameter_0_'.$name;
11881: $part=0;
11882: } else {
11883: $unikey='parameter'.$keyroot.'_'.$name;
11884: }
1.339 albertel 11885: if ($subp eq 'display') {
11886: $value.=' [Part: '.$part.']';
11887: }
1.599 albertel 11888: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11889: $metathesekeys{$unikey}=1;
1.599 albertel 11890: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11891: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11892: }
1.599 albertel 11893: if (defined($metaentry{':'.$unikey.'.default'})) {
11894: $metaentry{':'.$unikey}=
11895: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11896: }
1.339 albertel 11897: }
11898: }
11899: } else {
1.172 www 11900: #
11901: # This is not a package - some other kind of start tag
1.339 albertel 11902: #
11903: my $entry=$token->[1];
1.1068 www 11904: my $unikey='';
1.175 www 11905:
1.339 albertel 11906: if ($entry eq 'import') {
1.175 www 11907: #
11908: # Importing a library here
1.339 albertel 11909: #
1.1067 www 11910: my $location=$parser->get_text('/import');
11911: my $dir=$filename;
11912: $dir=~s|[^/]*$||;
11913: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 11914:
11915: my $importid=$token->[2]->{'id'};
1.1068 www 11916: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 11917: #
11918: # Check metadata for imported file to
11919: # see if it contained response items
11920: #
11921: my %currmetaentry = %metaentry;
11922: my $libresponseorder = &metadata($location,'responseorder');
11923: my $origfile;
11924: if ($libresponseorder ne '') {
11925: if ($#origfiletagids<0) {
11926: undef(%importedrespids);
11927: undef(%importedpartids);
11928: }
11929: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11930: if (@{$importedrespids{$importid}} > 0) {
11931: $importedresponses = 1;
11932: # We need to get the original file and the imported file to get the response order correct
11933: # Load and inspect original file
11934: if ($#origfiletagids<0) {
11935: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11936: $origfile=&getfile($origfilelocation);
11937: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11938: }
11939: }
11940: }
11941: # Do not overwrite contents of %metaentry hash for resource itself with
11942: # hash populated for imported library file
11943: %metaentry = %currmetaentry;
11944: undef(%currmetaentry);
1.1068 www 11945: if ($importmode eq 'problem') {
1.1069 www 11946: # Import as problem/response
1.1068 www 11947: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11948: } elsif ($importmode eq 'part') {
11949: # Import as part(s)
1.1069 www 11950: $importedparts=1;
11951: # We need to get the original file and the imported file to get the part order correct
11952: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 11953: # Load and inspect original file if we didn't do that already
11954: if ($#origfiletagids<0) {
11955: undef(%importedrespids);
11956: undef(%importedpartids);
11957: if ($origfile eq '') {
11958: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11959: $origfile=&getfile($origfilelocation);
11960: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11961: }
1.1070 www 11962: }
11963:
1.1069 www 11964: # Load and inspect imported file
11965: my $impfile=&getfile($location);
11966: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11967: if ($#impfilepartids>=0) {
11968: # This problem had parts
1.1070 www 11969: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11970: } else {
11971: # Importing by turning a single problem into a problem part
11972: # It gets the import-tags ID as part-ID
11973: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11974: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11975: }
1.1068 www 11976: } else {
11977: # Normal import
11978: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11979: if (defined($token->[2]->{'id'})) {
11980: $unikey.='_'.$token->[2]->{'id'};
11981: }
1.1067 www 11982: }
11983:
1.339 albertel 11984: if ($depthcount<20) {
1.736 albertel 11985: my $metadata =
11986: &metadata($uri,'keys', $location,$unikey,
11987: $depthcount+1);
11988: foreach my $meta (split(',',$metadata)) {
11989: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11990: $metathesekeys{$meta}=1;
1.339 albertel 11991: }
1.1068 www 11992:
11993: }
1.1067 www 11994: } else {
11995: #
11996: # Not importing, some other kind of non-package, non-library start tag
11997: #
11998: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11999: if (defined($token->[2]->{'id'})) {
12000: $unikey.='_'.$token->[2]->{'id'};
12001: }
1.339 albertel 12002: if (defined($token->[2]->{'name'})) {
12003: $unikey.='_'.$token->[2]->{'name'};
12004: }
12005: $metathesekeys{$unikey}=1;
1.736 albertel 12006: foreach my $param (@{$token->[3]}) {
12007: $metaentry{':'.$unikey.'.'.$param} =
12008: $token->[2]->{$param};
1.339 albertel 12009: }
12010: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12011: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12012: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12013: # only ws inside the tag, and not in default, so use default
12014: # as value
1.599 albertel 12015: $metaentry{':'.$unikey}=$default;
1.908 albertel 12016: } elsif ( $internaltext =~ /\S/ ) {
12017: # something interesting inside the tag
12018: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12019: } else {
1.908 albertel 12020: # no interesting values, don't set a default
1.339 albertel 12021: }
1.172 www 12022: # end of not-a-package not-a-library import
1.339 albertel 12023: }
1.172 www 12024: # end of not-a-package start tag
1.339 albertel 12025: }
1.172 www 12026: # the next is the end of "start tag"
1.339 albertel 12027: }
12028: }
1.483 albertel 12029: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12030: $extension = lc($extension);
12031: if ($extension eq 'htm') { $extension='html'; }
12032:
1.737 albertel 12033: foreach my $key (keys(%packagetab)) {
1.483 albertel 12034: #no specific packages #how's our extension
12035: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12036: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12037: \%metathesekeys);
12038: }
1.883 albertel 12039:
12040: if (!exists($metaentry{':packages'})
12041: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12042: foreach my $key (keys(%packagetab)) {
1.483 albertel 12043: #no specific packages well let's get default then
12044: if ($key!~/^default&/) { next; }
1.488 albertel 12045: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12046: \%metathesekeys);
12047: }
12048: }
1.338 www 12049: # are there custom rights to evaluate
1.599 albertel 12050: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12051:
1.338 www 12052: #
12053: # Importing a rights file here
1.339 albertel 12054: #
12055: unless ($depthcount) {
1.599 albertel 12056: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12057: my $dir=$filename;
12058: $dir=~s|[^/]*$||;
12059: $location=&filelocation($dir,$location);
1.736 albertel 12060: my $rights_metadata =
12061: &metadata($uri,'keys',$location,'_rights',
12062: $depthcount+1);
12063: foreach my $rights (split(',',$rights_metadata)) {
12064: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12065: $metathesekeys{$rights}=1;
1.339 albertel 12066: }
12067: }
12068: }
1.737 albertel 12069: # uniqifiy package listing
12070: my %seen;
12071: my @uniq_packages =
12072: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12073: $metaentry{':packages'} = join(',',@uniq_packages);
12074:
1.1172.2.99 raeburn 12075: if (($importedresponses) || ($importedparts)) {
12076: if ($importedparts) {
1.1070 www 12077: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 12078: $metaentry{':partorder'}='';
12079: $metathesekeys{'partorder'}=1;
12080: }
12081: if ($importedresponses) {
12082: # We had imported responses and need to rebuild responseorder
12083: $metaentry{':responseorder'}='';
12084: $metathesekeys{'responseorder'}=1;
12085: }
12086: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12087: my $origid = $origfiletagids[$index+1];
12088: if ($origfiletagids[$index] eq 'part') {
12089: # Original part, part of the problem
12090: if ($importedparts) {
12091: $metaentry{':partorder'}.=','.$origid;
12092: }
12093: } elsif ($origfiletagids[$index] eq 'import') {
12094: if ($importedparts) {
12095: # We have imported parts at this position
12096: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12097: }
12098: if ($importedresponses) {
12099: # We have imported responses at this position
12100: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12101: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12102: }
12103: }
12104: } else {
12105: # Original response item, part of the problem
12106: if ($importedresponses) {
12107: $metaentry{':responseorder'}.=','.$origid;
12108: }
12109: }
12110: }
12111: if ($importedparts) {
12112: $metaentry{':partorder'}=~s/^\,//;
12113: }
12114: if ($importedresponses) {
12115: $metaentry{':responseorder'}=~s/^\,//;
12116: }
1.1070 www 12117: }
12118:
1.737 albertel 12119: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12120: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 12121: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 12122: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 12123: # this is the end of "was not already recently cached
1.71 www 12124: }
1.599 albertel 12125: return $metaentry{':'.$what};
1.261 albertel 12126: }
12127:
1.488 albertel 12128: sub metadata_create_package_def {
1.483 albertel 12129: my ($uri,$key,$package,$metathesekeys)=@_;
12130: my ($pack,$name,$subp)=split(/\&/,$key);
12131: if ($subp eq 'default') { next; }
12132:
1.599 albertel 12133: if (defined($metaentry{':packages'})) {
12134: $metaentry{':packages'}.=','.$package;
1.483 albertel 12135: } else {
1.599 albertel 12136: $metaentry{':packages'}=$package;
1.483 albertel 12137: }
12138: my $value=$packagetab{$key};
12139: my $unikey;
12140: $unikey='parameter_0_'.$name;
1.599 albertel 12141: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12142: $$metathesekeys{$unikey}=1;
1.599 albertel 12143: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12144: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12145: }
1.599 albertel 12146: if (defined($metaentry{':'.$unikey.'.default'})) {
12147: $metaentry{':'.$unikey}=
12148: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12149: }
12150: }
12151:
1.261 albertel 12152: sub metadata_generate_part0 {
12153: my ($metadata,$metacache,$uri) = @_;
12154: my %allnames;
1.737 albertel 12155: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12156: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12157: my $part=$$metacache{':'.$metakey.'.part'};
12158: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12159: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12160: $allnames{$name}=$part;
12161: }
12162: }
12163: }
12164: foreach my $name (keys(%allnames)) {
12165: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12166: my $key=":parameter_0_$name";
1.261 albertel 12167: $$metacache{"$key.part"}='0';
12168: $$metacache{"$key.name"}=$name;
1.428 albertel 12169: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12170: $allnames{$name}.'_'.$name.
12171: '.type'};
1.428 albertel 12172: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12173: '.display'};
1.644 www 12174: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12175: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12176: $$metacache{"$key.display"}=$olddis;
12177: }
1.71 www 12178: }
12179:
1.764 albertel 12180: # ------------------------------------------------------ Devalidate title cache
12181:
12182: sub devalidate_title_cache {
12183: my ($url)=@_;
12184: if (!$env{'request.course.id'}) { return; }
12185: my $symb=&symbread($url);
12186: if (!$symb) { return; }
12187: my $key=$env{'request.course.id'}."\0".$symb;
12188: &devalidate_cache_new('title',$key);
12189: }
12190:
1.1014 droeschl 12191: # ------------------------------------------------- Get the title of a course
12192:
12193: sub current_course_title {
12194: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12195: }
1.301 www 12196: # ------------------------------------------------- Get the title of a resource
12197:
12198: sub gettitle {
12199: my $urlsymb=shift;
12200: my $symb=&symbread($urlsymb);
1.534 albertel 12201: if ($symb) {
1.620 albertel 12202: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12203: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12204: if (defined($cached)) {
12205: return $result;
12206: }
1.534 albertel 12207: my ($map,$resid,$url)=&decode_symb($symb);
12208: my $title='';
1.907 albertel 12209: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12210: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12211: } else {
12212: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12213: &GDBM_READER(),0640)) {
12214: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12215: $title=$bighash{'title_'.$mapid.'.'.$resid};
12216: untie(%bighash);
12217: }
1.534 albertel 12218: }
12219: $title=~s/\&colon\;/\:/gs;
12220: if ($title) {
1.1159 www 12221: # Remember both $symb and $title for dynamic metadata
12222: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12223: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12224: # Cache this title and then return it
1.599 albertel 12225: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12226: }
12227: $urlsymb=$url;
12228: }
12229: my $title=&metadata($urlsymb,'title');
12230: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12231: return $title;
1.301 www 12232: }
1.613 albertel 12233:
1.614 albertel 12234: sub get_slot {
12235: my ($which,$cnum,$cdom)=@_;
12236: if (!$cnum || !$cdom) {
1.790 albertel 12237: (undef,my $courseid)=&whichuser();
1.620 albertel 12238: $cdom=$env{'course.'.$courseid.'.domain'};
12239: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12240: }
1.703 albertel 12241: my $key=join("\0",'slots',$cdom,$cnum,$which);
12242: my %slotinfo;
12243: if (exists($remembered{$key})) {
12244: $slotinfo{$which} = $remembered{$key};
12245: } else {
12246: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12247: &Apache::lonhomework::showhash(%slotinfo);
12248: my ($tmp)=keys(%slotinfo);
12249: if ($tmp=~/^error:/) { return (); }
12250: $remembered{$key} = $slotinfo{$which};
12251: }
1.616 albertel 12252: if (ref($slotinfo{$which}) eq 'HASH') {
12253: return %{$slotinfo{$which}};
12254: }
12255: return $slotinfo{$which};
1.614 albertel 12256: }
1.1150 raeburn 12257:
12258: sub get_reservable_slots {
12259: my ($cnum,$cdom,$uname,$udom) = @_;
12260: my $now = time;
12261: my $reservable_info;
12262: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12263: if (exists($remembered{$key})) {
12264: $reservable_info = $remembered{$key};
12265: } else {
12266: my %resv;
12267: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12268: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12269: $reservable_info = \%resv;
12270: $remembered{$key} = $reservable_info;
12271: }
12272: return $reservable_info;
12273: }
12274:
12275: sub get_course_slots {
12276: my ($cnum,$cdom) = @_;
12277: my $hashid=$cnum.':'.$cdom;
12278: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12279: if (defined($cached)) {
12280: if (ref($result) eq 'HASH') {
12281: return %{$result};
12282: }
12283: } else {
12284: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12285: my ($tmp) = keys(%slots);
12286: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 12287: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12288: return %slots;
12289: }
12290: }
12291: return;
12292: }
12293:
12294: sub devalidate_slots_cache {
12295: my ($cnum,$cdom)=@_;
12296: my $hashid=$cnum.':'.$cdom;
12297: &devalidate_cache_new('allslots',$hashid);
12298: }
12299:
1.1172.2.8 raeburn 12300: sub get_coursechange {
12301: my ($cdom,$cnum) = @_;
12302: if ($cdom eq '' || $cnum eq '') {
12303: return unless ($env{'request.course.id'});
12304: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12305: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12306: }
12307: my $hashid=$cdom.'_'.$cnum;
12308: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12309: if ((defined($cached)) && ($change ne '')) {
12310: return $change;
12311: } else {
12312: my %crshash;
12313: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12314: if ($crshash{'internal.contentchange'} eq '') {
12315: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12316: if ($change eq '') {
12317: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12318: $change = $crshash{'internal.created'};
12319: }
12320: } else {
12321: $change = $crshash{'internal.contentchange'};
12322: }
12323: my $cachetime = 600;
12324: &do_cache_new('crschange',$hashid,$change,$cachetime);
12325: }
12326: return $change;
12327: }
12328:
12329: sub devalidate_coursechange_cache {
12330: my ($cnum,$cdom)=@_;
12331: my $hashid=$cnum.':'.$cdom;
12332: &devalidate_cache_new('crschange',$hashid);
12333: }
12334:
1.31 www 12335: # ------------------------------------------------- Update symbolic store links
12336:
12337: sub symblist {
12338: my ($mapname,%newhash)=@_;
1.438 www 12339: $mapname=&deversion(&declutter($mapname));
1.31 www 12340: my %hash;
1.620 albertel 12341: if (($env{'request.course.fn'}) && (%newhash)) {
12342: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12343: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12344: foreach my $url (keys(%newhash)) {
1.711 albertel 12345: next if ($url eq 'last_known'
12346: && $env{'form.no_update_last_known'});
12347: $hash{declutter($url)}=&encode_symb($mapname,
12348: $newhash{$url}->[1],
12349: $newhash{$url}->[0]);
1.191 harris41 12350: }
1.31 www 12351: if (untie(%hash)) {
12352: return 'ok';
12353: }
12354: }
12355: }
12356: return 'error';
1.212 www 12357: }
12358:
12359: # --------------------------------------------------------------- Verify a symb
12360:
12361: sub symbverify {
1.1172.2.11 raeburn 12362: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12363: my $thisfn=$thisurl;
1.439 www 12364: $thisfn=&declutter($thisfn);
1.215 www 12365: # direct jump to resource in page or to a sequence - will construct own symbs
12366: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12367: # check URL part
1.409 www 12368: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12369:
1.431 www 12370: unless ($url eq $thisfn) { return 0; }
1.213 www 12371:
1.216 www 12372: $symb=&symbclean($symb);
1.510 www 12373: $thisurl=&deversion($thisurl);
1.439 www 12374: $thisfn=&deversion($thisfn);
1.213 www 12375:
12376: my %bighash;
12377: my $okay=0;
1.431 www 12378:
1.620 albertel 12379: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12380: &GDBM_READER(),0640)) {
1.1032 raeburn 12381: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12382: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 12383: if ($map =~ m{^uploaded/.+\.page$}) {
12384: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12385: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12386: }
12387: }
12388: my $ids;
1.1172.2.122 raeburn 12389: if ($map =~ m{^uploaded/.+\.page$}) {
12390: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 12391: } else {
12392: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12393: }
1.1102 raeburn 12394: unless ($ids) {
1.1172.2.13 raeburn 12395: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 12396: $ids=$bighash{$idkey};
1.216 www 12397: }
12398: if ($ids) {
12399: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 12400: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12401: $symb =~ s/\?.+$//;
12402: }
1.800 albertel 12403: foreach my $id (split(/\,/,$ids)) {
12404: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12405: if (
12406: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 12407: eq $symb) {
1.1172.2.11 raeburn 12408: if (ref($encstate)) {
12409: $$encstate = $bighash{'encrypted_'.$id};
12410: }
1.1172.2.13 raeburn 12411: if (($env{'request.role.adv'}) ||
12412: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 12413: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 12414: $okay=1;
12415: last;
12416: }
12417: }
12418: }
1.216 www 12419: }
1.213 www 12420: untie(%bighash);
12421: }
12422: return $okay;
1.31 www 12423: }
12424:
1.210 www 12425: # --------------------------------------------------------------- Clean-up symb
12426:
12427: sub symbclean {
12428: my $symb=shift;
1.568 albertel 12429: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12430: # remove version from map
12431: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12432:
1.210 www 12433: # remove version from URL
12434: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12435:
1.507 www 12436: # remove wrapper
12437:
1.510 www 12438: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12439: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12440: return $symb;
1.409 www 12441: }
12442:
12443: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12444:
12445: sub encode_symb {
12446: my ($map,$resid,$url)=@_;
12447: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12448: }
1.409 www 12449:
12450: sub decode_symb {
1.568 albertel 12451: my $symb=shift;
12452: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12453: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12454: return (&fixversion($map),$resid,&fixversion($url));
12455: }
12456:
12457: sub fixversion {
12458: my $fn=shift;
1.609 banghart 12459: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12460: my %bighash;
12461: my $uri=&clutter($fn);
1.620 albertel 12462: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12463: # is this cached?
1.599 albertel 12464: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12465: if (defined($cached)) { return $result; }
12466: # unfortunately not cached, or expired
1.620 albertel 12467: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12468: &GDBM_READER(),0640)) {
12469: if ($bighash{'version_'.$uri}) {
12470: my $version=$bighash{'version_'.$uri};
1.444 www 12471: unless (($version eq 'mostrecent') ||
12472: ($version==&getversion($uri))) {
1.440 www 12473: $uri=~s/\.(\w+)$/\.$version\.$1/;
12474: }
12475: }
12476: untie %bighash;
1.413 www 12477: }
1.599 albertel 12478: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12479: }
12480:
12481: sub deversion {
12482: my $url=shift;
12483: $url=~s/\.\d+\.(\w+)$/\.$1/;
12484: return $url;
1.210 www 12485: }
12486:
1.31 www 12487: # ------------------------------------------------------ Return symb list entry
12488:
12489: sub symbread {
1.1172.2.126 raeburn 12490: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128 raeburn 12491: $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54 raeburn 12492: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128 raeburn 12493: if (defined($env{$cache_str})) {
1.1172.2.126 raeburn 12494: unless (ref($possibles) eq 'HASH') {
12495: if ($ignorecachednull) {
12496: return $env{$cache_str} unless ($env{$cache_str} eq '');
12497: } else {
12498: return $env{$cache_str};
12499: }
1.1172.2.66 raeburn 12500: }
12501: }
1.242 www 12502: # no filename provided? try from environment
1.1172.2.54 raeburn 12503: unless ($thisfn) {
1.620 albertel 12504: if ($env{'request.symb'}) {
1.1172.2.128 raeburn 12505: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13 raeburn 12506: }
12507: $thisfn=$env{'request.filename'};
1.44 www 12508: }
1.569 albertel 12509: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12510: # is that filename actually a symb? Verify, clean, and return
12511: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12512: if (&symbverify($thisfn,$1)) {
1.1172.2.128 raeburn 12513: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12514: }
1.242 www 12515: }
1.44 www 12516: $thisfn=declutter($thisfn);
1.31 www 12517: my %hash;
1.37 www 12518: my %bighash;
12519: my $syval='';
1.620 albertel 12520: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12521: my $targetfn = $thisfn;
1.609 banghart 12522: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12523: $targetfn = 'adm/wrapper/'.$thisfn;
12524: }
1.687 albertel 12525: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12526: $targetfn=$1;
12527: }
1.1172.2.128 raeburn 12528: unless ($ignoresymbdb) {
1.1172.2.126 raeburn 12529: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12530: &GDBM_READER(),0640)) {
12531: $syval=$hash{$targetfn};
12532: untie(%hash);
12533: }
1.1172.2.128 raeburn 12534: if ($syval && $checkforblock) {
12535: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126 raeburn 12536: if (@blockers) {
12537: $syval='';
12538: }
12539: }
1.37 www 12540: }
12541: # ---------------------------------------------------------- There was an entry
12542: if ($syval) {
1.601 albertel 12543: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12544: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12545: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12546: #return $env{$cache_str}='';
1.601 albertel 12547: #}
12548: #$syval.=$1;
12549: #}
1.37 www 12550: } else {
12551: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12552: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12553: &GDBM_READER(),0640)) {
1.37 www 12554: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12555: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12556: unless ($ids) {
12557: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12558: }
12559: unless ($ids) {
12560: # alias?
12561: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12562: }
1.37 www 12563: if ($ids) {
12564: # ------------------------------------------------------------------- Has ID(s)
12565: my @possibilities=split(/\,/,$ids);
1.39 www 12566: if ($#possibilities==0) {
12567: # ----------------------------------------------- There is only one possibility
1.37 www 12568: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12569: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12570: $resid,$thisfn);
1.1172.2.66 raeburn 12571: if (ref($possibles) eq 'HASH') {
1.1172.2.126 raeburn 12572: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12573: $possibles->{$syval} = 1;
12574: }
1.1172.2.66 raeburn 12575: }
12576: if ($checkforblock) {
1.1172.2.126 raeburn 12577: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127 raeburn 12578: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126 raeburn 12579: if (@blockers) {
12580: $syval = '';
12581: untie(%bighash);
12582: return $env{$cache_str}='';
12583: }
1.1172.2.66 raeburn 12584: }
12585: }
12586: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12587: # ------------------------------------------ There is more than one possibility
12588: my $realpossible=0;
1.800 albertel 12589: foreach my $id (@possibilities) {
12590: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12591: my $canaccess;
12592: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12593: $canaccess = 1;
12594: } else {
12595: $canaccess = &allowed('bre',$file);
12596: }
12597: if ($canaccess) {
12598: my ($mapid,$resid)=split(/\./,$id);
12599: if ($bighash{'map_type_'.$mapid} ne 'page') {
12600: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12601: $resid,$thisfn);
1.1172.2.126 raeburn 12602: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127 raeburn 12603: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 12604: if ($checkforblock) {
1.1172.2.127 raeburn 12605: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126 raeburn 12606: if (@blockers > 0) {
12607: $syval = '';
12608: } else {
1.1172.2.66 raeburn 12609: $syval = $poss_syval;
12610: $realpossible++;
12611: }
12612: } else {
12613: $syval = $poss_syval;
12614: $realpossible++;
12615: }
1.1172.2.126 raeburn 12616: if ($syval) {
12617: if (ref($possibles) eq 'HASH') {
12618: $possibles->{$syval} = 1;
12619: }
12620: }
1.1172.2.66 raeburn 12621: }
1.39 www 12622: }
1.191 harris41 12623: }
1.39 www 12624: if ($realpossible!=1) { $syval=''; }
1.249 www 12625: } else {
12626: $syval='';
1.37 www 12627: }
12628: }
1.1172.2.66 raeburn 12629: untie(%bighash);
1.481 raeburn 12630: }
1.31 www 12631: }
1.62 www 12632: if ($syval) {
1.1172.2.128 raeburn 12633: return $env{$cache_str}=$syval;
1.62 www 12634: }
1.31 www 12635: }
1.949 raeburn 12636: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12637: return $env{$cache_str}='';
1.31 www 12638: }
12639:
12640: # ---------------------------------------------------------- Return random seed
12641:
1.32 www 12642: sub numval {
12643: my $txt=shift;
12644: $txt=~tr/A-J/0-9/;
12645: $txt=~tr/a-j/0-9/;
12646: $txt=~tr/K-T/0-9/;
12647: $txt=~tr/k-t/0-9/;
12648: $txt=~tr/U-Z/0-5/;
12649: $txt=~tr/u-z/0-5/;
12650: $txt=~s/\D//g;
1.564 albertel 12651: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12652: return int($txt);
1.368 albertel 12653: }
12654:
1.484 albertel 12655: sub numval2 {
12656: my $txt=shift;
12657: $txt=~tr/A-J/0-9/;
12658: $txt=~tr/a-j/0-9/;
12659: $txt=~tr/K-T/0-9/;
12660: $txt=~tr/k-t/0-9/;
12661: $txt=~tr/U-Z/0-5/;
12662: $txt=~tr/u-z/0-5/;
12663: $txt=~s/\D//g;
12664: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12665: my $total;
12666: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12667: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12668: return int($total);
12669: }
12670:
1.575 albertel 12671: sub numval3 {
12672: use integer;
12673: my $txt=shift;
12674: $txt=~tr/A-J/0-9/;
12675: $txt=~tr/a-j/0-9/;
12676: $txt=~tr/K-T/0-9/;
12677: $txt=~tr/k-t/0-9/;
12678: $txt=~tr/U-Z/0-5/;
12679: $txt=~tr/u-z/0-5/;
12680: $txt=~s/\D//g;
12681: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12682: my $total;
12683: foreach my $val (@txts) { $total+=$val; }
12684: if ($_64bit) { $total=(($total<<32)>>32); }
12685: return $total;
12686: }
12687:
1.675 albertel 12688: sub digest {
12689: my ($data)=@_;
12690: my $digest=&Digest::MD5::md5($data);
12691: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12692: my ($e,$f);
12693: {
12694: use integer;
12695: $e=($a+$b);
12696: $f=($c+$d);
12697: if ($_64bit) {
12698: $e=(($e<<32)>>32);
12699: $f=(($f<<32)>>32);
12700: }
12701: }
12702: if (wantarray) {
12703: return ($e,$f);
12704: } else {
12705: my $g;
12706: {
12707: use integer;
12708: $g=($e+$f);
12709: if ($_64bit) {
12710: $g=(($g<<32)>>32);
12711: }
12712: }
12713: return $g;
12714: }
12715: }
12716:
1.368 albertel 12717: sub latest_rnd_algorithm_id {
1.675 albertel 12718: return '64bit5';
1.366 albertel 12719: }
1.32 www 12720:
1.503 albertel 12721: sub get_rand_alg {
12722: my ($courseid)=@_;
1.790 albertel 12723: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12724: if ($courseid) {
1.620 albertel 12725: return $env{"course.$courseid.rndseed"};
1.503 albertel 12726: }
12727: return &latest_rnd_algorithm_id();
12728: }
12729:
1.562 albertel 12730: sub validCODE {
12731: my ($CODE)=@_;
12732: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12733: return 0;
12734: }
12735:
1.491 albertel 12736: sub getCODE {
1.620 albertel 12737: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12738: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12739: defined($Apache::lonhomework::parsing_a_task) ) &&
12740: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12741: return $Apache::lonhomework::history{'resource.CODE'};
12742: }
12743: return undef;
12744: }
1.1133 foxr 12745: #
12746: # Determines the random seed for a specific context:
12747: #
12748: # parameters:
12749: # symb - in course context the symb for the seed.
12750: # course_id - The course id of the form domain_coursenum.
12751: # domain - Domain for the user.
12752: # course - Course for the user.
12753: # cenv - environment of the course.
12754: #
12755: # NOTE:
12756: # All parameters are picked out of the environment if missing
12757: # or not defined.
12758: # If a symb cannot be determined the current time is used instead.
12759: #
12760: # For a given well defined symb, courside, domain, username,
12761: # and course environment, the seed is reproducible.
12762: #
1.31 www 12763: sub rndseed {
1.1133 foxr 12764: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12765: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12766: if (!defined($symb)) {
1.366 albertel 12767: unless ($symb=$wsymb) { return time; }
12768: }
1.1146 foxr 12769: if (!defined $courseid) {
12770: $courseid=$wcourseid;
12771: }
12772: if (!defined $domain) { $domain=$wdomain; }
12773: if (!defined $username) { $username=$wusername }
1.1133 foxr 12774:
12775: my $which;
12776: if (defined($cenv->{'rndseed'})) {
12777: $which = $cenv->{'rndseed'};
12778: } else {
12779: $which =&get_rand_alg($courseid);
12780: }
1.491 albertel 12781: if (defined(&getCODE())) {
1.675 albertel 12782: if ($which eq '64bit5') {
12783: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12784: } elsif ($which eq '64bit4') {
1.575 albertel 12785: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12786: } else {
12787: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12788: }
1.675 albertel 12789: } elsif ($which eq '64bit5') {
12790: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12791: } elsif ($which eq '64bit4') {
12792: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12793: } elsif ($which eq '64bit3') {
12794: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12795: } elsif ($which eq '64bit2') {
12796: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12797: } elsif ($which eq '64bit') {
12798: return &rndseed_64bit($symb,$courseid,$domain,$username);
12799: }
12800: return &rndseed_32bit($symb,$courseid,$domain,$username);
12801: }
12802:
12803: sub rndseed_32bit {
12804: my ($symb,$courseid,$domain,$username)=@_;
12805: {
12806: use integer;
12807: my $symbchck=unpack("%32C*",$symb) << 27;
12808: my $symbseed=numval($symb) << 22;
12809: my $namechck=unpack("%32C*",$username) << 17;
12810: my $nameseed=numval($username) << 12;
12811: my $domainseed=unpack("%32C*",$domain) << 7;
12812: my $courseseed=unpack("%32C*",$courseid);
12813: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12814: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12815: #&logthis("rndseed :$num:$symb");
1.564 albertel 12816: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12817: return $num;
12818: }
12819: }
12820:
12821: sub rndseed_64bit {
12822: my ($symb,$courseid,$domain,$username)=@_;
12823: {
12824: use integer;
12825: my $symbchck=unpack("%32S*",$symb) << 21;
12826: my $symbseed=numval($symb) << 10;
12827: my $namechck=unpack("%32S*",$username);
12828:
12829: my $nameseed=numval($username) << 21;
12830: my $domainseed=unpack("%32S*",$domain) << 10;
12831: my $courseseed=unpack("%32S*",$courseid);
12832:
12833: my $num1=$symbchck+$symbseed+$namechck;
12834: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12835: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12836: #&logthis("rndseed :$num:$symb");
1.564 albertel 12837: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12838: return "$num1,$num2";
1.155 albertel 12839: }
1.366 albertel 12840: }
12841:
1.443 albertel 12842: sub rndseed_64bit2 {
12843: my ($symb,$courseid,$domain,$username)=@_;
12844: {
12845: use integer;
12846: # strings need to be an even # of cahracters long, it it is odd the
12847: # last characters gets thrown away
12848: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12849: my $symbseed=numval($symb) << 10;
12850: my $namechck=unpack("%32S*",$username.' ');
12851:
12852: my $nameseed=numval($username) << 21;
1.501 albertel 12853: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12854: my $courseseed=unpack("%32S*",$courseid.' ');
12855:
12856: my $num1=$symbchck+$symbseed+$namechck;
12857: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12858: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12859: #&logthis("rndseed :$num:$symb");
1.803 albertel 12860: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12861: return "$num1,$num2";
12862: }
12863: }
12864:
12865: sub rndseed_64bit3 {
12866: my ($symb,$courseid,$domain,$username)=@_;
12867: {
12868: use integer;
12869: # strings need to be an even # of cahracters long, it it is odd the
12870: # last characters gets thrown away
12871: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12872: my $symbseed=numval2($symb) << 10;
12873: my $namechck=unpack("%32S*",$username.' ');
12874:
12875: my $nameseed=numval2($username) << 21;
1.443 albertel 12876: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12877: my $courseseed=unpack("%32S*",$courseid.' ');
12878:
12879: my $num1=$symbchck+$symbseed+$namechck;
12880: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12881: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12882: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12883: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12884:
1.503 albertel 12885: return "$num1:$num2";
1.443 albertel 12886: }
12887: }
12888:
1.575 albertel 12889: sub rndseed_64bit4 {
12890: my ($symb,$courseid,$domain,$username)=@_;
12891: {
12892: use integer;
12893: # strings need to be an even # of cahracters long, it it is odd the
12894: # last characters gets thrown away
12895: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12896: my $symbseed=numval3($symb) << 10;
12897: my $namechck=unpack("%32S*",$username.' ');
12898:
12899: my $nameseed=numval3($username) << 21;
12900: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12901: my $courseseed=unpack("%32S*",$courseid.' ');
12902:
12903: my $num1=$symbchck+$symbseed+$namechck;
12904: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12905: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12906: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12907: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12908:
1.575 albertel 12909: return "$num1:$num2";
12910: }
12911: }
12912:
1.675 albertel 12913: sub rndseed_64bit5 {
12914: my ($symb,$courseid,$domain,$username)=@_;
12915: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12916: return "$num1:$num2";
12917: }
12918:
1.366 albertel 12919: sub rndseed_CODE_64bit {
12920: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12921: {
1.366 albertel 12922: use integer;
1.443 albertel 12923: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12924: my $symbseed=numval2($symb);
1.491 albertel 12925: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12926: my $CODEseed=numval(&getCODE());
1.443 albertel 12927: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12928: my $num1=$symbseed+$CODEchck;
12929: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12930: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12931: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12932: if ($_64bit) { $num1=(($num1<<32)>>32); }
12933: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12934: return "$num1:$num2";
1.366 albertel 12935: }
12936: }
12937:
1.575 albertel 12938: sub rndseed_CODE_64bit4 {
12939: my ($symb,$courseid,$domain,$username)=@_;
12940: {
12941: use integer;
12942: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12943: my $symbseed=numval3($symb);
12944: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12945: my $CODEseed=numval3(&getCODE());
12946: my $courseseed=unpack("%32S*",$courseid.' ');
12947: my $num1=$symbseed+$CODEchck;
12948: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12949: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12950: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12951: if ($_64bit) { $num1=(($num1<<32)>>32); }
12952: if ($_64bit) { $num2=(($num2<<32)>>32); }
12953: return "$num1:$num2";
12954: }
12955: }
12956:
1.675 albertel 12957: sub rndseed_CODE_64bit5 {
12958: my ($symb,$courseid,$domain,$username)=@_;
12959: my $code = &getCODE();
12960: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12961: return "$num1:$num2";
12962: }
12963:
1.366 albertel 12964: sub setup_random_from_rndseed {
12965: my ($rndseed)=@_;
1.503 albertel 12966: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 12967: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12968: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12969: &Math::Random::random_set_seed_from_phrase($rndseed);
12970: } else {
12971: &Math::Random::random_set_seed($num1,$num2);
12972: }
1.366 albertel 12973: } else {
12974: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12975: }
1.36 albertel 12976: }
12977:
1.474 albertel 12978: sub latest_receipt_algorithm_id {
1.835 albertel 12979: return 'receipt3';
1.474 albertel 12980: }
12981:
1.480 www 12982: sub recunique {
12983: my $fucourseid=shift;
12984: my $unique;
1.835 albertel 12985: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12986: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12987: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12988: } else {
12989: $unique=$perlvar{'lonReceipt'};
12990: }
12991: return unpack("%32C*",$unique);
12992: }
12993:
12994: sub recprefix {
12995: my $fucourseid=shift;
12996: my $prefix;
1.835 albertel 12997: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12998: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12999: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13000: } else {
13001: $prefix=$perlvar{'lonHostID'};
13002: }
13003: return unpack("%32C*",$prefix);
13004: }
13005:
1.76 www 13006: sub ireceipt {
1.474 albertel 13007: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13008:
13009: my $return =&recprefix($fucourseid).'-';
13010:
13011: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13012: $env{'request.state'} eq 'construct') {
13013: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13014: return $return;
13015: }
13016:
1.76 www 13017: my $cuname=unpack("%32C*",$funame);
13018: my $cudom=unpack("%32C*",$fudom);
13019: my $cucourseid=unpack("%32C*",$fucourseid);
13020: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13021: my $cunique=&recunique($fucourseid);
1.474 albertel 13022: my $cpart=unpack("%32S*",$part);
1.835 albertel 13023: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13024:
1.790 albertel 13025: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13026:
13027: $return.= ($cunique%$cuname+
13028: $cunique%$cudom+
13029: $cusymb%$cuname+
13030: $cusymb%$cudom+
13031: $cucourseid%$cuname+
13032: $cucourseid%$cudom+
13033: $cpart%$cuname+
13034: $cpart%$cudom);
13035: } else {
13036: $return.= ($cunique%$cuname+
13037: $cunique%$cudom+
13038: $cusymb%$cuname+
13039: $cusymb%$cudom+
13040: $cucourseid%$cuname+
13041: $cucourseid%$cudom);
13042: }
13043: return $return;
1.76 www 13044: }
13045:
13046: sub receipt {
1.474 albertel 13047: my ($part)=@_;
1.790 albertel 13048: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13049: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13050: }
1.260 ng 13051:
1.790 albertel 13052: sub whichuser {
13053: my ($passedsymb)=@_;
13054: my ($symb,$courseid,$domain,$name,$publicuser);
13055: if (defined($env{'form.grade_symb'})) {
13056: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13057: my $allowed=&allowed('vgr',$tmp_courseid);
13058: if (!$allowed &&
13059: exists($env{'request.course.sec'}) &&
13060: $env{'request.course.sec'} !~ /^\s*$/) {
13061: $allowed=&allowed('vgr',$tmp_courseid.
13062: '/'.$env{'request.course.sec'});
13063: }
13064: if ($allowed) {
13065: ($symb)=&get_env_multiple('form.grade_symb');
13066: $courseid=$tmp_courseid;
13067: ($domain)=&get_env_multiple('form.grade_domain');
13068: ($name)=&get_env_multiple('form.grade_username');
13069: return ($symb,$courseid,$domain,$name,$publicuser);
13070: }
13071: }
13072: if (!$passedsymb) {
13073: $symb=&symbread();
13074: } else {
13075: $symb=$passedsymb;
13076: }
13077: $courseid=$env{'request.course.id'};
13078: $domain=$env{'user.domain'};
13079: $name=$env{'user.name'};
13080: if ($name eq 'public' && $domain eq 'public') {
13081: if (!defined($env{'form.username'})) {
13082: $env{'form.username'}.=time.rand(10000000);
13083: }
13084: $name.=$env{'form.username'};
13085: }
13086: return ($symb,$courseid,$domain,$name,$publicuser);
13087:
13088: }
13089:
1.36 albertel 13090: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13091: # returns either the contents of the file or
13092: # -1 if the file doesn't exist
1.481 raeburn 13093: #
13094: # if the target is a file that was uploaded via DOCS,
13095: # a check will be made to see if a current copy exists on the local server,
13096: # if it does this will be served, otherwise a copy will be retrieved from
13097: # the home server for the course and stored in /home/httpd/html/userfiles on
13098: # the local server.
1.472 albertel 13099:
1.36 albertel 13100: sub getfile {
1.538 albertel 13101: my ($file) = @_;
1.609 banghart 13102: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13103: &repcopy($file);
13104: return &readfile($file);
13105: }
13106:
13107: sub repcopy_userfile {
13108: my ($file)=@_;
1.1142 raeburn 13109: my $londocroot = $perlvar{'lonDocRoot'};
13110: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13111: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13112: my ($cdom,$cnum,$filename) =
1.811 albertel 13113: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13114: my $uri="/uploaded/$cdom/$cnum/$filename";
13115: if (-e "$file") {
1.828 www 13116: # we already have a local copy, check it out
1.538 albertel 13117: my @fileinfo = stat($file);
1.828 www 13118: my $rtncode;
13119: my $info;
1.538 albertel 13120: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13121: if ($lwpresp ne 'ok') {
1.828 www 13122: # there is no such file anymore, even though we had a local copy
1.482 albertel 13123: if ($rtncode eq '404') {
1.538 albertel 13124: unlink($file);
1.482 albertel 13125: }
13126: return -1;
13127: }
13128: if ($info < $fileinfo[9]) {
1.828 www 13129: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13130: return 'ok';
1.828 www 13131: } else {
13132: # the file is outdated, get rid of it
13133: unlink($file);
1.482 albertel 13134: }
1.828 www 13135: }
13136: # one way or the other, at this point, we don't have the file
13137: # construct the correct path for the file
13138: my @parts = ($cdom,$cnum);
13139: if ($filename =~ m|^(.+)/[^/]+$|) {
13140: push @parts, split(/\//,$1);
13141: }
13142: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13143: foreach my $part (@parts) {
13144: $path .= '/'.$part;
13145: if (!-e $path) {
13146: mkdir($path,0770);
1.482 albertel 13147: }
13148: }
1.828 www 13149: # now the path exists for sure
13150: # get a user agent
13151: my $ua=new LWP::UserAgent;
13152: my $transferfile=$file.'.in.transfer';
13153: # FIXME: this should flock
13154: if (-e $transferfile) { return 'ok'; }
13155: my $request;
13156: $uri=~s/^\///;
1.980 raeburn 13157: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13158: my $hostname = &hostname($homeserver);
1.980 raeburn 13159: my $protocol = $protocol{$homeserver};
13160: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13161: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 13162: my $response=$ua->request($request,$transferfile);
13163: # did it work?
13164: if ($response->is_error()) {
13165: unlink($transferfile);
13166: &logthis("Userfile repcopy failed for $uri");
13167: return -1;
13168: }
13169: # worked, rename the transfer file
13170: rename($transferfile,$file);
1.607 raeburn 13171: return 'ok';
1.481 raeburn 13172: }
13173:
1.517 albertel 13174: sub tokenwrapper {
13175: my $uri=shift;
1.980 raeburn 13176: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13177: $uri=~s|^/||;
1.620 albertel 13178: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13179: my $token=$1;
1.552 albertel 13180: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13181: if ($udom && $uname && $file) {
13182: $file=~s|(\?\.*)*$||;
1.949 raeburn 13183: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13184: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 13185: my $hostname = &hostname($homeserver);
1.980 raeburn 13186: my $protocol = $protocol{$homeserver};
13187: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13188: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13189: (($uri=~/\?/)?'&':'?').'token='.$token.
13190: '&tokenissued='.$perlvar{'lonHostID'};
13191: } else {
13192: return '/adm/notfound.html';
13193: }
13194: }
13195:
1.828 www 13196: # call with reqtype HEAD: get last modification time
13197: # call with reqtype GET: get the file contents
13198: # Do not call this with reqtype GET for large files! It loads everything into memory
13199: #
1.481 raeburn 13200: sub getuploaded {
13201: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13202: $uri=~s/^\///;
1.980 raeburn 13203: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13204: my $hostname = &hostname($homeserver);
1.980 raeburn 13205: my $protocol = $protocol{$homeserver};
13206: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13207: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13208: my $ua=new LWP::UserAgent;
13209: my $request=new HTTP::Request($reqtype,$uri);
13210: my $response=$ua->request($request);
13211: $$rtncode = $response->code;
1.482 albertel 13212: if (! $response->is_success()) {
13213: return 'failed';
13214: }
13215: if ($reqtype eq 'HEAD') {
1.486 www 13216: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13217: } elsif ($reqtype eq 'GET') {
13218: $$info = $response->content;
1.472 albertel 13219: }
1.482 albertel 13220: return 'ok';
1.36 albertel 13221: }
13222:
1.481 raeburn 13223: sub readfile {
13224: my $file = shift;
13225: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13226: my $fh;
1.1172.2.96 raeburn 13227: open($fh,"<",$file);
1.481 raeburn 13228: my $a='';
1.800 albertel 13229: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13230: return $a;
13231: }
13232:
1.36 albertel 13233: sub filelocation {
1.590 banghart 13234: my ($dir,$file) = @_;
13235: my $location;
13236: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13237:
13238: if ($file =~ m-^/adm/-) {
13239: $file=~s-^/adm/wrapper/-/-;
13240: $file=~s-^/adm/coursedocs/showdoc/-/-;
13241: }
1.882 albertel 13242:
1.1139 www 13243: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13244: $location = $file;
1.609 banghart 13245: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13246: my ($udom,$uname,$filename)=
1.811 albertel 13247: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13248: my $home=&homeserver($uname,$udom);
13249: my $is_me=0;
13250: my @ids=¤t_machine_ids();
13251: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13252: if ($is_me) {
1.1117 foxr 13253: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13254: } else {
13255: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13256: $udom.'/'.$uname.'/'.$filename;
13257: }
1.882 albertel 13258: } elsif ($file =~ m-^/adm/-) {
13259: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13260: } else {
13261: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13262: $file=~s:^/(res|priv)/:/:;
13263: my $space=$1;
1.590 banghart 13264: if ( !( $file =~ m:^/:) ) {
13265: $location = $dir. '/'.$file;
13266: } else {
1.1142 raeburn 13267: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13268: }
1.59 albertel 13269: }
1.590 banghart 13270: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13271: while ($location=~m{/\.\./}) {
13272: if ($location =~ m{/[^/]+/\.\./}) {
13273: $location=~ s{/[^/]+/\.\./}{/}g;
13274: } else {
13275: $location=~ s{/\.\./}{/}g;
13276: }
13277: } #remove dir/..
1.590 banghart 13278: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13279: return $location;
1.46 www 13280: }
1.36 albertel 13281:
1.46 www 13282: sub hreflocation {
13283: my ($dir,$file)=@_;
1.980 raeburn 13284: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13285: $file=filelocation($dir,$file);
1.700 albertel 13286: } elsif ($file=~m-^/adm/-) {
13287: $file=~s-^/adm/wrapper/-/-;
13288: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13289: }
13290: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13291: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13292: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13293: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13294: {/uploaded/$1/$2/}x;
1.46 www 13295: }
1.913 albertel 13296: if ($file=~ m{^/userfiles/}) {
13297: $file =~ s{^/userfiles/}{/uploaded/};
13298: }
1.462 albertel 13299: return $file;
1.465 albertel 13300: }
13301:
1.1139 www 13302:
13303:
13304:
13305:
1.465 albertel 13306: sub current_machine_domains {
1.853 albertel 13307: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13308: }
13309:
13310: sub machine_domains {
13311: my ($hostname) = @_;
1.465 albertel 13312: my @domains;
1.838 albertel 13313: my %hostname = &all_hostnames();
1.465 albertel 13314: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13315: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13316: if ($hostname eq $name) {
1.844 albertel 13317: push(@domains,&host_domain($id));
1.465 albertel 13318: }
13319: }
13320: return @domains;
13321: }
13322:
13323: sub current_machine_ids {
1.853 albertel 13324: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13325: }
13326:
13327: sub machine_ids {
13328: my ($hostname) = @_;
13329: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13330: my @ids;
1.888 albertel 13331: my %name_to_host = &all_names();
1.889 albertel 13332: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13333: return @{ $name_to_host{$hostname} };
13334: }
13335: return;
1.31 www 13336: }
13337:
1.824 raeburn 13338: sub additional_machine_domains {
13339: my @domains;
1.1172.2.96 raeburn 13340: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 13341: while( my $line = <$fh>) {
13342: $line =~ s/\s//g;
13343: push(@domains,$line);
13344: }
13345: return @domains;
13346: }
13347:
13348: sub default_login_domain {
13349: my $domain = $perlvar{'lonDefDomain'};
13350: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13351: foreach my $posdom (¤t_machine_domains(),
13352: &additional_machine_domains()) {
13353: if (lc($posdom) eq lc($testdomain)) {
13354: $domain=$posdom;
13355: last;
13356: }
13357: }
13358: return $domain;
13359: }
13360:
1.1172.2.106 raeburn 13361: sub shared_institution {
1.1172.2.136! raeburn 13362: my ($dom,$lonhost) = @_;
! 13363: if ($lonhost eq '') {
! 13364: $lonhost = $perlvar{'lonHostID'};
! 13365: }
1.1172.2.106 raeburn 13366: my $same_intdom;
1.1172.2.136! raeburn 13367: my $hostintdom = &internet_dom($lonhost);
1.1172.2.106 raeburn 13368: if ($hostintdom ne '') {
13369: my %iphost = &get_iphost();
13370: my $primary_id = &domain($dom,'primary');
13371: my $primary_ip = &get_host_ip($primary_id);
13372: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13373: foreach my $id (@{$iphost{$primary_ip}}) {
13374: my $intdom = &internet_dom($id);
13375: if ($intdom eq $hostintdom) {
13376: $same_intdom = 1;
13377: last;
13378: }
13379: }
13380: }
13381: }
13382: return $same_intdom;
13383: }
13384:
1.1172.2.120 raeburn 13385: sub uses_sts {
13386: my ($ignore_cache) = @_;
13387: my $lonhost = $perlvar{'lonHostID'};
13388: my $hostname = &hostname($lonhost);
13389: my $sts_on;
13390: if ($protocol{$lonhost} eq 'https') {
13391: my $cachetime = 12*3600;
13392: if (!$ignore_cache) {
13393: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13394: if (defined($cached)) {
13395: return $sts_on;
13396: }
13397: }
1.1172.2.121 raeburn 13398: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 13399: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13400: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 13401: my $response=$ua->request($request);
1.1172.2.120 raeburn 13402: if ($response->is_success) {
13403: my $has_sts = $response->header('Strict-Transport-Security');
13404: if ($has_sts eq '') {
13405: $sts_on = 0;
13406: } else {
13407: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13408: my $maxage = $1;
13409: if ($maxage) {
13410: $sts_on = 1;
13411: } else {
13412: $sts_on = 0;
13413: }
13414: } else {
13415: $sts_on = 0;
13416: }
13417: }
13418: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13419: }
13420: }
13421: return;
13422: }
13423:
1.1172.2.134 raeburn 13424: sub get_requestor_ip {
13425: my ($r,$nolookup,$noproxy) = @_;
13426: my $from_ip;
13427: if (ref($r)) {
13428: $from_ip = $r->get_remote_host($nolookup);
13429: } else {
13430: $from_ip = $ENV{'REMOTE_ADDR'};
13431: }
13432: return $from_ip;
13433: }
13434:
1.31 www 13435: # ------------------------------------------------------------- Declutters URLs
13436:
13437: sub declutter {
13438: my $thisfn=shift;
1.569 albertel 13439: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 13440: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13441: $thisfn=~s{^/home/httpd/html}{};
13442: }
1.31 www 13443: $thisfn=~s/^\///;
1.697 albertel 13444: $thisfn=~s|^adm/wrapper/||;
13445: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13446: $thisfn=~s/^res\///;
1.1172 bisitz 13447: $thisfn=~s/^priv\///;
1.1032 raeburn 13448: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13449: $thisfn=~s/\?.+$//;
13450: }
1.268 www 13451: return $thisfn;
13452: }
13453:
13454: # ------------------------------------------------------------- Clutter up URLs
13455:
13456: sub clutter {
13457: my $thisfn='/'.&declutter(shift);
1.887 albertel 13458: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13459: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13460: $thisfn='/res'.$thisfn;
13461: }
1.1031 raeburn 13462: if ($thisfn !~m|^/adm|) {
13463: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13464: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13465: } else {
13466: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13467: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13468: if ($embstyle eq 'ssi'
13469: || ($embstyle eq 'hdn')
13470: || ($embstyle eq 'rat')
13471: || ($embstyle eq 'prv')
13472: || ($embstyle eq 'ign')) {
13473: #do nothing with these
13474: } elsif (($embstyle eq 'img')
1.695 albertel 13475: || ($embstyle eq 'emb')
13476: || ($embstyle eq 'wrp')) {
13477: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13478: } elsif ($embstyle eq 'unk'
13479: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13480: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13481: } else {
1.718 www 13482: # &logthis("Got a blank emb style");
1.695 albertel 13483: }
1.694 albertel 13484: }
13485: }
1.31 www 13486: return $thisfn;
1.12 www 13487: }
13488:
1.787 albertel 13489: sub clutter_with_no_wrapper {
13490: my $uri = &clutter(shift);
13491: if ($uri =~ m-^/adm/-) {
13492: $uri =~ s-^/adm/wrapper/-/-;
13493: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13494: }
13495: return $uri;
13496: }
13497:
1.557 albertel 13498: sub freeze_escape {
13499: my ($value)=@_;
13500: if (ref($value)) {
13501: $value=&nfreeze($value);
13502: return '__FROZEN__'.&escape($value);
13503: }
13504: return &escape($value);
13505: }
13506:
1.11 www 13507:
1.557 albertel 13508: sub thaw_unescape {
13509: my ($value)=@_;
13510: if ($value =~ /^__FROZEN__/) {
13511: substr($value,0,10,undef);
13512: $value=&unescape($value);
13513: return &thaw($value);
13514: }
13515: return &unescape($value);
13516: }
13517:
1.436 albertel 13518: sub correct_line_ends {
13519: my ($result)=@_;
13520: $$result =~s/\r\n/\n/mg;
13521: $$result =~s/\r/\n/mg;
1.415 albertel 13522: }
1.1 albertel 13523: # ================================================================ Main Program
13524:
1.184 www 13525: sub goodbye {
1.204 albertel 13526: &logthis("Starting Shut down");
1.443 albertel 13527: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13528: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13529: #converted
1.599 albertel 13530: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13531: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13532: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13533: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13534: #1.1 only
1.870 albertel 13535: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13536: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13537: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13538: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13539: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13540: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13541: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13542: &flushcourselogs();
13543: &logthis("Shutting down");
13544: }
13545:
1.852 albertel 13546: sub get_dns {
1.1172.2.17 raeburn 13547: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13548: if (!$ignore_cache) {
13549: my ($content,$cached)=
13550: &Apache::lonnet::is_cached_new('dns',$url);
13551: if ($cached) {
1.1172.2.17 raeburn 13552: &$func($content,$hashref);
1.869 albertel 13553: return;
13554: }
13555: }
13556:
13557: my %alldns;
1.1172.2.96 raeburn 13558: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13559: foreach my $dns (<$config>) {
13560: next if ($dns !~ /^\^(\S*)/x);
13561: my $line = $1;
13562: my ($host,$protocol) = split(/:/,$line);
13563: if ($protocol ne 'https') {
13564: $protocol = 'http';
13565: }
13566: $alldns{$host} = $protocol;
1.979 raeburn 13567: }
1.1172.2.96 raeburn 13568: close($config);
1.869 albertel 13569: }
13570: while (%alldns) {
1.1172.2.52 raeburn 13571: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 13572: my $ua=new LWP::UserAgent;
1.1134 raeburn 13573: $ua->timeout(30);
1.979 raeburn 13574: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 13575: my $response=$ua->request($request);
1.979 raeburn 13576: delete($alldns{$dns});
1.852 albertel 13577: next if ($response->is_error());
13578: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 13579: unless ($nocache) {
1.1172.2.23 raeburn 13580: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 13581: }
13582: &$func(\@content,$hashref);
1.869 albertel 13583: return;
1.852 albertel 13584: }
1.871 albertel 13585: my $which = (split('/',$url))[3];
13586: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 13587: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13588: my @content = <$config>;
13589: &$func(\@content,$hashref);
13590: }
1.1172.2.17 raeburn 13591: return;
13592: }
13593:
13594: # ------------------------------------------------------Get DNS checksums file
13595: sub parse_dns_checksums_tab {
13596: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 13597: my $lonhost = $perlvar{'lonHostID'};
13598: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 13599: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 13600: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13601: my $webconfdir = '/etc/httpd/conf';
13602: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13603: $webconfdir = '/etc/apache2';
13604: } elsif ($distro =~ /^sles(\d+)$/) {
13605: if ($1 >= 10) {
13606: $webconfdir = '/etc/apache2';
13607: }
13608: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13609: if ($1 >= 10.0) {
13610: $webconfdir = '/etc/apache2';
13611: }
13612: }
1.1172.2.17 raeburn 13613: my ($release,$timestamp) = split(/\-/,$loncaparev);
13614: my (%chksum,%revnum);
13615: if (ref($lines) eq 'ARRAY') {
13616: chomp(@{$lines});
1.1172.2.34 raeburn 13617: my $version = shift(@{$lines});
13618: if ($version eq $release) {
1.1172.2.17 raeburn 13619: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 13620: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 13621: if ($file =~ m{^/etc/httpd/conf}) {
13622: if ($webconfdir eq '/etc/apache2') {
13623: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13624: }
13625: }
1.1172.2.34 raeburn 13626: $chksum{$file} = $shasum;
13627: $revnum{$file} = $version;
1.1172.2.17 raeburn 13628: }
13629: if (ref($hashref) eq 'HASH') {
13630: %{$hashref} = (
13631: sums => \%chksum,
13632: versions => \%revnum,
13633: );
13634: }
13635: }
13636: }
1.869 albertel 13637: return;
1.852 albertel 13638: }
1.1172.2.17 raeburn 13639:
13640: sub fetch_dns_checksums {
13641: my %checksums;
1.1172.2.34 raeburn 13642: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 13643: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 13644: my ($release,$timestamp) = split(/\-/,$loncaparev);
13645: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 13646: \%checksums);
13647: return \%checksums;
13648: }
13649:
1.327 albertel 13650: # ------------------------------------------------------------ Read domain file
13651: {
1.852 albertel 13652: my $loaded;
1.846 albertel 13653: my %domain;
13654:
1.852 albertel 13655: sub parse_domain_tab {
13656: my ($lines) = @_;
13657: foreach my $line (@$lines) {
13658: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13659:
1.846 albertel 13660: chomp($line);
1.852 albertel 13661: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13662: my %this_domain;
13663: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13664: 'lang_def', 'city', 'longi', 'lati',
13665: 'primary') {
13666: $this_domain{$field} = shift(@elements);
13667: }
13668: $domain{$name} = \%this_domain;
1.852 albertel 13669: }
13670: }
1.864 albertel 13671:
13672: sub reset_domain_info {
13673: undef($loaded);
13674: undef(%domain);
13675: }
13676:
1.852 albertel 13677: sub load_domain_tab {
1.1172.2.70 raeburn 13678: my ($ignore_cache,$nocache) = @_;
13679: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13680: my $fh;
1.1172.2.96 raeburn 13681: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 13682: my @lines = <$fh>;
13683: &parse_domain_tab(\@lines);
1.448 albertel 13684: }
1.852 albertel 13685: close($fh);
13686: $loaded = 1;
1.327 albertel 13687: }
1.846 albertel 13688:
13689: sub domain {
1.852 albertel 13690: &load_domain_tab() if (!$loaded);
13691:
1.846 albertel 13692: my ($name,$what) = @_;
13693: return if ( !exists($domain{$name}) );
13694:
13695: if (!$what) {
13696: return $domain{$name}{'description'};
13697: }
13698: return $domain{$name}{$what};
13699: }
1.974 raeburn 13700:
13701: sub domain_info {
13702: &load_domain_tab() if (!$loaded);
13703: return %domain;
13704: }
13705:
1.327 albertel 13706: }
13707:
13708:
1.1 albertel 13709: # ------------------------------------------------------------- Read hosts file
13710: {
1.838 albertel 13711: my %hostname;
1.844 albertel 13712: my %hostdom;
1.845 albertel 13713: my %libserv;
1.852 albertel 13714: my $loaded;
1.888 albertel 13715: my %name_to_host;
1.1074 raeburn 13716: my %internetdom;
1.1107 raeburn 13717: my %LC_dns_serv;
1.852 albertel 13718:
13719: sub parse_hosts_tab {
13720: my ($file) = @_;
13721: foreach my $configline (@$file) {
13722: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13723: chomp($configline);
13724: if ($configline =~ /^\^/) {
13725: if ($configline =~ /^\^([\w.\-]+)/) {
13726: $LC_dns_serv{$1} = 1;
13727: }
13728: next;
13729: }
1.1074 raeburn 13730: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13731: $name=~s/\s//g;
13732: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 13733: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13734: my $curr = $hostname{$id};
13735: my $skip;
13736: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13737: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13738: $skip = 1;
13739: } else {
13740: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13741: }
13742: }
13743: unless ($skip) {
13744: push(@{$name_to_host{$name}},$id);
13745: }
13746: } else {
13747: push(@{$name_to_host{$name}},$id);
13748: }
1.852 albertel 13749: $hostname{$id}=$name;
13750: $hostdom{$id}=$domain;
13751: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13752: if (defined($protocol)) {
13753: if ($protocol eq 'https') {
13754: $protocol{$id} = $protocol;
13755: } else {
13756: $protocol{$id} = 'http';
13757: }
1.968 raeburn 13758: } else {
1.969 raeburn 13759: $protocol{$id} = 'http';
1.968 raeburn 13760: }
1.1074 raeburn 13761: if (defined($intdom)) {
13762: $internetdom{$id} = $intdom;
13763: }
1.852 albertel 13764: }
13765: }
13766: }
1.864 albertel 13767:
13768: sub reset_hosts_info {
1.897 albertel 13769: &purge_remembered();
1.864 albertel 13770: &reset_domain_info();
13771: &reset_hosts_ip_info();
1.892 albertel 13772: undef(%name_to_host);
1.864 albertel 13773: undef(%hostname);
13774: undef(%hostdom);
13775: undef(%libserv);
13776: undef($loaded);
13777: }
1.1 albertel 13778:
1.852 albertel 13779: sub load_hosts_tab {
1.1172.2.70 raeburn 13780: my ($ignore_cache,$nocache) = @_;
13781: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 13782: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 13783: my @config = <$config>;
13784: &parse_hosts_tab(\@config);
13785: close($config);
13786: $loaded=1;
1.1 albertel 13787: }
1.852 albertel 13788:
1.838 albertel 13789: sub hostname {
1.852 albertel 13790: &load_hosts_tab() if (!$loaded);
13791:
1.838 albertel 13792: my ($lonid) = @_;
13793: return $hostname{$lonid};
13794: }
1.845 albertel 13795:
1.838 albertel 13796: sub all_hostnames {
1.852 albertel 13797: &load_hosts_tab() if (!$loaded);
13798:
1.838 albertel 13799: return %hostname;
13800: }
1.845 albertel 13801:
1.888 albertel 13802: sub all_names {
1.1172.2.70 raeburn 13803: my ($ignore_cache,$nocache) = @_;
13804: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13805:
13806: return %name_to_host;
13807: }
13808:
1.974 raeburn 13809: sub all_host_domain {
13810: &load_hosts_tab() if (!$loaded);
13811: return %hostdom;
13812: }
13813:
1.845 albertel 13814: sub is_library {
1.852 albertel 13815: &load_hosts_tab() if (!$loaded);
13816:
1.845 albertel 13817: return exists($libserv{$_[0]});
13818: }
13819:
13820: sub all_library {
1.852 albertel 13821: &load_hosts_tab() if (!$loaded);
13822:
1.845 albertel 13823: return %libserv;
13824: }
13825:
1.1062 droeschl 13826: sub unique_library {
13827: #2x reverse removes all hostnames that appear more than once
13828: my %unique = reverse &all_library();
13829: return reverse %unique;
13830: }
13831:
1.841 albertel 13832: sub get_servers {
1.852 albertel 13833: &load_hosts_tab() if (!$loaded);
13834:
1.841 albertel 13835: my ($domain,$type) = @_;
13836: my %possible_hosts = ($type eq 'library') ? %libserv
13837: : %hostname;
13838: my %result;
1.842 albertel 13839: if (ref($domain) eq 'ARRAY') {
13840: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13841: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13842: $result{$host} = $hostname;
13843: }
13844: }
13845: } else {
13846: while ( my ($host,$hostname) = each(%possible_hosts)) {
13847: if ($hostdom{$host} eq $domain) {
13848: $result{$host} = $hostname;
13849: }
1.841 albertel 13850: }
13851: }
13852: return %result;
13853: }
1.845 albertel 13854:
1.1062 droeschl 13855: sub get_unique_servers {
13856: my %unique = reverse &get_servers(@_);
13857: return reverse %unique;
13858: }
13859:
1.844 albertel 13860: sub host_domain {
1.852 albertel 13861: &load_hosts_tab() if (!$loaded);
13862:
1.844 albertel 13863: my ($lonid) = @_;
13864: return $hostdom{$lonid};
13865: }
13866:
1.841 albertel 13867: sub all_domains {
1.852 albertel 13868: &load_hosts_tab() if (!$loaded);
13869:
1.841 albertel 13870: my %seen;
13871: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13872: return @uniq;
13873: }
1.1074 raeburn 13874:
13875: sub internet_dom {
13876: &load_hosts_tab() if (!$loaded);
13877:
13878: my ($lonid) = @_;
13879: return $internetdom{$lonid};
13880: }
1.1107 raeburn 13881:
13882: sub is_LC_dns {
13883: &load_hosts_tab() if (!$loaded);
13884:
13885: my ($hostname) = @_;
13886: return exists($LC_dns_serv{$hostname});
13887: }
13888:
1.1 albertel 13889: }
13890:
1.847 albertel 13891: {
13892: my %iphost;
1.856 albertel 13893: my %name_to_ip;
13894: my %lonid_to_ip;
1.869 albertel 13895:
1.847 albertel 13896: sub get_hosts_from_ip {
13897: my ($ip) = @_;
13898: my %iphosts = &get_iphost();
13899: if (ref($iphosts{$ip})) {
13900: return @{$iphosts{$ip}};
13901: }
13902: return;
1.839 albertel 13903: }
1.864 albertel 13904:
13905: sub reset_hosts_ip_info {
13906: undef(%iphost);
13907: undef(%name_to_ip);
13908: undef(%lonid_to_ip);
13909: }
1.856 albertel 13910:
13911: sub get_host_ip {
13912: my ($lonid) = @_;
13913: if (exists($lonid_to_ip{$lonid})) {
13914: return $lonid_to_ip{$lonid};
13915: }
13916: my $name=&hostname($lonid);
13917: my $ip = gethostbyname($name);
13918: return if (!$ip || length($ip) ne 4);
13919: $ip=inet_ntoa($ip);
13920: $name_to_ip{$name} = $ip;
13921: $lonid_to_ip{$lonid} = $ip;
13922: return $ip;
13923: }
1.847 albertel 13924:
13925: sub get_iphost {
1.1172.2.70 raeburn 13926: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13927:
1.869 albertel 13928: if (!$ignore_cache) {
13929: if (%iphost) {
13930: return %iphost;
13931: }
13932: my ($ip_info,$cached)=
13933: &Apache::lonnet::is_cached_new('iphost','iphost');
13934: if ($cached) {
13935: %iphost = %{$ip_info->[0]};
13936: %name_to_ip = %{$ip_info->[1]};
13937: %lonid_to_ip = %{$ip_info->[2]};
13938: return %iphost;
13939: }
13940: }
1.894 albertel 13941:
13942: # get yesterday's info for fallback
13943: my %old_name_to_ip;
13944: my ($ip_info,$cached)=
13945: &Apache::lonnet::is_cached_new('iphost','iphost');
13946: if ($cached) {
13947: %old_name_to_ip = %{$ip_info->[1]};
13948: }
13949:
1.1172.2.70 raeburn 13950: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13951: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13952: my $ip;
13953: if (!exists($name_to_ip{$name})) {
13954: $ip = gethostbyname($name);
13955: if (!$ip || length($ip) ne 4) {
1.894 albertel 13956: if (defined($old_name_to_ip{$name})) {
13957: $ip = $old_name_to_ip{$name};
13958: &logthis("Can't find $name defaulting to old $ip");
13959: } else {
13960: &logthis("Name $name no IP found");
13961: next;
13962: }
13963: } else {
13964: $ip=inet_ntoa($ip);
1.847 albertel 13965: }
13966: $name_to_ip{$name} = $ip;
13967: } else {
13968: $ip = $name_to_ip{$name};
1.653 albertel 13969: }
1.888 albertel 13970: foreach my $id (@{ $name_to_host{$name} }) {
13971: $lonid_to_ip{$id} = $ip;
13972: }
13973: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13974: }
1.1172.2.70 raeburn 13975: unless ($nocache) {
13976: &do_cache_new('iphost','iphost',
13977: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13978: 48*60*60);
13979: }
1.869 albertel 13980:
1.847 albertel 13981: return %iphost;
1.598 albertel 13982: }
13983:
1.992 raeburn 13984: #
13985: # Given a DNS returns the loncapa host name for that DNS
13986: #
13987: sub host_from_dns {
13988: my ($dns) = @_;
13989: my @hosts;
13990: my $ip;
13991:
1.993 raeburn 13992: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13993: $ip = $name_to_ip{$dns};
13994: }
13995: if (!$ip) {
13996: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13997: if (length($ip) == 4) {
13998: $ip = &IO::Socket::inet_ntoa($ip);
13999: }
14000: }
14001: if ($ip) {
14002: @hosts = get_hosts_from_ip($ip);
14003: return $hosts[0];
14004: }
14005: return undef;
1.986 foxr 14006: }
1.992 raeburn 14007:
1.1074 raeburn 14008: sub get_internet_names {
14009: my ($lonid) = @_;
14010: return if ($lonid eq '');
14011: my ($idnref,$cached)=
14012: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14013: if ($cached) {
14014: return $idnref;
14015: }
14016: my $ip = &get_host_ip($lonid);
14017: my @hosts = &get_hosts_from_ip($ip);
14018: my %iphost = &get_iphost();
14019: my (@idns,%seen);
14020: foreach my $id (@hosts) {
14021: my $dom = &host_domain($id);
14022: my $prim_id = &domain($dom,'primary');
14023: my $prim_ip = &get_host_ip($prim_id);
14024: next if ($seen{$prim_ip});
14025: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14026: foreach my $id (@{$iphost{$prim_ip}}) {
14027: my $intdom = &internet_dom($id);
14028: unless (grep(/^\Q$intdom\E$/,@idns)) {
14029: push(@idns,$intdom);
14030: }
14031: }
14032: }
14033: $seen{$prim_ip} = 1;
14034: }
1.1172.2.23 raeburn 14035: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14036: }
14037:
1.986 foxr 14038: }
14039:
1.1079 raeburn 14040: sub all_loncaparevs {
1.1172.2.39 raeburn 14041: 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 14042: }
14043:
1.1172.2.27 raeburn 14044: # ------------------------------------------------------- Read loncaparev table
14045: {
14046: sub load_loncaparevs {
14047: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 14048: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 14049: while (my $configline=<$config>) {
14050: chomp($configline);
14051: my ($hostid,$loncaparev)=split(/:/,$configline);
14052: $loncaparevs{$hostid}=$loncaparev;
14053: }
14054: close($config);
14055: }
14056: }
14057: }
14058: }
14059:
14060: # ----------------------------------------------------- Read serverhostID table
14061: {
14062: sub load_serverhomeIDs {
14063: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 14064: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 14065: while (my $configline=<$config>) {
14066: chomp($configline);
14067: my ($name,$id)=split(/:/,$configline);
14068: $serverhomeIDs{$name}=$id;
14069: }
14070: close($config);
14071: }
14072: }
14073: }
14074: }
14075:
14076:
1.862 albertel 14077: BEGIN {
14078:
14079: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14080: unless ($readit) {
14081: {
14082: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14083: %perlvar = (%perlvar,%{$configvars});
14084: }
14085:
14086:
1.1 albertel 14087: # ------------------------------------------------------ Read spare server file
14088: {
1.1172.2.96 raeburn 14089: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14090:
14091: while (my $configline=<$config>) {
14092: chomp($configline);
1.284 matthew 14093: if ($configline) {
1.784 albertel 14094: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14095: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14096: push(@{ $spareid{$type} }, $host);
1.1 albertel 14097: }
14098: }
1.448 albertel 14099: close($config);
1.1 albertel 14100: }
1.11 www 14101: # ------------------------------------------------------------ Read permissions
14102: {
1.1172.2.96 raeburn 14103: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14104:
14105: while (my $configline=<$config>) {
1.448 albertel 14106: chomp($configline);
14107: if ($configline) {
14108: my ($role,$perm)=split(/ /,$configline);
14109: if ($perm ne '') { $pr{$role}=$perm; }
14110: }
1.11 www 14111: }
1.448 albertel 14112: close($config);
1.11 www 14113: }
14114:
14115: # -------------------------------------------- Read plain texts for permissions
14116: {
1.1172.2.96 raeburn 14117: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14118:
14119: while (my $configline=<$config>) {
1.448 albertel 14120: chomp($configline);
14121: if ($configline) {
1.742 raeburn 14122: my ($short,@plain)=split(/:/,$configline);
14123: %{$prp{$short}} = ();
14124: if (@plain > 0) {
14125: $prp{$short}{'std'} = $plain[0];
14126: for (my $i=1; $i<@plain; $i++) {
14127: $prp{$short}{'alt'.$i} = $plain[$i];
14128: }
14129: }
1.448 albertel 14130: }
1.135 www 14131: }
1.448 albertel 14132: close($config);
1.135 www 14133: }
14134:
14135: # ---------------------------------------------------------- Read package table
14136: {
1.1172.2.96 raeburn 14137: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14138:
14139: while (my $configline=<$config>) {
1.483 albertel 14140: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14141: chomp($configline);
14142: my ($short,$plain)=split(/:/,$configline);
14143: my ($pack,$name)=split(/\&/,$short);
14144: if ($plain ne '') {
14145: $packagetab{$pack.'&'.$name.'&name'}=$name;
14146: $packagetab{$short}=$plain;
14147: }
1.11 www 14148: }
1.448 albertel 14149: close($config);
1.329 matthew 14150: }
14151:
1.1172.2.27 raeburn 14152: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 14153:
1.1172.2.27 raeburn 14154: &load_loncaparevs();
14155:
14156: # ------------------------------------------------------- Read serverhostID table
14157:
14158: &load_serverhomeIDs();
1.1074 raeburn 14159:
1.1172.2.27 raeburn 14160: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14161: {
14162: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14163: if (-e $file) {
14164: my $parser = HTML::LCParser->new($file);
14165: while (my $token = $parser->get_token()) {
14166: if ($token->[0] eq 'S') {
14167: my $item = $token->[1];
14168: my $name = $token->[2]{'name'};
14169: my $value = $token->[2]{'value'};
14170: if ($item ne '' && $name ne '' && $value ne '') {
14171: my $release = $parser->get_text();
14172: $release =~ s/(^\s*|\s*$ )//gx;
14173: $needsrelease{$item.':'.$name.':'.$value} = $release;
14174: }
14175: }
14176: }
14177: }
1.1073 raeburn 14178: }
14179:
1.1138 raeburn 14180: # ---------------------------------------------------------- Read managers table
14181: {
14182: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 14183: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14184: while (my $configline=<$config>) {
14185: chomp($configline);
14186: next if ($configline =~ /^\#/);
14187: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14188: $managerstab{$configline} = 1;
14189: }
14190: }
14191: close($config);
14192: }
14193: }
14194: }
14195:
1.329 matthew 14196: # ------------- set up temporary directory
14197: {
1.1117 foxr 14198: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14199:
1.11 www 14200: }
14201:
1.1172.2.104 raeburn 14202: # ------------- set default texengine (domain default overrides this)
14203: {
14204: $deftex = LONCAPA::texengine();
14205: }
14206:
1.1172.2.114 raeburn 14207: # ------------- set default minimum length for passwords for internal auth users
14208: {
14209: $passwdmin = LONCAPA::passwd_min();
14210: }
14211:
1.794 albertel 14212: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14213: 'compress_threshold'=> 20_000,
14214: });
1.185 www 14215:
1.281 www 14216: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14217: $dumpcount=0;
1.958 www 14218: $locknum=0;
1.22 www 14219:
1.163 harris41 14220: &logtouch();
1.672 albertel 14221: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14222: $readit=1;
1.564 albertel 14223: {
14224: use integer;
14225: my $test=(2**32)+1;
1.568 albertel 14226: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14227: &logthis(" Detected 64bit platform ($_64bit)");
14228: }
1.195 www 14229: }
1.1 albertel 14230: }
1.179 www 14231:
1.1 albertel 14232: 1;
1.191 harris41 14233: __END__
14234:
1.243 albertel 14235: =pod
14236:
1.191 harris41 14237: =head1 NAME
14238:
1.243 albertel 14239: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14240:
14241: =head1 SYNOPSIS
14242:
1.243 albertel 14243: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14244:
14245: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14246:
1.243 albertel 14247: Common parameters:
14248:
14249: =over 4
14250:
14251: =item *
14252:
14253: $uname : an internal username (if $cname expecting a course Id specifically)
14254:
14255: =item *
14256:
14257: $udom : a domain (if $cdom expecting a course's domain specifically)
14258:
14259: =item *
14260:
14261: $symb : a resource instance identifier
14262:
14263: =item *
14264:
14265: $namespace : the name of a .db file that contains the data needed or
14266: being set.
14267:
14268: =back
14269:
1.394 bowersj2 14270: =head1 OVERVIEW
1.191 harris41 14271:
1.394 bowersj2 14272: lonnet provides subroutines which interact with the
14273: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14274: about classes, users, and resources.
1.243 albertel 14275:
14276: For many of these objects you can also use this to store data about
14277: them or modify them in various ways.
1.191 harris41 14278:
1.394 bowersj2 14279: =head2 Symbs
1.191 harris41 14280:
1.394 bowersj2 14281: To identify a specific instance of a resource, LON-CAPA uses symbols
14282: or "symbs"X<symb>. These identifiers are built from the URL of the
14283: map, the resource number of the resource in the map, and the URL of
14284: the resource itself. The latter is somewhat redundant, but might help
14285: if maps change.
14286:
14287: An example is
14288:
14289: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14290:
14291: The respective map entry is
14292:
14293: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14294: title="Problem 2">
14295: </resource>
14296:
14297: Symbs are used by the random number generator, as well as to store and
14298: restore data specific to a certain instance of for example a problem.
14299:
14300: =head2 Storing And Retrieving Data
14301:
14302: X<store()>X<cstore()>X<restore()>Three of the most important functions
14303: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14304: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14305: is is the non-critical message twin of cstore. These functions are for
14306: handlers to store a perl hash to a user's permanent data space in an
14307: easy manner, and to retrieve it again on another call. It is expected
14308: that a handler would use this once at the beginning to retrieve data,
14309: and then again once at the end to send only the new data back.
14310:
14311: The data is stored in the user's data directory on the user's
14312: homeserver under the ID of the course.
14313:
14314: The hash that is returned by restore will have all of the previous
14315: value for all of the elements of the hash.
14316:
14317: Example:
14318:
14319: #creating a hash
14320: my %hash;
14321: $hash{'foo'}='bar';
14322:
14323: #storing it
14324: &Apache::lonnet::cstore(\%hash);
14325:
14326: #changing a value
14327: $hash{'foo'}='notbar';
14328:
14329: #adding a new value
14330: $hash{'bar'}='foo';
14331: &Apache::lonnet::cstore(\%hash);
14332:
14333: #retrieving the hash
14334: my %history=&Apache::lonnet::restore();
14335:
14336: #print the hash
14337: foreach my $key (sort(keys(%history))) {
14338: print("\%history{$key} = $history{$key}");
14339: }
14340:
14341: Will print out:
1.191 harris41 14342:
1.394 bowersj2 14343: %history{1:foo} = bar
14344: %history{1:keys} = foo:timestamp
14345: %history{1:timestamp} = 990455579
14346: %history{2:bar} = foo
14347: %history{2:foo} = notbar
14348: %history{2:keys} = foo:bar:timestamp
14349: %history{2:timestamp} = 990455580
14350: %history{bar} = foo
14351: %history{foo} = notbar
14352: %history{timestamp} = 990455580
14353: %history{version} = 2
14354:
14355: Note that the special hash entries C<keys>, C<version> and
14356: C<timestamp> were added to the hash. C<version> will be equal to the
14357: total number of versions of the data that have been stored. The
14358: C<timestamp> attribute will be the UNIX time the hash was
14359: stored. C<keys> is available in every historical section to list which
14360: keys were added or changed at a specific historical revision of a
14361: hash.
14362:
14363: B<Warning>: do not store the hash that restore returns directly. This
14364: will cause a mess since it will restore the historical keys as if the
14365: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14366:
1.394 bowersj2 14367: Calling convention:
1.191 harris41 14368:
1.1172.2.27 raeburn 14369: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 14370: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14371:
1.394 bowersj2 14372: For more detailed information, see lonnet specific documentation.
1.191 harris41 14373:
1.394 bowersj2 14374: =head1 RETURN MESSAGES
1.191 harris41 14375:
1.394 bowersj2 14376: =over 4
1.191 harris41 14377:
1.394 bowersj2 14378: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14379:
1.394 bowersj2 14380: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14381: when the connection is brought back up
1.191 harris41 14382:
1.394 bowersj2 14383: =item * B<con_failed>: unable to contact remote host and unable to save message
14384: for later delivery
1.191 harris41 14385:
1.967 bisitz 14386: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14387:
1.394 bowersj2 14388: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14389: that was requested
1.191 harris41 14390:
1.243 albertel 14391: =back
1.191 harris41 14392:
1.243 albertel 14393: =head1 PUBLIC SUBROUTINES
1.191 harris41 14394:
1.243 albertel 14395: =head2 Session Environment Functions
1.191 harris41 14396:
1.243 albertel 14397: =over 4
1.191 harris41 14398:
1.394 bowersj2 14399: =item *
14400: X<appenv()>
1.949 raeburn 14401: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14402: the user envirnoment file, and will be restored for each access this
1.620 albertel 14403: user makes during this session, also modifies the %env for the current
1.949 raeburn 14404: process. Optional rolesarrayref - if defined contains a reference to an array
14405: of roles which are exempt from the restriction on modifying user.role entries
14406: in the user's environment.db and in %env.
1.191 harris41 14407:
14408: =item *
1.394 bowersj2 14409: X<delenv()>
1.987 raeburn 14410: B<delenv($delthis,$regexp)>: removes all items from the session
14411: environment file that begin with $delthis. If the
14412: optional second arg - $regexp - is true, $delthis is treated as a
14413: regular expression, otherwise \Q$delthis\E is used.
14414: The values are also deleted from the current processes %env.
1.191 harris41 14415:
1.795 albertel 14416: =item * get_env_multiple($name)
14417:
14418: gets $name from the %env hash, it seemlessly handles the cases where multiple
14419: values may be defined and end up as an array ref.
14420:
14421: returns an array of values
14422:
1.243 albertel 14423: =back
14424:
14425: =head2 User Information
1.191 harris41 14426:
1.243 albertel 14427: =over 4
1.191 harris41 14428:
14429: =item *
1.394 bowersj2 14430: X<queryauthenticate()>
14431: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14432: authentication scheme
14433:
14434: =item *
1.394 bowersj2 14435: X<authenticate()>
1.1073 raeburn 14436: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14437: authenticate user from domain's lib servers (first use the current
14438: one). C<$upass> should be the users password.
1.1073 raeburn 14439: $checkdefauth is optional (value is 1 if a check should be made to
14440: authenticate user using default authentication method, and allow
14441: account creation if username does not have account in the domain).
14442: $clientcancheckhost is optional (value is 1 if checking whether the
14443: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14444:
14445: =item *
1.394 bowersj2 14446: X<homeserver()>
14447: B<homeserver($uname,$udom)>: find the server which has
14448: the user's directory and files (there must be only one), this caches
14449: the answer, and also caches if there is a borken connection.
1.191 harris41 14450:
14451: =item *
1.394 bowersj2 14452: X<idget()>
14453: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14454: (IDs are a unique resource in a domain, there must be only 1 ID per
14455: username, and only 1 username per ID in a specific domain) (returns
14456: hash: id=>name,id=>name)
1.191 harris41 14457:
14458: =item *
1.394 bowersj2 14459: X<idrget()>
14460: B<idrget($udom,@unames)>: find the IDs behind a list of
14461: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14462:
14463: =item *
1.394 bowersj2 14464: X<idput()>
14465: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 14466:
14467: =item *
1.394 bowersj2 14468: X<rolesinit()>
1.1169 droeschl 14469: B<rolesinit($udom,$username)>: get user privileges.
14470: returns user role, first access and timer interval hashes
1.243 albertel 14471:
14472: =item *
1.1171 droeschl 14473: X<privileged()>
14474: B<privileged($username,$domain)>: returns a true if user has a
14475: privileged and active role (i.e. su or dc), false otherwise.
14476:
14477: =item *
1.551 albertel 14478: X<getsection()>
14479: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14480: course $cname, return section name/number or '' for "not in course"
14481: and '-1' for "no section"
14482:
14483: =item *
1.394 bowersj2 14484: X<userenvironment()>
14485: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14486: passed in @what from the requested user's environment, returns a hash
14487:
1.858 raeburn 14488: =item *
14489: X<userlog_query()>
1.859 albertel 14490: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14491: activity.log file. %filters defines filters applied when parsing the
14492: log file. These can be start or end timestamps, or the type of action
14493: - log to look for Login or Logout events, check for Checkin or
14494: Checkout, role for role selection. The response is in the form
14495: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14496: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14497:
1.243 albertel 14498: =back
14499:
14500: =head2 User Roles
14501:
14502: =over 4
14503:
14504: =item *
14505:
1.1172.2.65 raeburn 14506: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14507: returns codes for allowed actions.
14508:
14509: The first argument is required, all others are optional.
14510:
14511: $priv is the privilege being checked.
14512: $uri contains additional information about what is being checked for access (e.g.,
14513: URL, course ID etc.).
14514: $symb is the unique resource instance identifier in a course; if needed,
14515: but not provided, it will be retrieved via a call to &symbread().
14516: $role is the role for which a priv is being checked (only used if priv is evb).
14517: $clientip is the user's IP address (only used when checking for access to portfolio
14518: files).
14519: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14520: prevents recursive calls to &allowed.
14521:
1.243 albertel 14522: F: full access
14523: U,I,K: authentication modes (cxx only)
14524: '': forbidden
14525: 1: user needs to choose course
14526: 2: browse allowed
1.766 albertel 14527: A: passphrase authentication needed
1.1172.2.65 raeburn 14528: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14529:
14530: =item *
14531:
1.1172.2.13 raeburn 14532: constructaccess($url,$setpriv) : check for access to construction space URL
14533:
14534: See if the owner domain and name in the URL match those in the
14535: expected environment. If so, return three element list
14536: ($ownername,$ownerdomain,$ownerhome).
14537:
14538: Otherwise return the null string.
14539:
14540: If second argument 'setpriv' is true, it assigns the privileges,
14541: and returns the same three element list, unless the owner has
14542: blocked "ad hoc" Domain Coordinator access to the Author Space,
14543: in which case the null string is returned.
14544:
14545: =item *
14546:
1.1172.2.84 raeburn 14547: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14548: define a custom role rolename set privileges in format of lonTabs/roles.tab
14549: for system, domain, and course level. $uname and $udom are optional (current
14550: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14551:
14552: =item *
14553:
1.988 raeburn 14554: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14555: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14556: $type is Course (default) or Community.
1.988 raeburn 14557: If $forcedefault evaluates to true, text returned will be default
14558: text for $type. Otherwise, if this is a course, the text returned
14559: will be a custom name for the role (if defined in the course's
14560: environment). If no custom name is defined the default is returned.
14561:
1.832 raeburn 14562: =item *
14563:
1.1172.2.23 raeburn 14564: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14565: All arguments are optional. Returns a hash of a roles, either for
14566: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14567: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14568: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14569: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14570: For each key, value is set to colon-separated start and end times for
14571: the role. If no username and domain are specified, will default to
1.934 raeburn 14572: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14573: of role statuses (active, future or previous), roles
14574: (e.g., cc,in, st etc.) and domains of the roles which can be used
14575: to restrict the list of roles reported. If no array ref is
14576: provided for types, will default to return only active roles.
1.834 albertel 14577:
1.1172.2.13 raeburn 14578: =item *
14579:
14580: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14581: user: $uname:$udom has a role in the course: $cdom_$cnum.
14582:
14583: Additional optional arguments are: $type (if role checking is to be restricted
14584: to certain user status types -- previous (expired roles), active (currently
14585: available roles) or future (roles available in the future), and
14586: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 14587: have active Domain Coordinator role in course's domain or in additional
14588: domains (specified in 'Domains to check for privileged users' in course
14589: environment -- set via: Course Settings -> Classlists and staff listing).
14590:
14591: =item *
14592:
14593: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14594: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14595: $possdomains and $possroles are optional array refs -- to domains to check and
14596: roles to check. If $possdomains is not specified, a dump will be done of the
14597: users' roles.db to check for a dc or su role in any domain. This can be
14598: time consuming if &privileged is called repeatedly (e.g., when displaying a
14599: classlist), so in such cases, supplying a $possdomains array is preferred, as
14600: this then allows &privileged_by_domain() to be used, which caches the identity
14601: of privileged users, eliminating the need for repeated calls to &dump().
14602:
14603: =item *
14604:
14605: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14606: where the outer hash keys are domains specified in the $possdomains array ref,
14607: next inner hash keys are privileged roles specified in the $roles array ref,
14608: and the innermost hash contains key = value pairs for username:domain = end:start
14609: for active or future "privileged" users with that role in that domain. To avoid
14610: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14611: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 14612:
1.243 albertel 14613: =back
14614:
14615: =head2 User Modification
14616:
14617: =over 4
14618:
14619: =item *
14620:
1.957 raeburn 14621: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14622: user for the level given by URL. Optional start and end dates (leave empty
14623: string or zero for "no date")
1.191 harris41 14624:
14625: =item *
14626:
1.243 albertel 14627: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14628: change a users, password, possible return values are: ok,
14629: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14630: refused
1.191 harris41 14631:
14632: =item *
14633:
1.243 albertel 14634: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14635:
14636: =item *
14637:
1.1058 raeburn 14638: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14639: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14640:
14641: will update user information (firstname,middlename,lastname,generation,
14642: permanentemail), and if forceid is true, student/employee ID also.
14643: A user's institutional affiliation(s) can also be updated.
14644: User information fields will not be overwritten with empty entries
14645: unless the field is included in the $candelete array reference.
14646: This array is included when a single user is modified via "Manage Users",
14647: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14648:
14649: =item *
14650:
1.286 matthew 14651: modifystudent
14652:
1.957 raeburn 14653: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 14654: The course id is resolved based on the current user's environment.
14655: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14656: associated with a course.
14657:
1.297 matthew 14658: This call is essentially a wrapper for lonnet::modifyuser and
14659: lonnet::modify_student_enrollment
1.286 matthew 14660:
14661: Inputs:
14662:
14663: =over 4
14664:
1.957 raeburn 14665: =item B<$udom> Student's loncapa domain
1.286 matthew 14666:
1.957 raeburn 14667: =item B<$uname> Student's loncapa login name
1.286 matthew 14668:
1.964 bisitz 14669: =item B<$uid> Student/Employee ID
1.286 matthew 14670:
1.957 raeburn 14671: =item B<$umode> Student's authentication mode
1.286 matthew 14672:
1.957 raeburn 14673: =item B<$upass> Student's password
1.286 matthew 14674:
1.957 raeburn 14675: =item B<$first> Student's first name
1.286 matthew 14676:
1.957 raeburn 14677: =item B<$middle> Student's middle name
1.286 matthew 14678:
1.957 raeburn 14679: =item B<$last> Student's last name
1.286 matthew 14680:
1.957 raeburn 14681: =item B<$gene> Student's generation
1.286 matthew 14682:
1.957 raeburn 14683: =item B<$usec> Student's section in course
1.286 matthew 14684:
14685: =item B<$end> Unix time of the roles expiration
14686:
14687: =item B<$start> Unix time of the roles start date
14688:
14689: =item B<$forceid> If defined, allow $uid to be changed
14690:
14691: =item B<$desiredhome> server to use as home server for student
14692:
1.957 raeburn 14693: =item B<$email> Student's permanent e-mail address
14694:
14695: =item B<$type> Type of enrollment (auto or manual)
14696:
1.963 raeburn 14697: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14698:
14699: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14700:
1.963 raeburn 14701: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14702:
1.963 raeburn 14703: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14704:
1.1172.2.19 raeburn 14705: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14706:
14707: =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 14708:
1.286 matthew 14709: =back
1.297 matthew 14710:
14711: =item *
14712:
14713: modify_student_enrollment
14714:
1.1172.2.31 raeburn 14715: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14716: 'role.request.course' must be defined for this function to proceed.
14717:
14718: Inputs:
14719:
14720: =over 4
14721:
1.1172.2.31 raeburn 14722: =item $udom, student's domain
1.297 matthew 14723:
1.1172.2.31 raeburn 14724: =item $uname, student's name
1.297 matthew 14725:
1.1172.2.31 raeburn 14726: =item $uid, student's user id
1.297 matthew 14727:
1.1172.2.31 raeburn 14728: =item $first, student's first name
1.297 matthew 14729:
14730: =item $middle
14731:
14732: =item $last
14733:
14734: =item $gene
14735:
14736: =item $usec
14737:
14738: =item $end
14739:
14740: =item $start
14741:
1.957 raeburn 14742: =item $type
14743:
14744: =item $locktype
14745:
14746: =item $cid
14747:
14748: =item $selfenroll
14749:
14750: =item $context
14751:
1.1172.2.19 raeburn 14752: =item $credits, number of credits student will earn from this class
14753:
1.1172.2.76 raeburn 14754: =item $instsec, institutional course section code for student
14755:
1.297 matthew 14756: =back
14757:
1.191 harris41 14758:
14759: =item *
14760:
1.243 albertel 14761: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14762: custom role; give a custom role to a user for the level given by URL. Specify
14763: name and domain of role author, and role name
1.191 harris41 14764:
14765: =item *
14766:
1.243 albertel 14767: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14768:
14769: =item *
14770:
1.243 albertel 14771: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14772:
14773: =back
14774:
14775: =head2 Course Infomation
14776:
14777: =over 4
1.191 harris41 14778:
14779: =item *
14780:
1.1118 foxr 14781: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14782: specified course id, including all environment settings for the
14783: course, the description of the course will be in the hash under the
14784: key 'description'
1.191 harris41 14785:
1.1118 foxr 14786: $options is an optional parameter that if supplied is a hash reference that controls
14787: what how this function works. It has the following key/values:
14788:
14789: =over 4
14790:
14791: =item freshen_cache
14792:
14793: If defined, and the environment cache for the course is valid, it is
14794: returned in the returned hash.
14795:
14796: =item one_time
14797:
14798: If defined, the last cache time is set to _now_
14799:
14800: =item user
14801:
14802: If defined, the supplied username is used instead of the current user.
14803:
14804:
14805: =back
14806:
1.191 harris41 14807: =item *
14808:
1.624 albertel 14809: resdata($name,$domain,$type,@which) : request for current parameter
14810: setting for a specific $type, where $type is either 'course' or 'user',
14811: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 14812: answers for 10 minutes.
1.243 albertel 14813:
1.877 foxr 14814: =item *
14815:
14816: get_courseresdata($courseid, $domain) : dump the entire course resource
14817: data base, returning a hash that is keyed by the resource name and has
14818: values that are the resource value. I believe that the timestamps and
14819: versions are also returned.
14820:
1.1172.2.31 raeburn 14821: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14822: supplemental content area. This routine caches the number of files for
14823: 10 minutes.
14824:
1.243 albertel 14825: =back
14826:
14827: =head2 Course Modification
14828:
14829: =over 4
1.191 harris41 14830:
14831: =item *
14832:
1.243 albertel 14833: writecoursepref($courseid,%prefs) : write preferences (environment
14834: database) for a course
1.191 harris41 14835:
14836: =item *
14837:
1.1011 raeburn 14838: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14839:
14840: =item *
14841:
1.1038 raeburn 14842: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14843:
1.1167 droeschl 14844: =item *
14845:
14846: is_course($courseid), is_course($cdom, $cnum)
14847:
14848: Accepts either a combined $courseid (in the form of domain_courseid) or the
14849: two component version $cdom, $cnum. It checks if the specified course exists.
14850:
14851: Returns:
14852: undef if the course doesn't exist, otherwise
14853: in scalar context the combined courseid.
14854: in list context the two components of the course identifier, domain and
14855: courseid.
14856:
1.243 albertel 14857: =back
14858:
1.1172.2.109 raeburn 14859: =head2 Bubblesheet Configuration
14860:
14861: =over 4
14862:
14863: =item *
14864:
14865: get_scantron_config($which)
14866:
14867: $which - the name of the configuration to parse from the file.
14868:
14869: Parses and returns the bubblesheet configuration line selected as a
14870: hash of configuration file fields.
14871:
14872:
14873: Returns:
14874: If the named configuration is not in the file, an empty
14875: hash is returned.
14876:
14877: a hash with the fields
14878: name - internal name for the this configuration setup
14879: description - text to display to operator that describes this config
14880: CODElocation - if 0 or the string 'none'
14881: - no CODE exists for this config
14882: if -1 || the string 'letter'
14883: - a CODE exists for this config and is
14884: a string of letters
14885: Unsupported value (but planned for future support)
14886: if a positive integer
14887: - The CODE exists as the first n items from
14888: the question section of the form
14889: if the string 'number'
14890: - The CODE exists for this config and is
14891: a string of numbers
14892: CODEstart - (only matter if a CODE exists) column in the line where
14893: the CODE starts
14894: CODElength - length of the CODE
14895: IDstart - column where the student/employee ID starts
14896: IDlength - length of the student/employee ID info
14897: Qstart - column where the information from the bubbled
14898: 'questions' start
14899: Qlength - number of columns comprising a single bubble line from
14900: the sheet. (usually either 1 or 10)
14901: Qon - either a single character representing the character used
14902: to signal a bubble was chosen in the positional setup, or
14903: the string 'letter' if the letter of the chosen bubble is
14904: in the final, or 'number' if a number representing the
14905: chosen bubble is in the file (1->A 0->J)
14906: Qoff - the character used to represent that a bubble was
14907: left blank
14908: PaperID - if the scanning process generates a unique number for each
14909: sheet scanned the column that this ID number starts in
14910: PaperIDlength - number of columns that comprise the unique ID number
14911: for the sheet of paper
14912: FirstName - column that the first name starts in
14913: FirstNameLength - number of columns that the first name spans
14914: LastName - column that the last name starts in
14915: LastNameLength - number of columns that the last name spans
14916: BubblesPerRow - number of bubbles available in each row used to
14917: bubble an answer. (If not specified, 10 assumed).
14918:
14919:
14920: =item *
14921:
14922: get_scantronformat_file($cdom)
14923:
14924: $cdom - the course's domain (optional); if not supplied, uses
14925: domain for current $env{'request.course.id'}.
14926:
14927: Returns an array containing lines from the scantron format file for
14928: the domain of the course.
14929:
14930: If a url for a custom.tab file is listed in domain's configuration.db,
14931: lines are from this file.
14932:
14933: Otherwise, if a default.tab has been published in RES space by the
14934: domainconfig user, lines are from this file.
14935:
14936: Otherwise, fall back to getting lines from the legacy file on the
14937: local server: /home/httpd/lonTabs/default_scantronformat.tab
14938:
14939: =back
14940:
1.243 albertel 14941: =head2 Resource Subroutines
14942:
14943: =over 4
1.191 harris41 14944:
14945: =item *
14946:
1.243 albertel 14947: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14948:
14949: =item *
14950:
1.243 albertel 14951: repcopy($filename) : subscribes to the requested file, and attempts to
14952: replicate from the owning library server, Might return
1.607 raeburn 14953: 'unavailable', 'not_found', 'forbidden', 'ok', or
14954: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14955: resource. Expects the local filesystem pathname
14956: (/home/httpd/html/res/....)
14957:
14958: =back
14959:
14960: =head2 Resource Information
14961:
14962: =over 4
1.191 harris41 14963:
14964: =item *
14965:
1.1172.2.28 raeburn 14966: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14967: and returns the value of a variety of different possible values,
14968: $varname should be a request string, and the other parameters can be
14969: used to specify who and what one is asking about. Ordinarily, $cid
14970: does not need to be specified, as it is retrived from
14971: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14972: within lonuserstate::loadmap() when initializing a course, before
14973: $env{'request.course.id'} has been set, so it needs to be provided
14974: in that one case.
1.243 albertel 14975:
14976: Possible values for $varname are environment.lastname (or other item
14977: from the envirnment hash), user.name (or someother aspect about the
14978: user), resource.0.maxtries (or some other part and parameter of a
14979: resource)
1.204 albertel 14980:
14981: =item *
14982:
1.243 albertel 14983: directcondval($number) : get current value of a condition; reads from a state
14984: string
1.204 albertel 14985:
14986: =item *
14987:
1.243 albertel 14988: condval($condidx) : value of condition index based on state
1.204 albertel 14989:
14990: =item *
14991:
1.243 albertel 14992: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14993: resource's metadata, $what should be either a specific key, or either
14994: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14995: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14996:
14997: this function automatically caches all requests
1.191 harris41 14998:
14999: =item *
15000:
1.243 albertel 15001: metadata_query($query,$custom,$customshow) : make a metadata query against the
15002: network of library servers; returns file handle of where SQL and regex results
15003: will be stored for query
1.191 harris41 15004:
15005: =item *
15006:
1.1172.2.66 raeburn 15007: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15008: return symbolic list entry (all arguments optional).
15009:
15010: Args: filename is the filename (including path) for the file for which a symb
15011: is required; donotrecurse, if true will prevent calls to allowed() being made
15012: to check access status if more than one resource was found in the bighash
15013: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15014: a randompick); ignorecachednull, if true will prevent a symb of '' being
15015: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15016: cause possible symbs to be checked to determine if they are subject to content
15017: blocking, if so they will not be included as possible symbs; possibles is a
15018: ref to a hash, which, as a side effect, will be populated with all possible
15019: symbs (content blocking not tested).
15020:
1.243 albertel 15021: returns the data handle
1.191 harris41 15022:
15023: =item *
15024:
1.1172.2.17 raeburn 15025: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 15026: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15027: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 15028: on failure, user must be in a course, as it assumes the existence of
15029: the course initial hash, and uses $env('request.course.id'}. The third
15030: arg is an optional reference to a scalar. If this arg is passed in the
15031: call to symbverify, it will be set to 1 if the symb has been set to be
15032: encrypted; otherwise it will be null.
1.243 albertel 15033:
1.191 harris41 15034: =item *
15035:
1.243 albertel 15036: symbclean($symb) : removes versions numbers from a symb, returns the
15037: cleaned symb
1.191 harris41 15038:
15039: =item *
15040:
1.243 albertel 15041: is_on_map($uri) : checks if the $uri is somewhere on the current
15042: course map, user must be in a course for it to work.
1.191 harris41 15043:
15044: =item *
15045:
1.243 albertel 15046: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15047:
15048: =item *
15049:
1.243 albertel 15050: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15051: a random seed, all arguments are optional, if they aren't sent it uses the
15052: environment to derive them. Note: if symb isn't sent and it can't get one
15053: from &symbread it will use the current time as its return value
1.191 harris41 15054:
15055: =item *
15056:
1.243 albertel 15057: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15058: unfakeable, receipt
1.191 harris41 15059:
15060: =item *
15061:
1.620 albertel 15062: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15063:
15064: =item *
15065:
1.243 albertel 15066: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15067:
15068: =item *
15069:
1.243 albertel 15070: 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 15071:
15072: =item *
15073:
1.243 albertel 15074: 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 15075:
15076: =item *
15077:
1.243 albertel 15078: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15079:
15080: =item *
15081:
1.243 albertel 15082: devalidate($symb) : devalidate temporary spreadsheet calculations,
15083: forcing spreadsheet to reevaluate the resource scores next time.
15084:
1.1172.2.13 raeburn 15085: =item *
15086:
15087: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15088: when viewing in course context.
15089:
15090: input: six args -- filename (decluttered), course number, course domain,
15091: url, symb (if registered) and group (if this is a
15092: group item -- e.g., bulletin board, group page etc.).
15093:
15094: output: array of five scalars --
15095: $cfile -- url for file editing if editable on current server
15096: $home -- homeserver of resource (i.e., for author if published,
15097: or course if uploaded.).
15098: $switchserver -- 1 if server switch will be needed.
15099: $forceedit -- 1 if icon/link should be to go to edit mode
15100: $forceview -- 1 if icon/link should be to go to view mode
15101:
15102: =item *
15103:
15104: is_course_upload($file,$cnum,$cdom)
15105:
15106: Used in course context to determine if current file was uploaded to
15107: the course (i.e., would be found in /userfiles/docs on the course's
15108: homeserver.
15109:
15110: input: 3 args -- filename (decluttered), course number and course domain.
15111: output: boolean -- 1 if file was uploaded.
15112:
1.243 albertel 15113: =back
15114:
15115: =head2 Storing/Retreiving Data
15116:
15117: =over 4
1.191 harris41 15118:
15119: =item *
15120:
1.1172.2.64 raeburn 15121: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15122: permanently for this url; hashref needs to be given and should be a \%hashname;
15123: the remaining args aren't required and if they aren't passed or are '' they will
15124: be derived from the env (with the exception of $laststore, which is an
15125: optional arg used when a user's submission is stored in grading).
15126: $laststore is $version=$timestamp, where $version is the most recent version
15127: number retrieved for the corresponding $symb in the $namespace db file, and
15128: $timestamp is the timestamp for that transaction (UNIX time).
15129: $laststore is currently only passed when cstore() is called by
15130: structuretags::finalize_storage().
1.191 harris41 15131:
15132: =item *
15133:
1.1172.2.64 raeburn 15134: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15135: but uses critical subroutine
1.191 harris41 15136:
15137: =item *
15138:
1.243 albertel 15139: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15140: all args are optional
1.191 harris41 15141:
15142: =item *
15143:
1.717 albertel 15144: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15145: dumps the complete (or key matching regexp) namespace into a hash
15146: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15147: normally &store()ed into
15148:
15149: $range should be either an integer '100' (give me the first 100
15150: matching records)
15151: or be two integers sperated by a - with no spaces
15152: '30-50' (give me the 30th through the 50th matching
15153: records)
15154:
15155:
15156: =item *
15157:
1.1172.2.59 raeburn 15158: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15159: replaces a &store() version of data with a replacement set of data
15160: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 15161: reference. If $tolog is true, the transaction is logged in the courselog
15162: with an action=PUTSTORE.
1.717 albertel 15163:
15164: =item *
15165:
1.243 albertel 15166: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15167: works very similar to store/cstore, but all data is stored in a
15168: temporary location and can be reset using tmpreset, $storehash should
15169: be a hash reference, returns nothing on success
1.191 harris41 15170:
15171: =item *
15172:
1.243 albertel 15173: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15174: similar to restore, but all data is stored in a temporary location and
15175: can be reset using tmpreset. Returns a hash of values on success,
15176: error string otherwise.
1.191 harris41 15177:
15178: =item *
15179:
1.243 albertel 15180: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15181: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15182:
15183: =item *
15184:
1.243 albertel 15185: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15186: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15187:
15188: =item *
15189:
1.243 albertel 15190: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15191: namesp ($udom and $uname are optional)
1.191 harris41 15192:
15193: =item *
15194:
1.702 albertel 15195: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15196: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15197: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15198:
1.702 albertel 15199: $range should be either an integer '100' (give me the first 100
15200: matching records)
15201: or be two integers sperated by a - with no spaces
15202: '30-50' (give me the 30th through the 50th matching
15203: records)
1.449 matthew 15204: =item *
15205:
15206: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15207: $store can be a scalar, an array reference, or if the amount to be
15208: incremented is > 1, a hash reference.
15209:
15210: ($udom and $uname are optional)
1.191 harris41 15211:
15212: =item *
15213:
1.243 albertel 15214: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15215: ($udom and $uname are optional)
1.191 harris41 15216:
15217: =item *
15218:
1.243 albertel 15219: cput($namespace,$storehash,$udom,$uname) : critical put
15220: ($udom and $uname are optional)
1.191 harris41 15221:
15222: =item *
15223:
1.748 albertel 15224: newput($namespace,$storehash,$udom,$uname) :
15225:
15226: Attempts to store the items in the $storehash, but only if they don't
15227: currently exist, if this succeeds you can be certain that you have
15228: successfully created a new key value pair in the $namespace db.
15229:
15230:
15231: Args:
15232: $namespace: name of database to store values to
15233: $storehash: hashref to store to the db
15234: $udom: (optional) domain of user containing the db
15235: $uname: (optional) name of user caontaining the db
15236:
15237: Returns:
15238: 'ok' -> succeeded in storing all keys of $storehash
15239: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15240: least <key> already existed in the db (other
15241: requested keys may also already exist)
1.967 bisitz 15242: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15243: 'con_lost' -> unable to contact request server
15244: 'refused' -> action was not allowed by remote machine
15245:
15246:
15247: =item *
15248:
1.243 albertel 15249: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15250: reference filled in from namesp (encrypts the return communication)
15251: ($udom and $uname are optional)
1.191 harris41 15252:
15253: =item *
15254:
1.243 albertel 15255: log($udom,$name,$home,$message) : write to permanent log for user; use
15256: critical subroutine
15257:
1.806 raeburn 15258: =item *
15259:
1.860 raeburn 15260: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15261: array reference filled in from namespace found in domain level on either
15262: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15263:
15264: =item *
15265:
1.860 raeburn 15266: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15267: domain level either on specified domain server ($uhome) or primary domain
15268: server ($udom and $uhome are optional)
1.806 raeburn 15269:
1.943 raeburn 15270: =item *
15271:
1.1172.2.35 raeburn 15272: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15273: for: authentication, language, quotas, timezone, date locale, and portal URL in
15274: the target domain.
15275:
15276: May also include additional key => value pairs for the following groups:
15277:
15278: =over
15279:
15280: =item
15281: disk quotas (MB allocated by default to portfolios and authoring spaces).
15282:
15283: =over
15284:
15285: =item defaultquota, authorquota
15286:
15287: =back
15288:
15289: =item
15290: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15291: portfolio for users).
15292:
15293: =over
15294:
15295: =item
15296: aboutme, blog, webdav, portfolio
15297:
15298: =back
15299:
15300: =item
15301: requestcourses: ability to request courses, and how requests are processed.
15302:
15303: =over
15304:
15305: =item
1.1172.2.37 raeburn 15306: official, unofficial, community, textbook
1.1172.2.35 raeburn 15307:
15308: =back
15309:
15310: =item
15311: inststatus: types of institutional affiliation, and order in which they are displayed.
15312:
15313: =over
15314:
15315: =item
1.1172.2.44 raeburn 15316: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 15317:
15318: =back
15319:
15320: =item
15321: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15322: for course's uploaded content.
15323:
15324: =over
15325:
15326: =item
1.1172.2.68 raeburn 15327: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15328: communityquota, textbookquota
1.1172.2.35 raeburn 15329:
15330: =back
15331:
15332: =item
15333: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15334: on your servers.
15335:
15336: =over
15337:
15338: =item
15339: remotesessions, hostedsessions
15340:
15341: =back
15342:
15343: =back
15344:
15345: In cases where a domain coordinator has never used the "Set Domain Configuration"
15346: utility to create a configuration.db file on a domain's primary library server
15347: only the following domain defaults: auth_def, auth_arg_def, lang_def
15348: -- corresponding values are authentication type (internal, krb4, krb5,
15349: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15350: will be available. Values are retrieved from cache (if current), unless the
15351: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15352: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15353:
15354: Typical usage:
1.943 raeburn 15355:
1.1172.2.35 raeburn 15356: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15357:
1.243 albertel 15358: =back
15359:
15360: =head2 Network Status Functions
15361:
15362: =over 4
1.191 harris41 15363:
15364: =item *
15365:
1.1137 raeburn 15366: dirlist() : return directory list based on URI (first arg).
15367:
15368: Inputs: 1 required, 5 optional.
15369:
15370: =over
15371:
15372: =item
15373: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15374:
15375: =item
15376: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15377:
15378: =item
15379: $username - username of user/course to be listed. Extracted from $uri if absent.
15380:
15381: =item
15382: $getpropath - boolean: 1 if prepend path using &propath().
15383:
15384: =item
15385: $getuserdir - boolean: 1 if prepend path for "userfiles".
15386:
15387: =item
15388: $alternateRoot - path to prepend in place of path from $uri.
15389:
15390: =back
15391:
15392: Returns: Array of up to two items.
15393:
15394: =over
15395:
15396: a reference to an array of files/subdirectories
15397:
15398: =over
15399:
15400: Each element in the array of files/subdirectories is a & separated list of
15401: item name and the result of running stat on the item. If dirlist was requested
15402: for a file instead of a directory, the item name will be ''. For a directory
15403: listing, if the item is a metadata file, the element will end &N&M
15404: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15405: default copyright set (1).
15406:
15407: =back
15408:
15409: a scalar containing error condition (if encountered).
15410:
15411: =over
15412:
15413: =item
15414: no_host (no homeserver identified for $username:$domain).
15415:
15416: =item
15417: no_such_host (server contacted for listing not identified as valid host).
15418:
15419: =item
15420: con_lost (connection to remote server failed).
15421:
15422: =item
15423: refused (invalid $username:$domain received on lond side).
15424:
15425: =item
15426: no_such_dir (directory at specified path on lond side does not exist).
15427:
15428: =item
15429: empty (directory at specified path on lond side is empty).
15430:
15431: =over
15432:
15433: This is currently not encountered because the &ls3, &ls2,
15434: &ls (_handler) routines on the lond side do not filter out
15435: . and .. from a directory listing.
15436:
15437: =back
15438:
15439: =back
15440:
15441: =back
1.191 harris41 15442:
15443: =item *
15444:
1.243 albertel 15445: spareserver() : find server with least workload from spare.tab
15446:
1.986 foxr 15447:
15448: =item *
15449:
15450: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15451: if there is no corresponding loncapa host.
15452:
1.243 albertel 15453: =back
15454:
1.986 foxr 15455:
1.243 albertel 15456: =head2 Apache Request
15457:
15458: =over 4
1.191 harris41 15459:
15460: =item *
15461:
1.243 albertel 15462: ssi($url,%hash) : server side include, does a complete request cycle on url to
15463: localhost, posts hash
15464:
15465: =back
15466:
15467: =head2 Data to String to Data
15468:
15469: =over 4
1.191 harris41 15470:
15471: =item *
15472:
1.243 albertel 15473: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15474: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15475:
15476: =item *
15477:
1.243 albertel 15478: hashref2str($hashref) : convert a hashref into a string complete with
15479: escaping and '=' and '&' separators, supports elements that are
15480: arrayrefs and hashrefs
1.191 harris41 15481:
15482: =item *
15483:
1.243 albertel 15484: arrayref2str($arrayref) : convert an arrayref into a string complete
15485: with escaping and '&' separators, supports elements that are arrayrefs
15486: and hashrefs
1.191 harris41 15487:
15488: =item *
15489:
1.243 albertel 15490: str2hash($string) : convert string to hash using unescaping and
15491: splitting on '=' and '&', supports elements that are arrayrefs and
15492: hashrefs
1.191 harris41 15493:
15494: =item *
15495:
1.243 albertel 15496: str2array($string) : convert string to hash using unescaping and
15497: splitting on '&', supports elements that are arrayrefs and hashrefs
15498:
15499: =back
15500:
15501: =head2 Logging Routines
15502:
15503:
15504: These routines allow one to make log messages in the lonnet.log and
15505: lonnet.perm logfiles.
1.191 harris41 15506:
1.1119 foxr 15507: =over 4
15508:
1.191 harris41 15509: =item *
15510:
1.243 albertel 15511: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15512:
15513: =item *
15514:
1.243 albertel 15515: logthis() : append message to the normal lonnet.log file, it gets
15516: preiodically rolled over and deleted.
1.191 harris41 15517:
15518: =item *
15519:
1.243 albertel 15520: logperm() : append a permanent message to lonnet.perm.log, this log
15521: file never gets deleted by any automated portion of the system, only
15522: messages of critical importance should go in here.
15523:
1.1119 foxr 15524:
1.243 albertel 15525: =back
15526:
15527: =head2 General File Helper Routines
15528:
15529: =over 4
1.191 harris41 15530:
15531: =item *
15532:
1.481 raeburn 15533: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15534: (a) files in /uploaded
15535: (i) If a local copy of the file exists -
15536: compares modification date of local copy with last-modified date for
15537: definitive version stored on home server for course. If local copy is
15538: stale, requests a new version from the home server and stores it.
15539: If the original has been removed from the home server, then local copy
15540: is unlinked.
15541: (ii) If local copy does not exist -
15542: requests the file from the home server and stores it.
15543:
15544: If $caller is 'uploadrep':
15545: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15546: for request for files originally uploaded via DOCS.
15547: - returns 'ok' if fresh local copy now available, -1 otherwise.
15548:
15549: Otherwise:
15550: This indicates a call from the content generation phase of the request.
15551: - returns the entire contents of the file or -1.
15552:
15553: (b) files in /res
15554: - returns the entire contents of a file or -1;
15555: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 15556:
1.712 albertel 15557:
15558: =item *
15559:
15560: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15561: reference
15562:
15563: returns either a stat() list of data about the file or an empty list
15564: if the file doesn't exist or couldn't find out about it (connection
15565: problems or user unknown)
15566:
1.191 harris41 15567: =item *
15568:
1.243 albertel 15569: filelocation($dir,$file) : returns file system location of a file
15570: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15571: directory that relative $file lookups are to looked in ($dir of /a/dir
15572: and a file of ../bob will become /a/bob)
1.191 harris41 15573:
15574: =item *
15575:
15576: hreflocation($dir,$file) : returns file system location or a URL; same as
15577: filelocation except for hrefs
15578:
15579: =item *
15580:
1.1172.2.49 raeburn 15581: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15582: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15583:
1.243 albertel 15584: =back
15585:
1.608 albertel 15586: =head2 Usererfile file routines (/uploaded*)
15587:
15588: =over 4
15589:
15590: =item *
15591:
15592: userfileupload(): main rotine for putting a file in a user or course's
15593: filespace, arguments are,
15594:
1.620 albertel 15595: formname - required - this is the name of the element in $env where the
1.608 albertel 15596: filename, and the contents of the file to create/modifed exist
1.620 albertel 15597: the filename is in $env{'form.'.$formname.'.filename'} and the
15598: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15599: context - if coursedoc, store the file in the course of the active role
15600: of the current user;
15601: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15602: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15603: subdir - required - subdirectory to put the file in under ../userfiles/
15604: if undefined, it will be placed in "unknown"
15605:
15606: (This routine calls clean_filename() to remove any dangerous
15607: characters from the filename, and then calls finuserfileupload() to
15608: complete the transaction)
15609:
15610: returns either the url of the uploaded file (/uploaded/....) if successful
15611: and /adm/notfound.html if unsuccessful
15612:
15613: =item *
15614:
15615: clean_filename(): routine for cleaing a filename up for storage in
15616: userfile space, argument is:
15617:
15618: filename - proposed filename
15619:
15620: returns: the new clean filename
15621:
15622: =item *
15623:
1.1090 raeburn 15624: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15625: userspace, probably shouldn't be called directly
15626:
15627: docuname: username or courseid of destination for the file
15628: docudom: domain of user/course of destination for the file
15629: formname: same as for userfileupload()
1.1090 raeburn 15630: fname: filename (including subdirectories) for the file
15631: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 15632: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 15633: allfiles: reference to hash used to store objects found by parser
15634: codebase: reference to hash used for codebases of java objects found by parser
15635: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15636: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15637: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15638: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15639: context: if 'overwrite', will move the uploaded file from its temporary location to
15640: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15641: mimetype: reference to scalar to accommodate mime type determined
15642: from File::MMagic if $parser = parse.
1.608 albertel 15643:
15644: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15645: and /adm/notfound.html if unsuccessful (or an error message if context
15646: was 'overwrite').
15647:
1.608 albertel 15648:
15649: =item *
15650:
15651: renameuserfile(): renames an existing userfile to a new name
15652:
15653: Args:
15654: docuname: username or courseid of destination for the file
15655: docudom: domain of user/course of destination for the file
15656: old: current file name (including any subdirs under userfiles)
15657: new: desired file name (including any subdirs under userfiles)
15658:
15659: =item *
15660:
15661: mkdiruserfile(): creates a directory is a userfiles dir
15662:
15663: Args:
15664: docuname: username or courseid of destination for the file
15665: docudom: domain of user/course of destination for the file
15666: dir: dir to create (including any subdirs under userfiles)
15667:
15668: =item *
15669:
15670: removeuserfile(): removes a file that exists in userfiles
15671:
15672: Args:
15673: docuname: username or courseid of destination for the file
15674: docudom: domain of user/course of destination for the file
15675: fname: filname to delete (including any subdirs under userfiles)
15676:
15677: =item *
15678:
15679: removeuploadedurl(): convience function for removeuserfile()
15680:
15681: Args:
15682: url: a full /uploaded/... url to delete
15683:
1.747 albertel 15684: =item *
15685:
15686: get_portfile_permissions():
15687: Args:
15688: domain: domain of user or course contain the portfolio files
15689: user: name of user or num of course contain the portfolio files
15690: Returns:
15691: hashref of a dump of the proper file_permissions.db
15692:
15693:
15694: =item *
15695:
15696: get_access_controls():
15697:
15698: Args:
15699: current_permissions: the hash ref returned from get_portfile_permissions()
15700: group: (optional) the group you want the files associated with
15701: file: (optional) the file you want access info on
15702:
15703: Returns:
1.749 raeburn 15704: a hash (keys are file names) of hashes containing
15705: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15706: values are XML containing access control settings (see below)
1.747 albertel 15707:
15708: Internal notes:
15709:
1.749 raeburn 15710: access controls are stored in file_permissions.db as key=value pairs.
15711: key -> path to file/file_name\0uniqueID:scope_end_start
15712: where scope -> public,guest,course,group,domains or users.
15713: end -> UNIX time for end of access (0 -> no end date)
15714: start -> UNIX time for start of access
15715:
15716: value -> XML description of access control
15717: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15718: <start></start>
15719: <end></end>
15720:
15721: <password></password> for scope type = guest
15722:
15723: <domain></domain> for scope type = course or group
15724: <number></number>
15725: <roles id="">
15726: <role></role>
15727: <access></access>
15728: <section></section>
15729: <group></group>
15730: </roles>
15731:
15732: <dom></dom> for scope type = domains
15733:
15734: <users> for scope type = users
15735: <user>
15736: <uname></uname>
15737: <udom></udom>
15738: </user>
15739: </users>
15740: </scope>
15741:
15742: Access data is also aggregated for each file in an additional key=value pair:
15743: key -> path to file/file_name\0accesscontrol
15744: value -> reference to hash
15745: hash contains key = value pairs
15746: where key = uniqueID:scope_end_start
15747: value = UNIX time record was last updated
15748:
15749: Used to improve speed of look-ups of access controls for each file.
15750:
15751: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15752:
1.1172.2.13 raeburn 15753: =item *
15754:
1.749 raeburn 15755: modify_access_controls():
15756:
15757: Modifies access controls for a portfolio file
15758: Args
15759: 1. file name
15760: 2. reference to hash of required changes,
15761: 3. domain
15762: 4. username
15763: where domain,username are the domain of the portfolio owner
15764: (either a user or a course)
15765:
15766: Returns:
15767: 1. result of additions or updates ('ok' or 'error', with error message).
15768: 2. result of deletions ('ok' or 'error', with error message).
15769: 3. reference to hash of any new or updated access controls.
15770: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15771: key = integer (inbound ID)
1.1172.2.13 raeburn 15772: value = uniqueID
15773:
15774: =item *
15775:
15776: get_timebased_id():
15777:
15778: Attempts to get a unique timestamp-based suffix for use with items added to a
15779: course via the Course Editor (e.g., folders, composite pages,
15780: group bulletin boards).
15781:
15782: Args: (first three required; six others optional)
15783:
15784: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15785: docssequence, or name of group
15786:
15787: 2. keyid (alphanumeric): name of temporary locking key in hash,
15788: e.g., num, boardids
15789:
15790: 3. namespace: name of gdbm file used to store suffixes already assigned;
15791: file will be named nohist_namespace.db
15792:
15793: 4. cdom: domain of course; default is current course domain from %env
15794:
15795: 5. cnum: course number; default is current course number from %env
15796:
15797: 6. idtype: set to concat if an additional digit is to be appended to the
15798: unix timestamp to form the suffix, if the plain timestamp is already
15799: in use. Default is to not do this, but simply increment the unix
15800: timestamp by 1 until a unique key is obtained.
15801:
15802: 7. who: holder of locking key; defaults to user:domain for user.
15803:
15804: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15805: retrying); default is 3.
15806:
15807: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15808:
15809: Returns:
15810:
15811: 1. suffix obtained (numeric)
15812:
15813: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15814:
15815: 3. error: contains (localized) error message if an error occurred.
15816:
1.747 albertel 15817:
1.608 albertel 15818: =back
15819:
1.243 albertel 15820: =head2 HTTP Helper Routines
15821:
15822: =over 4
15823:
1.191 harris41 15824: =item *
15825:
15826: escape() : unpack non-word characters into CGI-compatible hex codes
15827:
15828: =item *
15829:
15830: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15831:
1.243 albertel 15832: =back
15833:
15834: =head1 PRIVATE SUBROUTINES
15835:
15836: =head2 Underlying communication routines (Shouldn't call)
15837:
15838: =over 4
15839:
15840: =item *
15841:
15842: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15843:
15844: =item *
15845:
15846: reply() : uses subreply to send a message to remote machine, logs all failures
15847:
15848: =item *
15849:
15850: critical() : passes a critical message to another server; if cannot
15851: get through then place message in connection buffer directory and
15852: returns con_delayed, if incapable of saving message, returns
15853: con_failed
15854:
15855: =item *
15856:
15857: reconlonc() : tries to reconnect lonc client processes.
15858:
15859: =back
15860:
15861: =head2 Resource Access Logging
15862:
15863: =over 4
15864:
15865: =item *
15866:
15867: flushcourselogs() : flush (save) buffer logs and access logs
15868:
15869: =item *
15870:
15871: courselog($what) : save message for course in hash
15872:
15873: =item *
15874:
15875: courseacclog($what) : save message for course using &courselog(). Perform
15876: special processing for specific resource types (problems, exams, quizzes, etc).
15877:
1.191 harris41 15878: =item *
15879:
15880: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15881: as a PerlChildExitHandler
1.243 albertel 15882:
15883: =back
15884:
15885: =head2 Other
15886:
15887: =over 4
15888:
15889: =item *
15890:
15891: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15892:
15893: =back
15894:
15895: =cut
1.877 foxr 15896:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>