Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.93.4.12
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.93.4 12(raebu 4:19): # $Id: lonnet.pm,v 1.1172.2.93.4.11 2018/05/02 20:33:18 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1172.2.36 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.1172.2.79 raeburn 92: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.1172.2.79 raeburn 105: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
1.1172.2.93.4 7(raebur 145:7): open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.1172.2.93.4 7(raebur 157:7): if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.1172.2.93.4 7(raebur 170:7): if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
1.1172.2.35 raeburn 355: my ($lonhost,$cachekeys) = @_;
356: my $items;
357: return unless (ref($cachekeys) eq 'ARRAY');
358: my $cachestr = join('&',@{$cachekeys});
359: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 360: }
361:
1.1 albertel 362: # -------------------------------------------------- Non-critical communication
363: sub subreply {
364: my ($cmd,$server)=@_;
1.838 albertel 365: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 366: #
367: # With loncnew process trimming, there's a timing hole between lonc server
368: # process exit and the master server picking up the listen on the AF_UNIX
369: # socket. In that time interval, a lock file will exist:
370:
371: my $lockfile=$peerfile.".lock";
372: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 373: sleep(0.1);
1.549 foxr 374: }
375: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 376: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 377: #
1.550 foxr 378: # We'll give the connection a few tries before abandoning it. If
379: # connection is not possible, we'll con_lost back to the client.
380: #
381: my $client;
382: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
383: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
384: Type => SOCK_STREAM,
385: Timeout => 10);
1.869 albertel 386: if ($client) {
1.550 foxr 387: last; # Connected!
1.850 albertel 388: } else {
1.853 albertel 389: &create_connection(&hostname($server),$server);
1.550 foxr 390: }
1.1172.2.79 raeburn 391: sleep(0.1); # Try again later if failed connection.
1.550 foxr 392: }
393: my $answer;
394: if ($client) {
1.704 albertel 395: print $client "sethost:$server:$cmd\n";
1.550 foxr 396: $answer=<$client>;
397: if (!$answer) { $answer="con_lost"; }
398: chomp($answer);
399: } else {
400: $answer = 'con_lost'; # Failed connection.
401: }
1.1 albertel 402: return $answer;
403: }
404:
405: sub reply {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 408: my $answer=subreply($cmd,$server);
1.65 www 409: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 410: &logthis("<font color=\"blue\">WARNING:".
1.12 www 411: " $cmd to $server returned $answer</font>");
412: }
1.1 albertel 413: return $answer;
414: }
415:
416: # ----------------------------------------------------------- Send USR1 to lonc
417:
418: sub reconlonc {
1.891 albertel 419: my ($lonid) = @_;
420: if ($lonid) {
1.1172.2.72 raeburn 421: my $hostname = &hostname($lonid);
1.891 albertel 422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.93.4 7(raebur 439:7): if (open(my $fh,"<",$loncfile)) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 467: &reconlonc($server);
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
1.1172.2.93.4 7(raebur 479:7): if (open($dfh,">",$dfilename)) {
1.448 albertel 480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
1.1172.2.79 raeburn 484: sleep 1;
1.1 albertel 485: my $wcmd='';
486: {
1.448 albertel 487: my $dfh;
1.1172.2.93.4 7(raebur 488:7): if (open($dfh,"<",$dfilename)) {
1.448 albertel 489: $wcmd=<$dfh>;
490: close($dfh);
491: }
1.1 albertel 492: }
493: chomp($wcmd);
1.7 www 494: if ($wcmd eq $cmd) {
1.672 albertel 495: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 496: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 497: &logperm("D:$server:$cmd");
498: return 'con_delayed';
499: } else {
1.672 albertel 500: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 501: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 502: &logperm("F:$server:$cmd");
503: return 'con_failed';
504: }
505: }
506: }
507: return $answer;
1.405 albertel 508: }
509:
1.755 albertel 510: # ------------------------------------------- check if return value is an error
511:
512: sub error {
513: my ($result) = @_;
1.756 albertel 514: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 515: if ($2 == 2) { return undef; }
516: return $1;
517: }
518: return undef;
519: }
520:
1.783 albertel 521: sub convert_and_load_session_env {
522: my ($lonidsdir,$handle)=@_;
523: my @profile;
524: {
1.917 albertel 525: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
526: if (!$opened) {
1.915 albertel 527: return 0;
528: }
1.783 albertel 529: flock($idf,LOCK_SH);
530: @profile=<$idf>;
531: close($idf);
532: }
533: my %temp_env;
534: foreach my $line (@profile) {
1.786 albertel 535: if ($line !~ m/=/) {
536: return 0;
537: }
1.783 albertel 538: chomp($line);
539: my ($envname,$envvalue)=split(/=/,$line,2);
540: $temp_env{&unescape($envname)} = &unescape($envvalue);
541: }
542: unlink("$lonidsdir/$handle.id");
543: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
544: 0640)) {
545: %disk_env = %temp_env;
546: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
547: untie(%disk_env);
548: }
1.786 albertel 549: return 1;
1.783 albertel 550: }
551:
1.374 www 552: # ------------------------------------------- Transfer profile into environment
1.780 albertel 553: my $env_loaded;
554: sub transfer_profile_to_env {
1.788 albertel 555: my ($lonidsdir,$handle,$force_transfer) = @_;
556: if (!$force_transfer && $env_loaded) { return; }
1.374 www 557:
1.720 albertel 558: if (!defined($lonidsdir)) {
559: $lonidsdir = $perlvar{'lonIDsDir'};
560: }
561: if (!defined($handle)) {
562: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
563: }
564:
1.786 albertel 565: my $convert;
566: {
1.917 albertel 567: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
568: if (!$opened) {
1.915 albertel 569: return;
570: }
1.786 albertel 571: flock($idf,LOCK_SH);
572: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
573: &GDBM_READER(),0640)) {
574: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
575: untie(%disk_env);
576: } else {
577: $convert = 1;
578: }
579: }
580: if ($convert) {
581: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
582: &logthis("Failed to load session, or convert session.");
583: }
1.374 www 584: }
1.783 albertel 585:
1.786 albertel 586: my %remove;
1.783 albertel 587: while ( my $envname = each(%env) ) {
1.433 matthew 588: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
589: if ($time < time-300) {
1.783 albertel 590: $remove{$key}++;
1.433 matthew 591: }
592: }
593: }
1.783 albertel 594:
1.619 albertel 595: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 596: $env_loaded=1;
1.783 albertel 597: foreach my $expired_key (keys(%remove)) {
1.433 matthew 598: &delenv($expired_key);
1.374 www 599: }
1.1 albertel 600: }
601:
1.916 albertel 602: # ---------------------------------------------------- Check for valid session
603: sub check_for_valid_session {
1.1172.2.93.4 3(raebur 604:7): my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.1172.2.93.4 3(raebur 619:7): if (!-e "$lonidsdir/$handle.id") {
620:7): if ((ref($domref)) && ($name eq 'lonID') &&
621:7): ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
622:7): my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
623:7): if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
624:7): $$domref = $possudom;
625:7): }
626:7): }
627:7): return undef;
628:7): }
1.916 albertel 629:
1.917 albertel 630: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
631: return undef if (!$opened);
1.916 albertel 632:
633: flock($idf,LOCK_SH);
634: my %disk_env;
635: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
636: &GDBM_READER(),0640)) {
637: return undef;
638: }
639:
640: if (!defined($disk_env{'user.name'})
641: || !defined($disk_env{'user.domain'})) {
642: return undef;
643: }
1.1172.2.18 raeburn 644:
1.1172.2.36 raeburn 645: if (ref($userhashref) eq 'HASH') {
646: $userhashref->{'name'} = $disk_env{'user.name'};
647: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 648: }
649:
1.916 albertel 650: return $handle;
651: }
652:
1.830 albertel 653: sub timed_flock {
654: my ($file,$lock_type) = @_;
655: my $failed=0;
656: eval {
657: local $SIG{__DIE__}='DEFAULT';
658: local $SIG{ALRM}=sub {
659: $failed=1;
660: die("failed lock");
661: };
662: alarm(13);
663: flock($file,$lock_type);
664: alarm(0);
665: };
666: if ($failed) {
667: return undef;
668: } else {
669: return 1;
670: }
671: }
672:
1.5 www 673: # ---------------------------------------------------------- Append Environment
674:
675: sub appenv {
1.949 raeburn 676: my ($newenv,$roles) = @_;
677: if (ref($newenv) eq 'HASH') {
678: foreach my $key (keys(%{$newenv})) {
679: my $refused = 0;
680: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
681: $refused = 1;
682: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 683: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 684: if (grep(/^\Q$role\E$/,@{$roles})) {
685: $refused = 0;
686: }
687: }
688: }
689: if ($refused) {
690: &logthis("<font color=\"blue\">WARNING: ".
691: "Attempt to modify environment ".$key." to ".$newenv->{$key}
692: .'</font>');
693: delete($newenv->{$key});
694: } else {
695: $env{$key}=$newenv->{$key};
696: }
697: }
1.1172.2.93.4 11(raebu 698:18): my $lonids = $perlvar{'lonIDsDir'};
699:18): if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
700:18): my $opened = open(my $env_file,'+<',$env{'user.environment'});
701:18): if ($opened
702:18): && &timed_flock($env_file,LOCK_EX)
703:18): &&
704:18): tie(my %disk_env,'GDBM_File',$env{'user.environment'},
705:18): (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
706:18): while (my ($key,$value) = each(%{$newenv})) {
707:18): $disk_env{$key} = $value;
708:18): }
709:18): untie(%disk_env);
710:18): }
1.35 www 711: }
1.191 harris41 712: }
1.56 www 713: return 'ok';
714: }
715: # ----------------------------------------------------- Delete from Environment
716:
717: sub delenv {
1.1104 raeburn 718: my ($delthis,$regexp,$roles) = @_;
719: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
720: my $refused = 1;
721: if (ref($roles) eq 'ARRAY') {
722: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
723: if (grep(/^\Q$role\E$/,@{$roles})) {
724: $refused = 0;
725: }
726: }
727: if ($refused) {
728: &logthis("<font color=\"blue\">WARNING: ".
729: "Attempt to delete from environment ".$delthis);
730: return 'error';
731: }
1.56 www 732: }
1.917 albertel 733: my $opened = open(my $env_file,'+<',$env{'user.environment'});
734: if ($opened
1.915 albertel 735: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 736: &&
737: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
738: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 739: foreach my $key (keys(%disk_env)) {
1.987 raeburn 740: if ($regexp) {
741: if ($key=~/^$delthis/) {
742: delete($env{$key});
743: delete($disk_env{$key});
744: }
745: } else {
746: if ($key=~/^\Q$delthis\E/) {
747: delete($env{$key});
748: delete($disk_env{$key});
749: }
750: }
1.448 albertel 751: }
1.783 albertel 752: untie(%disk_env);
1.5 www 753: }
754: return 'ok';
1.369 albertel 755: }
756:
1.790 albertel 757: sub get_env_multiple {
758: my ($name) = @_;
759: my @values;
760: if (defined($env{$name})) {
761: # exists is it an array
762: if (ref($env{$name})) {
763: @values=@{ $env{$name} };
764: } else {
765: $values[0]=$env{$name};
766: }
767: }
768: return(@values);
769: }
770:
1.958 www 771: # ------------------------------------------------------------------- Locking
772:
773: sub set_lock {
774: my ($text)=@_;
775: $locknum++;
776: my $id=$$.'-'.$locknum;
777: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
778: 'session.lock.'.$id => $text});
779: return $id;
780: }
781:
782: sub get_locks {
783: my $num=0;
784: my %texts=();
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if ($lock=~/\w/) {
787: $num++;
788: $texts{$lock}=$env{'session.lock.'.$lock};
789: }
790: }
791: return ($num,%texts);
792: }
793:
794: sub remove_lock {
795: my ($id)=@_;
796: my $newlocks='';
797: foreach my $lock (split(/\,/,$env{'session.locks'})) {
798: if (($lock=~/\w/) && ($lock ne $id)) {
799: $newlocks.=','.$lock;
800: }
801: }
802: &appenv({'session.locks' => $newlocks});
803: &delenv('session.lock.'.$id);
804: }
805:
806: sub remove_all_locks {
807: my $activelocks=$env{'session.locks'};
808: foreach my $lock (split(/\,/,$env{'session.locks'})) {
809: if ($lock=~/\w/) {
810: &remove_lock($lock);
811: }
812: }
813: }
814:
815:
1.369 albertel 816: # ------------------------------------------ Find out current server userload
817: sub userload {
818: my $numusers=0;
819: {
820: opendir(LONIDS,$perlvar{'lonIDsDir'});
821: my $filename;
822: my $curtime=time;
823: while ($filename=readdir(LONIDS)) {
1.925 albertel 824: next if ($filename eq '.' || $filename eq '..');
825: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 826: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 827: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 828: }
829: closedir(LONIDS);
830: }
831: my $userloadpercent=0;
832: my $maxuserload=$perlvar{'lonUserLoadLim'};
833: if ($maxuserload) {
1.371 albertel 834: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 835: }
1.372 albertel 836: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 837: return $userloadpercent;
1.283 www 838: }
839:
1.1 albertel 840: # ------------------------------ Find server with least workload from spare.tab
1.11 www 841:
1.1 albertel 842: sub spareserver {
1.1083 raeburn 843: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 844: my $spare_server;
1.370 albertel 845: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 846: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
847: : $userloadpercent;
1.1083 raeburn 848: my ($uint_dom,$remotesessions);
849: if (($udom ne '') && (&domain($udom) ne '')) {
850: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
851: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
852: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
853: $remotesessions = $udomdefaults{'remotesessions'};
854: }
1.1123 raeburn 855: my $spareshash = &this_host_spares($udom);
856: if (ref($spareshash) eq 'HASH') {
857: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
858: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 859: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
860: $try_server));
1.1123 raeburn 861: ($spare_server, $lowest_load) =
862: &compare_server_load($try_server, $spare_server, $lowest_load);
863: }
1.1083 raeburn 864: }
1.784 albertel 865:
1.1123 raeburn 866: my $found_server = ($spare_server ne '' && $lowest_load < 100);
867:
868: if (!$found_server) {
869: if (ref($spareshash->{'default'}) eq 'ARRAY') {
870: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 871: next unless (&spare_can_host($udom,$uint_dom,
872: $remotesessions,$try_server));
1.1123 raeburn 873: ($spare_server, $lowest_load) =
874: &compare_server_load($try_server, $spare_server, $lowest_load);
875: }
876: }
877: }
1.784 albertel 878: }
879:
880: if (!$want_server_name) {
1.968 raeburn 881: my $protocol = 'http';
882: if ($protocol{$spare_server} eq 'https') {
883: $protocol = $protocol{$spare_server};
884: }
1.1001 raeburn 885: if (defined($spare_server)) {
886: my $hostname = &hostname($spare_server);
1.1083 raeburn 887: if (defined($hostname)) {
1.1001 raeburn 888: $spare_server = $protocol.'://'.$hostname;
889: }
890: }
1.784 albertel 891: }
892: return $spare_server;
893: }
894:
895: sub compare_server_load {
1.1172.2.41 raeburn 896: my ($try_server, $spare_server, $lowest_load, $required) = @_;
897:
898: if ($required) {
899: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
900: my $remoterev = &get_server_loncaparev(undef,$try_server);
901: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
902: if (($major eq '' && $minor eq '') ||
903: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
904: return ($spare_server,$lowest_load);
905: }
906: }
1.784 albertel 907:
908: my $loadans = &reply('load', $try_server);
909: my $userloadans = &reply('userload',$try_server);
910:
911: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 912: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 913: }
914:
915: my $load;
916: if ($loadans =~ /\d/) {
917: if ($userloadans =~ /\d/) {
918: #both are numbers, pick the bigger one
919: $load = ($loadans > $userloadans) ? $loadans
920: : $userloadans;
1.411 albertel 921: } else {
1.784 albertel 922: $load = $loadans;
1.411 albertel 923: }
1.784 albertel 924: } else {
925: $load = $userloadans;
926: }
927:
928: if (($load =~ /\d/) && ($load < $lowest_load)) {
929: $spare_server = $try_server;
930: $lowest_load = $load;
1.370 albertel 931: }
1.784 albertel 932: return ($spare_server,$lowest_load);
1.202 matthew 933: }
1.914 albertel 934:
935: # --------------------------- ask offload servers if user already has a session
936: sub find_existing_session {
937: my ($udom,$uname) = @_;
1.1123 raeburn 938: my $spareshash = &this_host_spares($udom);
939: if (ref($spareshash) eq 'HASH') {
940: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
941: foreach my $try_server (@{ $spareshash->{'primary'} }) {
942: return $try_server if (&has_user_session($try_server, $udom, $uname));
943: }
944: }
945: if (ref($spareshash->{'default'}) eq 'ARRAY') {
946: foreach my $try_server (@{ $spareshash->{'default'} }) {
947: return $try_server if (&has_user_session($try_server, $udom, $uname));
948: }
949: }
1.914 albertel 950: }
951: return;
952: }
953:
954: # -------------------------------- ask if server already has a session for user
955: sub has_user_session {
956: my ($lonid,$udom,$uname) = @_;
957: my $result = &reply(join(':','userhassession',
958: map {&escape($_)} ($udom,$uname)),$lonid);
959: return 1 if ($result eq 'ok');
960:
961: return 0;
962: }
963:
1.1076 raeburn 964: # --------- determine least loaded server in a user's domain which allows login
965:
966: sub choose_server {
1.1172.2.47 raeburn 967: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 968: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 969: my %servers = &get_servers($udom);
1.1076 raeburn 970: my $lowest_load = 30000;
1.1172.2.47 raeburn 971: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
972: if ($skiploadbal) {
973: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
974: unless (defined($cached)) {
975: my $cachetime = 60*60*24;
976: my %domconfig =
977: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
978: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
979: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
980: $cachetime);
981: }
982: }
983: }
1.1076 raeburn 984: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 985: my $loginvia;
1.1172.2.47 raeburn 986: if ($skiploadbal) {
987: if (ref($balancers) eq 'HASH') {
988: next if (exists($balancers->{$lonhost}));
989: }
990: }
1.1115 raeburn 991: if ($checkloginvia) {
992: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 993: if ($loginvia) {
994: my ($server,$path) = split(/:/,$loginvia);
995: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 996: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 997: if ($login_host eq $server) {
998: $portal_path = $path;
1.1151 raeburn 999: $isredirect = 1;
1.1116 raeburn 1000: }
1001: } else {
1002: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1003: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1004: if ($login_host eq $lonhost) {
1005: $portal_path = '';
1.1151 raeburn 1006: $isredirect = '';
1.1116 raeburn 1007: }
1008: }
1009: } else {
1.1076 raeburn 1010: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1011: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1012: }
1013: }
1014: if ($login_host ne '') {
1.1116 raeburn 1015: $hostname = &hostname($login_host);
1.1076 raeburn 1016: }
1.1172.2.88 raeburn 1017: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1018: }
1019:
1.202 matthew 1020: # --------------------------------------------- Try to change a user's password
1021:
1022: sub changepass {
1.799 raeburn 1023: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1024: $currentpass = &escape($currentpass);
1025: $newpass = &escape($newpass);
1.1030 raeburn 1026: my $lonhost = $perlvar{'lonHostID'};
1027: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1028: $server);
1029: if (! $answer) {
1030: &logthis("No reply on password change request to $server ".
1031: "by $uname in domain $udom.");
1032: } elsif ($answer =~ "^ok") {
1033: &logthis("$uname in $udom successfully changed their password ".
1034: "on $server.");
1035: } elsif ($answer =~ "^pwchange_failure") {
1036: &logthis("$uname in $udom was unable to change their password ".
1037: "on $server. The action was blocked by either lcpasswd ".
1038: "or pwchange");
1039: } elsif ($answer =~ "^non_authorized") {
1040: &logthis("$uname in $udom did not get their password correct when ".
1041: "attempting to change it on $server.");
1042: } elsif ($answer =~ "^auth_mode_error") {
1043: &logthis("$uname in $udom attempted to change their password despite ".
1044: "not being locally or internally authenticated on $server.");
1045: } elsif ($answer =~ "^unknown_user") {
1046: &logthis("$uname in $udom attempted to change their password ".
1047: "on $server but were unable to because $server is not ".
1048: "their home server.");
1049: } elsif ($answer =~ "^refused") {
1050: &logthis("$server refused to change $uname in $udom password because ".
1051: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1052: } elsif ($answer =~ "invalid_client") {
1053: &logthis("$server refused to change $uname in $udom password because ".
1054: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1055: }
1056: return $answer;
1.1 albertel 1057: }
1058:
1.169 harris41 1059: # ----------------------- Try to determine user's current authentication scheme
1060:
1061: sub queryauthenticate {
1062: my ($uname,$udom)=@_;
1.456 albertel 1063: my $uhome=&homeserver($uname,$udom);
1064: if (!$uhome) {
1065: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1066: return 'no_host';
1067: }
1068: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1069: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1070: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1071: }
1.456 albertel 1072: return $answer;
1.169 harris41 1073: }
1074:
1.1 albertel 1075: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1076:
1.1 albertel 1077: sub authenticate {
1.1073 raeburn 1078: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1079: $upass=&escape($upass);
1080: $uname= &LONCAPA::clean_username($uname);
1.836 www 1081: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1082: my $newhome;
1.836 www 1083: if ((!$uhome) || ($uhome eq 'no_host')) {
1084: # Maybe the machine was offline and only re-appeared again recently?
1085: &reconlonc();
1086: # One more
1.952 raeburn 1087: $uhome=&homeserver($uname,$udom,1);
1088: if (($uhome eq 'no_host') && $checkdefauth) {
1089: if (defined(&domain($udom,'primary'))) {
1090: $newhome=&domain($udom,'primary');
1091: }
1092: if ($newhome ne '') {
1093: $uhome = $newhome;
1094: }
1095: }
1.836 www 1096: if ((!$uhome) || ($uhome eq 'no_host')) {
1097: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1098: return 'no_host';
1099: }
1.1 albertel 1100: }
1.1073 raeburn 1101: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1102: if ($answer eq 'authorized') {
1.952 raeburn 1103: if ($newhome) {
1104: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1105: return 'no_account_on_host';
1106: } else {
1107: &logthis("User $uname at $udom authorized by $uhome");
1108: return $uhome;
1109: }
1.471 albertel 1110: }
1111: if ($answer eq 'non_authorized') {
1112: &logthis("User $uname at $udom rejected by $uhome");
1113: return 'no_host';
1.9 www 1114: }
1.471 albertel 1115: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1116: return 'no_host';
1117: }
1118:
1.1073 raeburn 1119: sub can_host_session {
1.1074 raeburn 1120: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1121: my $canhost = 1;
1.1074 raeburn 1122: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1123: if (ref($remotesessions) eq 'HASH') {
1124: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1125: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1126: $canhost = 0;
1127: } else {
1128: $canhost = 1;
1129: }
1130: }
1131: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1132: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1133: $canhost = 1;
1134: } else {
1135: $canhost = 0;
1136: }
1137: }
1138: if ($canhost) {
1139: if ($remotesessions->{'version'} ne '') {
1140: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1141: if ($reqmajor ne '' && $reqminor ne '') {
1142: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1143: my $major = $1;
1144: my $minor = $2;
1145: if (($major < $reqmajor ) ||
1146: (($major == $reqmajor) && ($minor < $reqminor))) {
1147: $canhost = 0;
1148: }
1149: } else {
1150: $canhost = 0;
1151: }
1152: }
1153: }
1154: }
1155: }
1156: if ($canhost) {
1157: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1158: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1159: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1160: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1161: if (($uint_dom ne '') &&
1162: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1163: $canhost = 0;
1164: } else {
1165: $canhost = 1;
1166: }
1167: }
1168: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1169: if (($uint_dom ne '') &&
1170: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1171: $canhost = 1;
1172: } else {
1173: $canhost = 0;
1174: }
1175: }
1176: }
1177: }
1178: return $canhost;
1179: }
1180:
1.1083 raeburn 1181: sub spare_can_host {
1182: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1183: my $canhost=1;
1.1172.2.62 raeburn 1184: my $try_server_hostname = &hostname($try_server);
1185: my $serverhomeID = &get_server_homeID($try_server_hostname);
1186: my $serverhomedom = &host_domain($serverhomeID);
1187: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1188: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1189: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1190: $canhost = 0;
1191: }
1192: }
1193: if (($canhost) && ($uint_dom)) {
1194: my @intdoms;
1195: my $internet_names = &get_internet_names($try_server);
1196: if (ref($internet_names) eq 'ARRAY') {
1197: @intdoms = @{$internet_names};
1198: }
1199: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1200: my $remoterev = &get_server_loncaparev(undef,$try_server);
1201: $canhost = &can_host_session($udom,$try_server,$remoterev,
1202: $remotesessions,
1203: $defdomdefaults{'hostedsessions'});
1204: }
1.1083 raeburn 1205: }
1206: return $canhost;
1207: }
1208:
1.1123 raeburn 1209: sub this_host_spares {
1210: my ($dom) = @_;
1.1126 raeburn 1211: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1212: my @hosts = ¤t_machine_ids();
1213: foreach my $lonhost (@hosts) {
1214: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1215: $dom_in_use = $dom;
1216: $lonhost_in_use = $lonhost;
1.1123 raeburn 1217: last;
1218: }
1219: }
1.1126 raeburn 1220: if ($dom_in_use ne '') {
1221: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1222: }
1223: if (ref($result) ne 'HASH') {
1224: $lonhost_in_use = $perlvar{'lonHostID'};
1225: $dom_in_use = &host_domain($lonhost_in_use);
1226: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1227: if (ref($result) ne 'HASH') {
1228: $result = \%spareid;
1229: }
1230: }
1231: return $result;
1232: }
1233:
1234: sub spares_for_offload {
1235: my ($dom_in_use,$lonhost_in_use) = @_;
1236: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1237: if (defined($cached)) {
1238: return $result;
1239: } else {
1.1126 raeburn 1240: my $cachetime = 60*60*24;
1241: my %domconfig =
1242: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1243: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1244: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1245: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1246: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1247: }
1248: }
1249: }
1250: }
1.1126 raeburn 1251: return;
1.1123 raeburn 1252: }
1253:
1.1129 raeburn 1254: sub get_lonbalancer_config {
1255: my ($servers) = @_;
1256: my ($currbalancer,$currtargets);
1257: if (ref($servers) eq 'HASH') {
1258: foreach my $server (keys(%{$servers})) {
1259: my %what = (
1260: spareid => 1,
1261: perlvar => 1,
1262: );
1263: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1264: if ($result eq 'ok') {
1265: if (ref($returnhash) eq 'HASH') {
1266: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1267: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1268: $currbalancer = $server;
1269: $currtargets = {};
1270: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1271: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1272: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1273: }
1274: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1275: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1276: }
1277: }
1278: last;
1279: }
1280: }
1281: }
1282: }
1283: }
1284: }
1285: return ($currbalancer,$currtargets);
1286: }
1287:
1288: sub check_loadbalancing {
1.1172.2.88 raeburn 1289: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1290: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1291: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1292: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1293: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1294: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1295: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1296: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1297: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1298: my $domneedscache;
1.1129 raeburn 1299: my $cachetime = 60*60*24;
1300:
1301: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1302: $dom_in_use = $udom;
1303: $homeintdom = 1;
1304: } else {
1305: $dom_in_use = $serverhomedom;
1306: }
1307: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1308: unless (defined($cached)) {
1309: my %domconfig =
1310: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1311: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1312: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1313: } else {
1314: $domneedscache = $dom_in_use;
1.1129 raeburn 1315: }
1316: }
1317: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1318: ($is_balancer,$currtargets,$currrules) =
1319: &check_balancer_result($result,@hosts);
1.1129 raeburn 1320: if ($is_balancer) {
1321: if (ref($currrules) eq 'HASH') {
1322: if ($homeintdom) {
1323: if ($uname ne '') {
1324: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1325: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1326: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1327: $rule_in_effect = $currrules->{'_LC_author'};
1328: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1329: $rule_in_effect = $currrules->{'_LC_adv'}
1330: }
1331: }
1332: if ($rule_in_effect eq '') {
1333: my %userenv = &userenvironment($udom,$uname,'inststatus');
1334: if ($userenv{'inststatus'} ne '') {
1335: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1336: my ($othertitle,$usertypes,$types) =
1337: &Apache::loncommon::sorted_inst_types($udom);
1338: if (ref($types) eq 'ARRAY') {
1339: foreach my $type (@{$types}) {
1340: if (grep(/^\Q$type\E$/,@statuses)) {
1341: if (exists($currrules->{$type})) {
1342: $rule_in_effect = $currrules->{$type};
1343: }
1344: }
1345: }
1346: }
1347: } else {
1348: if (exists($currrules->{'default'})) {
1349: $rule_in_effect = $currrules->{'default'};
1350: }
1351: }
1352: }
1353: } else {
1354: if (exists($currrules->{'default'})) {
1355: $rule_in_effect = $currrules->{'default'};
1356: }
1357: }
1358: } else {
1359: if ($currrules->{'_LC_external'} ne '') {
1360: $rule_in_effect = $currrules->{'_LC_external'};
1361: }
1362: }
1363: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1364: $uname,$udom);
1365: }
1366: }
1367: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1368: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1369: unless (defined($cached)) {
1370: my %domconfig =
1371: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1372: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1373: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1374: } else {
1375: $domneedscache = $serverhomedom;
1.1129 raeburn 1376: }
1377: }
1378: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1379: ($is_balancer,$currtargets,$currrules) =
1380: &check_balancer_result($result,@hosts);
1381: if ($is_balancer) {
1.1129 raeburn 1382: if (ref($currrules) eq 'HASH') {
1383: if ($currrules->{'_LC_internetdom'} ne '') {
1384: $rule_in_effect = $currrules->{'_LC_internetdom'};
1385: }
1386: }
1387: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1388: $uname,$udom);
1389: }
1390: } else {
1391: if ($perlvar{'lonBalancer'} eq 'yes') {
1392: $is_balancer = 1;
1393: $offloadto = &this_host_spares($dom_in_use);
1394: }
1.1172.2.75 raeburn 1395: unless (defined($cached)) {
1396: $domneedscache = $serverhomedom;
1397: }
1.1129 raeburn 1398: }
1399: } else {
1400: if ($perlvar{'lonBalancer'} eq 'yes') {
1401: $is_balancer = 1;
1402: $offloadto = &this_host_spares($dom_in_use);
1403: }
1.1172.2.75 raeburn 1404: unless (defined($cached)) {
1405: $domneedscache = $serverhomedom;
1406: }
1407: }
1408: if ($domneedscache) {
1409: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1410: }
1.1172.2.5 raeburn 1411: if ($is_balancer) {
1412: my $lowest_load = 30000;
1413: if (ref($offloadto) eq 'HASH') {
1414: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1415: foreach my $try_server (@{$offloadto->{'primary'}}) {
1416: ($otherserver,$lowest_load) =
1417: &compare_server_load($try_server,$otherserver,$lowest_load);
1418: }
1.1129 raeburn 1419: }
1.1172.2.5 raeburn 1420: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1421:
1.1172.2.5 raeburn 1422: if (!$found_server) {
1423: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1424: foreach my $try_server (@{$offloadto->{'default'}}) {
1425: ($otherserver,$lowest_load) =
1426: &compare_server_load($try_server,$otherserver,$lowest_load);
1427: }
1428: }
1429: }
1430: } elsif (ref($offloadto) eq 'ARRAY') {
1431: if (@{$offloadto} == 1) {
1432: $otherserver = $offloadto->[0];
1433: } elsif (@{$offloadto} > 1) {
1434: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1435: ($otherserver,$lowest_load) =
1436: &compare_server_load($try_server,$otherserver,$lowest_load);
1437: }
1438: }
1439: }
1.1172.2.88 raeburn 1440: unless ($caller eq 'login') {
1441: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1442: $is_balancer = 0;
1443: if ($uname ne '' && $udom ne '') {
1444: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5 raeburn 1445:
1.1172.2.88 raeburn 1446: &appenv({'user.loadbalexempt' => $lonhost,
1447: 'user.loadbalcheck.time' => time});
1448: }
1.1172.2.5 raeburn 1449: }
1.1129 raeburn 1450: }
1451: }
1452: }
1453: return ($is_balancer,$otherserver);
1454: }
1455:
1.1172.2.12 raeburn 1456: sub check_balancer_result {
1457: my ($result,@hosts) = @_;
1458: my ($is_balancer,$currtargets,$currrules);
1459: if (ref($result) eq 'HASH') {
1460: if ($result->{'lonhost'} ne '') {
1461: my $currbalancer = $result->{'lonhost'};
1462: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1463: $is_balancer = 1;
1464: $currtargets = $result->{'targets'};
1465: $currrules = $result->{'rules'};
1466: }
1467: } else {
1468: foreach my $key (keys(%{$result})) {
1469: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1470: (ref($result->{$key}) eq 'HASH')) {
1471: $is_balancer = 1;
1472: $currrules = $result->{$key}{'rules'};
1473: $currtargets = $result->{$key}{'targets'};
1474: last;
1475: }
1476: }
1477: }
1478: }
1479: return ($is_balancer,$currtargets,$currrules);
1480: }
1481:
1.1129 raeburn 1482: sub get_loadbalancer_targets {
1483: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1484: my $offloadto;
1.1172.2.4 raeburn 1485: if ($rule_in_effect eq 'none') {
1486: return [$perlvar{'lonHostID'}];
1487: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1488: $offloadto = $currtargets;
1489: } else {
1490: if ($rule_in_effect eq 'homeserver') {
1491: my $homeserver = &homeserver($uname,$udom);
1492: if ($homeserver ne 'no_host') {
1493: $offloadto = [$homeserver];
1494: }
1495: } elsif ($rule_in_effect eq 'externalbalancer') {
1496: my %domconfig =
1497: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1498: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1499: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1500: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1501: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1502: }
1503: }
1504: } else {
1.1172.2.7 raeburn 1505: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1506: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1507: if (&hostname($remotebalancer) ne '') {
1508: $offloadto = [$remotebalancer];
1509: }
1510: }
1511: } elsif (&hostname($rule_in_effect) ne '') {
1512: $offloadto = [$rule_in_effect];
1513: }
1514: }
1515: return $offloadto;
1516: }
1517:
1.1127 raeburn 1518: sub internet_dom_servers {
1519: my ($dom) = @_;
1520: my (%uniqservers,%servers);
1521: my $primaryserver = &hostname(&domain($dom,'primary'));
1522: my @machinedoms = &machine_domains($primaryserver);
1523: foreach my $mdom (@machinedoms) {
1524: my %currservers = %servers;
1525: my %server = &get_servers($mdom);
1526: %servers = (%currservers,%server);
1527: }
1528: my %by_hostname;
1529: foreach my $id (keys(%servers)) {
1530: push(@{$by_hostname{$servers{$id}}},$id);
1531: }
1532: foreach my $hostname (sort(keys(%by_hostname))) {
1533: if (@{$by_hostname{$hostname}} > 1) {
1534: my $match = 0;
1535: foreach my $id (@{$by_hostname{$hostname}}) {
1536: if (&host_domain($id) eq $dom) {
1537: $uniqservers{$id} = $hostname;
1538: $match = 1;
1539: }
1540: }
1541: unless ($match) {
1542: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1543: }
1544: } else {
1545: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1546: }
1547: }
1548: return %uniqservers;
1549: }
1550:
1.1 albertel 1551: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1552:
1.599 albertel 1553: my %homecache;
1.1 albertel 1554: sub homeserver {
1.230 stredwic 1555: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1556: my $index="$uname:$udom";
1.426 albertel 1557:
1.599 albertel 1558: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1559:
1560: my %servers = &get_servers($udom,'library');
1561: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1562: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1563: exists($badServerCache{$tryserver}));
1.841 albertel 1564:
1565: my $answer=reply("home:$udom:$uname",$tryserver);
1566: if ($answer eq 'found') {
1567: delete($badServerCache{$tryserver});
1568: return $homecache{$index}=$tryserver;
1569: } elsif ($answer eq 'no_host') {
1570: $badServerCache{$tryserver}=1;
1571: }
1.1 albertel 1572: }
1573: return 'no_host';
1.70 www 1574: }
1575:
1576: # ------------------------------------- Find the usernames behind a list of IDs
1577:
1578: sub idget {
1579: my ($udom,@ids)=@_;
1580: my %returnhash=();
1581:
1.841 albertel 1582: my %servers = &get_servers($udom,'library');
1583: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1584: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1585: $idlist=~tr/A-Z/a-z/;
1586: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1587: my @answer=();
1588: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1589: @answer=split(/\&/,$reply);
1590: } ;
1591: my $i;
1592: for ($i=0;$i<=$#ids;$i++) {
1593: if ($answer[$i]) {
1.1172.2.73 raeburn 1594: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1595: }
1596: }
1597: }
1.70 www 1598: return %returnhash;
1599: }
1600:
1601: # ------------------------------------- Find the IDs behind a list of usernames
1602:
1603: sub idrget {
1604: my ($udom,@unames)=@_;
1605: my %returnhash=();
1.800 albertel 1606: foreach my $uname (@unames) {
1607: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1608: }
1.70 www 1609: return %returnhash;
1610: }
1611:
1612: # ------------------------------- Store away a list of names and associated IDs
1613:
1614: sub idput {
1615: my ($udom,%ids)=@_;
1616: my %servers=();
1.800 albertel 1617: foreach my $uname (keys(%ids)) {
1618: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1619: my $uhom=&homeserver($uname,$udom);
1.70 www 1620: if ($uhom ne 'no_host') {
1.800 albertel 1621: my $id=&escape($ids{$uname});
1.70 www 1622: $id=~tr/A-Z/a-z/;
1.800 albertel 1623: my $esc_unam=&escape($uname);
1.70 www 1624: if ($servers{$uhom}) {
1.800 albertel 1625: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1626: } else {
1.800 albertel 1627: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1628: }
1629: }
1.191 harris41 1630: }
1.800 albertel 1631: foreach my $server (keys(%servers)) {
1632: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1633: }
1.344 www 1634: }
1635:
1.1172.2.30 raeburn 1636: # ---------------------------------------- Delete unwanted IDs from ids.db file
1637:
1638: sub iddel {
1639: my ($udom,$idshashref,$uhome)=@_;
1640: my %result=();
1641: unless (ref($idshashref) eq 'HASH') {
1642: return %result;
1643: }
1644: my %servers=();
1645: while (my ($id,$uname) = each(%{$idshashref})) {
1646: my $uhom;
1647: if ($uhome) {
1648: $uhom = $uhome;
1649: } else {
1650: $uhom=&homeserver($uname,$udom);
1651: }
1652: if ($uhom ne 'no_host') {
1653: if ($servers{$uhom}) {
1654: $servers{$uhom}.='&'.&escape($id);
1655: } else {
1656: $servers{$uhom}=&escape($id);
1657: }
1658: }
1659: }
1660: foreach my $server (keys(%servers)) {
1661: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1662: }
1663: return %result;
1664: }
1665:
1.1023 raeburn 1666: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1667: sub dump_dom {
1.1165 droeschl 1668: my ($namespace, $udom, $regexp) = @_;
1669:
1670: $udom ||= $env{'user.domain'};
1671:
1672: return () unless $udom;
1673:
1674: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1675: }
1676:
1.1023 raeburn 1677: # ------------------------------------------ get items from domain db files
1.806 raeburn 1678:
1679: sub get_dom {
1.860 raeburn 1680: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1681: return if ($udom eq 'public');
1.806 raeburn 1682: my $items='';
1683: foreach my $item (@$storearr) {
1684: $items.=&escape($item).'&';
1685: }
1686: $items=~s/\&$//;
1.860 raeburn 1687: if (!$udom) {
1688: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1689: return if ($udom eq 'public');
1.860 raeburn 1690: if (defined(&domain($udom,'primary'))) {
1691: $uhome=&domain($udom,'primary');
1692: } else {
1.874 albertel 1693: undef($uhome);
1.860 raeburn 1694: }
1695: } else {
1696: if (!$uhome) {
1697: if (defined(&domain($udom,'primary'))) {
1698: $uhome=&domain($udom,'primary');
1699: }
1700: }
1701: }
1702: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.93.4 2(raebur 1703:7): my $rep;
1704:7): if ($namespace =~ /^enc/) {
1705:7): $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
1706:7): } else {
1707:7): $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1708:7): }
1.866 raeburn 1709: my %returnhash;
1.875 albertel 1710: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1711: return %returnhash;
1712: }
1.806 raeburn 1713: my @pairs=split(/\&/,$rep);
1714: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1715: return @pairs;
1716: }
1717: my $i=0;
1718: foreach my $item (@$storearr) {
1719: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1720: $i++;
1721: }
1722: return %returnhash;
1723: } else {
1.880 banghart 1724: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1725: }
1726: }
1727:
1728: # -------------------------------------------- put items in domain db files
1729:
1730: sub put_dom {
1.860 raeburn 1731: my ($namespace,$storehash,$udom,$uhome)=@_;
1732: if (!$udom) {
1733: $udom=$env{'user.domain'};
1734: if (defined(&domain($udom,'primary'))) {
1735: $uhome=&domain($udom,'primary');
1736: } else {
1.874 albertel 1737: undef($uhome);
1.860 raeburn 1738: }
1739: } else {
1740: if (!$uhome) {
1741: if (defined(&domain($udom,'primary'))) {
1742: $uhome=&domain($udom,'primary');
1743: }
1744: }
1745: }
1746: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1747: my $items='';
1748: foreach my $item (keys(%$storehash)) {
1749: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1750: }
1751: $items=~s/\&$//;
1.1172.2.93.4 2(raebur 1752:7): if ($namespace =~ /^enc/) {
1753:7): return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
1754:7): } else {
1755:7): return &reply("putdom:$udom:$namespace:$items",$uhome);
1756:7): }
1.806 raeburn 1757: } else {
1.860 raeburn 1758: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1759: }
1760: }
1761:
1.1023 raeburn 1762: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1763: sub newput_dom {
1.1023 raeburn 1764: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1765: my $result;
1766: if (!$udom) {
1767: $udom=$env{'user.domain'};
1768: }
1.1023 raeburn 1769: if ($udom) {
1770: my $uname = &get_domainconfiguser($udom);
1771: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1772: }
1773: return $result;
1774: }
1775:
1.1023 raeburn 1776: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1777: sub del_dom {
1.1023 raeburn 1778: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1779: if (ref($storearr) eq 'ARRAY') {
1780: if (!$udom) {
1781: $udom=$env{'user.domain'};
1782: }
1.1023 raeburn 1783: if ($udom) {
1784: my $uname = &get_domainconfiguser($udom);
1785: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1786: }
1787: }
1788: }
1789:
1.1023 raeburn 1790: # ----------------------------------construct domainconfig user for a domain
1791: sub get_domainconfiguser {
1792: my ($udom) = @_;
1793: return $udom.'-domainconfig';
1794: }
1795:
1.837 raeburn 1796: sub retrieve_inst_usertypes {
1797: my ($udom) = @_;
1798: my (%returnhash,@order);
1.989 raeburn 1799: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1800: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1801: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1802: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1803: } else {
1804: if (defined(&domain($udom,'primary'))) {
1805: my $uhome=&domain($udom,'primary');
1806: my $rep=&reply("inst_usertypes:$udom",$uhome);
1807: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1808: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1809: return (\%returnhash,\@order);
1810: }
1811: my ($hashitems,$orderitems) = split(/:/,$rep);
1812: my @pairs=split(/\&/,$hashitems);
1813: foreach my $item (@pairs) {
1814: my ($key,$value)=split(/=/,$item,2);
1815: $key = &unescape($key);
1816: next if ($key =~ /^error: 2 /);
1817: $returnhash{$key}=&thaw_unescape($value);
1818: }
1819: my @esc_order = split(/\&/,$orderitems);
1820: foreach my $item (@esc_order) {
1821: push(@order,&unescape($item));
1822: }
1823: } else {
1.1172.2.44 raeburn 1824: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1825: }
1.1172.2.44 raeburn 1826: return (\%returnhash,\@order);
1.837 raeburn 1827: }
1828: }
1829:
1.868 raeburn 1830: sub is_domainimage {
1831: my ($url) = @_;
1.1172.2.74 raeburn 1832: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1833: if (&domain($1) ne '') {
1834: return '1';
1835: }
1836: }
1837: return;
1838: }
1839:
1.899 raeburn 1840: sub inst_directory_query {
1841: my ($srch) = @_;
1842: my $udom = $srch->{'srchdomain'};
1843: my %results;
1844: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1845: my $outcome;
1.899 raeburn 1846: if ($homeserver ne '') {
1.1172.2.93.4 4(raebur 1847:7): unless ($homeserver eq $perlvar{'lonHostID'}) {
1848:7): if ($srch->{'srchby'} eq 'email') {
1849:7): my $lcrev = &get_server_loncaparev(undef,$homeserver);
1850:7): my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.([\w.\-]+)\'?$/);
1851:7): if (($major eq '' && $minor eq '') || ($major < 2) ||
1852:7): (($major == 2) && ($minor < 11)) ||
1853:7): (($major == 2) && ($minor == 11) && ($subver !~ /^2\.B/))) {
1854:7): return;
1855:7): }
1856:7): }
1857:7): }
1.904 albertel 1858: my $queryid=&reply("querysend:instdirsearch:".
1859: &escape($srch->{'srchby'}).':'.
1860: &escape($srch->{'srchterm'}).':'.
1861: &escape($srch->{'srchtype'}),$homeserver);
1862: my $host=&hostname($homeserver);
1863: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.93.4 1(raebur 1864:7): &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 1865: return;
1866: }
1867: my $response = &get_query_reply($queryid);
1868: my $maxtries = 5;
1869: my $tries = 1;
1870: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1871: $response = &get_query_reply($queryid);
1872: $tries ++;
1873: }
1874:
1875: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1876: if ($response eq 'unavailable') {
1877: $outcome = $response;
1878: } else {
1879: $outcome = 'ok';
1880: my @matches = split(/\n/,$response);
1881: foreach my $match (@matches) {
1882: my ($key,$value) = split(/=/,$match);
1883: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1884: }
1.899 raeburn 1885: }
1886: }
1887: }
1.909 raeburn 1888: return ($outcome,%results);
1.899 raeburn 1889: }
1890:
1891: sub usersearch {
1892: my ($srch) = @_;
1893: my $dom = $srch->{'srchdomain'};
1894: my %results;
1895: my %libserv = &all_library();
1896: my $query = 'usersearch';
1897: foreach my $tryserver (keys(%libserv)) {
1898: if (&host_domain($tryserver) eq $dom) {
1.1172.2.93.4 4(raebur 1899:7): unless ($tryserver eq $perlvar{'lonHostID'}) {
1900:7): if ($srch->{'srchby'} eq 'email') {
1901:7): my $lcrev = &get_server_loncaparev(undef,$tryserver);
1902:7): my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.([\w.\-]+)\'?$/);
1903:7): next if (($major eq '' && $minor eq '') || ($major < 2) ||
1904:7): (($major == 2) && ($minor < 11)) ||
6(raebur 1905:7): (($major == 2) && ($minor == 11) && ($subver !~ /^2\.B/)));
4(raebur 1906:7): }
1907:7): }
1.899 raeburn 1908: my $host=&hostname($tryserver);
1909: my $queryid=
1.911 raeburn 1910: &reply("querysend:".&escape($query).':'.
1911: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1912: &escape($srch->{'srchtype'}).':'.
1913: &escape($srch->{'srchterm'}),$tryserver);
1914: if ($queryid !~/^\Q$host\E\_/) {
1915: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1916: next;
1.899 raeburn 1917: }
1918: my $reply = &get_query_reply($queryid);
1919: my $maxtries = 1;
1920: my $tries = 1;
1921: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1922: $reply = &get_query_reply($queryid);
1923: $tries ++;
1924: }
1925: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1926: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1927: } else {
1.911 raeburn 1928: my @matches;
1929: if ($reply =~ /\n/) {
1930: @matches = split(/\n/,$reply);
1931: } else {
1932: @matches = split(/\&/,$reply);
1933: }
1.899 raeburn 1934: foreach my $match (@matches) {
1935: my ($uname,$udom,%userhash);
1.911 raeburn 1936: foreach my $entry (split(/:/,$match)) {
1937: my ($key,$value) =
1938: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1939: $userhash{$key} = $value;
1940: if ($key eq 'username') {
1941: $uname = $value;
1942: } elsif ($key eq 'domain') {
1943: $udom = $value;
1.911 raeburn 1944: }
1.899 raeburn 1945: }
1946: $results{$uname.':'.$udom} = \%userhash;
1947: }
1948: }
1949: }
1950: }
1951: return %results;
1952: }
1953:
1.912 raeburn 1954: sub get_instuser {
1955: my ($udom,$uname,$id) = @_;
1956: my $homeserver = &domain($udom,'primary');
1957: my ($outcome,%results);
1958: if ($homeserver ne '') {
1959: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1960: &escape($id).':'.&escape($udom),$homeserver);
1961: my $host=&hostname($homeserver);
1962: if ($queryid !~/^\Q$host\E\_/) {
1963: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1964: return;
1965: }
1966: my $response = &get_query_reply($queryid);
1967: my $maxtries = 5;
1968: my $tries = 1;
1969: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1970: $response = &get_query_reply($queryid);
1971: $tries ++;
1972: }
1973: if (!&error($response) && $response ne 'refused') {
1974: if ($response eq 'unavailable') {
1975: $outcome = $response;
1976: } else {
1977: $outcome = 'ok';
1978: my @matches = split(/\n/,$response);
1979: foreach my $match (@matches) {
1980: my ($key,$value) = split(/=/,$match);
1981: $results{&unescape($key)} = &thaw_unescape($value);
1982: }
1983: }
1984: }
1985: }
1986: my %userinfo;
1987: if (ref($results{$uname}) eq 'HASH') {
1988: %userinfo = %{$results{$uname}};
1989: }
1990: return ($outcome,%userinfo);
1991: }
1992:
1.1172.2.69 raeburn 1993: sub get_multiple_instusers {
1994: my ($udom,$users,$caller) = @_;
1995: my ($outcome,$results);
1996: if (ref($users) eq 'HASH') {
1997: my $count = keys(%{$users});
1998: my $requested = &freeze_escape($users);
1999: my $homeserver = &domain($udom,'primary');
2000: if ($homeserver ne '') {
2001: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2002: my $host=&hostname($homeserver);
2003: if ($queryid !~/^\Q$host\E\_/) {
2004: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2005: ' for host: '.$homeserver.'in domain '.$udom);
2006: return ($outcome,$results);
2007: }
2008: my $response = &get_query_reply($queryid);
2009: my $maxtries = 5;
2010: if ($count > 100) {
2011: $maxtries = 1+int($count/20);
2012: }
2013: my $tries = 1;
2014: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2015: $response = &get_query_reply($queryid);
2016: $tries ++;
2017: }
2018: if ($response eq '') {
2019: $results = {};
2020: foreach my $key (keys(%{$users})) {
2021: my ($uname,$id);
2022: if ($caller eq 'id') {
2023: $id = $key;
2024: } else {
2025: $uname = $key;
2026: }
2027: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2028: $outcome = $resp;
2029: if ($resp eq 'ok') {
2030: %{$results} = (%{$results}, %info);
2031: } else {
2032: last;
2033: }
2034: }
2035: } elsif(!&error($response) && ($response ne 'refused')) {
2036: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2037: $outcome = $response;
2038: } else {
2039: ($outcome,my $userdata) = split(/=/,$response,2);
2040: if ($outcome eq 'ok') {
2041: $results = &thaw_unescape($userdata);
2042: }
2043: }
2044: }
2045: }
2046: }
2047: return ($outcome,$results);
2048: }
2049:
1.912 raeburn 2050: sub inst_rulecheck {
1.923 raeburn 2051: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2052: my %returnhash;
2053: if ($udom ne '') {
2054: if (ref($rules) eq 'ARRAY') {
2055: @{$rules} = map {&escape($_);} (@{$rules});
2056: my $rulestr = join(':',@{$rules});
2057: my $homeserver=&domain($udom,'primary');
2058: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2059: my $response;
2060: if ($item eq 'username') {
2061: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2062: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2063: $homeserver));
1.923 raeburn 2064: } elsif ($item eq 'id') {
2065: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2066: ':'.&escape($id).':'.$rulestr,
2067: $homeserver));
1.945 raeburn 2068: } elsif ($item eq 'selfcreate') {
2069: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2070: &escape($udom).':'.&escape($uname).
2071: ':'.$rulestr,$homeserver));
1.923 raeburn 2072: }
1.912 raeburn 2073: if ($response ne 'refused') {
2074: my @pairs=split(/\&/,$response);
2075: foreach my $item (@pairs) {
2076: my ($key,$value)=split(/=/,$item,2);
2077: $key = &unescape($key);
2078: next if ($key =~ /^error: 2 /);
2079: $returnhash{$key}=&thaw_unescape($value);
2080: }
2081: }
2082: }
2083: }
2084: }
2085: return %returnhash;
2086: }
2087:
2088: sub inst_userrules {
1.923 raeburn 2089: my ($udom,$check) = @_;
1.912 raeburn 2090: my (%ruleshash,@ruleorder);
2091: if ($udom ne '') {
2092: my $homeserver=&domain($udom,'primary');
2093: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2094: my $response;
2095: if ($check eq 'id') {
2096: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2097: $homeserver);
1.943 raeburn 2098: } elsif ($check eq 'email') {
2099: $response=&reply('instemailrules:'.&escape($udom),
2100: $homeserver);
1.923 raeburn 2101: } else {
2102: $response=&reply('instuserrules:'.&escape($udom),
2103: $homeserver);
2104: }
1.912 raeburn 2105: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2106: ($response ne 'unknown_cmd') &&
1.912 raeburn 2107: ($response ne 'no_such_host')) {
2108: my ($hashitems,$orderitems) = split(/:/,$response);
2109: my @pairs=split(/\&/,$hashitems);
2110: foreach my $item (@pairs) {
2111: my ($key,$value)=split(/=/,$item,2);
2112: $key = &unescape($key);
2113: next if ($key =~ /^error: 2 /);
2114: $ruleshash{$key}=&thaw_unescape($value);
2115: }
2116: my @esc_order = split(/\&/,$orderitems);
2117: foreach my $item (@esc_order) {
2118: push(@ruleorder,&unescape($item));
2119: }
2120: }
2121: }
2122: }
2123: return (\%ruleshash,\@ruleorder);
2124: }
2125:
1.976 raeburn 2126: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2127:
2128: sub get_domain_defaults {
1.1172.2.35 raeburn 2129: my ($domain,$ignore_cache) = @_;
2130: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2131: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2132: unless ($ignore_cache) {
2133: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2134: if (defined($cached)) {
2135: if (ref($result) eq 'HASH') {
2136: return %{$result};
2137: }
1.943 raeburn 2138: }
2139: }
2140: my %domdefaults;
2141: my %domconfig =
1.989 raeburn 2142: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2143: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2144: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2145: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2146: 'coursecategories','autoenroll',
2147: 'helpsettings'],$domain);
1.1172.2.41 raeburn 2148: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2149: if (ref($domconfig{'defaults'}) eq 'HASH') {
2150: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2151: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2152: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2153: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2154: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2155: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2156: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2157: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2158: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2159: } else {
2160: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2161: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2162: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2163: }
1.976 raeburn 2164: if (ref($domconfig{'quotas'}) eq 'HASH') {
2165: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2166: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2167: } else {
2168: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2169: }
1.1172.2.6 raeburn 2170: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2171: foreach my $item (@usertools) {
2172: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2173: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2174: }
2175: }
1.1172.2.29 raeburn 2176: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2177: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2178: }
1.976 raeburn 2179: }
1.985 raeburn 2180: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2181: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2182: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2183: }
2184: }
1.1172.2.9 raeburn 2185: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2186: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2187: }
1.989 raeburn 2188: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2189: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2190: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2191: }
2192: }
1.1047 raeburn 2193: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2194: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2195: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2196: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2197: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2198: }
1.1172.2.41 raeburn 2199: foreach my $type (@coursetypes) {
2200: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2201: unless ($type eq 'community') {
2202: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2203: }
2204: }
2205: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2206: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2207: }
1.1172.2.60 raeburn 2208: if ($domdefaults{'postsubmit'} eq 'on') {
2209: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2210: $domdefaults{$type.'postsubtimeout'} =
2211: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2212: }
2213: }
1.1172.2.30 raeburn 2214: }
1.1172.2.67 raeburn 2215: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2216: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2217: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2218: if (@clonecodes) {
2219: $domdefaults{'canclone'} = join('+',@clonecodes);
2220: }
2221: }
2222: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2223: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2224: }
1.1047 raeburn 2225: }
1.1073 raeburn 2226: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2227: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2228: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2229: }
2230: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2231: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2232: }
1.1172.2.62 raeburn 2233: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2234: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2235: }
1.1073 raeburn 2236: }
1.1172.2.41 raeburn 2237: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2238: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2239: my @settings = ('types','registered','enroll_dates','access_dates','section',
2240: 'approval','limit');
2241: foreach my $type (@coursetypes) {
2242: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2243: my @mgrdc = ();
2244: foreach my $item (@settings) {
2245: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2246: push(@mgrdc,$item);
2247: }
2248: }
2249: if (@mgrdc) {
2250: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2251: }
2252: }
2253: }
2254: }
2255: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2256: foreach my $type (@coursetypes) {
2257: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2258: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2259: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2260: }
2261: }
2262: }
2263: }
2264: }
1.1172.2.46 raeburn 2265: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2266: $domdefaults{'catauth'} = 'std';
2267: $domdefaults{'catunauth'} = 'std';
2268: if ($domconfig{'coursecategories'}{'auth'}) {
2269: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2270: }
2271: if ($domconfig{'coursecategories'}{'unauth'}) {
2272: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2273: }
2274: }
1.1172.2.76 raeburn 2275: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2276: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2277: }
1.1172.2.89 raeburn 2278: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2279: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2280: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2281: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2282: }
2283: }
1.1172.2.23 raeburn 2284: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2285: return %domdefaults;
2286: }
2287:
1.1172.2.93.4 2(raebur 2288:7): sub course_portal_url {
2289:7): my ($cnum,$cdom) = @_;
2290:7): my $chome = &homeserver($cnum,$cdom);
2291:7): my $hostname = &hostname($chome);
2292:7): my $protocol = $protocol{$chome};
2293:7): $protocol = 'http' if ($protocol ne 'https');
2294:7): my %domdefaults = &get_domain_defaults($cdom);
2295:7): my $firsturl;
2296:7): if ($domdefaults{'portal_def'}) {
2297:7): $firsturl = $domdefaults{'portal_def'};
2298:7): } else {
2299:7): $firsturl = $protocol.'://'.$hostname;
2300:7): }
2301:7): return $firsturl;
2302:7): }
2303:7):
1.344 www 2304: # --------------------------------------------------- Assign a key to a student
2305:
2306: sub assign_access_key {
1.364 www 2307: #
2308: # a valid key looks like uname:udom#comments
2309: # comments are being appended
2310: #
1.498 www 2311: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2312: $kdom=
1.620 albertel 2313: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2314: $knum=
1.620 albertel 2315: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2316: $cdom=
1.620 albertel 2317: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2318: $cnum=
1.620 albertel 2319: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2320: $udom=$env{'user.name'} unless (defined($udom));
2321: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2322: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2323: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2324: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2325: # assigned to this person
2326: # - this should not happen,
1.345 www 2327: # unless something went wrong
2328: # the first time around
2329: # ready to assign
1.364 www 2330: $logentry=$1.'; '.$logentry;
1.496 www 2331: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2332: $kdom,$knum) eq 'ok') {
1.345 www 2333: # key now belongs to user
1.346 www 2334: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2335: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2336: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2337: return 'ok';
2338: } else {
2339: return
2340: 'error: Count not permanently assign key, will need to be re-entered later.';
2341: }
2342: } else {
2343: return 'error: Could not assign key, try again later.';
2344: }
1.364 www 2345: } elsif (!$existing{$ckey}) {
1.345 www 2346: # the key does not exist
2347: return 'error: The key does not exist';
2348: } else {
2349: # the key is somebody else's
2350: return 'error: The key is already in use';
2351: }
1.344 www 2352: }
2353:
1.364 www 2354: # ------------------------------------------ put an additional comment on a key
2355:
2356: sub comment_access_key {
2357: #
2358: # a valid key looks like uname:udom#comments
2359: # comments are being appended
2360: #
2361: my ($ckey,$cdom,$cnum,$logentry)=@_;
2362: $cdom=
1.620 albertel 2363: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2364: $cnum=
1.620 albertel 2365: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2366: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2367: if ($existing{$ckey}) {
2368: $existing{$ckey}.='; '.$logentry;
2369: # ready to assign
1.367 www 2370: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2371: $cdom,$cnum) eq 'ok') {
2372: return 'ok';
2373: } else {
2374: return 'error: Count not store comment.';
2375: }
2376: } else {
2377: # the key does not exist
2378: return 'error: The key does not exist';
2379: }
2380: }
2381:
1.344 www 2382: # ------------------------------------------------------ Generate a set of keys
2383:
2384: sub generate_access_keys {
1.364 www 2385: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2386: $cdom=
1.620 albertel 2387: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2388: $cnum=
1.620 albertel 2389: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2390: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2391: unless (($cdom) && ($cnum)) { return 0; }
2392: if ($number>10000) { return 0; }
2393: sleep(2); # make sure don't get same seed twice
2394: srand(time()^($$+($$<<15))); # from "Programming Perl"
2395: my $total=0;
2396: for (my $i=1;$i<=$number;$i++) {
2397: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2398: sprintf("%lx",int(100000*rand)).'-'.
2399: sprintf("%lx",int(100000*rand));
2400: $newkey=~s/1/g/g; # folks mix up 1 and l
2401: $newkey=~s/0/h/g; # and also 0 and O
2402: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2403: if ($existing{$newkey}) {
2404: $i--;
2405: } else {
1.364 www 2406: if (&put('accesskeys',
2407: { $newkey => '# generated '.localtime().
1.620 albertel 2408: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2409: '; '.$logentry },
2410: $cdom,$cnum) eq 'ok') {
1.344 www 2411: $total++;
2412: }
2413: }
2414: }
1.620 albertel 2415: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2416: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2417: return $total;
2418: }
2419:
2420: # ------------------------------------------------------- Validate an accesskey
2421:
2422: sub validate_access_key {
2423: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2424: $cdom=
1.620 albertel 2425: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2426: $cnum=
1.620 albertel 2427: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2428: $udom=$env{'user.domain'} unless (defined($udom));
2429: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2430: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2431: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2432: }
2433:
2434: # ------------------------------------- Find the section of student in a course
1.652 albertel 2435: sub devalidate_getsection_cache {
2436: my ($udom,$unam,$courseid)=@_;
2437: my $hashid="$udom:$unam:$courseid";
2438: &devalidate_cache_new('getsection',$hashid);
2439: }
1.298 matthew 2440:
1.815 albertel 2441: sub courseid_to_courseurl {
2442: my ($courseid) = @_;
2443: #already url style courseid
2444: return $courseid if ($courseid =~ m{^/});
2445:
2446: if (exists($env{'course.'.$courseid.'.num'})) {
2447: my $cnum = $env{'course.'.$courseid.'.num'};
2448: my $cdom = $env{'course.'.$courseid.'.domain'};
2449: return "/$cdom/$cnum";
2450: }
2451:
2452: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2453: if (exists($courseinfo{'num'})) {
2454: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2455: }
2456:
2457: return undef;
2458: }
2459:
1.298 matthew 2460: sub getsection {
2461: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2462: my $cachetime=1800;
1.551 albertel 2463:
2464: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2465: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2466: if (defined($cached)) { return $result; }
2467:
1.298 matthew 2468: my %Pending;
2469: my %Expired;
2470: #
2471: # Each role can either have not started yet (pending), be active,
2472: # or have expired.
2473: #
2474: # If there is an active role, we are done.
2475: #
2476: # If there is more than one role which has not started yet,
2477: # choose the one which will start sooner
2478: # If there is one role which has not started yet, return it.
2479: #
2480: # If there is more than one expired role, choose the one which ended last.
2481: # If there is a role which has expired, return it.
2482: #
1.815 albertel 2483: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2484: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2485: foreach my $key (keys(%roleshash)) {
1.479 albertel 2486: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2487: my $section=$1;
2488: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2489: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2490: my $now=time;
1.548 albertel 2491: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2492: $Expired{$end}=$section;
2493: next;
2494: }
1.548 albertel 2495: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2496: $Pending{$start}=$section;
2497: next;
2498: }
1.599 albertel 2499: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2500: }
2501: #
2502: # Presumedly there will be few matching roles from the above
2503: # loop and the sorting time will be negligible.
2504: if (scalar(keys(%Pending))) {
2505: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2506: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2507: }
2508: if (scalar(keys(%Expired))) {
2509: my @sorted = sort {$a <=> $b} keys(%Expired);
2510: my $time = pop(@sorted);
1.599 albertel 2511: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2512: }
1.599 albertel 2513: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2514: }
1.70 www 2515:
1.599 albertel 2516: sub save_cache {
2517: &purge_remembered();
1.722 albertel 2518: #&Apache::loncommon::validate_page();
1.620 albertel 2519: undef(%env);
1.780 albertel 2520: undef($env_loaded);
1.599 albertel 2521: }
1.452 albertel 2522:
1.599 albertel 2523: my $to_remember=-1;
2524: my %remembered;
2525: my %accessed;
2526: my $kicks=0;
2527: my $hits=0;
1.849 albertel 2528: sub make_key {
2529: my ($name,$id) = @_;
1.872 albertel 2530: if (length($id) > 65
2531: && length(&escape($id)) > 200) {
2532: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2533: }
1.849 albertel 2534: return &escape($name.':'.$id);
2535: }
2536:
1.599 albertel 2537: sub devalidate_cache_new {
2538: my ($name,$id,$debug) = @_;
2539: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2540: my $remembered_id=$name.':'.$id;
1.849 albertel 2541: $id=&make_key($name,$id);
1.599 albertel 2542: $memcache->delete($id);
1.1172.2.81 raeburn 2543: delete($remembered{$remembered_id});
2544: delete($accessed{$remembered_id});
1.599 albertel 2545: }
2546:
2547: sub is_cached_new {
2548: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2549: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2550: # keys in %remembered hash, which persists for
2551: # duration of request (no restriction on key length).
2552: if (exists($remembered{$remembered_id})) {
2553: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2554: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2555: $hits++;
1.1172.2.81 raeburn 2556: return ($remembered{$remembered_id},1);
1.599 albertel 2557: }
1.1172.2.81 raeburn 2558: $id=&make_key($name,$id);
1.599 albertel 2559: my $value = $memcache->get($id);
2560: if (!(defined($value))) {
2561: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2562: return (undef,undef);
1.416 albertel 2563: }
1.599 albertel 2564: if ($value eq '__undef__') {
2565: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2566: $value=undef;
2567: }
1.1172.2.81 raeburn 2568: &make_room($remembered_id,$value,$debug);
1.599 albertel 2569: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2570: return ($value,1);
2571: }
2572:
2573: sub do_cache_new {
2574: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2575: my $remembered_id=$name.':'.$id;
1.849 albertel 2576: $id=&make_key($name,$id);
1.599 albertel 2577: my $setvalue=$value;
2578: if (!defined($setvalue)) {
2579: $setvalue='__undef__';
2580: }
1.623 albertel 2581: if (!defined($time) ) {
2582: $time=600;
2583: }
1.599 albertel 2584: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2585: my $result = $memcache->set($id,$setvalue,$time);
2586: if (! $result) {
1.872 albertel 2587: &logthis("caching of id -> $id failed");
1.910 albertel 2588: $memcache->disconnect_all();
1.872 albertel 2589: }
1.600 albertel 2590: # need to make a copy of $value
1.1172.2.81 raeburn 2591: &make_room($remembered_id,$value,$debug);
1.599 albertel 2592: return $value;
2593: }
2594:
2595: sub make_room {
1.1172.2.81 raeburn 2596: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2597:
1.1172.2.81 raeburn 2598: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2599: : $value;
1.599 albertel 2600: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2601: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2602: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2603: my $to_kick;
2604: my $max_time=0;
2605: foreach my $other (keys(%accessed)) {
2606: if (&tv_interval($accessed{$other}) > $max_time) {
2607: $to_kick=$other;
2608: $max_time=&tv_interval($accessed{$other});
2609: }
2610: }
2611: delete($remembered{$to_kick});
2612: delete($accessed{$to_kick});
2613: $kicks++;
2614: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2615: return;
2616: }
2617:
1.599 albertel 2618: sub purge_remembered {
1.604 albertel 2619: #&logthis("Tossing ".scalar(keys(%remembered)));
2620: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2621: undef(%remembered);
2622: undef(%accessed);
1.428 albertel 2623: }
1.70 www 2624: # ------------------------------------- Read an entry from a user's environment
2625:
2626: sub userenvironment {
2627: my ($udom,$unam,@what)=@_;
1.976 raeburn 2628: my $items;
2629: foreach my $item (@what) {
2630: $items.=&escape($item).'&';
2631: }
2632: $items=~s/\&$//;
1.70 www 2633: my %returnhash=();
1.1009 raeburn 2634: my $uhome = &homeserver($unam,$udom);
2635: unless ($uhome eq 'no_host') {
2636: my @answer=split(/\&/,
2637: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2638: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2639: return %returnhash;
2640: }
1.1009 raeburn 2641: my $i;
2642: for ($i=0;$i<=$#what;$i++) {
2643: $returnhash{$what[$i]}=&unescape($answer[$i]);
2644: }
1.70 www 2645: }
2646: return %returnhash;
1.1 albertel 2647: }
2648:
1.617 albertel 2649: # ---------------------------------------------------------- Get a studentphoto
2650: sub studentphoto {
2651: my ($udom,$unam,$ext) = @_;
2652: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2653: if (defined($env{'request.course.id'})) {
1.708 raeburn 2654: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2655: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2656: return(&retrievestudentphoto($udom,$unam,$ext));
2657: } else {
2658: my ($result,$perm_reqd)=
1.707 albertel 2659: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2660: if ($result eq 'ok') {
2661: if (!($perm_reqd eq 'yes')) {
2662: return(&retrievestudentphoto($udom,$unam,$ext));
2663: }
2664: }
2665: }
2666: }
2667: } else {
2668: my ($result,$perm_reqd) =
1.707 albertel 2669: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2670: if ($result eq 'ok') {
2671: if (!($perm_reqd eq 'yes')) {
2672: return(&retrievestudentphoto($udom,$unam,$ext));
2673: }
2674: }
2675: }
2676: return '/adm/lonKaputt/lonlogo_broken.gif';
2677: }
2678:
2679: sub retrievestudentphoto {
2680: my ($udom,$unam,$ext,$type) = @_;
2681: my $home=&Apache::lonnet::homeserver($unam,$udom);
2682: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2683: if ($ret eq 'ok') {
2684: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2685: if ($type eq 'thumbnail') {
2686: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2687: }
2688: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2689: return $tokenurl;
2690: } else {
2691: if ($type eq 'thumbnail') {
2692: return '/adm/lonKaputt/genericstudent_tn.gif';
2693: } else {
2694: return '/adm/lonKaputt/lonlogo_broken.gif';
2695: }
1.617 albertel 2696: }
2697: }
2698:
1.263 www 2699: # -------------------------------------------------------------------- New chat
2700:
2701: sub chatsend {
1.724 raeburn 2702: my ($newentry,$anon,$group)=@_;
1.620 albertel 2703: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2704: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2705: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2706: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2707: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2708: &escape($newentry)).':'.$group,$chome);
1.292 www 2709: }
2710:
2711: # ------------------------------------------ Find current version of a resource
2712:
2713: sub getversion {
2714: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2715: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2716: return ¤tversion(&filelocation('',$fname));
2717: }
2718:
2719: sub currentversion {
2720: my $fname=shift;
2721: my $author=$fname;
2722: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2723: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2724: my $home=&homeserver($uname,$udom);
1.292 www 2725: if ($home eq 'no_host') {
2726: return -1;
2727: }
1.1112 www 2728: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2729: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2730: return -1;
2731: }
1.1112 www 2732: return $answer;
1.263 www 2733: }
2734:
1.1111 www 2735: #
2736: # Return special version number of resource if set by override, empty otherwise
2737: #
2738: sub usedversion {
2739: my $fname=shift;
2740: unless ($fname) { $fname=$env{'request.uri'}; }
2741: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2742: if ($urlversion) { return $urlversion; }
2743: return '';
2744: }
2745:
1.1 albertel 2746: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2747:
1.1 albertel 2748: sub subscribe {
2749: my $fname=shift;
1.761 raeburn 2750: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2751: $fname=~s/[\n\r]//g;
1.1 albertel 2752: my $author=$fname;
2753: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2754: my ($udom,$uname)=split(/\//,$author);
2755: my $home=homeserver($uname,$udom);
1.335 albertel 2756: if ($home eq 'no_host') {
2757: return 'not_found';
1.1 albertel 2758: }
2759: my $answer=reply("sub:$fname",$home);
1.64 www 2760: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2761: $answer.=' by '.$home;
2762: }
1.1 albertel 2763: return $answer;
2764: }
2765:
1.8 www 2766: # -------------------------------------------------------------- Replicate file
2767:
2768: sub repcopy {
2769: my $filename=shift;
1.23 www 2770: $filename=~s/\/+/\//g;
1.1142 raeburn 2771: my $londocroot = $perlvar{'lonDocRoot'};
2772: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2773: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2774: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2775: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2776: return &repcopy_userfile($filename);
2777: }
1.532 albertel 2778: $filename=~s/[\n\r]//g;
1.8 www 2779: my $transname="$filename.in.transfer";
1.828 www 2780: # FIXME: this should flock
1.607 raeburn 2781: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2782: my $remoteurl=subscribe($filename);
1.64 www 2783: if ($remoteurl =~ /^con_lost by/) {
2784: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2785: return 'unavailable';
1.8 www 2786: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2787: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2788: return 'not_found';
1.64 www 2789: } elsif ($remoteurl =~ /^rejected by/) {
2790: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2791: return 'forbidden';
1.20 www 2792: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2793: return 'ok';
1.8 www 2794: } else {
1.290 www 2795: my $author=$filename;
2796: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2797: my ($udom,$uname)=split(/\//,$author);
2798: my $home=homeserver($uname,$udom);
2799: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2800: my @parts=split(/\//,$filename);
2801: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2802: if ($path ne "$londocroot/res") {
1.8 www 2803: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2804: return 'bad_request';
1.8 www 2805: }
2806: my $count;
2807: for ($count=5;$count<$#parts;$count++) {
2808: $path.="/$parts[$count]";
2809: if ((-e $path)!=1) {
2810: mkdir($path,0777);
2811: }
2812: }
2813: my $ua=new LWP::UserAgent;
2814: my $request=new HTTP::Request('GET',"$remoteurl");
2815: my $response=$ua->request($request,$transname);
2816: if ($response->is_error()) {
2817: unlink($transname);
2818: my $message=$response->status_line;
1.672 albertel 2819: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2820: ." LWP get: $message: $filename</font>");
1.607 raeburn 2821: return 'unavailable';
1.8 www 2822: } else {
1.16 www 2823: if ($remoteurl!~/\.meta$/) {
2824: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2825: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2826: if ($mresponse->is_error()) {
2827: unlink($filename.'.meta');
2828: &logthis(
1.672 albertel 2829: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2830: }
2831: }
1.8 www 2832: rename($transname,$filename);
1.607 raeburn 2833: return 'ok';
1.8 www 2834: }
1.290 www 2835: }
1.8 www 2836: }
1.330 www 2837: }
2838:
2839: # ------------------------------------------------ Get server side include body
2840: sub ssi_body {
1.381 albertel 2841: my ($filelink,%form)=@_;
1.606 matthew 2842: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2843: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2844: }
1.953 www 2845: my $output='';
2846: my $response;
1.980 raeburn 2847: if ($filelink=~/^https?\:/) {
1.954 raeburn 2848: ($output,$response)=&externalssi($filelink);
1.953 www 2849: } else {
1.1004 droeschl 2850: $filelink .= $filelink=~/\?/ ? '&' : '?';
2851: $filelink .= 'inhibitmenu=yes';
1.953 www 2852: ($output,$response)=&ssi($filelink,%form);
2853: }
1.778 albertel 2854: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2855: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2856: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2857: if (wantarray) {
2858: return ($output, $response);
2859: } else {
2860: return $output;
2861: }
1.8 www 2862: }
2863:
1.15 www 2864: # --------------------------------------------------------- Server Side Include
2865:
1.782 albertel 2866: sub absolute_url {
2867: my ($host_name) = @_;
2868: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2869: if ($host_name eq '') {
2870: $host_name = $ENV{'SERVER_NAME'};
2871: }
2872: return $protocol.$host_name;
2873: }
2874:
1.942 foxr 2875: #
2876: # Server side include.
2877: # Parameters:
2878: # fn Possibly encrypted resource name/id.
2879: # form Hash that describes how the rendering should be done
2880: # and other things.
1.944 foxr 2881: # Returns:
1.950 raeburn 2882: # Scalar context: The content of the response.
2883: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2884: #
1.15 www 2885: sub ssi {
2886:
1.944 foxr 2887: my ($fn,%form)=@_;
1.15 www 2888: my $ua=new LWP::UserAgent;
1.23 www 2889: my $request;
1.711 albertel 2890:
2891: $form{'no_update_last_known'}=1;
1.895 albertel 2892: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2893: if (%form) {
1.782 albertel 2894: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2895: $request->content(join('&',map {
2896: my $name = escape($_);
2897: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2898: ? join("&$name=", map {escape($_) } @{$form{$_}})
2899: : &escape($form{$_}) );
2900: } keys(%form)));
1.23 www 2901: } else {
1.782 albertel 2902: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2903: }
2904:
1.15 www 2905: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2906: my $response= $ua->request($request);
1.944 foxr 2907: if (wantarray) {
1.1172.2.3 raeburn 2908: return ($response->content, $response);
1.944 foxr 2909: } else {
1.1172.2.3 raeburn 2910: return $response->content;
1.942 foxr 2911: }
1.324 www 2912: }
2913:
2914: sub externalssi {
2915: my ($url)=@_;
2916: my $ua=new LWP::UserAgent;
2917: my $request=new HTTP::Request('GET',$url);
2918: my $response=$ua->request($request);
1.954 raeburn 2919: if (wantarray) {
2920: return ($response->content, $response);
2921: } else {
2922: return $response->content;
2923: }
1.15 www 2924: }
1.254 www 2925:
1.492 albertel 2926: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2927:
2928: sub allowuploaded {
2929: my ($srcurl,$url)=@_;
2930: $url=&clutter(&declutter($url));
2931: my $dir=$url;
2932: $dir=~s/\/[^\/]+$//;
2933: my %httpref=();
2934: my $httpurl=&hreflocation('',$url);
2935: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2936: &Apache::lonnet::appenv(\%httpref);
1.254 www 2937: }
1.477 raeburn 2938:
1.1172.2.13 raeburn 2939: #
2940: # Determine if the current user should be able to edit a particular resource,
2941: # when viewing in course context.
2942: # (a) When viewing resource used to determine if "Edit" item is included in
2943: # Functions.
2944: # (b) When displaying folder contents in course editor, used to determine if
2945: # "Edit" link will be displayed alongside resource.
2946: #
2947: # input: six args -- filename (decluttered), course number, course domain,
2948: # url, symb (if registered) and group (if this is a group
2949: # item -- e.g., bulletin board, group page etc.).
2950: # output: array of five scalars --
2951: # $cfile -- url for file editing if editable on current server
2952: # $home -- homeserver of resource (i.e., for author if published,
2953: # or course if uploaded.).
2954: # $switchserver -- 1 if server switch will be needed.
2955: # $forceedit -- 1 if icon/link should be to go to edit mode
2956: # $forceview -- 1 if icon/link should be to go to view mode
2957: #
2958:
2959: sub can_edit_resource {
2960: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2961: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2962: #
2963: # For aboutme pages user can only edit his/her own.
2964: #
2965: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2966: my ($sdom,$sname) = ($1,$2);
2967: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2968: $home = $env{'user.home'};
2969: $cfile = $resurl;
2970: if ($env{'form.forceedit'}) {
2971: $forceview = 1;
2972: } else {
2973: $forceedit = 1;
2974: }
2975: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2976: } else {
2977: return;
2978: }
2979: }
2980:
2981: if ($env{'request.course.id'}) {
2982: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2983: if ($group ne '') {
2984: # if this is a group homepage or group bulletin board, check group privs
2985: my $allowed = 0;
2986: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2987: if ((&allowed('mdg',$env{'request.course.id'}.
2988: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2989: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2990: $allowed = 1;
2991: }
2992: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2993: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2994: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2995: $allowed = 1;
2996: }
2997: }
2998: if ($allowed) {
2999: $home=&homeserver($cnum,$cdom);
3000: if ($env{'form.forceedit'}) {
3001: $forceview = 1;
3002: } else {
3003: $forceedit = 1;
3004: }
3005: $cfile = $resurl;
3006: } else {
3007: return;
3008: }
3009: } else {
1.1172.2.15 raeburn 3010: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3011: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3012: return;
3013: }
3014: } elsif (!$crsedit) {
1.1172.2.13 raeburn 3015: #
3016: # No edit allowed where CC has switched to student role.
3017: #
3018: return;
3019: }
3020: }
3021: }
3022:
3023: if ($file ne '') {
3024: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3025: if (&is_course_upload($file,$cnum,$cdom)) {
3026: $uploaded = 1;
3027: $incourse = 1;
3028: if ($file =~/\.(htm|html|css|js|txt)$/) {
3029: $cfile = &hreflocation('',$file);
3030: if ($env{'form.forceedit'}) {
3031: $forceview = 1;
3032: } else {
3033: $forceedit = 1;
3034: }
3035: }
3036: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3037: $incourse = 1;
3038: if ($env{'form.forceedit'}) {
3039: $forceview = 1;
3040: } else {
3041: $forceedit = 1;
3042: }
3043: $cfile = $resurl;
3044: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3045: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3046: $incourse = 1;
3047: if ($env{'form.forceedit'}) {
3048: $forceview = 1;
3049: } else {
3050: $forceedit = 1;
3051: }
3052: $cfile = $resurl;
3053: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3054: $incourse = 1;
3055: $cfile = $resurl.'/smpedit';
3056: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3057: $incourse = 1;
3058: if ($env{'form.forceedit'}) {
3059: $forceview = 1;
3060: } else {
3061: $forceedit = 1;
3062: }
3063: $cfile = $resurl;
1.1172.2.93.4 2(raebur 3064:7): } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3065:7): $incourse = 1;
3066:7): if ($env{'form.forceedit'}) {
3067:7): $forceview = 1;
3068:7): } else {
3069:7): $forceedit = 1;
3070:7): }
3071:7): $cfile = $resurl;
1.1172.2.15 raeburn 3072: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3073: $incourse = 1;
3074: if ($env{'form.forceedit'}) {
3075: $forceview = 1;
3076: } else {
3077: $forceedit = 1;
3078: }
3079: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3080: }
3081: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3082: my $template = '/res/lib/templates/simpleproblem.problem';
3083: if (&is_on_map($template)) {
3084: $incourse = 1;
3085: $forceview = 1;
3086: $cfile = $template;
3087: }
3088: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3089: $incourse = 1;
3090: if ($env{'form.forceedit'}) {
3091: $forceview = 1;
3092: } else {
3093: $forceedit = 1;
3094: }
3095: $cfile = $resurl;
1.1172.2.93.4 2(raebur 3096:7): } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3097:7): $incourse = 1;
3098:7): if ($env{'form.forceedit'}) {
3099:7): $forceview = 1;
3100:7): } else {
3101:7): $forceedit = 1;
3102:7): }
3103:7): $cfile = $resurl;
1.1172.2.13 raeburn 3104: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3105: $incourse = 1;
3106: $forceview = 1;
3107: if ($symb) {
3108: my ($map,$id,$res)=&decode_symb($symb);
3109: $env{'request.symb'} = $symb;
3110: $cfile = &clutter($res);
3111: } else {
3112: $cfile = $env{'form.suppurl'};
1.1172.2.93.4 1(raebur 3113:7): my $escfile = &unescape($cfile);
2(raebur 3114:7): if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3115:7): $cfile = '/adm/wrapper'.$escfile;
3116:7): } else {
3117:7): $escfile =~ s{^http://}{};
3118:7): $cfile = &escape("/adm/wrapper/ext/$escfile");
3119:7): }
1.1172.2.13 raeburn 3120: }
1.1172.2.31 raeburn 3121: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3122: if ($env{'form.forceedit'}) {
3123: $forceview = 1;
3124: } else {
3125: $forceedit = 1;
3126: }
3127: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3128: }
3129: }
3130: if ($uploaded || $incourse) {
3131: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3132: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3133: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3134: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3135: # Check that the user has permission to edit this resource
3136: my $setpriv = 1;
3137: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3138: if (defined($cfudom)) {
3139: $home=&homeserver($cfuname,$cfudom);
3140: $cfile=$file;
3141: }
3142: }
3143: if (($cfile ne '') && (!$incourse || $uploaded) &&
3144: (($home ne '') && ($home ne 'no_host'))) {
3145: my @ids=¤t_machine_ids();
3146: unless (grep(/^\Q$home\E$/,@ids)) {
3147: $switchserver=1;
3148: }
3149: }
3150: }
3151: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3152: }
3153:
3154: sub is_course_upload {
3155: my ($file,$cnum,$cdom) = @_;
3156: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3157: $uploadpath =~ s{^\/}{};
3158: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3159: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3160: return 1;
3161: }
3162: return;
3163: }
3164:
3165: sub in_course {
3166: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3167: if ($hideprivileged) {
3168: my $skipuser;
1.1172.2.23 raeburn 3169: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3170: my @possdoms = ($cdom);
3171: if ($coursehash{'checkforpriv'}) {
3172: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3173: }
3174: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3175: $skipuser = 1;
3176: if ($coursehash{'nothideprivileged'}) {
3177: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3178: my $user;
3179: if ($item =~ /:/) {
3180: $user = $item;
3181: } else {
3182: $user = join(':',split(/[\@]/,$item));
3183: }
3184: if ($user eq $uname.':'.$udom) {
3185: undef($skipuser);
3186: last;
3187: }
3188: }
3189: }
3190: if ($skipuser) {
3191: return 0;
3192: }
3193: }
3194: }
3195: $type ||= 'any';
3196: if (!defined($cdom) || !defined($cnum)) {
3197: my $cid = $env{'request.course.id'};
3198: $cdom = $env{'course.'.$cid.'.domain'};
3199: $cnum = $env{'course.'.$cid.'.num'};
3200: }
3201: my $typesref;
3202: if (($type eq 'any') || ($type eq 'all')) {
3203: $typesref = ['active','previous','future'];
3204: } elsif ($type eq 'previous' || $type eq 'future') {
3205: $typesref = [$type];
3206: }
3207: my %roles = &get_my_roles($uname,$udom,'userroles',
3208: $typesref,undef,[$cdom]);
3209: my ($tmp) = keys(%roles);
3210: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3211: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3212: if (@course_roles > 0) {
3213: return 1;
3214: }
3215: return 0;
3216: }
3217:
1.478 albertel 3218: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3219: # input: action, courseID, current domain, intended
1.637 raeburn 3220: # path to file, source of file, instruction to parse file for objects,
3221: # ref to hash for embedded objects,
3222: # ref to hash for codebase of java objects.
1.1095 raeburn 3223: # reference to scalar to accommodate mime type determined
3224: # from File::MMagic if $parser = parse.
1.637 raeburn 3225: #
1.485 raeburn 3226: # output: url to file (if action was uploaddoc),
3227: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3228: #
1.478 albertel 3229: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3230: # course.
1.477 raeburn 3231: #
1.478 albertel 3232: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3233: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3234: # course's home server.
1.477 raeburn 3235: #
1.478 albertel 3236: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3237: # be copied from $source (current location) to
3238: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3239: # and will then be copied to
3240: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3241: # course's home server.
1.485 raeburn 3242: #
1.481 raeburn 3243: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3244: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3245: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3246: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3247: # in course's home server.
1.637 raeburn 3248: #
1.477 raeburn 3249:
3250: sub process_coursefile {
1.1095 raeburn 3251: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3252: $mimetype)=@_;
1.477 raeburn 3253: my $fetchresult;
1.638 albertel 3254: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3255: if ($action eq 'propagate') {
1.638 albertel 3256: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3257: $home);
1.481 raeburn 3258: } else {
1.477 raeburn 3259: my $fpath = '';
3260: my $fname = $file;
1.478 albertel 3261: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3262: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3263: my $filepath = &build_filepath($fpath);
1.481 raeburn 3264: if ($action eq 'copy') {
3265: if ($source eq '') {
3266: $fetchresult = 'no source file';
3267: return $fetchresult;
3268: } else {
3269: my $destination = $filepath.'/'.$fname;
3270: rename($source,$destination);
3271: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3272: $home);
1.481 raeburn 3273: }
3274: } elsif ($action eq 'uploaddoc') {
1.1172.2.93.4 7(raebur 3275:7): open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3276: print $fh $env{'form.'.$source};
1.481 raeburn 3277: close($fh);
1.637 raeburn 3278: if ($parser eq 'parse') {
1.1024 raeburn 3279: my $mm = new File::MMagic;
1.1095 raeburn 3280: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3281: if ($type eq 'text/html') {
1.1024 raeburn 3282: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3283: unless ($parse_result eq 'ok') {
3284: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3285: }
1.637 raeburn 3286: }
1.1095 raeburn 3287: if (ref($mimetype)) {
3288: $$mimetype = $type;
3289: }
1.637 raeburn 3290: }
1.477 raeburn 3291: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3292: $home);
1.481 raeburn 3293: if ($fetchresult eq 'ok') {
3294: return '/uploaded/'.$fpath.'/'.$fname;
3295: } else {
3296: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3297: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3298: return '/adm/notfound.html';
3299: }
1.477 raeburn 3300: }
3301: }
1.485 raeburn 3302: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3303: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3304: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3305: }
3306: return $fetchresult;
3307: }
3308:
1.637 raeburn 3309: sub build_filepath {
3310: my ($fpath) = @_;
3311: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3312: unless ($fpath eq '') {
3313: my @parts=split('/',$fpath);
3314: foreach my $part (@parts) {
3315: $filepath.= '/'.$part;
3316: if ((-e $filepath)!=1) {
3317: mkdir($filepath,0777);
3318: }
3319: }
3320: }
3321: return $filepath;
3322: }
3323:
3324: sub store_edited_file {
1.638 albertel 3325: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3326: my $file = $primary_url;
3327: $file =~ s#^/uploaded/$docudom/$docuname/##;
3328: my $fpath = '';
3329: my $fname = $file;
3330: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3331: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3332: my $filepath = &build_filepath($fpath);
1.1172.2.93.4 7(raebur 3333:7): open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3334: print $fh $content;
3335: close($fh);
1.638 albertel 3336: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3337: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3338: $home);
1.637 raeburn 3339: if ($$fetchresult eq 'ok') {
3340: return '/uploaded/'.$fpath.'/'.$fname;
3341: } else {
1.638 albertel 3342: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3343: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3344: return '/adm/notfound.html';
3345: }
3346: }
3347:
1.531 albertel 3348: sub clean_filename {
1.831 albertel 3349: my ($fname,$args)=@_;
1.315 www 3350: # Replace Windows backslashes by forward slashes
1.257 www 3351: $fname=~s/\\/\//g;
1.831 albertel 3352: if (!$args->{'keep_path'}) {
3353: # Get rid of everything but the actual filename
3354: $fname=~s/^.*\/([^\/]+)$/$1/;
3355: }
1.315 www 3356: # Replace spaces by underscores
3357: $fname=~s/\s+/\_/g;
3358: # Replace all other weird characters by nothing
1.831 albertel 3359: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3360: # Replace all .\d. sequences with _\d. so they no longer look like version
3361: # numbers
3362: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3363: return $fname;
3364: }
1.1051 raeburn 3365: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3366: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3367: # image with the same aspect ratio as the original, but with dimensions which do
3368: # not exceed $resizewidth and $resizeheight.
3369:
1.984 neumanie 3370: sub resizeImage {
1.1051 raeburn 3371: my ($img_path,$resizewidth,$resizeheight) = @_;
3372: my $ima = Image::Magick->new;
3373: my $resized;
3374: if (-e $img_path) {
3375: $ima->Read($img_path);
3376: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3377: my $width = $ima->Get('width');
3378: my $height = $ima->Get('height');
3379: if ($width > $resizewidth) {
3380: my $factor = $width/$resizewidth;
3381: my $newheight = $height/$factor;
3382: $ima->Scale(width=>$resizewidth,height=>$newheight);
3383: $resized = 1;
3384: }
3385: }
3386: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3387: my $width = $ima->Get('width');
3388: my $height = $ima->Get('height');
3389: if ($height > $resizeheight) {
3390: my $factor = $height/$resizeheight;
3391: my $newwidth = $width/$factor;
3392: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3393: $resized = 1;
3394: }
3395: }
3396: if ($resized) {
3397: $ima->Write($img_path);
3398: }
3399: }
3400: return;
1.977 amueller 3401: }
3402:
1.608 albertel 3403: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3404: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3405: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3406: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.93.4 12(raebu 3407:19): # canceloverwrite, scantron or ''.
1.1090 raeburn 3408: # if 'coursedoc': upload to the current course
3409: # if 'existingfile': write file to tmp/overwrites directory
3410: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3411: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3412: # $subdir - directory in userfile to store the file into
1.1172.2.93.4 12(raebu 3413:19): # $parser - instruction to parse file for objects ($parser = parse) or
3414:19): # if context is 'scantron', $parser is hashref of csv column mapping
3415:19): # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3416:19): # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3417: # $allfiles - reference to hash for embedded objects
3418: # $codebase - reference to hash for codebase of java objects
3419: # $desuname - username for permanent storage of uploaded file
3420: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3421: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3422: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3423: # $resizewidth - width (pixels) to which to resize uploaded image
3424: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3425: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3426: # from File::MMagic.
1.858 raeburn 3427: #
1.686 albertel 3428: # output: url of file in userspace, or error: <message>
3429: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3430:
1.531 albertel 3431: sub userfileupload {
1.1090 raeburn 3432: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3433: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3434: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3435: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3436: $fname=&clean_filename($fname);
1.1090 raeburn 3437: # See if there is anything left
1.257 www 3438: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3439: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3440: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3441: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3442: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3443: my $now = time;
1.1090 raeburn 3444: my $filepath;
1.1095 raeburn 3445: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3446: $filepath = 'tmp/helprequests/'.$now;
3447: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3448: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3449: '_'.$env{'user.domain'}.'/pending';
3450: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3451: my ($docuname,$docudom);
1.1172.2.93.4 5(raebur 3452:7): if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3453: $docudom = $destudom;
3454: } else {
3455: $docudom = $env{'user.domain'};
3456: }
1.1172.2.93.4 5(raebur 3457:7): if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3458: $docuname = $destuname;
3459: } else {
3460: $docuname = $env{'user.name'};
3461: }
3462: if (exists($env{'form.group'})) {
3463: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3464: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3465: }
3466: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3467: if ($context eq 'canceloverwrite') {
3468: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3469: if (-e $tempfile) {
3470: my @info = stat($tempfile);
3471: if ($info[9] eq $env{'form.timestamp'}) {
3472: unlink($tempfile);
3473: }
3474: }
3475: return;
1.523 raeburn 3476: }
3477: }
1.1090 raeburn 3478: # Create the directory if not present
1.741 raeburn 3479: my @parts=split(/\//,$filepath);
3480: my $fullpath = $perlvar{'lonDaemons'};
3481: for (my $i=0;$i<@parts;$i++) {
3482: $fullpath .= '/'.$parts[$i];
3483: if ((-e $fullpath)!=1) {
3484: mkdir($fullpath,0777);
3485: }
3486: }
1.1172.2.93.4 7(raebur 3487:7): open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3488: print $fh $env{'form.'.$formname};
3489: close($fh);
1.1090 raeburn 3490: if ($context eq 'existingfile') {
3491: my @info = stat($fullpath.'/'.$fname);
3492: return ($fullpath.'/'.$fname,$info[9]);
3493: } else {
3494: return $fullpath.'/'.$fname;
3495: }
1.523 raeburn 3496: }
1.995 raeburn 3497: if ($subdir eq 'scantron') {
3498: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3499: } else {
1.995 raeburn 3500: $fname="$subdir/$fname";
3501: }
1.1090 raeburn 3502: if ($context eq 'coursedoc') {
1.638 albertel 3503: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3504: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3505: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3506: return &finishuserfileupload($docuname,$docudom,
3507: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3508: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3509: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3510: } else {
1.1172.2.21 raeburn 3511: if ($env{'form.folder'}) {
3512: $fname=$env{'form.folder'}.'/'.$fname;
3513: }
1.638 albertel 3514: return &process_coursefile('uploaddoc',$docuname,$docudom,
3515: $fname,$formname,$parser,
1.1095 raeburn 3516: $allfiles,$codebase,$mimetype);
1.481 raeburn 3517: }
1.719 banghart 3518: } elsif (defined($destuname)) {
3519: my $docuname=$destuname;
3520: my $docudom=$destudom;
1.860 raeburn 3521: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3522: $parser,$allfiles,$codebase,
1.1051 raeburn 3523: $thumbwidth,$thumbheight,
1.1095 raeburn 3524: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3525: } else {
1.638 albertel 3526: my $docuname=$env{'user.name'};
3527: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3528: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3529: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3530: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3531: }
1.860 raeburn 3532: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3533: $parser,$allfiles,$codebase,
1.1051 raeburn 3534: $thumbwidth,$thumbheight,
1.1095 raeburn 3535: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3536: }
1.271 www 3537: }
3538:
3539: sub finishuserfileupload {
1.860 raeburn 3540: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3541: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3542: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3543: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3544:
1.860 raeburn 3545: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3546: $file=$fname;
3547: if ($fname=~m|/|) {
3548: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3549: $path.=$fnamepath.'/';
3550: }
1.259 www 3551: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3552: my $count;
3553: for ($count=4;$count<=$#parts;$count++) {
3554: $filepath.="/$parts[$count]";
3555: if ((-e $filepath)!=1) {
3556: mkdir($filepath,0777);
3557: }
3558: }
1.984 neumanie 3559:
1.258 www 3560: # Save the file
3561: {
1.1172.2.93.4 7(raebur 3562:7): if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 3563: &logthis('Failed to create '.$filepath.'/'.$file);
3564: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3565: return '/adm/notfound.html';
3566: }
1.1090 raeburn 3567: if ($context eq 'overwrite') {
1.1117 foxr 3568: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3569: my $target = $filepath.'/'.$file;
3570: if (-e $source) {
3571: my @info = stat($source);
3572: if ($info[9] eq $env{'form.timestamp'}) {
3573: unless (&File::Copy::move($source,$target)) {
3574: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3575: return "Moving from $source failed";
3576: }
3577: } else {
3578: return "Temporary file: $source had unexpected date/time for last modification";
3579: }
3580: } else {
3581: return "Temporary file: $source missing";
3582: }
3583: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3584: &logthis('Failed to write to '.$filepath.'/'.$file);
3585: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3586: return '/adm/notfound.html';
3587: }
1.570 albertel 3588: close(FH);
1.1051 raeburn 3589: if ($resizewidth && $resizeheight) {
3590: my $mm = new File::MMagic;
3591: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3592: if ($mime_type =~ m{^image/}) {
3593: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3594: }
1.977 amueller 3595: }
1.258 www 3596: }
1.1152 raeburn 3597: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3598: if (ref($mimetype)) {
3599: if ($$mimetype eq '') {
3600: my $mm = new File::MMagic;
3601: my $type = $mm->checktype_filename($filepath.'/'.$file);
3602: $$mimetype = $type;
3603: }
3604: }
3605: }
1.1172.2.93.4 12(raebu 3606:19): if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 3607: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3608: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3609: $allfiles,$codebase);
3610: unless ($parse_result eq 'ok') {
3611: &logthis('Failed to parse '.$filepath.$file.
3612: ' for embedded media: '.$parse_result);
3613: }
1.637 raeburn 3614: }
1.1172.2.93.4 12(raebu 3615:19): } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
3616:19): my $format = $env{'form.scantron_format'};
3617:19): &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 3618: }
1.860 raeburn 3619: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3620: my $input = $filepath.'/'.$file;
3621: my $output = $filepath.'/'.'tn-'.$file;
3622: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.93.4 7(raebur 3623:7): my @args = ('convert','-sample',$thumbsize,$input,$output);
3624:7): system({$args[0]} @args);
1.860 raeburn 3625: if (-e $filepath.'/'.'tn-'.$file) {
3626: $fetchthumb = 1;
3627: }
3628: }
1.858 raeburn 3629:
1.259 www 3630: # Notify homeserver to grep it
3631: #
1.984 neumanie 3632: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3633: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3634: if ($fetchresult eq 'ok') {
1.860 raeburn 3635: if ($fetchthumb) {
3636: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3637: if ($thumbresult ne 'ok') {
3638: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3639: $docuhome.': '.$thumbresult);
3640: }
3641: }
1.259 www 3642: #
1.258 www 3643: # Return the URL to it
1.494 albertel 3644: return '/uploaded/'.$path.$file;
1.263 www 3645: } else {
1.494 albertel 3646: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3647: ': '.$fetchresult);
1.263 www 3648: return '/adm/notfound.html';
1.858 raeburn 3649: }
1.493 albertel 3650: }
3651:
1.637 raeburn 3652: sub extract_embedded_items {
1.961 raeburn 3653: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3654: my @state = ();
1.1164 raeburn 3655: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3656: my %javafiles = (
3657: codebase => '',
3658: code => '',
3659: archive => ''
3660: );
3661: my %mediafiles = (
3662: src => '',
3663: movie => '',
3664: );
1.648 raeburn 3665: my $p;
3666: if ($content) {
3667: $p = HTML::LCParser->new($content);
3668: } else {
1.961 raeburn 3669: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3670: }
1.641 albertel 3671: while (my $t=$p->get_token()) {
1.640 albertel 3672: if ($t->[0] eq 'S') {
3673: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3674: push(@state, $tagname);
1.648 raeburn 3675: if (lc($tagname) eq 'allow') {
3676: &add_filetype($allfiles,$attr->{'src'},'src');
3677: }
1.640 albertel 3678: if (lc($tagname) eq 'img') {
3679: &add_filetype($allfiles,$attr->{'src'},'src');
3680: }
1.886 albertel 3681: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3682: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3683: &add_filetype($allfiles,$attr->{'href'},'href');
3684: }
1.886 albertel 3685: }
1.645 raeburn 3686: if (lc($tagname) eq 'script') {
1.1164 raeburn 3687: my $src;
1.645 raeburn 3688: if ($attr->{'archive'} =~ /\.jar$/i) {
3689: &add_filetype($allfiles,$attr->{'archive'},'archive');
3690: } else {
1.1164 raeburn 3691: if ($attr->{'src'} ne '') {
3692: $src = $attr->{'src'};
3693: &add_filetype($allfiles,$src,'src');
3694: }
3695: }
3696: my $text = $p->get_trimmed_text();
3697: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3698: my @swfargs = split(/,/,$1);
3699: foreach my $item (@swfargs) {
3700: $item =~ s/["']//g;
3701: $item =~ s/^\s+//;
3702: $item =~ s/\s+$//;
3703: }
3704: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3705: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3706: push(@{$related{$swfargs[0]}},$swfargs[2]);
3707: } else {
3708: $related{$swfargs[0]} = [$swfargs[2]];
3709: }
3710: }
1.645 raeburn 3711: }
3712: }
3713: if (lc($tagname) eq 'link') {
3714: if (lc($attr->{'rel'}) eq 'stylesheet') {
3715: &add_filetype($allfiles,$attr->{'href'},'href');
3716: }
3717: }
1.640 albertel 3718: if (lc($tagname) eq 'object' ||
3719: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3720: foreach my $item (keys(%javafiles)) {
3721: $javafiles{$item} = '';
3722: }
1.1164 raeburn 3723: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3724: $lastids{lc($tagname)} = $attr->{'id'};
3725: }
1.640 albertel 3726: }
3727: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3728: my $name = lc($attr->{'name'});
3729: foreach my $item (keys(%javafiles)) {
3730: if ($name eq $item) {
3731: $javafiles{$item} = $attr->{'value'};
3732: last;
3733: }
3734: }
1.1164 raeburn 3735: my $pathfrom;
1.640 albertel 3736: foreach my $item (keys(%mediafiles)) {
3737: if ($name eq $item) {
1.1164 raeburn 3738: $pathfrom = $attr->{'value'};
3739: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3740: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3741: last;
3742: }
3743: }
1.1164 raeburn 3744: if ($name eq 'flashvars') {
3745: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3746: }
3747: if ($pathfrom ne '') {
3748: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3749: $pathfrom);
3750: }
1.640 albertel 3751: }
3752: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3753: foreach my $item (keys(%javafiles)) {
3754: if ($attr->{$item}) {
3755: $javafiles{$item} = $attr->{$item};
3756: last;
3757: }
3758: }
3759: foreach my $item (keys(%mediafiles)) {
3760: if ($attr->{$item}) {
3761: &add_filetype($allfiles,$attr->{$item},$item);
3762: last;
3763: }
3764: }
1.1164 raeburn 3765: if (lc($tagname) eq 'embed') {
3766: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3767: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3768: $attr->{'src'});
3769: }
3770: }
1.640 albertel 3771: }
1.1172.2.35 raeburn 3772: if (lc($tagname) eq 'iframe') {
3773: my $src = $attr->{'src'} ;
3774: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3775: &add_filetype($allfiles,$src,'src');
3776: } elsif ($src =~ m{^/}) {
3777: if ($env{'request.course.id'}) {
3778: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3779: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3780: my $url = &hreflocation('',$fullpath);
3781: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3782: my $relpath = $1;
3783: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3784: &add_filetype($allfiles,$1,'src');
3785: }
3786: }
3787: }
3788: }
3789: }
1.1164 raeburn 3790: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3791: pop(@state);
1.1164 raeburn 3792: }
1.640 albertel 3793: } elsif ($t->[0] eq 'E') {
3794: my ($tagname) = ($t->[1]);
3795: if ($javafiles{'codebase'} ne '') {
3796: $javafiles{'codebase'} .= '/';
3797: }
3798: if (lc($tagname) eq 'applet' ||
3799: lc($tagname) eq 'object' ||
3800: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3801: ) {
3802: foreach my $item (keys(%javafiles)) {
3803: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3804: my $file=$javafiles{'codebase'}.$javafiles{$item};
3805: &add_filetype($allfiles,$file,$item);
3806: }
3807: }
3808: }
3809: pop @state;
3810: }
3811: }
1.1164 raeburn 3812: foreach my $id (sort(keys(%flashvars))) {
3813: if ($shockwave{$id} ne '') {
3814: my @pairs = split(/\&/,$flashvars{$id});
3815: foreach my $pair (@pairs) {
3816: my ($key,$value) = split(/\=/,$pair);
3817: if ($key eq 'thumb') {
3818: &add_filetype($allfiles,$value,$key);
3819: } elsif ($key eq 'content') {
3820: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3821: my ($ext) = ($value =~ /\.([^.]+)$/);
3822: if ($ext ne '') {
3823: &add_filetype($allfiles,$path.$value,$ext);
3824: }
3825: }
3826: }
3827: }
3828: }
1.637 raeburn 3829: return 'ok';
3830: }
3831:
1.639 albertel 3832: sub add_filetype {
3833: my ($allfiles,$file,$type)=@_;
3834: if (exists($allfiles->{$file})) {
3835: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3836: push(@{$allfiles->{$file}}, &escape($type));
3837: }
3838: } else {
3839: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3840: }
3841: }
3842:
1.1164 raeburn 3843: sub embedded_dependency {
3844: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3845: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3846: if (($identifier ne '') &&
3847: (ref($related->{$identifier}) eq 'ARRAY') &&
3848: ($pathfrom ne '')) {
3849: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3850: foreach my $dep (@{$related->{$identifier}}) {
3851: &add_filetype($allfiles,$path.$dep,'object');
3852: }
3853: }
3854: }
3855: return;
3856: }
3857:
1.1172.2.93.4 12(raebu 3858:19): sub bubblesheet_converter {
3859:19): my ($cdom,$fullpath,$config,$format) = @_;
3860:19): if ((&domain($cdom) ne '') &&
3861:19): ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
3862:19): (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
3863:19): my (%csvcols,%csvoptions);
3864:19): if (ref($config->{'fields'}) eq 'HASH') {
3865:19): %csvcols = %{$config->{'fields'}};
3866:19): }
3867:19): if (ref($config->{'options'}) eq 'HASH') {
3868:19): %csvoptions = %{$config->{'options'}};
3869:19): }
3870:19): my %csvbynum = reverse(%csvcols);
3871:19): my %scantronconf = &get_scantron_config($format,$cdom);
3872:19): if (keys(%scantronconf)) {
3873:19): my %bynum = (
3874:19): $scantronconf{CODEstart} => 'CODEstart',
3875:19): $scantronconf{IDstart} => 'IDstart',
3876:19): $scantronconf{PaperID} => 'PaperID',
3877:19): $scantronconf{FirstName} => 'FirstName',
3878:19): $scantronconf{LastName} => 'LastName',
3879:19): $scantronconf{Qstart} => 'Qstart',
3880:19): );
3881:19): my @ordered;
3882:19): foreach my $item (sort { $a <=> $b } keys(%bynum)) {
3883:19): push(@ordered,$bynum{$item});
3884:19): }
3885:19): my %mapstart = (
3886:19): CODEstart => 'CODE',
3887:19): IDstart => 'ID',
3888:19): PaperID => 'PaperID',
3889:19): FirstName => 'FirstName',
3890:19): LastName => 'LastName',
3891:19): Qstart => 'FirstQuestion',
3892:19): );
3893:19): my %maplength = (
3894:19): CODEstart => 'CODElength',
3895:19): IDstart => 'IDlength',
3896:19): PaperID => 'PaperIDlength',
3897:19): FirstName => 'FirstNamelength',
3898:19): LastName => 'LastNamelength',
3899:19): );
3900:19): if (open(my $fh,'<',$fullpath)) {
3901:19): my $output;
3902:19): my %lettdig = &letter_to_digits();
3903:19): my %diglett = reverse(%lettdig);
3904:19): my $numletts = scalar(keys(%lettdig));
3905:19): my $num = 0;
3906:19): while (my $line=<$fh>) {
3907:19): $num ++;
3908:19): next if (($num == 1) && ($csvoptions{'hdr'} == 1));
3909:19): $line =~ s{[\r\n]+$}{};
3910:19): my %found;
3911:19): my @values = split(/,/,$line);
3912:19): my ($qstart,$record);
3913:19): for (my $i=0; $i<@values; $i++) {
3914:19): if ((($qstart ne '') && ($i > $qstart)) ||
3915:19): ($csvbynum{$i} eq 'FirstQuestion')) {
3916:19): if ($values[$i] eq '') {
3917:19): $values[$i] = $scantronconf{'Qoff'};
3918:19): } elsif ($scantronconf{'Qon'} eq 'number') {
3919:19): if ($values[$i] =~ /^[A-Ja-j]$/) {
3920:19): $values[$i] = $lettdig{uc($values[$i])};
3921:19): }
3922:19): } elsif ($scantronconf{'Qon'} eq 'letter') {
3923:19): if ($values[$i] =~ /^[0-9]$/) {
3924:19): $values[$i] = $diglett{$values[$i]};
3925:19): }
3926:19): } else {
3927:19): if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
3928:19): my $digit;
3929:19): if ($values[$i] =~ /^[A-Ja-j]$/) {
3930:19): $digit = $lettdig{uc($values[$i])}-1;
3931:19): if ($values[$i] eq 'J') {
3932:19): $digit += $numletts;
3933:19): }
3934:19): } elsif ($values[$i] =~ /^[0-9]$/) {
3935:19): $digit = $values[$i]-1;
3936:19): if ($values[$i] eq '0') {
3937:19): $digit += $numletts;
3938:19): }
3939:19): }
3940:19): my $qval='';
3941:19): for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
3942:19): if ($j == $digit) {
3943:19): $qval .= $scantronconf{'Qon'};
3944:19): } else {
3945:19): $qval .= $scantronconf{'Qoff'};
3946:19): }
3947:19): }
3948:19): $values[$i] = $qval;
3949:19): }
3950:19): }
3951:19): if (length($values[$i]) > $scantronconf{'Qlength'}) {
3952:19): $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
3953:19): }
3954:19): my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
3955:19): if ($numblank > 0) {
3956:19): $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
3957:19): }
3958:19): if ($csvbynum{$i} eq 'FirstQuestion') {
3959:19): $qstart = $i;
3960:19): $found{$csvbynum{$i}} = $values[$i];
3961:19): } else {
3962:19): $found{'FirstQuestion'} .= $values[$i];
3963:19): }
3964:19): } elsif (exists($csvbynum{$i})) {
3965:19): if ($csvoptions{'rem'}) {
3966:19): $values[$i] =~ s/^\s+//;
3967:19): }
3968:19): if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
3969:19): while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
3970:19): $values[$i] = '0'.$values[$i];
3971:19): }
3972:19): }
3973:19): $found{$csvbynum{$i}} = $values[$i];
3974:19): }
3975:19): }
3976:19): foreach my $item (@ordered) {
3977:19): my $currlength = 1+length($record);
3978:19): my $numspaces = $scantronconf{$item} - $currlength;
3979:19): if ($numspaces > 0) {
3980:19): $record .= (' ' x $numspaces);
3981:19): }
3982:19): if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
3983:19): unless ($item eq 'Qstart') {
3984:19): if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
3985:19): $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
3986:19): }
3987:19): }
3988:19): $record .= $found{$mapstart{$item}};
3989:19): }
3990:19): }
3991:19): $output .= "$record\n";
3992:19): }
3993:19): close($fh);
3994:19): if ($output) {
3995:19): if (open(my $fh,'>',$fullpath)) {
3996:19): print $fh $output;
3997:19): close($fh);
3998:19): }
3999:19): }
4000:19): }
4001:19): }
4002:19): return;
4003:19): }
4004:19): }
4005:19):
4006:19): sub letter_to_digits {
4007:19): my %lettdig = (
4008:19): A => 1,
4009:19): B => 2,
4010:19): C => 3,
4011:19): D => 4,
4012:19): E => 5,
4013:19): F => 6,
4014:19): G => 7,
4015:19): H => 8,
4016:19): I => 9,
4017:19): J => 0,
4018:19): );
4019:19): return %lettdig;
4020:19): }
4021:19):
4022:19): sub get_scantron_config {
4023:19): my ($which,$cdom) = @_;
4024:19): my @lines = &get_scantronformat_file($cdom);
4025:19): my %config;
4026:19): #FIXME probably should move to XML it has already gotten a bit much now
4027:19): foreach my $line (@lines) {
4028:19): my ($name,$descrip)=split(/:/,$line);
4029:19): if ($name ne $which ) { next; }
4030:19): chomp($line);
4031:19): my @config=split(/:/,$line);
4032:19): $config{'name'}=$config[0];
4033:19): $config{'description'}=$config[1];
4034:19): $config{'CODElocation'}=$config[2];
4035:19): $config{'CODEstart'}=$config[3];
4036:19): $config{'CODElength'}=$config[4];
4037:19): $config{'IDstart'}=$config[5];
4038:19): $config{'IDlength'}=$config[6];
4039:19): $config{'Qstart'}=$config[7];
4040:19): $config{'Qlength'}=$config[8];
4041:19): $config{'Qoff'}=$config[9];
4042:19): $config{'Qon'}=$config[10];
4043:19): $config{'PaperID'}=$config[11];
4044:19): $config{'PaperIDlength'}=$config[12];
4045:19): $config{'FirstName'}=$config[13];
4046:19): $config{'FirstNamelength'}=$config[14];
4047:19): $config{'LastName'}=$config[15];
4048:19): $config{'LastNamelength'}=$config[16];
4049:19): $config{'BubblesPerRow'}=$config[17];
4050:19): last;
4051:19): }
4052:19): return %config;
4053:19): }
4054:19):
4055:19): sub get_scantronformat_file {
4056:19): my ($cdom) = @_;
4057:19): if ($cdom eq '') {
4058:19): $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4059:19): }
4060:19): my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4061:19): my $gottab = 0;
4062:19): my @lines;
4063:19): if (ref($domconfig{'scantron'}) eq 'HASH') {
4064:19): if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4065:19): my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4066:19): if ($formatfile ne '-1') {
4067:19): @lines = split("\n",$formatfile,-1);
4068:19): $gottab = 1;
4069:19): }
4070:19): }
4071:19): }
4072:19): if (!$gottab) {
4073:19): my $confname = $cdom.'-domainconfig';
4074:19): my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4075:19): my $formatfile = &getfile($default);
4076:19): if ($formatfile ne '-1') {
4077:19): @lines = split("\n",$formatfile,-1);
4078:19): $gottab = 1;
4079:19): }
4080:19): }
4081:19): if (!$gottab) {
4082:19): my @domains = ¤t_machine_domains();
4083:19): if (grep(/^\Q$cdom\E$/,@domains)) {
4084:19): if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4085:19): @lines = <$fh>;
4086:19): close($fh);
4087:19): }
4088:19): } else {
4089:19): if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4090:19): @lines = <$fh>;
4091:19): close($fh);
4092:19): }
4093:19): }
4094:19): }
4095:19): return @lines;
4096:19): }
4097:19):
1.493 albertel 4098: sub removeuploadedurl {
1.984 neumanie 4099: my ($url)=@_;
4100: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4101: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4102: }
4103:
4104: sub removeuserfile {
4105: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4106: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4107: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4108: if ($result eq 'ok') {
1.798 raeburn 4109: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4110: my $metafile = $fname.'.meta';
4111: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4112: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4113: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4114: my $sqlresult =
1.823 albertel 4115: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4116: 'portfolio_metadata',$group,
4117: 'delete');
1.798 raeburn 4118: }
4119: }
4120: return $result;
1.257 www 4121: }
1.15 www 4122:
1.530 albertel 4123: sub mkdiruserfile {
4124: my ($docuname,$docudom,$dir)=@_;
4125: my $home=&homeserver($docuname,$docudom);
4126: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4127: }
4128:
1.531 albertel 4129: sub renameuserfile {
4130: my ($docuname,$docudom,$old,$new)=@_;
4131: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4132: my $result = &reply("renameuserfile:$docudom:$docuname:".
4133: &escape("$old").':'.&escape("$new"),$home);
4134: if ($result eq 'ok') {
4135: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4136: my $oldmeta = $old.'.meta';
4137: my $newmeta = $new.'.meta';
4138: my $metaresult =
4139: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4140: my $url = "/uploaded/$docudom/$docuname/$old";
4141: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4142: my $sqlresult =
1.823 albertel 4143: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4144: 'portfolio_metadata',$group,
4145: 'delete');
1.798 raeburn 4146: }
4147: }
4148: return $result;
1.531 albertel 4149: }
4150:
1.14 www 4151: # ------------------------------------------------------------------------- Log
4152:
4153: sub log {
4154: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4155: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4156: }
4157:
4158: # ------------------------------------------------------------------ Course Log
1.352 www 4159: #
4160: # This routine flushes several buffers of non-mission-critical nature
4161: #
1.157 www 4162:
4163: sub flushcourselogs {
1.352 www 4164: &logthis('Flushing log buffers');
4165: #
4166: # course logs
4167: # This is a log of all transactions in a course, which can be used
4168: # for data mining purposes
4169: #
4170: # It also collects the courseid database, which lists last transaction
4171: # times and course titles for all courseids
4172: #
4173: my %courseidbuffer=();
1.921 raeburn 4174: foreach my $crsid (keys(%courselogs)) {
1.352 www 4175: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4176: &escape($courselogs{$crsid}),
4177: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4178: delete $courselogs{$crsid};
4179: } else {
4180: &logthis('Failed to flush log buffer for '.$crsid);
4181: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4182: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4183: " exceeded maximum size, deleting.</font>");
4184: delete $courselogs{$crsid};
4185: }
1.352 www 4186: }
1.920 raeburn 4187: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4188: 'description' => $coursedescrbuf{$crsid},
4189: 'inst_code' => $courseinstcodebuf{$crsid},
4190: 'type' => $coursetypebuf{$crsid},
4191: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4192: };
1.191 harris41 4193: }
1.352 www 4194: #
4195: # Write course id database (reverse lookup) to homeserver of courses
4196: # Is used in pickcourse
4197: #
1.840 albertel 4198: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4199: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4200: $courseidbuffer{$crs_home},
4201: $crs_home,'timeonly');
1.352 www 4202: }
4203: #
4204: # File accesses
4205: # Writes to the dynamic metadata of resources to get hit counts, etc.
4206: #
1.449 matthew 4207: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4208: if ($entry =~ /___count$/) {
4209: my ($dom,$name);
1.807 albertel 4210: ($dom,$name,undef)=
1.811 albertel 4211: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4212: if (! defined($dom) || $dom eq '' ||
4213: ! defined($name) || $name eq '') {
1.620 albertel 4214: my $cid = $env{'request.course.id'};
4215: $dom = $env{'request.'.$cid.'.domain'};
4216: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4217: }
1.450 matthew 4218: my $value = $accesshash{$entry};
4219: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4220: my %temphash=($url => $value);
1.449 matthew 4221: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4222: if ($result eq 'ok') {
4223: delete $accesshash{$entry};
4224: }
4225: } else {
1.811 albertel 4226: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4227: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4228: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4229: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4230: delete $accesshash{$entry};
4231: }
1.185 www 4232: }
1.191 harris41 4233: }
1.352 www 4234: #
4235: # Roles
4236: # Reverse lookup of user roles for course faculty/staff and co-authorship
4237: #
1.800 albertel 4238: foreach my $entry (keys(%userrolehash)) {
1.351 www 4239: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4240: split(/\:/,$entry);
4241: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4242: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4243: $rudom,$runame) eq 'ok') {
4244: delete $userrolehash{$entry};
4245: }
4246: }
1.662 raeburn 4247: #
1.1172.2.90 raeburn 4248: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4249: #
4250: my %domrolebuffer = ();
1.1000 raeburn 4251: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4252: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4253: if ($domrolebuffer{$rudom}) {
4254: $domrolebuffer{$rudom}.='&'.&escape($entry).
4255: '='.&escape($domainrolehash{$entry});
4256: } else {
4257: $domrolebuffer{$rudom}.=&escape($entry).
4258: '='.&escape($domainrolehash{$entry});
4259: }
4260: delete $domainrolehash{$entry};
4261: }
4262: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4263: my %servers;
4264: if (defined(&domain($dom,'primary'))) {
4265: my $primary=&domain($dom,'primary');
4266: my $hostname=&hostname($primary);
4267: $servers{$primary} = $hostname;
4268: } else {
4269: %servers = &get_servers($dom,'library');
4270: }
1.841 albertel 4271: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4272: if (&reply('domroleput:'.$dom.':'.
4273: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4274: last;
4275: } else {
1.841 albertel 4276: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4277: }
1.662 raeburn 4278: }
4279: }
1.186 www 4280: $dumpcount++;
1.157 www 4281: }
4282:
4283: sub courselog {
4284: my $what=shift;
1.158 www 4285: $what=time.':'.$what;
1.620 albertel 4286: unless ($env{'request.course.id'}) { return ''; }
4287: $coursedombuf{$env{'request.course.id'}}=
4288: $env{'course.'.$env{'request.course.id'}.'.domain'};
4289: $coursenumbuf{$env{'request.course.id'}}=
4290: $env{'course.'.$env{'request.course.id'}.'.num'};
4291: $coursehombuf{$env{'request.course.id'}}=
4292: $env{'course.'.$env{'request.course.id'}.'.home'};
4293: $coursedescrbuf{$env{'request.course.id'}}=
4294: $env{'course.'.$env{'request.course.id'}.'.description'};
4295: $courseinstcodebuf{$env{'request.course.id'}}=
4296: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4297: $courseownerbuf{$env{'request.course.id'}}=
4298: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4299: $coursetypebuf{$env{'request.course.id'}}=
4300: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4301: if (defined $courselogs{$env{'request.course.id'}}) {
4302: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4303: } else {
1.620 albertel 4304: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4305: }
1.620 albertel 4306: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4307: &flushcourselogs();
4308: }
1.158 www 4309: }
4310:
4311: sub courseacclog {
4312: my $fnsymb=shift;
1.620 albertel 4313: unless ($env{'request.course.id'}) { return ''; }
4314: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4315: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4316: $what.=':POST';
1.583 matthew 4317: # FIXME: Probably ought to escape things....
1.800 albertel 4318: foreach my $key (keys(%env)) {
4319: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4320: my $formitem = $1;
4321: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4322: $what.=':'.$formitem.'='.$env{$key};
4323: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4324: $what.=':'.$formitem.'='.$env{$key};
4325: }
1.158 www 4326: }
1.191 harris41 4327: }
1.583 matthew 4328: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4329: # FIXME: We should not be depending on a form parameter that someone
4330: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4331: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4332: $what.= ':POST';
4333: # FIXME: Probably ought to escape things....
4334: foreach my $element ('courseexp','crsfulltext','crsrelated',
4335: 'crsdiscuss') {
1.620 albertel 4336: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4337: }
4338: }
1.158 www 4339: }
4340: &courselog($what);
1.149 www 4341: }
4342:
1.185 www 4343: sub countacc {
4344: my $url=&declutter(shift);
1.458 matthew 4345: return if (! defined($url) || $url eq '');
1.620 albertel 4346: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4347: #
4348: # Mark that this url was used in this course
4349: #
1.620 albertel 4350: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4351: #
4352: # Increase the access count for this resource in this child process
4353: #
1.281 www 4354: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4355: $accesshash{$key}++;
1.185 www 4356: }
1.349 www 4357:
1.361 www 4358: sub linklog {
4359: my ($from,$to)=@_;
4360: $from=&declutter($from);
4361: $to=&declutter($to);
4362: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4363: $accesshash{$to.'___'.$from.'___goto'}=1;
4364: }
1.1160 www 4365:
4366: sub statslog {
4367: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4368: if ($users<2) { return; }
4369: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4370: 'course' => $env{'request.course.id'},
4371: 'sections' => '"all"',
4372: 'num_students' => $users,
4373: 'part' => $part,
4374: 'symb' => $symb,
4375: 'mean_tries' => $av_attempts,
4376: 'deg_of_diff' => $degdiff});
4377: foreach my $key (keys(%dynstore)) {
4378: $accesshash{$key}=$dynstore{$key};
4379: }
4380: }
1.361 www 4381:
1.349 www 4382: sub userrolelog {
4383: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4384: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4385: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4386: $userrolehash
4387: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4388: =$tend.':'.$tstart;
1.662 raeburn 4389: }
1.1169 droeschl 4390: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4391: $userrolehash
4392: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4393: =$tend.':'.$tstart;
4394: }
1.1172.2.90 raeburn 4395: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4396: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4397: $domainrolehash
4398: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4399: = $tend.':'.$tstart;
4400: }
1.351 www 4401: }
4402:
1.957 raeburn 4403: sub courserolelog {
4404: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4405: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4406: my $cdom = $1;
4407: my $cnum = $2;
4408: my $sec = $3;
4409: my $namespace = 'rolelog';
4410: my %storehash = (
4411: role => $trole,
4412: start => $tstart,
4413: end => $tend,
4414: selfenroll => $selfenroll,
4415: context => $context,
4416: );
4417: if ($trole eq 'gr') {
4418: $namespace = 'groupslog';
4419: $storehash{'group'} = $sec;
4420: } else {
4421: $storehash{'section'} = $sec;
4422: }
4423: &write_log('course',$namespace,\%storehash,$delflag,$username,
4424: $domain,$cnum,$cdom);
4425: if (($trole ne 'st') || ($sec ne '')) {
4426: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4427: }
4428: }
4429: return;
4430: }
4431:
1.1172.2.9 raeburn 4432: sub domainrolelog {
4433: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4434: if ($area =~ m{^/($match_domain)/$}) {
4435: my $cdom = $1;
4436: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4437: my $namespace = 'rolelog';
4438: my %storehash = (
4439: role => $trole,
4440: start => $tstart,
4441: end => $tend,
4442: context => $context,
4443: );
4444: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4445: $domain,$domconfiguser,$cdom);
4446: }
4447: return;
4448:
4449: }
4450:
4451: sub coauthorrolelog {
4452: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4453: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4454: my $audom = $1;
4455: my $auname = $2;
4456: my $namespace = 'rolelog';
4457: my %storehash = (
4458: role => $trole,
4459: start => $tstart,
4460: end => $tend,
4461: context => $context,
4462: );
4463: &write_log('author',$namespace,\%storehash,$delflag,$username,
4464: $domain,$auname,$audom);
4465: }
4466: return;
4467: }
4468:
1.351 www 4469: sub get_course_adv_roles {
1.948 raeburn 4470: my ($cid,$codes) = @_;
1.620 albertel 4471: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4472: my %coursehash=&coursedescription($cid);
1.988 raeburn 4473: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4474: my %nothide=();
1.800 albertel 4475: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4476: if ($user !~ /:/) {
4477: $nothide{join(':',split(/[\@]/,$user))}=1;
4478: } else {
4479: $nothide{$user}=1;
4480: }
1.470 www 4481: }
1.1172.2.23 raeburn 4482: my @possdoms = ($coursehash{'domain'});
4483: if ($coursehash{'checkforpriv'}) {
4484: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4485: }
1.351 www 4486: my %returnhash=();
4487: my %dumphash=
4488: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4489: my $now=time;
1.997 raeburn 4490: my %privileged;
1.1000 raeburn 4491: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4492: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4493: if (($tstart) && ($tstart<0)) { next; }
4494: if (($tend) && ($tend<$now)) { next; }
4495: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4496: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4497: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4498: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4499: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4500: if ($role eq 'cr') { next; }
1.948 raeburn 4501: if ($codes) {
4502: if ($section) { $role .= ':'.$section; }
4503: if ($returnhash{$role}) {
4504: $returnhash{$role}.=','.$username.':'.$domain;
4505: } else {
4506: $returnhash{$role}=$username.':'.$domain;
4507: }
1.351 www 4508: } else {
1.988 raeburn 4509: my $key=&plaintext($role,$crstype);
1.973 bisitz 4510: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4511: if ($returnhash{$key}) {
4512: $returnhash{$key}.=','.$username.':'.$domain;
4513: } else {
4514: $returnhash{$key}=$username.':'.$domain;
4515: }
1.351 www 4516: }
1.948 raeburn 4517: }
1.400 www 4518: return %returnhash;
4519: }
4520:
4521: sub get_my_roles {
1.937 raeburn 4522: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4523: unless (defined($uname)) { $uname=$env{'user.name'}; }
4524: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4525: my (%dumphash,%nothide);
1.1086 raeburn 4526: if ($context eq 'userroles') {
1.1166 raeburn 4527: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4528: } else {
1.1172.2.23 raeburn 4529: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4530: if ($hidepriv) {
4531: my %coursehash=&coursedescription($udom.'_'.$uname);
4532: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4533: if ($user !~ /:/) {
4534: $nothide{join(':',split(/[\@]/,$user))} = 1;
4535: } else {
4536: $nothide{$user} = 1;
4537: }
4538: }
4539: }
1.858 raeburn 4540: }
1.400 www 4541: my %returnhash=();
4542: my $now=time;
1.999 raeburn 4543: my %privileged;
1.800 albertel 4544: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4545: my ($role,$tend,$tstart);
4546: if ($context eq 'userroles') {
1.1149 raeburn 4547: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4548: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4549: } else {
4550: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4551: }
1.400 www 4552: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4553: my $status = 'active';
1.939 raeburn 4554: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4555: $status = 'previous';
4556: }
4557: if (($tstart) && ($now<$tstart)) {
4558: $status = 'future';
4559: }
4560: if (ref($types) eq 'ARRAY') {
4561: if (!grep(/^\Q$status\E$/,@{$types})) {
4562: next;
4563: }
4564: } else {
4565: if ($status ne 'active') {
4566: next;
4567: }
4568: }
1.867 raeburn 4569: my ($rolecode,$username,$domain,$section,$area);
4570: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4571: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4572: (undef,$domain,$username,$section) = split(/\//,$area);
4573: } else {
4574: ($role,$username,$domain,$section) = split(/\:/,$entry);
4575: }
1.832 raeburn 4576: if (ref($roledoms) eq 'ARRAY') {
4577: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4578: next;
4579: }
4580: }
4581: if (ref($roles) eq 'ARRAY') {
4582: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4583: if ($role =~ /^cr\//) {
4584: if (!grep(/^cr$/,@{$roles})) {
4585: next;
4586: }
1.1104 raeburn 4587: } elsif ($role =~ /^gr\//) {
4588: if (!grep(/^gr$/,@{$roles})) {
4589: next;
4590: }
1.922 raeburn 4591: } else {
4592: next;
4593: }
1.832 raeburn 4594: }
1.867 raeburn 4595: }
1.937 raeburn 4596: if ($hidepriv) {
1.1172.2.23 raeburn 4597: my @privroles = ('dc','su');
1.999 raeburn 4598: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4599: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4600: } else {
1.1172.2.23 raeburn 4601: my $possdoms = [$domain];
4602: if (ref($roledoms) eq 'ARRAY') {
4603: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4604: }
1.1172.2.23 raeburn 4605: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4606: if (!$nothide{$username.':'.$domain}) {
4607: next;
4608: }
4609: }
1.937 raeburn 4610: }
4611: }
1.933 raeburn 4612: if ($withsec) {
4613: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4614: $tstart.':'.$tend;
4615: } else {
4616: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4617: }
1.832 raeburn 4618: }
1.373 www 4619: return %returnhash;
1.399 www 4620: }
4621:
1.1172.2.89 raeburn 4622: sub get_all_adhocroles {
4623: my ($dom) = @_;
4624: my @roles_by_num = ();
4625: my %domdefaults = &get_domain_defaults($dom);
4626: my (%description,%access_in_dom,%access_info);
4627: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4628: my $count = 0;
4629: my %domcurrent = %{$domdefaults{'adhocroles'}};
4630: my %ordered;
4631: foreach my $role (sort(keys(%domcurrent))) {
4632: my ($order,$desc,$access_in_dom);
4633: if (ref($domcurrent{$role}) eq 'HASH') {
4634: $order = $domcurrent{$role}{'order'};
4635: $desc = $domcurrent{$role}{'desc'};
4636: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4637: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4638: }
4639: if ($order eq '') {
4640: $order = $count;
4641: }
4642: $ordered{$order} = $role;
4643: if ($desc ne '') {
4644: $description{$role} = $desc;
4645: } else {
4646: $description{$role}= $role;
4647: }
4648: $count++;
4649: }
4650: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4651: push(@roles_by_num,$ordered{$item});
4652: }
4653: }
4654: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4655: }
4656:
4657: sub get_my_adhocroles {
4658: my ($cid,$checkreg) = @_;
4659: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4660: if ($env{'request.course.id'} eq $cid) {
4661: $cdom = $env{'course.'.$cid.'.domain'};
4662: $cnum = $env{'course.'.$cid.'.num'};
4663: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4664: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4665: $cdom = $1;
4666: $cnum = $2;
4667: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4668: $cdom,$cnum);
4669: }
4670: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4671: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4672: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4673: if ($rosterhash{$user} ne '') {
4674: my $type = (split(/:/,$rosterhash{$user}))[5];
4675: return ([],{}) if ($type eq 'auto');
4676: }
4677: }
4678: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 4679: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 4680: my $then=$env{'user.login.time'};
4681: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 4682: if (!$update) {
4683: $update = $then;
4684: }
4685: my @liveroles;
4686: foreach my $role ('dh','da') {
4687: if ($env{"user.role.$role./$cdom/"}) {
4688: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
4689: my $limit = $update;
4690: if ($env{'request.role'} eq "$role./$cdom/") {
4691: $limit = $then;
4692: }
4693: my $activerole = 1;
4694: if ($tstart && $tstart>$limit) { $activerole = 0; }
4695: if ($tend && $tend <$limit) { $activerole = 0; }
4696: if ($activerole) {
4697: push(@liveroles,$role);
4698: }
4699: }
4700: }
4701: if (@liveroles) {
1.1172.2.89 raeburn 4702: if (&homeserver($cnum,$cdom) ne 'no_host') {
4703: my ($accessref,$accessinfo,%access_in_dom);
4704: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4705: if (ref($roles_by_num) eq 'ARRAY') {
4706: if (@{$roles_by_num}) {
4707: my %settings;
4708: if ($env{'request.course.id'} eq $cid) {
4709: foreach my $envkey (keys(%env)) {
4710: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4711: $settings{$1} = $env{$envkey};
4712: }
4713: }
4714: } else {
4715: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4716: }
4717: my %setincrs;
4718: if ($settings{'internal.adhocaccess'}) {
4719: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4720: }
4721: my @statuses;
4722: if ($env{'environment.inststatus'}) {
4723: @statuses = split(/,/,$env{'environment.inststatus'});
4724: }
4725: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4726: if (ref($accessref) eq 'HASH') {
4727: %access_in_dom = %{$accessref};
4728: }
4729: foreach my $role (@{$roles_by_num}) {
4730: my ($curraccess,@okstatus,@personnel);
4731: if ($setincrs{$role}) {
4732: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4733: if ($curraccess eq 'status') {
4734: @okstatus = split(/\&/,$rest);
4735: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4736: @personnel = split(/\&/,$rest);
4737: }
4738: } else {
4739: $curraccess = $access_in_dom{$role};
4740: if (ref($accessinfo) eq 'HASH') {
4741: if ($curraccess eq 'status') {
4742: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4743: @okstatus = @{$accessinfo->{$role}};
4744: }
4745: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4746: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4747: @personnel = @{$accessinfo->{$role}};
4748: }
4749: }
4750: }
4751: }
4752: if ($curraccess eq 'none') {
4753: next;
4754: } elsif ($curraccess eq 'all') {
4755: push(@possroles,$role);
1.1172.2.90 raeburn 4756: } elsif ($curraccess eq 'dh') {
4757: if (grep(/^dh$/,@liveroles)) {
4758: push(@possroles,$role);
4759: } else {
4760: next;
4761: }
4762: } elsif ($curraccess eq 'da') {
4763: if (grep(/^da$/,@liveroles)) {
4764: push(@possroles,$role);
4765: } else {
4766: next;
4767: }
1.1172.2.89 raeburn 4768: } elsif ($curraccess eq 'status') {
4769: if (@okstatus) {
4770: if (!@statuses) {
4771: if (grep(/^default$/,@okstatus)) {
4772: push(@possroles,$role);
4773: }
4774: } else {
4775: foreach my $status (@okstatus) {
4776: if (grep(/^\Q$status\E$/,@statuses)) {
4777: push(@possroles,$role);
4778: last;
4779: }
4780: }
4781: }
4782: }
4783: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4784: if (grep(/^\Q$user\E$/,@personnel)) {
4785: if ($curraccess eq 'exc') {
4786: push(@possroles,$role);
4787: }
4788: } elsif ($curraccess eq 'inc') {
4789: push(@possroles,$role);
4790: }
4791: }
4792: }
4793: }
4794: }
4795: }
4796: }
4797: }
4798: }
4799: unless (ref($description) eq 'HASH') {
4800: if (ref($roles_by_num) eq 'ARRAY') {
4801: my %desc;
4802: map { $desc{$_} = $_; } (@{$roles_by_num});
4803: $description = \%desc;
4804: } else {
4805: $description = {};
4806: }
4807: }
4808: return (\@possroles,$description);
4809: }
4810:
1.399 www 4811: # ----------------------------------------------------- Frontpage Announcements
4812: #
4813: #
4814:
4815: sub postannounce {
4816: my ($server,$text)=@_;
1.844 albertel 4817: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4818: unless ($text=~/\w/) { $text=''; }
4819: return &reply('setannounce:'.&escape($text),$server);
4820: }
4821:
4822: sub getannounce {
1.448 albertel 4823:
1.1172.2.93.4 7(raebur 4824:7): if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4825: my $announcement='';
1.800 albertel 4826: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4827: close($fh);
1.399 www 4828: if ($announcement=~/\w/) {
4829: return
4830: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4831: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4832: } else {
4833: return '';
4834: }
4835: } else {
4836: return '';
4837: }
1.351 www 4838: }
1.353 www 4839:
4840: # ---------------------------------------------------------- Course ID routines
4841: # Deal with domain's nohist_courseid.db files
4842: #
4843:
4844: sub courseidput {
1.921 raeburn 4845: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4846: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4847: my $outcome;
4848: if ($caller eq 'timeonly') {
4849: my $cids = '';
4850: foreach my $item (keys(%$storehash)) {
4851: $cids.=&escape($item).'&';
4852: }
4853: $cids=~s/\&$//;
4854: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4855: $coursehome);
4856: } else {
4857: my $items = '';
4858: foreach my $item (keys(%$storehash)) {
4859: $items.= &escape($item).'='.
4860: &freeze_escape($$storehash{$item}).'&';
4861: }
4862: $items=~s/\&$//;
4863: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4864: $coursehome);
1.918 raeburn 4865: }
4866: if ($outcome eq 'unknown_cmd') {
4867: my $what;
4868: foreach my $cid (keys(%$storehash)) {
4869: $what .= &escape($cid).'=';
1.921 raeburn 4870: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4871: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4872: }
4873: $what =~ s/\:$/&/;
4874: }
4875: $what =~ s/\&$//;
4876: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4877: } else {
4878: return $outcome;
4879: }
1.353 www 4880: }
4881:
4882: sub courseiddump {
1.921 raeburn 4883: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4884: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4885: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4886: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4887: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4888: my $as_hash = 1;
4889: my %returnhash;
4890: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4891: my %libserv = &all_library();
4892: foreach my $tryserver (keys(%libserv)) {
4893: if ( ( $hostidflag == 1
4894: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4895: || (!defined($hostidflag)) ) {
4896:
1.918 raeburn 4897: if (($domfilter eq '') ||
4898: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4899: my $rep;
4900: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4901: $rep = &LONCAPA::Lond::dump_course_id_handler(
4902: join(":", (&host_domain($tryserver), $sincefilter,
4903: &escape($descfilter), &escape($instcodefilter),
4904: &escape($ownerfilter), &escape($coursefilter),
4905: &escape($typefilter), &escape($regexp_ok),
4906: $as_hash, &escape($selfenrollonly),
4907: &escape($catfilter), $showhidden, $caller,
4908: &escape($cloner), &escape($cc_clone), $cloneonly,
4909: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4910: &escape($creationcontext),$domcloner,$hasuniquecode,
4911: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4912: } else {
4913: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4914: $sincefilter.':'.&escape($descfilter).':'.
4915: &escape($instcodefilter).':'.&escape($ownerfilter).
4916: ':'.&escape($coursefilter).':'.&escape($typefilter).
4917: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4918: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4919: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4920: &escape($cc_clone).':'.$cloneonly.':'.
4921: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4922: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4923: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4924: }
4925:
1.918 raeburn 4926: my @pairs=split(/\&/,$rep);
4927: foreach my $item (@pairs) {
4928: my ($key,$value)=split(/\=/,$item,2);
4929: $key = &unescape($key);
4930: next if ($key =~ /^error: 2 /);
4931: my $result = &thaw_unescape($value);
4932: if (ref($result) eq 'HASH') {
4933: $returnhash{$key}=$result;
4934: } else {
1.921 raeburn 4935: my @responses = split(/:/,$value);
4936: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4937: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4938: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4939: }
1.1008 raeburn 4940: }
1.353 www 4941: }
4942: }
4943: }
4944: }
4945: return %returnhash;
4946: }
4947:
1.1055 raeburn 4948: sub courselastaccess {
4949: my ($cdom,$cnum,$hostidref) = @_;
4950: my %returnhash;
4951: if ($cdom && $cnum) {
4952: my $chome = &homeserver($cnum,$cdom);
4953: if ($chome ne 'no_host') {
4954: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4955: &extract_lastaccess(\%returnhash,$rep);
4956: }
4957: } else {
4958: if (!$cdom) { $cdom=''; }
4959: my %libserv = &all_library();
4960: foreach my $tryserver (keys(%libserv)) {
4961: if (ref($hostidref) eq 'ARRAY') {
4962: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4963: }
4964: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4965: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4966: &extract_lastaccess(\%returnhash,$rep);
4967: }
4968: }
4969: }
4970: return %returnhash;
4971: }
4972:
4973: sub extract_lastaccess {
4974: my ($returnhash,$rep) = @_;
4975: if (ref($returnhash) eq 'HASH') {
4976: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4977: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4978: $rep eq '') {
4979: my @pairs=split(/\&/,$rep);
4980: foreach my $item (@pairs) {
4981: my ($key,$value)=split(/\=/,$item,2);
4982: $key = &unescape($key);
4983: next if ($key =~ /^error: 2 /);
4984: $returnhash->{$key} = &thaw_unescape($value);
4985: }
4986: }
4987: }
4988: return;
4989: }
4990:
1.658 raeburn 4991: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4992:
4993: sub dcmailput {
1.685 raeburn 4994: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4995: my $status = &Apache::lonnet::critical(
1.740 www 4996: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4997: &escape($message),$server);
1.662 raeburn 4998: return $status;
4999: }
5000:
1.658 raeburn 5001: sub dcmaildump {
5002: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5003: my %returnhash=();
1.846 albertel 5004:
5005: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5006: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5007: &escape($enddate).':';
5008: my @esc_senders=map { &escape($_)} @$senders;
5009: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5010: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5011: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5012: if (($key) && ($value)) {
5013: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5014: }
5015: }
5016: }
5017: return %returnhash;
5018: }
1.662 raeburn 5019: # ---------------------------------------------------------- Domain roles
5020:
5021: sub get_domain_roles {
5022: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5023: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5024: $startdate = '.';
5025: }
1.1018 raeburn 5026: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5027: $enddate = '.';
5028: }
1.922 raeburn 5029: my $rolelist;
5030: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5031: $rolelist = join('&',@{$roles});
1.922 raeburn 5032: }
1.662 raeburn 5033: my %personnel = ();
1.841 albertel 5034:
5035: my %servers = &get_servers($dom,'library');
5036: foreach my $tryserver (keys(%servers)) {
5037: %{$personnel{$tryserver}}=();
5038: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5039: &escape($startdate).':'.
5040: &escape($enddate).':'.
5041: &escape($rolelist), $tryserver))) {
5042: my ($key,$value) = split(/\=/,$line,2);
5043: if (($key) && ($value)) {
5044: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5045: }
5046: }
1.662 raeburn 5047: }
5048: return %personnel;
5049: }
1.658 raeburn 5050:
1.1172.2.89 raeburn 5051: sub get_active_domroles {
5052: my ($dom,$roles) = @_;
5053: return () unless (ref($roles) eq 'ARRAY');
5054: my $now = time;
5055: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5056: my %domroles;
5057: foreach my $server (keys(%dompersonnel)) {
5058: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5059: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5060: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5061: }
5062: }
5063: return %domroles;
5064: }
5065:
1.1057 www 5066: # ----------------------------------------------------------- Interval timing
1.149 www 5067:
1.1153 www 5068: {
5069: # Caches needed for speedup of navmaps
5070: # We don't want to cache this for very long at all (5 seconds at most)
5071: #
5072: # The user for whom we cache
5073: my $cachedkey='';
5074: # The cached times for this user
5075: my %cachedtimes=();
5076: # When this was last done
1.1172.2.66 raeburn 5077: my $cachedtime='';
1.1153 www 5078:
5079: sub load_all_first_access {
1.1172.2.93.4 1(raebur 5080:7): my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5081: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.93.4 1(raebur 5082:7): (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5083:7): (!$ignorecache)) {
1.1154 raeburn 5084: return;
5085: }
5086: $cachedtime=time;
5087: $cachedkey=$uname.':'.$udom;
5088: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5089: }
5090:
1.504 albertel 5091: sub get_first_access {
1.1172.2.93.4 1(raebur 5092:7): my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5093: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5094: if ($argsymb) { $symb=$argsymb; }
5095: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5096: if ($argmap) { $map = $argmap; }
1.926 albertel 5097: if ($type eq 'course') {
5098: $res='course';
5099: } elsif ($type eq 'map') {
1.588 albertel 5100: $res=&symbread($map);
5101: } else {
5102: $res=$symb;
5103: }
1.1172.2.93.4 1(raebur 5104:7): &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5105: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5106: }
5107:
5108: sub set_first_access {
1.1162 raeburn 5109: my ($type,$interval)=@_;
1.790 albertel 5110: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5111: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5112: if ($type eq 'course') {
5113: $res='course';
5114: } elsif ($type eq 'map') {
1.588 albertel 5115: $res=&symbread($map);
5116: } else {
5117: $res=$symb;
5118: }
1.1153 www 5119: $cachedkey='';
1.1162 raeburn 5120: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 5121: if (!$firstaccess) {
1.1162 raeburn 5122: my $start = time;
5123: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5124: $udom,$uname);
5125: if ($putres eq 'ok') {
5126: &put('timerinterval',{"$courseid\0$res"=>$interval},
5127: $udom,$uname);
5128: &appenv(
5129: {
5130: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5131: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5132: }
5133: );
5134: }
5135: return $putres;
1.505 albertel 5136: }
5137: return 'already_set';
1.504 albertel 5138: }
1.1153 www 5139: }
1.1172.2.32 raeburn 5140:
5141: sub checkout {
5142: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5143: my $now=time;
5144: my $lonhost=$perlvar{'lonHostID'};
5145: my $infostr=&escape(
5146: 'CHECKOUTTOKEN&'.
5147: $tuname.'&'.
5148: $tudom.'&'.
5149: $tcrsid.'&'.
5150: $symb.'&'.
5151: $now.'&'.$ENV{'REMOTE_ADDR'});
5152: my $token=&reply('tmpput:'.$infostr,$lonhost);
5153: if ($token=~/^error\:/) {
5154: &logthis("<font color=\"blue\">WARNING: ".
5155: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5156: "</font>");
5157: return '';
5158: }
5159:
5160: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5161: $token=~tr/a-z/A-Z/;
5162:
5163: my %infohash=('resource.0.outtoken' => $token,
5164: 'resource.0.checkouttime' => $now,
5165: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
5166:
5167: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5168: return '';
5169: } else {
5170: &logthis("<font color=\"blue\">WARNING: ".
5171: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5172: "</font>");
5173: }
5174:
5175: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5176: &escape('Checkout '.$infostr.' - '.
5177: $token)) ne 'ok') {
5178: return '';
5179: } else {
5180: &logthis("<font color=\"blue\">WARNING: ".
5181: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5182: "</font>");
5183: }
5184: return $token;
5185: }
5186:
5187: # ------------------------------------------------------------ Check in an item
5188:
5189: sub checkin {
5190: my $token=shift;
5191: my $now=time;
5192: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5193: $lonhost=~tr/A-Z/a-z/;
5194: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5195: $dtoken=~s/\W/\_/g;
5196: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5197: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5198:
5199: unless (($tuname) && ($tudom)) {
5200: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5201: return '';
5202: }
5203:
5204: unless (&allowed('mgr',$tcrsid)) {
5205: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5206: $env{'user.name'}.' - '.$env{'user.domain'});
5207: return '';
5208: }
5209:
5210: my %infohash=('resource.0.intoken' => $token,
5211: 'resource.0.checkintime' => $now,
5212: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
5213:
5214: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5215: return '';
5216: }
5217:
5218: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5219: &escape('Checkin - '.$token)) ne 'ok') {
5220: return '';
5221: }
5222:
5223: return ($symb,$tuname,$tudom,$tcrsid);
5224: }
5225:
1.110 www 5226: # --------------------------------------------- Set Expire Date for Spreadsheet
5227:
5228: sub expirespread {
5229: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5230: my $cid=$env{'request.course.id'};
1.110 www 5231: if ($cid) {
5232: my $now=time;
5233: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5234: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5235: $env{'course.'.$cid.'.num'}.
1.110 www 5236: ':nohist_expirationdates:'.
5237: &escape($key).'='.$now,
1.620 albertel 5238: $env{'course.'.$cid.'.home'})
1.110 www 5239: }
5240: return 'ok';
1.14 www 5241: }
5242:
1.109 www 5243: # ----------------------------------------------------- Devalidate Spreadsheets
5244:
5245: sub devalidate {
1.325 www 5246: my ($symb,$uname,$udom)=@_;
1.620 albertel 5247: my $cid=$env{'request.course.id'};
1.109 www 5248: if ($cid) {
1.391 matthew 5249: # delete the stored spreadsheets for
5250: # - the student level sheet of this user in course's homespace
5251: # - the assessment level sheet for this resource
5252: # for this user in user's homespace
1.553 albertel 5253: # - current conditional state info
1.325 www 5254: my $key=$uname.':'.$udom.':';
1.109 www 5255: my $status=
1.299 matthew 5256: &del('nohist_calculatedsheets',
1.391 matthew 5257: [$key.'studentcalc:'],
1.620 albertel 5258: $env{'course.'.$cid.'.domain'},
5259: $env{'course.'.$cid.'.num'})
1.133 albertel 5260: .' '.
5261: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5262: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5263: unless ($status eq 'ok ok') {
5264: &logthis('Could not devalidate spreadsheet '.
1.325 www 5265: $uname.' at '.$udom.' for '.
1.109 www 5266: $symb.': '.$status);
1.133 albertel 5267: }
1.553 albertel 5268: &delenv('user.state.'.$cid);
1.109 www 5269: }
5270: }
5271:
1.265 albertel 5272: sub get_scalar {
5273: my ($string,$end) = @_;
5274: my $value;
5275: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5276: $value = $1;
5277: } elsif ($$string =~ s/^([^&]*?)&//) {
5278: $value = $1;
5279: }
5280: return &unescape($value);
5281: }
5282:
5283: sub array2str {
5284: my (@array) = @_;
5285: my $result=&arrayref2str(\@array);
5286: $result=~s/^__ARRAY_REF__//;
5287: $result=~s/__END_ARRAY_REF__$//;
5288: return $result;
5289: }
5290:
1.204 albertel 5291: sub arrayref2str {
5292: my ($arrayref) = @_;
1.265 albertel 5293: my $result='__ARRAY_REF__';
1.204 albertel 5294: foreach my $elem (@$arrayref) {
1.265 albertel 5295: if(ref($elem) eq 'ARRAY') {
5296: $result.=&arrayref2str($elem).'&';
5297: } elsif(ref($elem) eq 'HASH') {
5298: $result.=&hashref2str($elem).'&';
5299: } elsif(ref($elem)) {
5300: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5301: } else {
5302: $result.=&escape($elem).'&';
5303: }
5304: }
5305: $result=~s/\&$//;
1.265 albertel 5306: $result .= '__END_ARRAY_REF__';
1.204 albertel 5307: return $result;
5308: }
5309:
1.168 albertel 5310: sub hash2str {
1.204 albertel 5311: my (%hash) = @_;
5312: my $result=&hashref2str(\%hash);
1.265 albertel 5313: $result=~s/^__HASH_REF__//;
5314: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5315: return $result;
5316: }
5317:
5318: sub hashref2str {
5319: my ($hashref)=@_;
1.265 albertel 5320: my $result='__HASH_REF__';
1.800 albertel 5321: foreach my $key (sort(keys(%$hashref))) {
5322: if (ref($key) eq 'ARRAY') {
5323: $result.=&arrayref2str($key).'=';
5324: } elsif (ref($key) eq 'HASH') {
5325: $result.=&hashref2str($key).'=';
5326: } elsif (ref($key)) {
1.265 albertel 5327: $result.='=';
1.800 albertel 5328: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5329: } else {
1.1132 raeburn 5330: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5331: }
5332:
1.800 albertel 5333: if(ref($hashref->{$key}) eq 'ARRAY') {
5334: $result.=&arrayref2str($hashref->{$key}).'&';
5335: } elsif(ref($hashref->{$key}) eq 'HASH') {
5336: $result.=&hashref2str($hashref->{$key}).'&';
5337: } elsif(ref($hashref->{$key})) {
1.265 albertel 5338: $result.='&';
1.800 albertel 5339: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5340: } else {
1.800 albertel 5341: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5342: }
5343: }
1.168 albertel 5344: $result=~s/\&$//;
1.265 albertel 5345: $result .= '__END_HASH_REF__';
1.168 albertel 5346: return $result;
5347: }
5348:
5349: sub str2hash {
1.265 albertel 5350: my ($string)=@_;
5351: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5352: return %$hash;
5353: }
5354:
5355: sub str2hashref {
1.168 albertel 5356: my ($string) = @_;
1.265 albertel 5357:
5358: my %hash;
5359:
5360: if($string !~ /^__HASH_REF__/) {
5361: if (! ($string eq '' || !defined($string))) {
5362: $hash{'error'}='Not hash reference';
5363: }
5364: return (\%hash, $string);
5365: }
5366:
5367: $string =~ s/^__HASH_REF__//;
5368:
5369: while($string !~ /^__END_HASH_REF__/) {
5370: #key
5371: my $key='';
5372: if($string =~ /^__HASH_REF__/) {
5373: ($key, $string)=&str2hashref($string);
5374: if(defined($key->{'error'})) {
5375: $hash{'error'}='Bad data';
5376: return (\%hash, $string);
5377: }
5378: } elsif($string =~ /^__ARRAY_REF__/) {
5379: ($key, $string)=&str2arrayref($string);
5380: if($key->[0] eq 'Array reference error') {
5381: $hash{'error'}='Bad data';
5382: return (\%hash, $string);
5383: }
5384: } else {
5385: $string =~ s/^(.*?)=//;
1.267 albertel 5386: $key=&unescape($1);
1.265 albertel 5387: }
5388: $string =~ s/^=//;
5389:
5390: #value
5391: my $value='';
5392: if($string =~ /^__HASH_REF__/) {
5393: ($value, $string)=&str2hashref($string);
5394: if(defined($value->{'error'})) {
5395: $hash{'error'}='Bad data';
5396: return (\%hash, $string);
5397: }
5398: } elsif($string =~ /^__ARRAY_REF__/) {
5399: ($value, $string)=&str2arrayref($string);
5400: if($value->[0] eq 'Array reference error') {
5401: $hash{'error'}='Bad data';
5402: return (\%hash, $string);
5403: }
5404: } else {
5405: $value=&get_scalar(\$string,'__END_HASH_REF__');
5406: }
5407: $string =~ s/^&//;
5408:
5409: $hash{$key}=$value;
1.204 albertel 5410: }
1.265 albertel 5411:
5412: $string =~ s/^__END_HASH_REF__//;
5413:
5414: return (\%hash, $string);
1.204 albertel 5415: }
5416:
5417: sub str2array {
1.265 albertel 5418: my ($string)=@_;
5419: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5420: return @$array;
5421: }
5422:
5423: sub str2arrayref {
1.204 albertel 5424: my ($string) = @_;
1.265 albertel 5425: my @array;
5426:
5427: if($string !~ /^__ARRAY_REF__/) {
5428: if (! ($string eq '' || !defined($string))) {
5429: $array[0]='Array reference error';
5430: }
5431: return (\@array, $string);
5432: }
5433:
5434: $string =~ s/^__ARRAY_REF__//;
5435:
5436: while($string !~ /^__END_ARRAY_REF__/) {
5437: my $value='';
5438: if($string =~ /^__HASH_REF__/) {
5439: ($value, $string)=&str2hashref($string);
5440: if(defined($value->{'error'})) {
5441: $array[0] ='Array reference error';
5442: return (\@array, $string);
5443: }
5444: } elsif($string =~ /^__ARRAY_REF__/) {
5445: ($value, $string)=&str2arrayref($string);
5446: if($value->[0] eq 'Array reference error') {
5447: $array[0] ='Array reference error';
5448: return (\@array, $string);
5449: }
5450: } else {
5451: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5452: }
5453: $string =~ s/^&//;
5454:
5455: push(@array, $value);
1.191 harris41 5456: }
1.265 albertel 5457:
5458: $string =~ s/^__END_ARRAY_REF__//;
5459:
5460: return (\@array, $string);
1.168 albertel 5461: }
5462:
1.167 albertel 5463: # -------------------------------------------------------------------Temp Store
5464:
1.168 albertel 5465: sub tmpreset {
5466: my ($symb,$namespace,$domain,$stuname) = @_;
5467: if (!$symb) {
5468: $symb=&symbread();
1.620 albertel 5469: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5470: }
5471: $symb=escape($symb);
5472:
1.620 albertel 5473: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5474: $namespace=~s/\//\_/g;
5475: $namespace=~s/\W//g;
5476:
1.620 albertel 5477: if (!$domain) { $domain=$env{'user.domain'}; }
5478: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5479: if ($domain eq 'public' && $stuname eq 'public') {
5480: $stuname=$ENV{'REMOTE_ADDR'};
5481: }
1.1117 foxr 5482: my $path=LONCAPA::tempdir();
1.168 albertel 5483: my %hash;
5484: if (tie(%hash,'GDBM_File',
5485: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5486: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5487: foreach my $key (keys(%hash)) {
1.180 albertel 5488: if ($key=~ /:$symb/) {
1.168 albertel 5489: delete($hash{$key});
5490: }
5491: }
5492: }
5493: }
5494:
1.167 albertel 5495: sub tmpstore {
1.168 albertel 5496: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5497:
5498: if (!$symb) {
5499: $symb=&symbread();
1.620 albertel 5500: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5501: }
5502: $symb=escape($symb);
5503:
5504: if (!$namespace) {
5505: # I don't think we would ever want to store this for a course.
5506: # it seems this will only be used if we don't have a course.
1.620 albertel 5507: #$namespace=$env{'request.course.id'};
1.168 albertel 5508: #if (!$namespace) {
1.620 albertel 5509: $namespace=$env{'request.state'};
1.168 albertel 5510: #}
5511: }
5512: $namespace=~s/\//\_/g;
5513: $namespace=~s/\W//g;
1.620 albertel 5514: if (!$domain) { $domain=$env{'user.domain'}; }
5515: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5516: if ($domain eq 'public' && $stuname eq 'public') {
5517: $stuname=$ENV{'REMOTE_ADDR'};
5518: }
1.168 albertel 5519: my $now=time;
5520: my %hash;
1.1117 foxr 5521: my $path=LONCAPA::tempdir();
1.168 albertel 5522: if (tie(%hash,'GDBM_File',
5523: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5524: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5525: $hash{"version:$symb"}++;
5526: my $version=$hash{"version:$symb"};
5527: my $allkeys='';
5528: foreach my $key (keys(%$storehash)) {
5529: $allkeys.=$key.':';
1.591 albertel 5530: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5531: }
5532: $hash{"$version:$symb:timestamp"}=$now;
5533: $allkeys.='timestamp';
5534: $hash{"$version:keys:$symb"}=$allkeys;
5535: if (untie(%hash)) {
5536: return 'ok';
5537: } else {
5538: return "error:$!";
5539: }
5540: } else {
5541: return "error:$!";
5542: }
5543: }
1.167 albertel 5544:
1.168 albertel 5545: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5546:
1.168 albertel 5547: sub tmprestore {
5548: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5549:
1.168 albertel 5550: if (!$symb) {
5551: $symb=&symbread();
1.620 albertel 5552: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5553: }
5554: $symb=escape($symb);
5555:
1.620 albertel 5556: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5557:
1.620 albertel 5558: if (!$domain) { $domain=$env{'user.domain'}; }
5559: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5560: if ($domain eq 'public' && $stuname eq 'public') {
5561: $stuname=$ENV{'REMOTE_ADDR'};
5562: }
1.168 albertel 5563: my %returnhash;
5564: $namespace=~s/\//\_/g;
5565: $namespace=~s/\W//g;
5566: my %hash;
1.1117 foxr 5567: my $path=LONCAPA::tempdir();
1.168 albertel 5568: if (tie(%hash,'GDBM_File',
5569: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5570: &GDBM_READER(),0640)) {
1.168 albertel 5571: my $version=$hash{"version:$symb"};
5572: $returnhash{'version'}=$version;
5573: my $scope;
5574: for ($scope=1;$scope<=$version;$scope++) {
5575: my $vkeys=$hash{"$scope:keys:$symb"};
5576: my @keys=split(/:/,$vkeys);
5577: my $key;
5578: $returnhash{"$scope:keys"}=$vkeys;
5579: foreach $key (@keys) {
1.591 albertel 5580: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5581: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5582: }
5583: }
1.168 albertel 5584: if (!(untie(%hash))) {
5585: return "error:$!";
5586: }
5587: } else {
5588: return "error:$!";
5589: }
5590: return %returnhash;
1.167 albertel 5591: }
5592:
1.9 www 5593: # ----------------------------------------------------------------------- Store
5594:
5595: sub store {
1.1172.2.64 raeburn 5596: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5597: my $home='';
5598:
1.168 albertel 5599: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5600:
1.213 www 5601: $symb=&symbclean($symb);
1.122 albertel 5602: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5603:
1.620 albertel 5604: if (!$domain) { $domain=$env{'user.domain'}; }
5605: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5606:
5607: &devalidate($symb,$stuname,$domain);
1.109 www 5608:
5609: $symb=escape($symb);
1.187 www 5610: if (!$namespace) {
1.620 albertel 5611: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5612: return '';
5613: }
5614: }
1.620 albertel 5615: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5616:
5617: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5618: $$storehash{'host'}=$perlvar{'lonHostID'};
5619:
1.12 www 5620: my $namevalue='';
1.800 albertel 5621: foreach my $key (keys(%$storehash)) {
5622: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5623: }
1.12 www 5624: $namevalue=~s/\&$//;
1.187 www 5625: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5626: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5627: }
5628:
1.47 www 5629: # -------------------------------------------------------------- Critical Store
5630:
5631: sub cstore {
1.1172.2.64 raeburn 5632: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5633: my $home='';
5634:
1.168 albertel 5635: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5636:
1.213 www 5637: $symb=&symbclean($symb);
1.122 albertel 5638: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5639:
1.620 albertel 5640: if (!$domain) { $domain=$env{'user.domain'}; }
5641: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5642:
5643: &devalidate($symb,$stuname,$domain);
1.109 www 5644:
5645: $symb=escape($symb);
1.187 www 5646: if (!$namespace) {
1.620 albertel 5647: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5648: return '';
5649: }
5650: }
1.620 albertel 5651: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5652:
5653: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5654: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5655:
1.47 www 5656: my $namevalue='';
1.800 albertel 5657: foreach my $key (keys(%$storehash)) {
5658: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5659: }
1.47 www 5660: $namevalue=~s/\&$//;
1.187 www 5661: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5662: return critical
1.1172.2.64 raeburn 5663: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5664: }
5665:
1.9 www 5666: # --------------------------------------------------------------------- Restore
5667:
5668: sub restore {
1.124 www 5669: my ($symb,$namespace,$domain,$stuname) = @_;
5670: my $home='';
5671:
1.168 albertel 5672: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5673:
1.122 albertel 5674: if (!$symb) {
1.1172.2.26 raeburn 5675: return if ($namespace eq 'courserequests');
5676: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5677: } else {
1.1172.2.26 raeburn 5678: unless ($namespace eq 'courserequests') {
5679: $symb=&escape(&symbclean($symb));
5680: }
1.122 albertel 5681: }
1.188 www 5682: if (!$namespace) {
1.620 albertel 5683: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5684: return '';
5685: }
5686: }
1.620 albertel 5687: if (!$domain) { $domain=$env{'user.domain'}; }
5688: if (!$stuname) { $stuname=$env{'user.name'}; }
5689: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5690: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5691:
1.12 www 5692: my %returnhash=();
1.800 albertel 5693: foreach my $line (split(/\&/,$answer)) {
5694: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5695: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5696: }
1.75 www 5697: my $version;
5698: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5699: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5700: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5701: }
1.75 www 5702: }
1.13 www 5703: return %returnhash;
1.34 www 5704: }
5705:
5706: # ---------------------------------------------------------- Course Description
1.1118 foxr 5707: #
5708: #
1.34 www 5709:
5710: sub coursedescription {
1.731 albertel 5711: my ($courseid,$args)=@_;
1.34 www 5712: $courseid=~s/^\///;
1.49 www 5713: $courseid=~s/\_/\//g;
1.34 www 5714: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5715: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5716: my $normalid=$cdomain.'_'.$cnum;
5717: # need to always cache even if we get errors otherwise we keep
5718: # trying and trying and trying to get the course description.
5719: my %envhash=();
5720: my %returnhash=();
1.731 albertel 5721:
5722: my $expiretime=600;
5723: if ($env{'request.course.id'} eq $normalid) {
5724: $expiretime=120;
5725: }
5726:
5727: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5728: if (!$args->{'freshen_cache'}
5729: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5730: foreach my $key (keys(%env)) {
5731: next if ($key !~ /^\Q$prefix\E(.*)/);
5732: my ($setting) = $1;
5733: $returnhash{$setting} = $env{$key};
5734: }
5735: return %returnhash;
5736: }
5737:
1.1118 foxr 5738: # get the data again
5739:
1.731 albertel 5740: if (!$args->{'one_time'}) {
5741: $envhash{'course.'.$normalid.'.last_cache'}=time;
5742: }
1.811 albertel 5743:
1.34 www 5744: if ($chome ne 'no_host') {
1.302 albertel 5745: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5746: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5747: my $username = $env{'user.name'}; # Defult username
5748: if(defined $args->{'user'}) {
5749: $username = $args->{'user'};
5750: }
1.129 albertel 5751: $returnhash{'home'}= $chome;
5752: $returnhash{'domain'} = $cdomain;
5753: $returnhash{'num'} = $cnum;
1.741 raeburn 5754: if (!defined($returnhash{'type'})) {
5755: $returnhash{'type'} = 'Course';
5756: }
1.130 albertel 5757: while (my ($name,$value) = each %returnhash) {
1.53 www 5758: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5759: }
1.270 www 5760: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5761: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5762: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5763: $envhash{'course.'.$normalid.'.home'}=$chome;
5764: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5765: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5766: }
5767: }
1.731 albertel 5768: if (!$args->{'one_time'}) {
1.949 raeburn 5769: &appenv(\%envhash);
1.731 albertel 5770: }
1.302 albertel 5771: return %returnhash;
1.461 www 5772: }
5773:
1.1080 raeburn 5774: sub update_released_required {
5775: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5776: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5777: $cid = $env{'request.course.id'};
5778: $cdom = $env{'course.'.$cid.'.domain'};
5779: $cnum = $env{'course.'.$cid.'.num'};
5780: $chome = $env{'course.'.$cid.'.home'};
5781: }
5782: if ($needsrelease) {
5783: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5784: my $needsupdate;
5785: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5786: $needsupdate = 1;
5787: } else {
5788: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5789: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5790: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5791: $needsupdate = 1;
5792: }
5793: }
5794: if ($needsupdate) {
5795: my %needshash = (
5796: 'internal.releaserequired' => $needsrelease,
5797: );
5798: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5799: if ($putresult eq 'ok') {
5800: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5801: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5802: if (ref($crsinfo{$cid}) eq 'HASH') {
5803: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5804: &courseidput($cdom,\%crsinfo,$chome,'notime');
5805: }
5806: }
5807: }
5808: }
5809: return;
5810: }
5811:
1.461 www 5812: # -------------------------------------------------See if a user is privileged
5813:
5814: sub privileged {
1.1172.2.23 raeburn 5815: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5816: my $now = time;
1.1172.2.23 raeburn 5817: my $roles;
5818: if (ref($possroles) eq 'ARRAY') {
5819: $roles = $possroles;
5820: } else {
5821: $roles = ['dc','su'];
5822: }
5823: if (ref($possdomains) eq 'ARRAY') {
5824: my %privileged = &privileged_by_domain($possdomains,$roles);
5825: foreach my $dom (@{$possdomains}) {
5826: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5827: (ref($privileged{$dom}) eq 'HASH')) {
5828: foreach my $role (@{$roles}) {
5829: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5830: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5831: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5832: return 1 unless (($end && $end < $now) ||
5833: ($start && $start > $now));
5834: }
5835: }
5836: }
5837: }
5838: }
5839: } else {
5840: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5841: my $now = time;
1.1170 droeschl 5842:
1.1172.2.58 raeburn 5843: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5844: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5845: if (grep(/^\Q$trole\E$/,@{$roles})) {
5846: return 1 unless ($tend && $tend < $now)
5847: or ($tstart && $tstart > $now);
1.1170 droeschl 5848: }
1.1172.2.23 raeburn 5849: }
5850: }
1.461 www 5851: return 0;
1.9 www 5852: }
1.1 albertel 5853:
1.1172.2.23 raeburn 5854: sub privileged_by_domain {
5855: my ($domains,$roles) = @_;
5856: my %privileged = ();
5857: my $cachetime = 60*60*24;
5858: my $now = time;
5859: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5860: return %privileged;
5861: }
5862: foreach my $dom (@{$domains}) {
5863: next if (ref($privileged{$dom}) eq 'HASH');
5864: my $needroles;
5865: foreach my $role (@{$roles}) {
5866: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5867: if (defined($cached)) {
5868: if (ref($result) eq 'HASH') {
5869: $privileged{$dom}{$role} = $result;
5870: }
5871: } else {
5872: $needroles = 1;
5873: }
5874: }
5875: if ($needroles) {
5876: my %dompersonnel = &get_domain_roles($dom,$roles);
5877: $privileged{$dom} = {};
5878: foreach my $server (keys(%dompersonnel)) {
5879: if (ref($dompersonnel{$server}) eq 'HASH') {
5880: foreach my $item (keys(%{$dompersonnel{$server}})) {
5881: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5882: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5883: next if ($end && $end < $now);
5884: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5885: $dompersonnel{$server}{$item};
5886: }
5887: }
5888: }
5889: if (ref($privileged{$dom}) eq 'HASH') {
5890: foreach my $role (@{$roles}) {
5891: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5892: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5893: } else {
5894: my %hash = ();
5895: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5896: }
5897: }
5898: }
5899: }
5900: }
5901: return %privileged;
5902: }
5903:
1.103 harris41 5904: # -------------------------------------------------------- Get user privileges
1.11 www 5905:
5906: sub rolesinit {
1.1169 droeschl 5907: my ($domain, $username) = @_;
5908: my %userroles = ('user.login.time' => time);
5909: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5910:
5911: # firstaccess and timerinterval are related to timed maps/resources.
5912: # also, blocking can be triggered by an activating timer
5913: # it's saved in the user's %env.
5914: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5915: my %timerinterval = &dump('timerinterval', $domain, $username);
5916: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5917: %timerintchk, %timerintenv);
5918:
1.1162 raeburn 5919: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5920: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5921: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5922: }
1.1169 droeschl 5923:
1.1162 raeburn 5924: foreach my $key (keys(%timerinterval)) {
5925: my ($cid,$rest) = split(/\0/,$key);
5926: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5927: }
1.1169 droeschl 5928:
1.11 www 5929: my %allroles=();
1.1162 raeburn 5930: my %allgroups=();
1.11 www 5931:
1.1172.2.58 raeburn 5932: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5933: my $role = $rolesdump{$area};
5934: $area =~ s/\_\w\w$//;
5935:
5936: my ($trole, $tend, $tstart, $group_privs);
5937:
5938: if ($role =~ /^cr/) {
5939: # Custom role, defined by a user
5940: # e.g., user.role.cr/msu/smith/mynewrole
5941: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5942: $trole = $1;
5943: ($tend, $tstart) = split('_', $2);
5944: } else {
5945: $trole = $role;
5946: }
5947: } elsif ($role =~ m|^gr/|) {
5948: # Role of member in a group, defined within a course/community
5949: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5950: ($trole, $tend, $tstart) = split(/_/, $role);
5951: next if $tstart eq '-1';
5952: ($trole, $group_privs) = split(/\//, $trole);
5953: $group_privs = &unescape($group_privs);
5954: } else {
5955: # Just a normal role, defined in roles.tab
5956: ($trole, $tend, $tstart) = split(/_/,$role);
5957: }
5958:
5959: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5960: $username);
5961: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5962:
5963: # role expired or not available yet?
5964: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5965: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5966:
5967: next if $area eq '' or $trole eq '';
5968:
5969: my $spec = "$trole.$area";
5970: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5971:
5972: if ($trole =~ /^cr\//) {
5973: # Custom role, defined by a user
5974: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5975: } elsif ($trole eq 'gr') {
5976: # Role of a member in a group, defined within a course/community
5977: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5978: next;
5979: } else {
5980: # Normal role, defined in roles.tab
5981: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5982: }
5983:
5984: my $cid = $tdomain.'_'.$trest;
5985: unless ($firstaccchk{$cid}) {
5986: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5987: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5988: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5989: $coursetimerstarts{$cid}{$item};
5990: }
5991: }
5992: $firstaccchk{$cid} = 1;
5993: }
5994: unless ($timerintchk{$cid}) {
5995: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5996: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5997: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5998: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5999: }
1.12 www 6000: }
1.1169 droeschl 6001: $timerintchk{$cid} = 1;
1.191 harris41 6002: }
1.11 www 6003: }
1.1169 droeschl 6004:
1.1172.2.91 raeburn 6005: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6006: \%allroles, \%allgroups);
1.1169 droeschl 6007: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6008: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6009:
1.1162 raeburn 6010: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6011: }
6012:
1.567 raeburn 6013: sub set_arearole {
1.1172.2.19 raeburn 6014: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6015: unless ($nolog) {
1.567 raeburn 6016: # log the associated role with the area
1.1172.2.19 raeburn 6017: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6018: }
1.743 albertel 6019: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6020: }
6021:
6022: sub custom_roleprivs {
6023: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6024: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6025: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6026: if (&hostname($homsvr) ne '') {
1.567 raeburn 6027: my ($rdummy,$roledef)=
6028: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6029: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6030: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6031: if (defined($syspriv)) {
1.1043 raeburn 6032: if ($trest =~ /^$match_community$/) {
6033: $syspriv =~ s/bre\&S//;
6034: }
1.567 raeburn 6035: $$allroles{'cm./'}.=':'.$syspriv;
6036: $$allroles{$spec.'./'}.=':'.$syspriv;
6037: }
6038: if ($tdomain ne '') {
6039: if (defined($dompriv)) {
6040: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6041: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6042: }
6043: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6044: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6045: my $rolename = $1;
6046: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6047: }
1.567 raeburn 6048: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6049: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6050: }
6051: }
6052: }
6053: }
6054: }
6055:
1.1172.2.89 raeburn 6056: sub course_adhocrole_privs {
6057: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6058: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6059: if ($overrides{"internal.adhocpriv.$rolename"}) {
6060: my (%currprivs,%storeprivs);
6061: foreach my $item (split(/:/,$coursepriv)) {
6062: my ($priv,$restrict) = split(/\&/,$item);
6063: $currprivs{$priv} = $restrict;
6064: }
6065: my (%possadd,%possremove,%full);
6066: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6067: my ($priv,$restrict)=split(/\&/,$item);
6068: $full{$priv} = $restrict;
6069: }
6070: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6071: next if ($item eq '');
6072: my ($rule,$rest) = split(/=/,$item);
6073: next unless (($rule eq 'off') || ($rule eq 'on'));
6074: foreach my $priv (split(/:/,$rest)) {
6075: if ($priv ne '') {
6076: if ($rule eq 'off') {
6077: $possremove{$priv} = 1;
6078: } else {
6079: $possadd{$priv} = 1;
6080: }
6081: }
6082: }
6083: }
6084: foreach my $priv (sort(keys(%full))) {
6085: if (exists($currprivs{$priv})) {
6086: unless (exists($possremove{$priv})) {
6087: $storeprivs{$priv} = $currprivs{$priv};
6088: }
6089: } elsif (exists($possadd{$priv})) {
6090: $storeprivs{$priv} = $full{$priv};
6091: }
6092: }
6093: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6094: }
6095: return $coursepriv;
6096: }
6097:
1.678 raeburn 6098: sub group_roleprivs {
6099: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6100: my $access = 1;
6101: my $now = time;
6102: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6103: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6104: if ($access) {
1.811 albertel 6105: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6106: $$allgroups{$course}{$group} .=':'.$group_privs;
6107: }
6108: }
1.567 raeburn 6109:
6110: sub standard_roleprivs {
6111: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6112: if (defined($pr{$trole.':s'})) {
6113: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6114: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6115: }
6116: if ($tdomain ne '') {
6117: if (defined($pr{$trole.':d'})) {
6118: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6119: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6120: }
6121: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6122: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6123: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6124: }
6125: }
6126: }
6127:
6128: sub set_userprivs {
1.1064 raeburn 6129: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6130: my $author=0;
6131: my $adv=0;
1.1172.2.91 raeburn 6132: my $rar=0;
1.678 raeburn 6133: my %grouproles = ();
6134: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6135: my @groupkeys;
1.1000 raeburn 6136: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6137: push(@groupkeys,$role);
6138: }
6139: if (ref($groups_roles) eq 'HASH') {
6140: foreach my $key (keys(%{$groups_roles})) {
6141: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6142: push(@groupkeys,$key);
6143: }
6144: }
6145: }
6146: if (@groupkeys > 0) {
6147: foreach my $role (@groupkeys) {
6148: my ($trole,$area,$sec,$extendedarea);
6149: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6150: $trole = $1;
6151: $area = $2;
6152: $sec = $3;
6153: $extendedarea = $area.$sec;
6154: if (exists($$allgroups{$area})) {
6155: foreach my $group (keys(%{$$allgroups{$area}})) {
6156: my $spec = $trole.'.'.$extendedarea;
6157: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6158: $$allgroups{$area}{$group};
1.1064 raeburn 6159: }
1.678 raeburn 6160: }
6161: }
6162: }
6163: }
6164: }
1.800 albertel 6165: foreach my $group (keys(%grouproles)) {
6166: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6167: }
1.800 albertel 6168: foreach my $role (keys(%{$allroles})) {
6169: my %thesepriv;
1.941 raeburn 6170: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6171: foreach my $item (split(/:/,$$allroles{$role})) {
6172: if ($item ne '') {
6173: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6174: if ($restrictions eq '') {
6175: $thesepriv{$privilege}='F';
6176: } elsif ($thesepriv{$privilege} ne 'F') {
6177: $thesepriv{$privilege}.=$restrictions;
6178: }
6179: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 6180: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6181: }
6182: }
6183: my $thesestr='';
1.1104 raeburn 6184: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6185: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6186: }
6187: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6188: }
1.1172.2.91 raeburn 6189: return ($author,$adv,$rar);
1.567 raeburn 6190: }
6191:
1.994 raeburn 6192: sub role_status {
1.1104 raeburn 6193: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6194: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 6195: my ($one,$two) = split(m{\./},$rolekey,2);
6196: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6197: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 6198: $$where = '/'.$two;
1.994 raeburn 6199: $$trolecode=$$role.'.'.$$where;
6200: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6201: $$tstatus='is';
1.1104 raeburn 6202: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6203: $$tstatus='future';
1.1034 raeburn 6204: if ($$tstart<$now) {
6205: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6206: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6207: my (%allroles,%allgroups,$group_privs,
6208: %groups_roles,@rolecodes);
1.1002 raeburn 6209: my %userroles = (
6210: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6211: );
1.1064 raeburn 6212: @rolecodes = ('cm');
1.1002 raeburn 6213: my $spec=$$role.'.'.$$where;
6214: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6215: if ($$role =~ /^cr\//) {
6216: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6217: push(@rolecodes,'cr');
1.1002 raeburn 6218: } elsif ($$role eq 'gr') {
1.1064 raeburn 6219: push(@rolecodes,$$role);
1.1002 raeburn 6220: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6221: $env{'user.name'});
1.1064 raeburn 6222: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6223: (undef,my $group_privs) = split(/\//,$trole);
6224: $group_privs = &unescape($group_privs);
6225: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6226: 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 6227: &get_groups_roles($tdomain,$trest,
6228: \%course_roles,\@rolecodes,
6229: \%groups_roles);
1.1002 raeburn 6230: } else {
1.1064 raeburn 6231: push(@rolecodes,$$role);
1.1002 raeburn 6232: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6233: }
1.1172.2.91 raeburn 6234: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6235: \%groups_roles);
1.1064 raeburn 6236: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6237: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6238: }
6239: }
1.1034 raeburn 6240: $$tstatus = 'is';
1.1002 raeburn 6241: }
1.994 raeburn 6242: }
6243: if ($$tend) {
1.1104 raeburn 6244: if ($$tend<$update) {
1.994 raeburn 6245: $$tstatus='expired';
6246: } elsif ($$tend<$now) {
6247: $$tstatus='will_not';
6248: }
6249: }
6250: }
6251: }
6252: }
6253:
1.1104 raeburn 6254: sub get_groups_roles {
6255: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6256: return unless((ref($cdom_courseroles) eq 'HASH') &&
6257: (ref($rolecodes) eq 'ARRAY') &&
6258: (ref($groups_roles) eq 'HASH'));
6259: if (keys(%{$cdom_courseroles}) > 0) {
6260: my ($cnum) = ($rest =~ /^($match_courseid)/);
6261: if ($cdom ne '' && $cnum ne '') {
6262: foreach my $key (keys(%{$cdom_courseroles})) {
6263: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6264: my $crsrole = $1;
6265: my $crssec = $2;
6266: if ($crsrole =~ /^cr/) {
6267: unless (grep(/^cr$/,@{$rolecodes})) {
6268: push(@{$rolecodes},'cr');
6269: }
6270: } else {
6271: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6272: push(@{$rolecodes},$crsrole);
6273: }
6274: }
6275: my $rolekey = "$crsrole./$cdom/$cnum";
6276: if ($crssec ne '') {
6277: $rolekey .= "/$crssec";
6278: }
6279: $rolekey .= './';
6280: $groups_roles->{$rolekey} = $rolecodes;
6281: }
6282: }
6283: }
6284: }
6285: return;
6286: }
6287:
6288: sub delete_env_groupprivs {
6289: my ($where,$courseroles,$possroles) = @_;
6290: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6291: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6292: unless (ref($courseroles->{$udom}) eq 'HASH') {
6293: %{$courseroles->{$udom}} =
6294: &get_my_roles('','','userroles',['active'],
6295: $possroles,[$udom],1);
6296: }
6297: if (ref($courseroles->{$udom}) eq 'HASH') {
6298: foreach my $item (keys(%{$courseroles->{$udom}})) {
6299: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6300: my $area = '/'.$cdom.'/'.$cnum;
6301: my $privkey = "user.priv.$crsrole.$area";
6302: if ($crssec ne '') {
6303: $privkey .= '/'.$crssec;
6304: }
6305: $privkey .= ".$area/$group";
6306: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6307: }
6308: }
6309: return;
6310: }
6311:
1.994 raeburn 6312: sub check_adhoc_privs {
1.1172.2.86 raeburn 6313: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6314: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6315: if ($sec) {
6316: $cckey .= '/'.$sec;
6317: }
1.1172.2.9 raeburn 6318: my $setprivs;
1.994 raeburn 6319: if ($env{$cckey}) {
6320: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6321: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6322: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6323: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6324: $setprivs = 1;
1.994 raeburn 6325: }
6326: } else {
1.1172.2.87 raeburn 6327: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6328: $setprivs = 1;
1.994 raeburn 6329: }
1.1172.2.9 raeburn 6330: return $setprivs;
1.994 raeburn 6331: }
6332:
6333: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6334: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6335: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6336: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6337: if ($sec ne '') {
6338: $area .= '/'.$sec;
6339: }
1.994 raeburn 6340: my $spec = $role.'.'.$area;
6341: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6342: $env{'user.name'},1);
1.1172.2.84 raeburn 6343: my %rolehash = ();
1.1172.2.89 raeburn 6344: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6345: my $rolename = $1;
1.1172.2.84 raeburn 6346: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6347: my %domdef = &get_domain_defaults($dcdom);
6348: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6349: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6350: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6351: }
6352: }
1.1172.2.84 raeburn 6353: } else {
6354: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6355: }
1.1172.2.91 raeburn 6356: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6357: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6358: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6359: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6360: &appenv( {'request.role' => $spec,
6361: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6362: 'request.course.sec' => $sec,
1.1088 raeburn 6363: }
6364: );
6365: my $tadv=0;
6366: if (&allowed('adv') eq 'F') { $tadv=1; }
6367: &appenv({'request.role.adv' => $tadv});
6368: }
1.994 raeburn 6369: }
6370:
1.12 www 6371: # --------------------------------------------------------------- get interface
6372:
6373: sub get {
1.131 albertel 6374: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6375: my $items='';
1.800 albertel 6376: foreach my $item (@$storearr) {
6377: $items.=&escape($item).'&';
1.191 harris41 6378: }
1.12 www 6379: $items=~s/\&$//;
1.620 albertel 6380: if (!$udomain) { $udomain=$env{'user.domain'}; }
6381: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6382: my $uhome=&homeserver($uname,$udomain);
6383:
1.133 albertel 6384: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6385: my @pairs=split(/\&/,$rep);
1.273 albertel 6386: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6387: return @pairs;
6388: }
1.15 www 6389: my %returnhash=();
1.42 www 6390: my $i=0;
1.800 albertel 6391: foreach my $item (@$storearr) {
6392: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6393: $i++;
1.191 harris41 6394: }
1.15 www 6395: return %returnhash;
1.27 www 6396: }
6397:
6398: # --------------------------------------------------------------- del interface
6399:
6400: sub del {
1.133 albertel 6401: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6402: my $items='';
1.800 albertel 6403: foreach my $item (@$storearr) {
6404: $items.=&escape($item).'&';
1.191 harris41 6405: }
1.984 neumanie 6406:
1.27 www 6407: $items=~s/\&$//;
1.620 albertel 6408: if (!$udomain) { $udomain=$env{'user.domain'}; }
6409: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6410: my $uhome=&homeserver($uname,$udomain);
6411: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6412: }
6413:
6414: # -------------------------------------------------------------- dump interface
6415:
1.1172.2.22 raeburn 6416: sub unserialize {
6417: my ($rep, $escapedkeys) = @_;
6418:
6419: return {} if $rep =~ /^error/;
6420:
6421: my %returnhash=();
6422: foreach my $item (split(/\&/,$rep)) {
6423: my ($key, $value) = split(/=/, $item, 2);
6424: $key = unescape($key) unless $escapedkeys;
6425: next if $key =~ /^error: 2 /;
6426: $returnhash{$key} = &thaw_unescape($value);
6427: }
6428: return \%returnhash;
6429: }
6430:
6431: # see Lond::dump_with_regexp
6432: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6433: sub dump {
1.1172.2.22 raeburn 6434: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6435: if (!$udomain) { $udomain=$env{'user.domain'}; }
6436: if (!$uname) { $uname=$env{'user.name'}; }
6437: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6438:
1.1172.2.55 raeburn 6439: if ($regexp) {
6440: $regexp=&escape($regexp);
6441: } else {
6442: $regexp='.';
6443: }
1.1172.2.22 raeburn 6444: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6445: # user is hosted on this machine
1.1172.2.55 raeburn 6446: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6447: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6448: return %{&unserialize($reply, $escapedkeys)};
6449: }
1.1166 raeburn 6450: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6451: my @pairs=split(/\&/,$rep);
6452: my %returnhash=();
1.1098 foxr 6453: if (!($rep =~ /^error/ )) {
6454: foreach my $item (@pairs) {
6455: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6456: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6457: next if ($key =~ /^error: 2 /);
6458: $returnhash{$key}=&thaw_unescape($value);
6459: }
1.755 albertel 6460: }
6461: return %returnhash;
1.407 www 6462: }
6463:
1.1098 foxr 6464:
1.717 albertel 6465: # --------------------------------------------------------- dumpstore interface
6466:
6467: sub dumpstore {
6468: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6469: # same as dump but keys must be escaped. They may contain colon separated
6470: # lists of values that may themself contain colons (e.g. symbs).
6471: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6472: }
6473:
1.407 www 6474: # -------------------------------------------------------------- keys interface
6475:
6476: sub getkeys {
6477: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6478: if (!$udomain) { $udomain=$env{'user.domain'}; }
6479: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6480: my $uhome=&homeserver($uname,$udomain);
6481: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6482: my @keyarray=();
1.800 albertel 6483: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6484: next if ($key =~ /^error: 2 /);
1.800 albertel 6485: push(@keyarray,&unescape($key));
1.407 www 6486: }
6487: return @keyarray;
1.318 matthew 6488: }
6489:
1.319 matthew 6490: # --------------------------------------------------------------- currentdump
6491: sub currentdump {
1.328 matthew 6492: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6493: $courseid = $env{'request.course.id'} if (! defined($courseid));
6494: $sdom = $env{'user.domain'} if (! defined($sdom));
6495: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6496: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6497: my $rep;
6498:
6499: if (grep { $_ eq $uhome } current_machine_ids()) {
6500: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6501: $courseid)));
6502: } else {
6503: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6504: }
6505:
1.318 matthew 6506: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6507: #
1.318 matthew 6508: my %returnhash=();
1.319 matthew 6509: #
1.1172.2.93.4 2(raebur 6510:7): if ($rep eq 'unknown_cmd') {
1.319 matthew 6511: # an old lond will not know currentdump
6512: # Do a dump and make it look like a currentdump
1.822 albertel 6513: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6514: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6515: my %hash = @tmp;
6516: @tmp=();
1.424 matthew 6517: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6518: } else {
6519: my @pairs=split(/\&/,$rep);
1.800 albertel 6520: foreach my $pair (@pairs) {
6521: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6522: my ($symb,$param) = split(/:/,$key);
6523: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6524: &thaw_unescape($value);
1.319 matthew 6525: }
1.191 harris41 6526: }
1.12 www 6527: return %returnhash;
1.424 matthew 6528: }
6529:
6530: sub convert_dump_to_currentdump{
6531: my %hash = %{shift()};
6532: my %returnhash;
6533: # Code ripped from lond, essentially. The only difference
6534: # here is the unescaping done by lonnet::dump(). Conceivably
6535: # we might run in to problems with parameter names =~ /^v\./
6536: while (my ($key,$value) = each(%hash)) {
6537: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6538: $symb = &unescape($symb);
6539: $param = &unescape($param);
1.424 matthew 6540: next if ($v eq 'version' || $symb eq 'keys');
6541: next if (exists($returnhash{$symb}) &&
6542: exists($returnhash{$symb}->{$param}) &&
6543: $returnhash{$symb}->{'v.'.$param} > $v);
6544: $returnhash{$symb}->{$param}=$value;
6545: $returnhash{$symb}->{'v.'.$param}=$v;
6546: }
6547: #
6548: # Remove all of the keys in the hashes which keep track of
6549: # the version of the parameter.
6550: while (my ($symb,$param_hash) = each(%returnhash)) {
6551: # use a foreach because we are going to delete from the hash.
6552: foreach my $key (keys(%$param_hash)) {
6553: delete($param_hash->{$key}) if ($key =~ /^v\./);
6554: }
6555: }
6556: return \%returnhash;
1.12 www 6557: }
6558:
1.627 albertel 6559: # ------------------------------------------------------ critical inc interface
6560:
6561: sub cinc {
6562: return &inc(@_,'critical');
6563: }
6564:
1.449 matthew 6565: # --------------------------------------------------------------- inc interface
6566:
6567: sub inc {
1.627 albertel 6568: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6569: if (!$udomain) { $udomain=$env{'user.domain'}; }
6570: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6571: my $uhome=&homeserver($uname,$udomain);
6572: my $items='';
6573: if (! ref($store)) {
6574: # got a single value, so use that instead
6575: $items = &escape($store).'=&';
6576: } elsif (ref($store) eq 'SCALAR') {
6577: $items = &escape($$store).'=&';
6578: } elsif (ref($store) eq 'ARRAY') {
6579: $items = join('=&',map {&escape($_);} @{$store});
6580: } elsif (ref($store) eq 'HASH') {
6581: while (my($key,$value) = each(%{$store})) {
6582: $items.= &escape($key).'='.&escape($value).'&';
6583: }
6584: }
6585: $items=~s/\&$//;
1.627 albertel 6586: if ($critical) {
6587: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6588: } else {
6589: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6590: }
1.449 matthew 6591: }
6592:
1.12 www 6593: # --------------------------------------------------------------- put interface
6594:
6595: sub put {
1.134 albertel 6596: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6597: if (!$udomain) { $udomain=$env{'user.domain'}; }
6598: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6599: my $uhome=&homeserver($uname,$udomain);
1.12 www 6600: my $items='';
1.800 albertel 6601: foreach my $item (keys(%$storehash)) {
6602: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6603: }
1.12 www 6604: $items=~s/\&$//;
1.134 albertel 6605: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6606: }
6607:
1.631 albertel 6608: # ------------------------------------------------------------ newput interface
6609:
6610: sub newput {
6611: my ($namespace,$storehash,$udomain,$uname)=@_;
6612: if (!$udomain) { $udomain=$env{'user.domain'}; }
6613: if (!$uname) { $uname=$env{'user.name'}; }
6614: my $uhome=&homeserver($uname,$udomain);
6615: my $items='';
6616: foreach my $key (keys(%$storehash)) {
6617: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6618: }
6619: $items=~s/\&$//;
6620: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6621: }
6622:
6623: # --------------------------------------------------------- putstore interface
6624:
1.524 raeburn 6625: sub putstore {
1.1172.2.59 raeburn 6626: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6627: if (!$udomain) { $udomain=$env{'user.domain'}; }
6628: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6629: my $uhome=&homeserver($uname,$udomain);
6630: my $items='';
1.715 albertel 6631: foreach my $key (keys(%$storehash)) {
6632: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6633: }
1.715 albertel 6634: $items=~s/\&$//;
1.716 albertel 6635: my $esc_symb=&escape($symb);
6636: my $esc_v=&escape($version);
1.715 albertel 6637: my $reply =
1.716 albertel 6638: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6639: $uhome);
1.1172.2.59 raeburn 6640: if (($tolog) && ($reply eq 'ok')) {
6641: my $namevalue='';
6642: foreach my $key (keys(%{$storehash})) {
6643: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6644: }
6645: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6646: '&host='.&escape($perlvar{'lonHostID'}).
6647: '&version='.$esc_v.
6648: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6649: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6650: }
1.715 albertel 6651: if ($reply eq 'unknown_cmd') {
1.716 albertel 6652: # gfall back to way things use to be done
1.715 albertel 6653: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6654: $uname);
1.524 raeburn 6655: }
1.715 albertel 6656: return $reply;
6657: }
6658:
6659: sub old_putstore {
1.716 albertel 6660: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6661: if (!$udomain) { $udomain=$env{'user.domain'}; }
6662: if (!$uname) { $uname=$env{'user.name'}; }
6663: my $uhome=&homeserver($uname,$udomain);
6664: my %newstorehash;
1.800 albertel 6665: foreach my $item (keys(%$storehash)) {
6666: my $key = $version.':'.&escape($symb).':'.$item;
6667: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6668: }
6669: my $items='';
6670: my %allitems = ();
1.800 albertel 6671: foreach my $item (keys(%newstorehash)) {
6672: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6673: my $key = $1.':keys:'.$2;
6674: $allitems{$key} .= $3.':';
6675: }
1.800 albertel 6676: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6677: }
1.800 albertel 6678: foreach my $item (keys(%allitems)) {
6679: $allitems{$item} =~ s/\:$//;
6680: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6681: }
6682: $items=~s/\&$//;
6683: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6684: }
6685:
1.47 www 6686: # ------------------------------------------------------ critical put interface
6687:
6688: sub cput {
1.134 albertel 6689: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6690: if (!$udomain) { $udomain=$env{'user.domain'}; }
6691: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6692: my $uhome=&homeserver($uname,$udomain);
1.47 www 6693: my $items='';
1.800 albertel 6694: foreach my $item (keys(%$storehash)) {
6695: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6696: }
1.47 www 6697: $items=~s/\&$//;
1.134 albertel 6698: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6699: }
6700:
6701: # -------------------------------------------------------------- eget interface
6702:
6703: sub eget {
1.133 albertel 6704: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6705: my $items='';
1.800 albertel 6706: foreach my $item (@$storearr) {
6707: $items.=&escape($item).'&';
1.191 harris41 6708: }
1.12 www 6709: $items=~s/\&$//;
1.620 albertel 6710: if (!$udomain) { $udomain=$env{'user.domain'}; }
6711: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6712: my $uhome=&homeserver($uname,$udomain);
6713: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6714: my @pairs=split(/\&/,$rep);
6715: my %returnhash=();
1.42 www 6716: my $i=0;
1.800 albertel 6717: foreach my $item (@$storearr) {
6718: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6719: $i++;
1.191 harris41 6720: }
1.12 www 6721: return %returnhash;
6722: }
6723:
1.667 albertel 6724: # ------------------------------------------------------------ tmpput interface
6725: sub tmpput {
1.802 raeburn 6726: my ($storehash,$server,$context)=@_;
1.667 albertel 6727: my $items='';
1.800 albertel 6728: foreach my $item (keys(%$storehash)) {
6729: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6730: }
6731: $items=~s/\&$//;
1.802 raeburn 6732: if (defined($context)) {
6733: $items .= ':'.&escape($context);
6734: }
1.667 albertel 6735: return &reply("tmpput:$items",$server);
6736: }
6737:
6738: # ------------------------------------------------------------ tmpget interface
6739: sub tmpget {
1.688 albertel 6740: my ($token,$server)=@_;
6741: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6742: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6743: my %returnhash;
1.1172.2.85 raeburn 6744: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6745: return %returnhash;
6746: }
1.667 albertel 6747: foreach my $item (split(/\&/,$rep)) {
6748: my ($key,$value)=split(/=/,$item);
6749: $returnhash{&unescape($key)}=&thaw_unescape($value);
6750: }
6751: return %returnhash;
6752: }
6753:
1.1113 raeburn 6754: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6755: sub tmpdel {
6756: my ($token,$server)=@_;
6757: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6758: return &reply("tmpdel:$token",$server);
6759: }
6760:
1.1172.2.13 raeburn 6761: # ------------------------------------------------------------ get_timebased_id
6762:
6763: sub get_timebased_id {
6764: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6765: $maxtries) = @_;
6766: my ($newid,$error,$dellock);
6767: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6768: return ('','ok','invalid call to get suffix');
6769: }
6770:
6771: # set defaults for any optional args for which values were not supplied
6772: if ($who eq '') {
6773: $who = $env{'user.name'}.':'.$env{'user.domain'};
6774: }
6775: if (!$locktries) {
6776: $locktries = 3;
6777: }
6778: if (!$maxtries) {
6779: $maxtries = 10;
6780: }
6781:
6782: if (($cdom eq '') || ($cnum eq '')) {
6783: if ($env{'request.course.id'}) {
6784: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6785: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6786: }
6787: if (($cdom eq '') || ($cnum eq '')) {
6788: return ('','ok','call to get suffix not in course context');
6789: }
6790: }
6791:
6792: # construct locking item
6793: my $lockhash = {
6794: $prefix."\0".'locked_'.$keyid => $who,
6795: };
6796: my $tries = 0;
6797:
6798: # attempt to get lock on nohist_$namespace file
6799: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6800: while (($gotlock ne 'ok') && $tries <$locktries) {
6801: $tries ++;
6802: sleep 1;
6803: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6804: }
6805:
6806: # attempt to get unique identifier, based on current timestamp
6807: if ($gotlock eq 'ok') {
6808: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6809: my $id = time;
6810: $newid = $id;
1.1172.2.56 raeburn 6811: if ($idtype eq 'addcode') {
6812: $newid .= &sixnum_code();
6813: }
1.1172.2.13 raeburn 6814: my $idtries = 0;
6815: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6816: if ($idtype eq 'concat') {
6817: $newid = $id.$idtries;
1.1172.2.56 raeburn 6818: } elsif ($idtype eq 'addcode') {
6819: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6820: } else {
6821: $newid ++;
6822: }
6823: $idtries ++;
6824: }
6825: if (!exists($inuse{$prefix."\0".$newid})) {
6826: my %new_item = (
6827: $prefix."\0".$newid => $who,
6828: );
6829: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6830: $cdom,$cnum);
6831: if ($putresult ne 'ok') {
6832: undef($newid);
6833: $error = 'error saving new item: '.$putresult;
6834: }
6835: } else {
1.1172.2.56 raeburn 6836: undef($newid);
1.1172.2.13 raeburn 6837: $error = ('error: no unique suffix available for the new item ');
6838: }
6839: # remove lock
6840: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6841: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6842: } else {
6843: $error = "error: could not obtain lockfile\n";
6844: $dellock = 'ok';
1.1172.2.58 raeburn 6845: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6846: $dellock = 'nolock';
6847: }
1.1172.2.13 raeburn 6848: }
6849: return ($newid,$dellock,$error);
6850: }
6851:
1.1172.2.56 raeburn 6852: sub sixnum_code {
6853: my $code;
6854: for (0..6) {
6855: $code .= int( rand(9) );
6856: }
6857: return $code;
6858: }
6859:
1.765 albertel 6860: # -------------------------------------------------- portfolio access checking
6861:
6862: sub portfolio_access {
1.1172.2.77 raeburn 6863: my ($requrl,$clientip) = @_;
1.765 albertel 6864: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 6865: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6866: if ($result) {
6867: my %setters;
6868: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6869: my ($startblock,$endblock) =
6870: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6871: if ($startblock && $endblock) {
6872: return 'B';
6873: }
6874: } else {
6875: my ($startblock,$endblock) =
6876: &Apache::loncommon::blockcheck(\%setters,'port');
6877: if ($startblock && $endblock) {
6878: return 'B';
6879: }
6880: }
6881: }
1.765 albertel 6882: if ($result eq 'ok') {
1.766 albertel 6883: return 'F';
1.765 albertel 6884: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6885: return 'A';
1.765 albertel 6886: }
1.766 albertel 6887: return '';
1.765 albertel 6888: }
6889:
6890: sub get_portfolio_access {
1.1172.2.77 raeburn 6891: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6892:
6893: if (!ref($access_hash)) {
6894: my $current_perms = &get_portfile_permissions($udom,$unum);
6895: my %access_controls = &get_access_controls($current_perms,$group,
6896: $file_name);
6897: $access_hash = $access_controls{$file_name};
6898: }
6899:
1.1172.2.77 raeburn 6900: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6901: my $now = time;
6902: if (ref($access_hash) eq 'HASH') {
6903: foreach my $key (keys(%{$access_hash})) {
6904: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6905: if ($start > $now) {
6906: next;
6907: }
6908: if ($end && $end<$now) {
6909: next;
6910: }
6911: if ($scope eq 'public') {
6912: $public = $key;
6913: last;
6914: } elsif ($scope eq 'guest') {
6915: $guest = $key;
6916: } elsif ($scope eq 'domains') {
6917: push(@domains,$key);
6918: } elsif ($scope eq 'users') {
6919: push(@users,$key);
6920: } elsif ($scope eq 'course') {
6921: push(@courses,$key);
6922: } elsif ($scope eq 'group') {
6923: push(@groups,$key);
1.1172.2.77 raeburn 6924: } elsif ($scope eq 'ip') {
6925: push(@ips,$key);
1.765 albertel 6926: }
6927: }
6928: if ($public) {
6929: return 'ok';
1.1172.2.77 raeburn 6930: } elsif (@ips > 0) {
6931: my $allowed;
6932: foreach my $ipkey (@ips) {
6933: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6934: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6935: $allowed = 1;
6936: last;
6937: }
6938: }
6939: }
6940: if ($allowed) {
6941: return 'ok';
6942: }
1.765 albertel 6943: }
6944: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6945: if ($guest) {
6946: return $guest;
6947: }
6948: } else {
6949: if (@domains > 0) {
6950: foreach my $domkey (@domains) {
6951: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6952: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6953: return 'ok';
6954: }
6955: }
6956: }
6957: }
6958: if (@users > 0) {
6959: foreach my $userkey (@users) {
1.865 raeburn 6960: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6961: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6962: if (ref($item) eq 'HASH') {
6963: if (($item->{'uname'} eq $env{'user.name'}) &&
6964: ($item->{'udom'} eq $env{'user.domain'})) {
6965: return 'ok';
6966: }
6967: }
6968: }
6969: }
1.765 albertel 6970: }
6971: }
6972: my %roleshash;
6973: my @courses_and_groups = @courses;
6974: push(@courses_and_groups,@groups);
6975: if (@courses_and_groups > 0) {
6976: my (%allgroups,%allroles);
6977: my ($start,$end,$role,$sec,$group);
6978: foreach my $envkey (%env) {
1.1060 raeburn 6979: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6980: my $cid = $2.'_'.$3;
6981: if ($1 eq 'gr') {
6982: $group = $4;
6983: $allgroups{$cid}{$group} = $env{$envkey};
6984: } else {
6985: if ($4 eq '') {
6986: $sec = 'none';
6987: } else {
6988: $sec = $4;
6989: }
6990: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6991: }
1.811 albertel 6992: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6993: my $cid = $2.'_'.$3;
6994: if ($4 eq '') {
6995: $sec = 'none';
6996: } else {
6997: $sec = $4;
6998: }
6999: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7000: }
7001: }
7002: if (keys(%allroles) == 0) {
7003: return;
7004: }
7005: foreach my $key (@courses_and_groups) {
7006: my %content = %{$$access_hash{$key}};
7007: my $cnum = $content{'number'};
7008: my $cdom = $content{'domain'};
7009: my $cid = $cdom.'_'.$cnum;
7010: if (!exists($allroles{$cid})) {
7011: next;
7012: }
7013: foreach my $role_id (keys(%{$content{'roles'}})) {
7014: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7015: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7016: my @status = @{$content{'roles'}{$role_id}{'access'}};
7017: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7018: foreach my $role (keys(%{$allroles{$cid}})) {
7019: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7020: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7021: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7022: if (grep/^all$/,@sections) {
7023: return 'ok';
7024: } else {
7025: if (grep/^$sec$/,@sections) {
7026: return 'ok';
7027: }
7028: }
7029: }
7030: }
7031: if (keys(%{$allgroups{$cid}}) == 0) {
7032: if (grep/^none$/,@groups) {
7033: return 'ok';
7034: }
7035: } else {
7036: if (grep/^all$/,@groups) {
7037: return 'ok';
7038: }
7039: foreach my $group (keys(%{$allgroups{$cid}})) {
7040: if (grep/^$group$/,@groups) {
7041: return 'ok';
7042: }
7043: }
7044: }
7045: }
7046: }
7047: }
7048: }
7049: }
7050: if ($guest) {
7051: return $guest;
7052: }
7053: }
7054: }
7055: return;
7056: }
7057:
7058: sub course_group_datechecker {
7059: my ($dates,$now,$status) = @_;
7060: my ($start,$end) = split(/\./,$dates);
7061: if (!$start && !$end) {
7062: return 'ok';
7063: }
7064: if (grep/^active$/,@{$status}) {
7065: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7066: return 'ok';
7067: }
7068: }
7069: if (grep/^previous$/,@{$status}) {
7070: if ($end > $now ) {
7071: return 'ok';
7072: }
7073: }
7074: if (grep/^future$/,@{$status}) {
7075: if ($start > $now) {
7076: return 'ok';
7077: }
7078: }
7079: return;
7080: }
7081:
7082: sub parse_portfolio_url {
7083: my ($url) = @_;
7084:
7085: my ($type,$udom,$unum,$group,$file_name);
7086:
1.823 albertel 7087: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7088: $type = 1;
7089: $udom = $1;
7090: $unum = $2;
7091: $file_name = $3;
1.823 albertel 7092: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7093: $type = 2;
7094: $udom = $1;
7095: $unum = $2;
7096: $group = $3;
7097: $file_name = $3.'/'.$4;
7098: }
7099: if (wantarray) {
7100: return ($type,$udom,$unum,$file_name,$group);
7101: }
7102: return $type;
7103: }
7104:
7105: sub is_portfolio_url {
7106: my ($url) = @_;
7107: return scalar(&parse_portfolio_url($url));
7108: }
7109:
1.798 raeburn 7110: sub is_portfolio_file {
7111: my ($file) = @_;
1.820 raeburn 7112: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7113: return 1;
7114: }
7115: return;
7116: }
7117:
1.976 raeburn 7118: sub usertools_access {
1.1084 raeburn 7119: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7120: my ($access,%tools);
7121: if ($context eq '') {
7122: $context = 'tools';
7123: }
7124: if ($context eq 'requestcourses') {
7125: %tools = (
7126: official => 1,
7127: unofficial => 1,
1.1006 raeburn 7128: community => 1,
1.1172.2.37 raeburn 7129: textbook => 1,
1.985 raeburn 7130: );
1.1172.2.9 raeburn 7131: } elsif ($context eq 'requestauthor') {
7132: %tools = (
7133: requestauthor => 1,
7134: );
1.985 raeburn 7135: } else {
7136: %tools = (
7137: aboutme => 1,
7138: blog => 1,
1.1172.2.6 raeburn 7139: webdav => 1,
1.985 raeburn 7140: portfolio => 1,
7141: );
7142: }
1.976 raeburn 7143: return if (!defined($tools{$tool}));
7144:
1.1172.2.35 raeburn 7145: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7146: $udom = $env{'user.domain'};
7147: $uname = $env{'user.name'};
7148: }
7149:
1.978 raeburn 7150: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7151: if ($action ne 'reload') {
1.985 raeburn 7152: if ($context eq 'requestcourses') {
7153: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 7154: } elsif ($context eq 'requestauthor') {
7155: return $env{'environment.canrequest.author'};
1.985 raeburn 7156: } else {
7157: return $env{'environment.availabletools.'.$tool};
7158: }
7159: }
1.976 raeburn 7160: }
7161:
1.1172.2.9 raeburn 7162: my ($toolstatus,$inststatus,$envkey);
7163: if ($context eq 'requestauthor') {
7164: $envkey = $context;
7165: } else {
7166: $envkey = $context.'.'.$tool;
7167: }
1.976 raeburn 7168:
1.985 raeburn 7169: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7170: ($action ne 'reload')) {
1.1172.2.9 raeburn 7171: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7172: $inststatus = $env{'environment.inststatus'};
7173: } else {
1.1084 raeburn 7174: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 7175: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7176: $inststatus = $userenvref->{'inststatus'};
7177: } else {
1.1172.2.9 raeburn 7178: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7179: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7180: $inststatus = $userenv{'inststatus'};
7181: }
1.976 raeburn 7182: }
7183:
7184: if ($toolstatus ne '') {
7185: if ($toolstatus) {
7186: $access = 1;
7187: } else {
7188: $access = 0;
7189: }
7190: return $access;
7191: }
7192:
1.1084 raeburn 7193: my ($is_adv,%domdef);
7194: if (ref($is_advref) eq 'HASH') {
7195: $is_adv = $is_advref->{'is_adv'};
7196: } else {
7197: $is_adv = &is_advanced_user($udom,$uname);
7198: }
7199: if (ref($domdefref) eq 'HASH') {
7200: %domdef = %{$domdefref};
7201: } else {
7202: %domdef = &get_domain_defaults($udom);
7203: }
1.976 raeburn 7204: if (ref($domdef{$tool}) eq 'HASH') {
7205: if ($is_adv) {
7206: if ($domdef{$tool}{'_LC_adv'} ne '') {
7207: if ($domdef{$tool}{'_LC_adv'}) {
7208: $access = 1;
7209: } else {
7210: $access = 0;
7211: }
7212: return $access;
7213: }
7214: }
7215: if ($inststatus ne '') {
7216: my ($hasaccess,$hasnoaccess);
7217: foreach my $affiliation (split(/:/,$inststatus)) {
7218: if ($domdef{$tool}{$affiliation} ne '') {
7219: if ($domdef{$tool}{$affiliation}) {
7220: $hasaccess = 1;
7221: } else {
7222: $hasnoaccess = 1;
7223: }
7224: }
7225: }
7226: if ($hasaccess || $hasnoaccess) {
7227: if ($hasaccess) {
7228: $access = 1;
7229: } elsif ($hasnoaccess) {
7230: $access = 0;
7231: }
7232: return $access;
7233: }
7234: } else {
7235: if ($domdef{$tool}{'default'} ne '') {
7236: if ($domdef{$tool}{'default'}) {
7237: $access = 1;
7238: } elsif ($domdef{$tool}{'default'} == 0) {
7239: $access = 0;
7240: }
7241: return $access;
7242: }
7243: }
7244: } else {
1.1172.2.6 raeburn 7245: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7246: $access = 1;
7247: } else {
7248: $access = 0;
7249: }
1.976 raeburn 7250: return $access;
7251: }
7252: }
7253:
1.1050 raeburn 7254: sub is_course_owner {
7255: my ($cdom,$cnum,$udom,$uname) = @_;
7256: if (($udom eq '') || ($uname eq '')) {
7257: $udom = $env{'user.domain'};
7258: $uname = $env{'user.name'};
7259: }
7260: unless (($udom eq '') || ($uname eq '')) {
7261: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7262: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7263: return 1;
7264: } else {
7265: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7266: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7267: return 1;
7268: }
7269: }
7270: }
7271: }
7272: return;
7273: }
7274:
1.976 raeburn 7275: sub is_advanced_user {
7276: my ($udom,$uname) = @_;
1.1085 raeburn 7277: if ($udom ne '' && $uname ne '') {
7278: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7279: if (wantarray) {
7280: return ($env{'user.adv'},$env{'user.author'});
7281: } else {
7282: return $env{'user.adv'};
7283: }
1.1085 raeburn 7284: }
7285: }
1.976 raeburn 7286: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7287: my %allroles;
1.1128 raeburn 7288: my ($is_adv,$is_author);
1.976 raeburn 7289: foreach my $role (keys(%roleshash)) {
7290: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7291: my $area = '/'.$tdomain.'/'.$trest;
7292: if ($sec ne '') {
7293: $area .= '/'.$sec;
7294: }
7295: if (($area ne '') && ($trole ne '')) {
7296: my $spec=$trole.'.'.$area;
7297: if ($trole =~ /^cr\//) {
7298: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7299: } elsif ($trole ne 'gr') {
7300: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7301: }
1.1128 raeburn 7302: if ($trole eq 'au') {
7303: $is_author = 1;
7304: }
1.976 raeburn 7305: }
7306: }
7307: foreach my $role (keys(%allroles)) {
7308: last if ($is_adv);
7309: foreach my $item (split(/:/,$allroles{$role})) {
7310: if ($item ne '') {
7311: my ($privilege,$restrictions)=split(/&/,$item);
7312: if ($privilege eq 'adv') {
7313: $is_adv = 1;
7314: last;
7315: }
7316: }
7317: }
7318: }
1.1128 raeburn 7319: if (wantarray) {
7320: return ($is_adv,$is_author);
7321: }
1.976 raeburn 7322: return $is_adv;
7323: }
1.798 raeburn 7324:
1.1035 raeburn 7325: sub check_can_request {
1.1036 raeburn 7326: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7327: my $canreq = 0;
7328: my ($types,$typename) = &Apache::loncommon::course_types();
7329: my @options = ('approval','validate','autolimit');
7330: my $optregex = join('|',@options);
7331: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7332: foreach my $type (@{$types}) {
7333: if (&usertools_access($env{'user.name'},
7334: $env{'user.domain'},
7335: $type,undef,'requestcourses')) {
7336: $canreq ++;
1.1036 raeburn 7337: if (ref($request_domains) eq 'HASH') {
7338: push(@{$request_domains->{$type}},$env{'user.domain'});
7339: }
1.1035 raeburn 7340: if ($dom eq $env{'user.domain'}) {
7341: $can_request->{$type} = 1;
7342: }
7343: }
7344: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7345: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7346: if (@curr > 0) {
1.1036 raeburn 7347: foreach my $item (@curr) {
7348: if (ref($request_domains) eq 'HASH') {
7349: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7350: if ($otherdom ne '') {
7351: if (ref($request_domains->{$type}) eq 'ARRAY') {
7352: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7353: push(@{$request_domains->{$type}},$otherdom);
7354: }
7355: } else {
7356: push(@{$request_domains->{$type}},$otherdom);
7357: }
7358: }
7359: }
7360: }
7361: unless($dom eq $env{'user.domain'}) {
7362: $canreq ++;
1.1035 raeburn 7363: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7364: $can_request->{$type} = 1;
7365: }
7366: }
7367: }
7368: }
7369: }
7370: }
7371: return $canreq;
7372: }
7373:
1.341 www 7374: # ---------------------------------------------- Custom access rule evaluation
7375:
7376: sub customaccess {
7377: my ($priv,$uri)=@_;
1.807 albertel 7378: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7379: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7380: $udom = &LONCAPA::clean_domain($udom);
7381: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7382: my $access=0;
1.800 albertel 7383: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7384: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7385: if ($type eq 'user') {
7386: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7387: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7388: if ($tdom) {
7389: if ($tdom ne $env{'user.domain'}) { next; }
7390: }
1.896 albertel 7391: if ($tuname) {
7392: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7393: }
7394: $access=($effect eq 'allow');
7395: last;
7396: }
7397: } else {
7398: if ($role) {
7399: if ($role ne $urole) { next; }
7400: }
7401: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7402: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7403: if ($tdom) {
7404: if ($tdom ne $udom) { next; }
7405: }
7406: if ($tcrs) {
7407: if ($tcrs ne $ucrs) { next; }
7408: }
7409: if ($tsec) {
7410: if ($tsec ne $usec) { next; }
7411: }
7412: $access=($effect eq 'allow');
7413: last;
7414: }
7415: if ($realm eq '' && $role eq '') {
7416: $access=($effect eq 'allow');
7417: }
1.402 bowersj2 7418: }
1.341 www 7419: }
7420: return $access;
7421: }
7422:
1.103 harris41 7423: # ------------------------------------------------- Check for a user privilege
1.12 www 7424:
7425: sub allowed {
1.1172.2.65 raeburn 7426: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7427: my $ver_orguri=$uri;
1.439 www 7428: $uri=&deversion($uri);
1.152 www 7429: my $orguri=$uri;
1.52 www 7430: $uri=&declutter($uri);
1.809 raeburn 7431:
1.810 raeburn 7432: if ($priv eq 'evb') {
7433: # Evade communication block restrictions for specified role in a course
7434: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7435: return $1;
7436: } else {
7437: return;
7438: }
7439: }
7440:
1.620 albertel 7441: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7442: # Free bre access to adm and meta resources
1.1172.2.93.4 2(raebur 7443:7): if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
1.769 albertel 7444: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7445: && ($priv eq 'bre')) {
1.14 www 7446: return 'F';
1.159 www 7447: }
7448:
1.545 banghart 7449: # Free bre access to user's own portfolio contents
1.714 raeburn 7450: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7451: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7452: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7453: my %setters;
7454: my ($startblock,$endblock) =
7455: &Apache::loncommon::blockcheck(\%setters,'port');
7456: if ($startblock && $endblock) {
7457: return 'B';
7458: } else {
7459: return 'F';
7460: }
1.545 banghart 7461: }
7462:
1.762 raeburn 7463: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7464: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7465: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7466: if (exists($env{'request.course.id'})) {
7467: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7468: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7469: if (($domain eq $cdom) && ($name eq $cnum)) {
7470: my $courseprivid=$env{'request.course.id'};
7471: $courseprivid=~s/\_/\//;
7472: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7473: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7474: return $1;
1.762 raeburn 7475: } else {
7476: if ($env{'request.course.sec'}) {
7477: $courseprivid.='/'.$env{'request.course.sec'};
7478: }
7479: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7480: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7481: return $2;
7482: }
1.714 raeburn 7483: }
7484: }
7485: }
7486: }
7487:
1.159 www 7488: # Free bre to public access
7489:
7490: if ($priv eq 'bre') {
1.238 www 7491: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7492: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7493: return 'F';
7494: }
1.238 www 7495: if ($copyright eq 'priv') {
7496: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7497: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7498: return '';
7499: }
7500: }
7501: if ($copyright eq 'domain') {
7502: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7503: unless (($env{'user.domain'} eq $1) ||
7504: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7505: return '';
7506: }
1.262 matthew 7507: }
1.620 albertel 7508: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7509: # Library role, so allow browsing of resources in this domain.
7510: return 'F';
1.238 www 7511: }
1.341 www 7512: if ($copyright eq 'custom') {
7513: unless (&customaccess($priv,$uri)) { return ''; }
7514: }
1.14 www 7515: }
1.264 matthew 7516: # Domain coordinator is trying to create a course
1.620 albertel 7517: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7518: # uri is the requested domain in this case.
7519: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7520: # a role of dc for the domain in question.
1.620 albertel 7521: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7522: }
1.29 www 7523:
1.52 www 7524: my $thisallowed='';
7525: my $statecond=0;
7526: my $courseprivid='';
7527:
1.1039 raeburn 7528: my $ownaccess;
1.1043 raeburn 7529: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7530: if (($priv eq 'bro') && ($env{'user.author'})) {
7531: if ($uri eq '') {
7532: $ownaccess = 1;
7533: } else {
7534: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7535: my $udom = $env{'user.domain'};
7536: my $uname = $env{'user.name'};
7537: if ($uri =~ m{^\Q$udom\E/?$}) {
7538: $ownaccess = 1;
1.1040 raeburn 7539: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7540: unless ($uri =~ m{\.\./}) {
7541: $ownaccess = 1;
7542: }
7543: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7544: my $now = time;
7545: if ($uri =~ m{^([^/]+)/?$}) {
7546: my $adom = $1;
7547: foreach my $key (keys(%env)) {
1.1042 raeburn 7548: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7549: my ($start,$end) = split('.',$env{$key});
7550: if (($now >= $start) && (!$end || $end < $now)) {
7551: $ownaccess = 1;
7552: last;
7553: }
7554: }
7555: }
7556: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7557: my $adom = $1;
7558: my $aname = $2;
1.1042 raeburn 7559: foreach my $role ('ca','aa') {
7560: if ($env{"user.role.$role./$adom/$aname"}) {
7561: my ($start,$end) =
7562: split('.',$env{"user.role.$role./$adom/$aname"});
7563: if (($now >= $start) && (!$end || $end < $now)) {
7564: $ownaccess = 1;
7565: last;
7566: }
1.1039 raeburn 7567: }
7568: }
7569: }
7570: }
7571: }
7572: }
7573: }
7574:
1.52 www 7575: # Course
7576:
1.620 albertel 7577: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7578: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7579: $thisallowed.=$1;
7580: }
1.52 www 7581: }
1.29 www 7582:
1.52 www 7583: # Domain
7584:
1.620 albertel 7585: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7586: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7587: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7588: $thisallowed.=$1;
7589: }
1.12 www 7590: }
1.52 www 7591:
1.1141 raeburn 7592: # User who is not author or co-author might still be able to edit
7593: # resource of an author in the domain (e.g., if Domain Coordinator).
7594: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7595: (&allowed('mdc',$env{'request.course.id'}))) {
7596: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7597: $thisallowed.=$1;
7598: }
7599: }
7600:
1.52 www 7601: # Course: uri itself is a course
1.66 www 7602: my $courseuri=$uri;
7603: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7604: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7605:
1.620 albertel 7606: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7607: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7608: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7609: $thisallowed.=$1;
7610: }
1.12 www 7611: }
1.29 www 7612:
1.665 albertel 7613: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7614: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7615: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7616: $thisallowed='';
1.671 raeburn 7617: my ($match)=&is_on_map($uri);
7618: if ($match) {
7619: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7620: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 7621: my $value = $1;
7622: if ($noblockcheck) {
7623: $thisallowed.=$value;
1.1162 raeburn 7624: } else {
1.1172.2.65 raeburn 7625: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7626: if (@blockers > 0) {
7627: $thisallowed = 'B';
7628: } else {
7629: $thisallowed.=$value;
7630: }
1.1162 raeburn 7631: }
1.671 raeburn 7632: }
7633: } else {
1.705 albertel 7634: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7635: if ($refuri) {
7636: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7637: $thisallowed='F';
1.671 raeburn 7638: } else {
7639: $refuri=&declutter($refuri);
7640: my ($match) = &is_on_map($refuri);
7641: if ($match) {
1.1172.2.65 raeburn 7642: if ($noblockcheck) {
1.1162 raeburn 7643: $thisallowed='F';
1.1172.2.65 raeburn 7644: } else {
7645: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7646: if (@blockers > 0) {
7647: $thisallowed = 'B';
7648: } else {
7649: $thisallowed='F';
7650: }
1.1162 raeburn 7651: }
1.671 raeburn 7652: }
1.669 raeburn 7653: }
1.671 raeburn 7654: }
7655: }
1.314 www 7656: }
1.492 albertel 7657:
1.766 albertel 7658: if ($priv eq 'bre'
7659: && $thisallowed ne 'F'
7660: && $thisallowed ne '2'
7661: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 7662: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7663: }
7664:
1.52 www 7665: # Full access at system, domain or course-wide level? Exit.
1.29 www 7666: if ($thisallowed=~/F/) {
7667: return 'F';
7668: }
7669:
1.52 www 7670: # If this is generating or modifying users, exit with special codes
1.29 www 7671:
1.643 www 7672: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7673: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7674: my ($audom,$auname)=split('/',$uri);
1.643 www 7675: # no author name given, so this just checks on the general right to make a co-author in this domain
7676: unless ($auname) { return $thisallowed; }
7677: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7678: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7679: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7680: ($audom ne $env{'request.role.domain'}))) { return ''; }
7681: }
1.52 www 7682: return $thisallowed;
7683: }
7684: #
1.103 harris41 7685: # Gathered so far: system, domain and course wide privileges
1.52 www 7686: #
7687: # Course: See if uri or referer is an individual resource that is part of
7688: # the course
7689:
1.620 albertel 7690: if ($env{'request.course.id'}) {
1.232 www 7691:
1.620 albertel 7692: $courseprivid=$env{'request.course.id'};
7693: if ($env{'request.course.sec'}) {
7694: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7695: }
7696: $courseprivid=~s/\_/\//;
7697: my $checkreferer=1;
1.232 www 7698: my ($match,$cond)=&is_on_map($uri);
7699: if ($match) {
7700: $statecond=$cond;
1.620 albertel 7701: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7702: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7703: my $value = $1;
7704: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7705: if ($noblockcheck) {
1.1162 raeburn 7706: $thisallowed.=$value;
1.1172.2.65 raeburn 7707: } else {
7708: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7709: if (@blockers > 0) {
7710: $thisallowed = 'B';
7711: } else {
7712: $thisallowed.=$value;
7713: }
1.1162 raeburn 7714: }
7715: } else {
7716: $thisallowed.=$value;
7717: }
1.52 www 7718: $checkreferer=0;
7719: }
1.29 www 7720: }
1.83 www 7721:
1.148 www 7722: if ($checkreferer) {
1.620 albertel 7723: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7724: unless ($refuri) {
1.800 albertel 7725: foreach my $key (keys(%env)) {
7726: if ($key=~/^httpref\..*\*/) {
7727: my $pattern=$key;
1.156 www 7728: $pattern=~s/^httpref\.\/res\///;
1.148 www 7729: $pattern=~s/\*/\[\^\/\]\+/g;
7730: $pattern=~s/\//\\\//g;
1.152 www 7731: if ($orguri=~/$pattern/) {
1.800 albertel 7732: $refuri=$env{$key};
1.148 www 7733: }
7734: }
1.191 harris41 7735: }
1.148 www 7736: }
1.232 www 7737:
1.148 www 7738: if ($refuri) {
1.152 www 7739: $refuri=&declutter($refuri);
1.232 www 7740: my ($match,$cond)=&is_on_map($refuri);
7741: if ($match) {
7742: my $refstatecond=$cond;
1.620 albertel 7743: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7744: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7745: my $value = $1;
7746: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7747: if ($noblockcheck) {
1.1162 raeburn 7748: $thisallowed.=$value;
1.1172.2.65 raeburn 7749: } else {
7750: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7751: if (@blockers > 0) {
7752: $thisallowed = 'B';
7753: } else {
7754: $thisallowed.=$value;
7755: }
1.1162 raeburn 7756: }
7757: } else {
7758: $thisallowed.=$value;
7759: }
1.53 www 7760: $uri=$refuri;
7761: $statecond=$refstatecond;
1.52 www 7762: }
7763: }
1.148 www 7764: }
1.29 www 7765: }
1.52 www 7766: }
1.29 www 7767:
1.52 www 7768: #
1.103 harris41 7769: # Gathered now: all privileges that could apply, and condition number
1.52 www 7770: #
7771: #
7772: # Full or no access?
7773: #
1.29 www 7774:
1.52 www 7775: if ($thisallowed=~/F/) {
7776: return 'F';
7777: }
1.29 www 7778:
1.52 www 7779: unless ($thisallowed) {
7780: return '';
7781: }
1.29 www 7782:
1.52 www 7783: # Restrictions exist, deal with them
7784: #
7785: # C:according to course preferences
7786: # R:according to resource settings
7787: # L:unless locked
7788: # X:according to user session state
7789: #
7790:
7791: # Possibly locked functionality, check all courses
1.54 www 7792: # Locks might take effect only after 10 minutes cache expiration for other
7793: # courses, and 2 minutes for current course
1.52 www 7794:
7795: my $envkey;
7796: if ($thisallowed=~/L/) {
1.1000 raeburn 7797: foreach $envkey (keys(%env)) {
1.54 www 7798: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7799: my $courseid=$2;
7800: my $roleid=$1.'.'.$2;
1.92 www 7801: $courseid=~s/^\///;
1.54 www 7802: my $expiretime=600;
1.620 albertel 7803: if ($env{'request.role'} eq $roleid) {
1.54 www 7804: $expiretime=120;
7805: }
7806: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7807: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7808: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7809: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7810: }
1.620 albertel 7811: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7812: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7813: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7814: &log($env{'user.domain'},$env{'user.name'},
7815: $env{'user.home'},
1.57 www 7816: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7817: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7818: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7819: return '';
7820: }
7821: }
1.620 albertel 7822: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7823: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7824: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7825: &log($env{'user.domain'},$env{'user.name'},
7826: $env{'user.home'},
1.57 www 7827: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7828: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7829: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7830: return '';
7831: }
7832: }
7833: }
1.29 www 7834: }
1.52 www 7835: }
7836:
7837: #
7838: # Rest of the restrictions depend on selected course
7839: #
7840:
1.620 albertel 7841: unless ($env{'request.course.id'}) {
1.766 albertel 7842: if ($thisallowed eq 'A') {
7843: return 'A';
1.814 raeburn 7844: } elsif ($thisallowed eq 'B') {
7845: return 'B';
1.766 albertel 7846: } else {
7847: return '1';
7848: }
1.52 www 7849: }
1.29 www 7850:
1.52 www 7851: #
7852: # Now user is definitely in a course
7853: #
1.53 www 7854:
7855:
7856: # Course preferences
7857:
7858: if ($thisallowed=~/C/) {
1.620 albertel 7859: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7860: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7861: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7862: =~/\Q$rolecode\E/) {
1.1103 raeburn 7863: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7864: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7865: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7866: $env{'request.course.id'});
7867: }
1.237 www 7868: return '';
7869: }
7870:
1.620 albertel 7871: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7872: =~/\Q$unamedom\E/) {
1.1103 raeburn 7873: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7874: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7875: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7876: $env{'request.course.id'});
7877: }
1.54 www 7878: return '';
7879: }
1.53 www 7880: }
7881:
7882: # Resource preferences
7883:
7884: if ($thisallowed=~/R/) {
1.620 albertel 7885: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7886: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7887: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7888: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7889: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7890: }
7891: return '';
1.54 www 7892: }
1.53 www 7893: }
1.30 www 7894:
1.246 www 7895: # Restricted by state or randomout?
1.30 www 7896:
1.52 www 7897: if ($thisallowed=~/X/) {
1.620 albertel 7898: if ($env{'acc.randomout'}) {
1.579 albertel 7899: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7900: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7901: return '';
7902: }
1.247 www 7903: }
7904: if (&condval($statecond)) {
1.52 www 7905: return '2';
7906: } else {
7907: return '';
7908: }
7909: }
1.30 www 7910:
1.766 albertel 7911: if ($thisallowed eq 'A') {
7912: return 'A';
1.814 raeburn 7913: } elsif ($thisallowed eq 'B') {
7914: return 'B';
1.766 albertel 7915: }
1.52 www 7916: return 'F';
1.232 www 7917: }
1.1162 raeburn 7918:
1.1172.2.13 raeburn 7919: # ------------------------------------------- Check construction space access
7920:
7921: sub constructaccess {
7922: my ($url,$setpriv)=@_;
7923:
7924: # We do not allow editing of previous versions of files
7925: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7926:
7927: # Get username and domain from URL
7928: my ($ownername,$ownerdomain,$ownerhome);
7929:
7930: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 7931: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 7932:
7933: # The URL does not really point to any authorspace, forget it
7934: unless (($ownername) && ($ownerdomain)) { return ''; }
7935:
7936: # Now we need to see if the user has access to the authorspace of
7937: # $ownername at $ownerdomain
7938:
7939: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7940: # Real author for this?
7941: $ownerhome = $env{'user.home'};
7942: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7943: return ($ownername,$ownerdomain,$ownerhome);
7944: }
7945: } else {
7946: # Co-author for this?
7947: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7948: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7949: $ownerhome = &homeserver($ownername,$ownerdomain);
7950: return ($ownername,$ownerdomain,$ownerhome);
7951: }
7952: }
7953:
7954: # We don't have any access right now. If we are not possibly going to do anything about this,
7955: # we might as well leave
7956: unless ($setpriv) { return ''; }
7957:
7958: # Backdoor access?
7959: my $allowed=&allowed('eco',$ownerdomain);
7960: # Nope
7961: unless ($allowed) { return ''; }
7962: # Looks like we may have access, but could be locked by the owner of the construction space
7963: if ($allowed eq 'U') {
7964: my %blocked=&get('environment',['domcoord.author'],
7965: $ownerdomain,$ownername);
7966: # Is blocked by owner
7967: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7968: }
7969: if (($allowed eq 'F') || ($allowed eq 'U')) {
7970: # Grant temporary access
7971: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7972: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7973: if (!$update) { $update = $then; }
7974: my $refresh=$env{'user.refresh.time'};
7975: if (!$refresh) { $refresh = $update; }
7976: my $now = time;
7977: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7978: $now,'ca','constructaccess');
7979: $ownerhome = &homeserver($ownername,$ownerdomain);
7980: return($ownername,$ownerdomain,$ownerhome);
7981: }
7982: # No business here
7983: return '';
7984: }
7985:
1.1172.2.66 raeburn 7986: # ----------------------------------------------------------- Content Blocking
7987:
7988: {
7989: # Caches for faster Course Contents display where content blocking
7990: # is in operation (i.e., interval param set) for timed quiz.
7991: #
7992: # User for whom data are being temporarily cached.
7993: my $cacheduser='';
7994: # Cached blockers for this user (a hash of blocking items).
7995: my %cachedblockers=();
7996: # When the data were last cached.
7997: my $cachedlast='';
7998:
7999: sub load_all_blockers {
8000: my ($uname,$udom,$blocks)=@_;
8001: if (($uname ne '') && ($udom ne '')) {
8002: if (($cacheduser eq $uname.':'.$udom) &&
8003: (abs($cachedlast-time)<5)) {
8004: return;
8005: }
8006: }
8007: $cachedlast=time;
8008: $cacheduser=$uname.':'.$udom;
8009: %cachedblockers = &get_commblock_resources($blocks);
8010: }
8011:
1.1162 raeburn 8012: sub get_comm_blocks {
8013: my ($cdom,$cnum) = @_;
8014: if ($cdom eq '' || $cnum eq '') {
8015: return unless ($env{'request.course.id'});
8016: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8017: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8018: }
8019: my %commblocks;
8020: my $hashid=$cdom.'_'.$cnum;
8021: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8022: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8023: %commblocks = %{$blocksref};
8024: } else {
8025: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8026: my $cachetime = 600;
8027: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8028: }
8029: return %commblocks;
8030: }
8031:
1.1172.2.66 raeburn 8032: sub get_commblock_resources {
8033: my ($blocks) = @_;
8034: my %blockers = ();
8035: return %blockers unless ($env{'request.course.id'});
8036: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8037: my %commblocks;
8038: if (ref($blocks) eq 'HASH') {
8039: %commblocks = %{$blocks};
8040: } else {
8041: %commblocks = &get_comm_blocks();
8042: }
1.1172.2.66 raeburn 8043: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8044: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8045: return %blockers unless (ref($navmap));
8046: my $now = time;
1.1162 raeburn 8047: foreach my $block (keys(%commblocks)) {
8048: if ($block =~ /^(\d+)____(\d+)$/) {
8049: my ($start,$end) = ($1,$2);
8050: if ($start <= $now && $end >= $now) {
8051: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8052: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8053: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8054: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8055: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8056: }
8057: }
8058: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8059: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8060: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8061: }
8062: }
8063: }
8064: }
8065: }
8066: } elsif ($block =~ /^firstaccess____(.+)$/) {
8067: my $item = $1;
1.1163 raeburn 8068: my @to_test;
1.1162 raeburn 8069: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8070: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 8071: my @interval;
8072: my $type = 'map';
8073: if ($item eq 'course') {
8074: $type = 'course';
8075: @interval=&EXT("resource.0.interval");
8076: } else {
8077: if ($item =~ /___\d+___/) {
8078: $type = 'resource';
8079: @interval=&EXT("resource.0.interval",$item);
8080: if (ref($navmap)) {
8081: my $res = $navmap->getBySymb($item);
8082: push(@to_test,$res);
8083: }
1.1162 raeburn 8084: } else {
1.1172.2.66 raeburn 8085: my $mapsymb = &symbread($item,1);
8086: if ($mapsymb) {
8087: if (ref($navmap)) {
8088: my $mapres = $navmap->getBySymb($mapsymb);
8089: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8090: foreach my $res (@to_test) {
8091: my $symb = $res->symb();
8092: next if ($symb eq $mapsymb);
8093: if ($symb ne '') {
8094: @interval=&EXT("resource.0.interval",$symb);
8095: if ($interval[1] eq 'map') {
8096: last;
1.1162 raeburn 8097: }
8098: }
8099: }
8100: }
8101: }
8102: }
1.1172.2.66 raeburn 8103: }
1.1172.2.93.4 1(raebur 8104:7): if ($interval[0] =~ /^(\d+)/) {
8105:7): my $timelimit = $1;
1.1172.2.66 raeburn 8106: my $first_access;
8107: if ($type eq 'resource') {
8108: $first_access=&get_first_access($interval[1],$item);
8109: } elsif ($type eq 'map') {
8110: $first_access=&get_first_access($interval[1],undef,$item);
8111: } else {
8112: $first_access=&get_first_access($interval[1]);
8113: }
8114: if ($first_access) {
1.1172.2.93.4 1(raebur 8115:7): my $timesup = $first_access+$timelimit;
1.1172.2.66 raeburn 8116: if ($timesup > $now) {
8117: my $activeblock;
8118: foreach my $res (@to_test) {
8119: if ($res->answerable()) {
8120: $activeblock = 1;
8121: last;
8122: }
8123: }
8124: if ($activeblock) {
8125: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8126: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8127: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8128: }
8129: }
8130: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8131: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8132: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8133: }
1.1162 raeburn 8134: }
8135: }
8136: }
8137: }
8138: }
8139: }
8140: }
8141: }
8142: }
1.1172.2.66 raeburn 8143: return %blockers;
1.1162 raeburn 8144: }
8145:
1.1172.2.66 raeburn 8146: sub has_comm_blocking {
8147: my ($priv,$symb,$uri,$blocks) = @_;
8148: my @blockers;
8149: return unless ($env{'request.course.id'});
8150: return unless ($priv eq 'bre');
8151: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8152: return if ($env{'request.state'} eq 'construct');
8153: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8154: return unless (keys(%cachedblockers) > 0);
8155: my (%possibles,@symbs);
8156: if (!$symb) {
8157: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 8158: }
1.1172.2.66 raeburn 8159: if ($symb) {
8160: @symbs = ($symb);
8161: } elsif (keys(%possibles)) {
8162: @symbs = keys(%possibles);
8163: }
8164: my $noblock;
8165: foreach my $symb (@symbs) {
8166: last if ($noblock);
8167: my ($map,$resid,$resurl)=&decode_symb($symb);
8168: foreach my $block (keys(%cachedblockers)) {
8169: if ($block =~ /^firstaccess____(.+)$/) {
8170: my $item = $1;
8171: if (($item eq $map) || ($item eq $symb)) {
8172: $noblock = 1;
8173: last;
8174: }
1.1162 raeburn 8175: }
1.1172.2.66 raeburn 8176: if (ref($cachedblockers{$block}) eq 'HASH') {
8177: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8178: if ($cachedblockers{$block}{'resources'}{$symb}) {
8179: unless (grep(/^\Q$block\E$/,@blockers)) {
8180: push(@blockers,$block);
8181: }
8182: }
8183: }
8184: }
8185: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8186: if ($cachedblockers{$block}{'maps'}{$map}) {
8187: unless (grep(/^\Q$block\E$/,@blockers)) {
8188: push(@blockers,$block);
8189: }
8190: }
1.1162 raeburn 8191: }
8192: }
8193: }
1.1172.2.66 raeburn 8194: return if ($noblock);
8195: return @blockers;
8196: }
1.1162 raeburn 8197: }
8198:
1.1172.2.66 raeburn 8199: # -------------------------------- Deversion and split uri into path an filename
8200:
1.1133 foxr 8201: #
1.1172.2.66 raeburn 8202: # Removes the version from a URI and
1.1133 foxr 8203: # splits it in to its filename and path to the filename.
8204: # Seems like File::Basename could have done this more clearly.
8205: # Parameters:
8206: # $uri - input URI
8207: # Returns:
8208: # Two element list consisting of
8209: # $pathname - the URI up to and excluding the trailing /
8210: # $filename - The part of the URI following the last /
8211: # NOTE:
8212: # Another realization of this is simply:
8213: # use File::Basename;
8214: # ...
8215: # $uri = shift;
8216: # $filename = basename($uri);
8217: # $path = dirname($uri);
8218: # return ($filename, $path);
8219: #
8220: # The implementation below is probably faster however.
8221: #
1.710 albertel 8222: sub split_uri_for_cond {
8223: my $uri=&deversion(&declutter(shift));
8224: my @uriparts=split(/\//,$uri);
8225: my $filename=pop(@uriparts);
8226: my $pathname=join('/',@uriparts);
8227: return ($pathname,$filename);
8228: }
1.232 www 8229: # --------------------------------------------------- Is a resource on the map?
8230:
8231: sub is_on_map {
1.710 albertel 8232: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8233: #Trying to find the conditional for the file
1.620 albertel 8234: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8235: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8236: if ($match) {
1.289 bowersj2 8237: return (1,$1);
8238: } else {
1.434 www 8239: return (0,0);
1.289 bowersj2 8240: }
1.12 www 8241: }
8242:
1.427 www 8243: # --------------------------------------------------------- Get symb from alias
8244:
8245: sub get_symb_from_alias {
8246: my $symb=shift;
8247: my ($map,$resid,$url)=&decode_symb($symb);
8248: # Already is a symb
8249: if ($url) { return $symb; }
8250: # Must be an alias
8251: my $aliassymb='';
8252: my %bighash;
1.620 albertel 8253: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8254: &GDBM_READER(),0640)) {
8255: my $rid=$bighash{'mapalias_'.$symb};
8256: if ($rid) {
8257: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8258: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8259: $resid,$bighash{'src_'.$rid});
1.427 www 8260: }
8261: untie %bighash;
8262: }
8263: return $aliassymb;
8264: }
8265:
1.12 www 8266: # ----------------------------------------------------------------- Define Role
8267:
8268: sub definerole {
8269: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8270: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8271: foreach my $role (split(':',$sysrole)) {
8272: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8273: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8274: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8275: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8276: return "refused:s:$crole&$cqual";
8277: }
8278: }
1.191 harris41 8279: }
1.800 albertel 8280: foreach my $role (split(':',$domrole)) {
8281: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8282: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8283: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8284: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8285: return "refused:d:$crole&$cqual";
8286: }
8287: }
1.191 harris41 8288: }
1.800 albertel 8289: foreach my $role (split(':',$courole)) {
8290: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8291: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8292: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8293: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8294: return "refused:c:$crole&$cqual";
8295: }
8296: }
1.191 harris41 8297: }
1.1172.2.84 raeburn 8298: my $uhome;
8299: if (($uname ne '') && ($udom ne '')) {
8300: $uhome = &homeserver($uname,$udom);
8301: return $uhome if ($uhome eq 'no_host');
8302: } else {
8303: $uname = $env{'user.name'};
8304: $udom = $env{'user.domain'};
8305: $uhome = $env{'user.home'};
8306: }
1.620 albertel 8307: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8308: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8309: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8310: return reply($command,$uhome);
1.12 www 8311: } else {
8312: return 'refused';
8313: }
1.105 harris41 8314: }
8315:
8316: # ---------------- Make a metadata query against the network of library servers
8317:
8318: sub metadata_query {
1.1172.2.33 raeburn 8319: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8320: my %rhash;
1.845 albertel 8321: my %libserv = &all_library();
1.244 matthew 8322: my @server_list = (defined($server_array) ? @$server_array
8323: : keys(%libserv) );
8324: for my $server (@server_list) {
1.1172.2.33 raeburn 8325: my $domains = '';
8326: if (ref($domains_hash) eq 'HASH') {
8327: $domains = $domains_hash->{$server};
8328: }
1.118 harris41 8329: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8330: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8331: $rhash{$server}=$reply;
8332: }
8333: else {
8334: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8335: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8336: $server);
8337: $rhash{$server}=$reply;
8338: }
1.112 harris41 8339: }
1.118 harris41 8340: return \%rhash;
1.240 www 8341: }
8342:
8343: # ----------------------------------------- Send log queries and wait for reply
8344:
8345: sub log_query {
8346: my ($uname,$udom,$query,%filters)=@_;
8347: my $uhome=&homeserver($uname,$udom);
8348: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8349: my $uhost=&hostname($uhome);
1.800 albertel 8350: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8351: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8352: $uhome);
1.479 albertel 8353: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8354: return get_query_reply($queryid);
8355: }
8356:
1.818 raeburn 8357: # -------------------------- Update MySQL table for portfolio file
8358:
8359: sub update_portfolio_table {
1.821 raeburn 8360: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8361: if ($group ne '') {
8362: $file_name =~s /^\Q$group\E//;
8363: }
1.818 raeburn 8364: my $homeserver = &homeserver($uname,$udom);
8365: my $queryid=
1.821 raeburn 8366: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8367: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8368: my $reply = &get_query_reply($queryid);
8369: return $reply;
8370: }
8371:
1.899 raeburn 8372: # -------------------------- Update MySQL allusers table
8373:
8374: sub update_allusers_table {
8375: my ($uname,$udom,$names) = @_;
8376: my $homeserver = &homeserver($uname,$udom);
8377: my $queryid=
8378: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8379: 'lastname='.&escape($names->{'lastname'}).'%%'.
8380: 'firstname='.&escape($names->{'firstname'}).'%%'.
8381: 'middlename='.&escape($names->{'middlename'}).'%%'.
8382: 'generation='.&escape($names->{'generation'}).'%%'.
8383: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8384: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8385: return;
1.899 raeburn 8386: }
8387:
1.508 raeburn 8388: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8389:
8390: sub fetch_enrollment_query {
1.511 raeburn 8391: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8392: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8393: my $maxtries = 1;
1.508 raeburn 8394: if ($context eq 'automated') {
8395: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8396: $sleep = 2;
8397: $loopmax = 100;
1.547 raeburn 8398: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8399: } else {
8400: $homeserver = &homeserver($cnum,$dom);
8401: }
1.838 albertel 8402: my $host=&hostname($homeserver);
1.506 raeburn 8403: my $cmd = '';
1.1000 raeburn 8404: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8405: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8406: }
8407: $cmd =~ s/%%$//;
8408: $cmd = &escape($cmd);
8409: my $query = 'fetchenrollment';
1.620 albertel 8410: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8411: unless ($queryid=~/^\Q$host\E\_/) {
8412: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8413: return 'error: '.$queryid;
8414: }
1.1172.2.93 raeburn 8415: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8416: my $tries = 1;
8417: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8418: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8419: $tries ++;
8420: }
1.526 raeburn 8421: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8422: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8423: } else {
1.901 albertel 8424: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8425: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8426: foreach my $line (@responses) {
8427: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8428: $$replyref{$key} = $value;
8429: }
8430: } else {
1.1117 foxr 8431: my $pathname = LONCAPA::tempdir();
1.800 albertel 8432: foreach my $line (@responses) {
8433: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8434: $$replyref{$key} = $value;
8435: if ($value > 0) {
1.800 albertel 8436: foreach my $item (@{$$affiliatesref{$key}}) {
8437: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8438: my $destname = $pathname.'/'.$filename;
8439: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8440: if ($xml_classlist =~ /^error/) {
8441: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8442: } else {
1.1172.2.93.4 7(raebur 8443:7): if ( open(FILE,">",$destname) ) {
1.506 raeburn 8444: print FILE &unescape($xml_classlist);
8445: close(FILE);
1.526 raeburn 8446: } else {
8447: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8448: }
8449: }
8450: }
8451: }
8452: }
8453: }
8454: return 'ok';
8455: }
8456: return 'error';
8457: }
8458:
1.242 www 8459: sub get_query_reply {
1.1172.2.79 raeburn 8460: my ($queryid,$sleep,$loopmax) = @_;
8461: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8462: $sleep = 0.2;
8463: }
8464: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8465: $loopmax = 100;
8466: }
1.1117 foxr 8467: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8468: my $reply='';
1.1172.2.79 raeburn 8469: for (1..$loopmax) {
8470: sleep($sleep);
1.240 www 8471: if (-e $replyfile.'.end') {
1.1172.2.93.4 7(raebur 8472:7): if (open(my $fh,"<",$replyfile)) {
1.904 albertel 8473: $reply = join('',<$fh>);
8474: close($fh);
1.240 www 8475: } else { return 'error: reply_file_error'; }
1.242 www 8476: return &unescape($reply);
8477: }
1.240 www 8478: }
1.242 www 8479: return 'timeout:'.$queryid;
1.240 www 8480: }
8481:
8482: sub courselog_query {
1.241 www 8483: #
8484: # possible filters:
8485: # url: url or symb
8486: # username
8487: # domain
8488: # action: view, submit, grade
8489: # start: timestamp
8490: # end: timestamp
8491: #
1.240 www 8492: my (%filters)=@_;
1.620 albertel 8493: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8494: if ($filters{'url'}) {
8495: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8496: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8497: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8498: }
1.620 albertel 8499: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8500: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8501: return &log_query($cname,$cdom,'courselog',%filters);
8502: }
8503:
8504: sub userlog_query {
1.858 raeburn 8505: #
8506: # possible filters:
8507: # action: log check role
8508: # start: timestamp
8509: # end: timestamp
8510: #
1.240 www 8511: my ($uname,$udom,%filters)=@_;
8512: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8513: }
8514:
1.506 raeburn 8515: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8516:
8517: sub auto_run {
1.508 raeburn 8518: my ($cnum,$cdom) = @_;
1.876 raeburn 8519: my $response = 0;
8520: my $settings;
8521: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8522: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8523: $settings = $domconfig{'autoenroll'};
8524: if ($settings->{'run'} eq '1') {
8525: $response = 1;
8526: }
8527: } else {
1.934 raeburn 8528: my $homeserver;
8529: if (&is_course($cdom,$cnum)) {
8530: $homeserver = &homeserver($cnum,$cdom);
8531: } else {
8532: $homeserver = &domain($cdom,'primary');
8533: }
8534: if ($homeserver ne 'no_host') {
8535: $response = &reply('autorun:'.$cdom,$homeserver);
8536: }
1.876 raeburn 8537: }
1.506 raeburn 8538: return $response;
8539: }
1.776 albertel 8540:
1.506 raeburn 8541: sub auto_get_sections {
1.508 raeburn 8542: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8543: my $homeserver;
8544: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8545: $homeserver = &homeserver($cnum,$cdom);
8546: }
8547: if (!defined($homeserver)) {
8548: if ($cdom =~ /^$match_domain$/) {
8549: $homeserver = &domain($cdom,'primary');
8550: }
8551: }
8552: my @secs;
8553: if (defined($homeserver)) {
8554: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8555: unless ($response eq 'refused') {
8556: @secs = split(/:/,$response);
8557: }
1.506 raeburn 8558: }
8559: return @secs;
8560: }
1.776 albertel 8561:
1.506 raeburn 8562: sub auto_new_course {
1.1099 raeburn 8563: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8564: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8565: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8566: return $response;
8567: }
1.776 albertel 8568:
1.506 raeburn 8569: sub auto_validate_courseID {
1.508 raeburn 8570: my ($cnum,$cdom,$inst_course_id) = @_;
8571: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8572: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8573: return $response;
8574: }
1.776 albertel 8575:
1.1007 raeburn 8576: sub auto_validate_instcode {
1.1020 raeburn 8577: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8578: my ($homeserver,$response);
8579: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8580: $homeserver = &homeserver($cnum,$cdom);
8581: }
8582: if (!defined($homeserver)) {
8583: if ($cdom =~ /^$match_domain$/) {
8584: $homeserver = &domain($cdom,'primary');
8585: }
8586: }
1.1065 raeburn 8587: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8588: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 8589: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8590: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8591: }
8592:
1.506 raeburn 8593: sub auto_create_password {
1.873 raeburn 8594: my ($cnum,$cdom,$authparam,$udom) = @_;
8595: my ($homeserver,$response);
1.506 raeburn 8596: my $create_passwd = 0;
8597: my $authchk = '';
1.873 raeburn 8598: if ($udom =~ /^$match_domain$/) {
8599: $homeserver = &domain($udom,'primary');
8600: }
8601: if ($homeserver eq '') {
8602: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8603: $homeserver = &homeserver($cnum,$cdom);
8604: }
8605: }
8606: if ($homeserver eq '') {
8607: $authchk = 'nodomain';
1.506 raeburn 8608: } else {
1.873 raeburn 8609: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8610: if ($response eq 'refused') {
8611: $authchk = 'refused';
8612: } else {
1.901 albertel 8613: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8614: }
1.506 raeburn 8615: }
8616: return ($authparam,$create_passwd,$authchk);
8617: }
8618:
1.706 raeburn 8619: sub auto_photo_permission {
8620: my ($cnum,$cdom,$students) = @_;
8621: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8622: my ($outcome,$perm_reqd,$conditions) =
8623: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8624: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8625: return (undef,undef);
8626: }
1.706 raeburn 8627: return ($outcome,$perm_reqd,$conditions);
8628: }
8629:
8630: sub auto_checkphotos {
8631: my ($uname,$udom,$pid) = @_;
8632: my $homeserver = &homeserver($uname,$udom);
8633: my ($result,$resulttype);
8634: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8635: &escape($uname).':'.&escape($pid),
8636: $homeserver));
1.709 albertel 8637: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8638: return (undef,undef);
8639: }
1.706 raeburn 8640: if ($outcome) {
8641: ($result,$resulttype) = split(/:/,$outcome);
8642: }
8643: return ($result,$resulttype);
8644: }
8645:
8646: sub auto_photochoice {
8647: my ($cnum,$cdom) = @_;
8648: my $homeserver = &homeserver($cnum,$cdom);
8649: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8650: &escape($cdom),
8651: $homeserver)));
1.709 albertel 8652: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8653: return (undef,undef);
8654: }
1.706 raeburn 8655: return ($update,$comment);
8656: }
8657:
8658: sub auto_photoupdate {
8659: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8660: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8661: my $host=&hostname($homeserver);
1.706 raeburn 8662: my $cmd = '';
8663: my $maxtries = 1;
1.800 albertel 8664: foreach my $affiliate (keys(%{$affiliatesref})) {
8665: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8666: }
8667: $cmd =~ s/%%$//;
8668: $cmd = &escape($cmd);
8669: my $query = 'institutionalphotos';
8670: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8671: unless ($queryid=~/^\Q$host\E\_/) {
8672: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8673: return 'error: '.$queryid;
8674: }
8675: my $reply = &get_query_reply($queryid);
8676: my $tries = 1;
8677: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8678: $reply = &get_query_reply($queryid);
8679: $tries ++;
8680: }
8681: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8682: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8683: } else {
8684: my @responses = split(/:/,$reply);
8685: my $outcome = shift(@responses);
8686: foreach my $item (@responses) {
8687: my ($key,$value) = split(/=/,$item);
8688: $$photo{$key} = $value;
8689: }
8690: return $outcome;
8691: }
8692: return 'error';
8693: }
8694:
1.521 raeburn 8695: sub auto_instcode_format {
1.793 albertel 8696: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8697: $cat_order) = @_;
1.521 raeburn 8698: my $courses = '';
1.772 raeburn 8699: my @homeservers;
1.521 raeburn 8700: if ($caller eq 'global') {
1.841 albertel 8701: my %servers = &get_servers($codedom,'library');
8702: foreach my $tryserver (keys(%servers)) {
8703: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8704: push(@homeservers,$tryserver);
8705: }
1.584 raeburn 8706: }
1.1022 raeburn 8707: } elsif ($caller eq 'requests') {
8708: if ($codedom =~ /^$match_domain$/) {
8709: my $chome = &domain($codedom,'primary');
8710: unless ($chome eq 'no_host') {
8711: push(@homeservers,$chome);
8712: }
8713: }
1.521 raeburn 8714: } else {
1.772 raeburn 8715: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8716: }
1.793 albertel 8717: foreach my $code (keys(%{$instcodes})) {
8718: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8719: }
8720: chop($courses);
1.772 raeburn 8721: my $ok_response = 0;
8722: my $response;
8723: while (@homeservers > 0 && $ok_response == 0) {
8724: my $server = shift(@homeservers);
8725: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8726: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8727: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8728: split(/:/,$response);
1.772 raeburn 8729: %{$codes} = (%{$codes},&str2hash($codes_str));
8730: push(@{$codetitles},&str2array($codetitles_str));
8731: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8732: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8733: $ok_response = 1;
8734: }
8735: }
8736: if ($ok_response) {
1.521 raeburn 8737: return 'ok';
1.772 raeburn 8738: } else {
8739: return $response;
1.521 raeburn 8740: }
8741: }
8742:
1.792 raeburn 8743: sub auto_instcode_defaults {
8744: my ($domain,$returnhash,$code_order) = @_;
8745: my @homeservers;
1.841 albertel 8746:
8747: my %servers = &get_servers($domain,'library');
8748: foreach my $tryserver (keys(%servers)) {
8749: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8750: push(@homeservers,$tryserver);
8751: }
1.792 raeburn 8752: }
1.841 albertel 8753:
1.792 raeburn 8754: my $response;
1.841 albertel 8755: foreach my $server (@homeservers) {
1.792 raeburn 8756: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8757: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8758:
8759: foreach my $pair (split(/\&/,$response)) {
8760: my ($name,$value)=split(/\=/,$pair);
8761: if ($name eq 'code_order') {
8762: @{$code_order} = split(/\&/,&unescape($value));
8763: } else {
8764: $returnhash->{&unescape($name)}=&unescape($value);
8765: }
8766: }
8767: return 'ok';
1.792 raeburn 8768: }
1.841 albertel 8769:
8770: return $response;
1.1003 raeburn 8771: }
8772:
8773: sub auto_possible_instcodes {
1.1007 raeburn 8774: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8775: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8776: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8777: return;
8778: }
1.1003 raeburn 8779: my (@homeservers,$uhome);
8780: if (defined(&domain($domain,'primary'))) {
8781: $uhome=&domain($domain,'primary');
8782: push(@homeservers,&domain($domain,'primary'));
8783: } else {
8784: my %servers = &get_servers($domain,'library');
8785: foreach my $tryserver (keys(%servers)) {
8786: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8787: push(@homeservers,$tryserver);
8788: }
8789: }
8790: }
8791: my $response;
8792: foreach my $server (@homeservers) {
8793: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8794: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8795: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8796: split(':',$response);
8797: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8798: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8799: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8800: my ($name,$value)=split('=',$item);
8801: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8802: }
8803: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8804: my ($name,$value)=split('=',$item);
8805: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8806: }
8807: return 'ok';
8808: }
8809: return $response;
8810: }
1.792 raeburn 8811:
1.1010 raeburn 8812: sub auto_courserequest_checks {
8813: my ($dom) = @_;
1.1020 raeburn 8814: my ($homeserver,%validations);
8815: if ($dom =~ /^$match_domain$/) {
8816: $homeserver = &domain($dom,'primary');
8817: }
8818: unless ($homeserver eq 'no_host') {
8819: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8820: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8821: my @items = split(/&/,$response);
8822: foreach my $item (@items) {
8823: my ($key,$value) = split('=',$item);
8824: $validations{&unescape($key)} = &thaw_unescape($value);
8825: }
8826: }
8827: }
1.1010 raeburn 8828: return %validations;
8829: }
8830:
1.1020 raeburn 8831: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8832: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8833: my ($homeserver,$response);
8834: if ($dom =~ /^$match_domain$/) {
8835: $homeserver = &domain($dom,'primary');
8836: }
1.1172.2.43 raeburn 8837: unless ($homeserver eq 'no_host') {
8838: my $customdata;
8839: if (ref($custominfo) eq 'HASH') {
8840: $customdata = &freeze_escape($custominfo);
8841: }
1.1020 raeburn 8842: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8843: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8844: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8845: $customdata,$homeserver));
1.1020 raeburn 8846: }
8847: return $response;
8848: }
8849:
1.777 albertel 8850: sub auto_validate_class_sec {
1.918 raeburn 8851: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8852: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8853: my $ownerlist;
8854: if (ref($owners) eq 'ARRAY') {
8855: $ownerlist = join(',',@{$owners});
8856: } else {
8857: $ownerlist = $owners;
8858: }
1.773 raeburn 8859: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8860: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8861: return $response;
8862: }
8863:
1.1172.2.93.4 10(raebu 8864:18): sub auto_validate_instclasses {
8865:18): my ($cdom,$cnum,$owners,$classesref) = @_;
8866:18): my ($homeserver,%validations);
8867:18): $homeserver = &homeserver($cnum,$cdom);
8868:18): unless ($homeserver eq 'no_host') {
8869:18): my $ownerlist;
8870:18): if (ref($owners) eq 'ARRAY') {
8871:18): $ownerlist = join(',',@{$owners});
8872:18): } else {
8873:18): $ownerlist = $owners;
8874:18): }
8875:18): if (ref($classesref) eq 'HASH') {
8876:18): my $classes = &freeze_escape($classesref);
8877:18): my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
8878:18): ':'.$cdom.':'.$classes,$homeserver);
8879:18): unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8880:18): my @items = split(/&/,$response);
8881:18): foreach my $item (@items) {
8882:18): my ($key,$value) = split('=',$item);
8883:18): $validations{&unescape($key)} = &thaw_unescape($value);
8884:18): }
8885:18): }
8886:18): }
8887:18): }
8888:18): return %validations;
8889:18): }
8890:18):
1.1172.2.38 raeburn 8891: sub auto_crsreq_update {
8892: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8893: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8894: my ($homeserver,%crsreqresponse);
8895: if ($cdom =~ /^$match_domain$/) {
8896: $homeserver = &domain($cdom,'primary');
8897: }
8898: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8899: my $info;
8900: if (ref($inbound) eq 'HASH') {
8901: $info = &freeze_escape($inbound);
8902: }
8903: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8904: ':'.&escape($action).':'.&escape($ownername).':'.
8905: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8906: &escape($title).':'.&escape($code).':'.
8907: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8908: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8909: my @items = split(/&/,$response);
8910: foreach my $item (@items) {
8911: my ($key,$value) = split('=',$item);
8912: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8913: }
8914: }
8915: }
8916: return \%crsreqresponse;
8917: }
8918:
1.1172.2.78 raeburn 8919: sub auto_export_grades {
8920: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8921: my ($homeserver,%exportresponse);
8922: if ($cdom =~ /^$match_domain$/) {
8923: $homeserver = &domain($cdom,'primary');
8924: }
8925: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8926: my $info;
8927: if (ref($inforef) eq 'HASH') {
8928: $info = &freeze_escape($inforef);
8929: }
8930: if (ref($gradesref) eq 'HASH') {
8931: my $grades = &freeze_escape($gradesref);
8932: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8933: $info.':'.$grades,$homeserver);
8934: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8935: my @items = split(/&/,$response);
8936: foreach my $item (@items) {
8937: my ($key,$value) = split('=',$item);
8938: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8939: }
8940: }
8941: }
8942: }
8943: return \%exportresponse;
8944: }
8945:
1.1172.2.68 raeburn 8946: sub check_instcode_cloning {
8947: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8948: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8949: return;
8950: }
8951: my $canclone;
8952: if (@{$code_order} > 0) {
8953: my $instcoderegexp ='^';
8954: my @clonecodes = split(/\&/,$cloner);
8955: foreach my $item (@{$code_order}) {
8956: if (grep(/^\Q$item\E=/,@clonecodes)) {
8957: foreach my $pair (@clonecodes) {
8958: my ($key,$val) = split(/\=/,$pair,2);
8959: $val = &unescape($val);
8960: if ($key eq $item) {
8961: $instcoderegexp .= '('.$val.')';
8962: last;
8963: }
8964: }
8965: } else {
8966: $instcoderegexp .= $codedefaults->{$item};
8967: }
8968: }
8969: $instcoderegexp .= '$';
8970: my (@from,@to);
8971: eval {
8972: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8973: (@to) = ($clonetocode =~ /$instcoderegexp/);
8974: };
8975: if ((@from > 0) && (@to > 0)) {
8976: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8977: if (!@diffs) {
8978: $canclone = 1;
8979: }
8980: }
8981: }
8982: return $canclone;
8983: }
8984:
8985: sub default_instcode_cloning {
8986: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8987: my (%codedefaults,@code_order,$canclone);
8988: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8989: %codedefaults = %{$codedefaultsref};
8990: @code_order = @{$codeorderref};
8991: } elsif ($clonedom) {
8992: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8993: }
8994: if (($domdefclone) && (@code_order)) {
8995: my @clonecodes = split(/\+/,$domdefclone);
8996: my $instcoderegexp ='^';
8997: foreach my $item (@code_order) {
8998: if (grep(/^\Q$item\E$/,@clonecodes)) {
8999: $instcoderegexp .= '('.$codedefaults{$item}.')';
9000: } else {
9001: $instcoderegexp .= $codedefaults{$item};
9002: }
9003: }
9004: $instcoderegexp .= '$';
9005: my (@from,@to);
9006: eval {
9007: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9008: (@to) = ($clonetocode =~ /$instcoderegexp/);
9009: };
9010: if ((@from > 0) && (@to > 0)) {
9011: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9012: if (!@diffs) {
9013: $canclone = 1;
9014: }
9015: }
9016: }
9017: return $canclone;
9018: }
9019:
1.679 raeburn 9020: # ------------------------------------------------------- Course Group routines
9021:
9022: sub get_coursegroups {
1.809 raeburn 9023: my ($cdom,$cnum,$group,$namespace) = @_;
9024: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9025: }
9026:
1.679 raeburn 9027: sub modify_coursegroup {
9028: my ($cdom,$cnum,$groupsettings) = @_;
9029: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9030: }
9031:
1.809 raeburn 9032: sub toggle_coursegroup_status {
9033: my ($cdom,$cnum,$group,$action) = @_;
9034: my ($from_namespace,$to_namespace);
9035: if ($action eq 'delete') {
9036: $from_namespace = 'coursegroups';
9037: $to_namespace = 'deleted_groups';
9038: } else {
9039: $from_namespace = 'deleted_groups';
9040: $to_namespace = 'coursegroups';
9041: }
9042: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9043: if (my $tmp = &error(%curr_group)) {
9044: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9045: return ('read error',$tmp);
9046: } else {
9047: my %savedsettings = %curr_group;
1.809 raeburn 9048: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9049: my $deloutcome;
9050: if ($result eq 'ok') {
1.809 raeburn 9051: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9052: } else {
9053: return ('write error',$result);
9054: }
9055: if ($deloutcome eq 'ok') {
9056: return 'ok';
9057: } else {
9058: return ('delete error',$deloutcome);
9059: }
9060: }
9061: }
9062:
1.679 raeburn 9063: sub modify_group_roles {
1.957 raeburn 9064: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9065: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9066: my $role = 'gr/'.&escape($userprivs);
9067: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9068: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9069: if ($result eq 'ok') {
9070: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9071: }
1.679 raeburn 9072: return $result;
9073: }
9074:
9075: sub modify_coursegroup_membership {
9076: my ($cdom,$cnum,$membership) = @_;
9077: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9078: return $result;
9079: }
9080:
1.682 raeburn 9081: sub get_active_groups {
9082: my ($udom,$uname,$cdom,$cnum) = @_;
9083: my $now = time;
9084: my %groups = ();
9085: foreach my $key (keys(%env)) {
1.811 albertel 9086: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9087: my ($start,$end) = split(/\./,$env{$key});
9088: if (($end!=0) && ($end<$now)) { next; }
9089: if (($start!=0) && ($start>$now)) { next; }
9090: if ($1 eq $cdom && $2 eq $cnum) {
9091: $groups{$3} = $env{$key} ;
9092: }
9093: }
9094: }
9095: return %groups;
9096: }
9097:
1.683 raeburn 9098: sub get_group_membership {
9099: my ($cdom,$cnum,$group) = @_;
9100: return(&dump('groupmembership',$cdom,$cnum,$group));
9101: }
9102:
9103: sub get_users_groups {
9104: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9105: my @usersgroups;
1.683 raeburn 9106: my $cachetime=1800;
9107:
9108: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9109: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9110: if (defined($cached)) {
1.734 albertel 9111: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9112: } else {
9113: $grouplist = '';
1.816 raeburn 9114: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9115: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9116: my $access_end = $env{'course.'.$courseid.
9117: '.default_enrollment_end_date'};
9118: my $now = time;
9119: foreach my $key (keys(%roleshash)) {
9120: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9121: my $group = $1;
9122: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9123: my $start = $2;
9124: my $end = $1;
9125: if ($start == -1) { next; } # deleted from group
9126: if (($start!=0) && ($start>$now)) { next; }
9127: if (($end!=0) && ($end<$now)) {
9128: if ($access_end && $access_end < $now) {
9129: if ($access_end - $end < 86400) {
9130: push(@usersgroups,$group);
1.733 raeburn 9131: }
9132: }
1.817 raeburn 9133: next;
1.733 raeburn 9134: }
1.817 raeburn 9135: push(@usersgroups,$group);
1.683 raeburn 9136: }
9137: }
9138: }
1.817 raeburn 9139: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9140: $grouplist = join(':',@usersgroups);
9141: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9142: }
1.733 raeburn 9143: return @usersgroups;
1.683 raeburn 9144: }
9145:
9146: sub devalidate_getgroups_cache {
9147: my ($udom,$uname,$cdom,$cnum)=@_;
9148: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9149:
1.683 raeburn 9150: my $hashid="$udom:$uname:$courseid";
9151: &devalidate_cache_new('getgroups',$hashid);
9152: }
9153:
1.12 www 9154: # ------------------------------------------------------------------ Plain Text
9155:
9156: sub plaintext {
1.988 raeburn 9157: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9158: if ($short =~ m{^cr/}) {
1.758 albertel 9159: return (split('/',$short))[-1];
9160: }
1.742 raeburn 9161: if (!defined($cid)) {
9162: $cid = $env{'request.course.id'};
9163: }
9164: my %rolenames = (
1.1008 raeburn 9165: Course => 'std',
9166: Community => 'alt1',
1.742 raeburn 9167: );
1.1037 raeburn 9168: if ($cid ne '') {
9169: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9170: unless ($forcedefault) {
9171: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9172: &Apache::lonlocal::mt_escape(\$roletext);
9173: return &Apache::lonlocal::mt($roletext);
9174: }
9175: }
9176: }
9177: if ((defined($type)) && (defined($rolenames{$type})) &&
9178: (defined($rolenames{$type})) &&
9179: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9180: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9181: } elsif ($cid ne '') {
9182: my $crstype = $env{'course.'.$cid.'.type'};
9183: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9184: (defined($prp{$short}{$rolenames{$crstype}}))) {
9185: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9186: }
1.742 raeburn 9187: }
1.1037 raeburn 9188: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9189: }
9190:
9191: # ----------------------------------------------------------------- Assign Role
9192:
9193: sub assignrole {
1.957 raeburn 9194: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9195: $context)=@_;
1.21 www 9196: my $mrole;
9197: if ($role =~ /^cr\//) {
1.393 www 9198: my $cwosec=$url;
1.811 albertel 9199: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9200: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9201: my $refused = 1;
9202: if ($context eq 'requestcourses') {
9203: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9204: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9205: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9206: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9207: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9208: if ($crsenv{'internal.courseowner'} eq
9209: $env{'user.name'}.':'.$env{'user.domain'}) {
9210: $refused = '';
9211: }
9212: }
9213: }
9214: }
9215: }
9216: if ($refused) {
9217: &logthis('Refused custom assignrole: '.
9218: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9219: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9220: return 'refused';
9221: }
1.104 www 9222: }
1.21 www 9223: $mrole='cr';
1.678 raeburn 9224: } elsif ($role =~ /^gr\//) {
9225: my $cwogrp=$url;
1.811 albertel 9226: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9227: unless (&allowed('mdg',$cwogrp)) {
9228: &logthis('Refused group assignrole: '.
9229: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9230: $env{'user.name'}.' at '.$env{'user.domain'});
9231: return 'refused';
9232: }
9233: $mrole='gr';
1.21 www 9234: } else {
1.82 www 9235: my $cwosec=$url;
1.811 albertel 9236: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9237: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9238: my $refused;
9239: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9240: if (!(&allowed('c'.$role,$url))) {
9241: $refused = 1;
9242: }
9243: } else {
9244: $refused = 1;
9245: }
1.947 raeburn 9246: if ($refused) {
1.1045 raeburn 9247: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9248: if (!$selfenroll && $context eq 'course') {
9249: my %crsenv;
9250: if ($role eq 'cc' || $role eq 'co') {
9251: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9252: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9253: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9254: if ($crsenv{'internal.courseowner'} eq
9255: $env{'user.name'}.':'.$env{'user.domain'}) {
9256: $refused = '';
9257: }
9258: }
9259: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9260: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9261: if ($crsenv{'internal.courseowner'} eq
9262: $env{'user.name'}.':'.$env{'user.domain'}) {
9263: $refused = '';
9264: }
9265: }
9266: }
9267: }
9268: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9269: $refused = '';
1.1017 raeburn 9270: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9271: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9272: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9273: my $wrongcc;
9274: if ($cnum =~ /^$match_community$/) {
9275: $wrongcc = 1 if ($role eq 'cc');
9276: } else {
9277: $wrongcc = 1 if ($role eq 'co');
9278: }
9279: unless ($wrongcc) {
9280: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9281: if ($crsenv{'internal.courseowner'} eq
9282: $env{'user.name'}.':'.$env{'user.domain'}) {
9283: $refused = '';
9284: }
1.1017 raeburn 9285: }
9286: }
1.1172.2.9 raeburn 9287: } elsif ($context eq 'requestauthor') {
9288: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9289: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9290: if ($env{'environment.requestauthor'} eq 'automatic') {
9291: $refused = '';
9292: } else {
9293: my %domdefaults = &get_domain_defaults($udom);
9294: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9295: my $checkbystatus;
9296: if ($env{'user.adv'}) {
9297: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9298: if ($disposition eq 'automatic') {
9299: $refused = '';
9300: } elsif ($disposition eq '') {
9301: $checkbystatus = 1;
9302: }
9303: } else {
9304: $checkbystatus = 1;
9305: }
9306: if ($checkbystatus) {
9307: if ($env{'environment.inststatus'}) {
9308: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9309: foreach my $type (@inststatuses) {
9310: if (($type ne '') &&
9311: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9312: $refused = '';
9313: }
9314: }
9315: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9316: $refused = '';
9317: }
9318: }
9319: }
9320: }
9321: }
1.1017 raeburn 9322: }
9323: if ($refused) {
1.947 raeburn 9324: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9325: ' '.$role.' '.$end.' '.$start.' by '.
9326: $env{'user.name'}.' at '.$env{'user.domain'});
9327: return 'refused';
9328: }
1.932 raeburn 9329: }
1.1131 raeburn 9330: } elsif ($role eq 'au') {
9331: if ($url ne '/'.$udom.'/') {
9332: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9333: ' to assign author role for '.$uname.':'.$udom.
9334: ' in domain: '.$url.' refused (wrong domain).');
9335: return 'refused';
9336: }
1.104 www 9337: }
1.21 www 9338: $mrole=$role;
9339: }
1.620 albertel 9340: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9341: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9342: if ($end) { $command.='_'.$end; }
1.21 www 9343: if ($start) {
9344: if ($end) {
1.81 www 9345: $command.='_'.$start;
1.21 www 9346: } else {
1.81 www 9347: $command.='_0_'.$start;
1.21 www 9348: }
9349: }
1.739 raeburn 9350: my $origstart = $start;
9351: my $origend = $end;
1.957 raeburn 9352: my $delflag;
1.357 www 9353: # actually delete
9354: if ($deleteflag) {
1.373 www 9355: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9356: # modify command to delete the role
1.620 albertel 9357: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9358: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9359: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9360: # set start and finish to negative values for userrolelog
9361: $start=-1;
9362: $end=-1;
1.957 raeburn 9363: $delflag = 1;
1.357 www 9364: }
9365: }
9366: # send command
1.349 www 9367: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9368: # log new user role if status is ok
1.349 www 9369: if ($answer eq 'ok') {
1.663 raeburn 9370: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9371: if (($role eq 'cc') || ($role eq 'in') ||
9372: ($role eq 'ep') || ($role eq 'ad') ||
9373: ($role eq 'ta') || ($role eq 'st') ||
9374: ($role=~/^cr/) || ($role eq 'gr') ||
9375: ($role eq 'co')) {
1.1172.2.13 raeburn 9376: # for course roles, perform group memberships changes triggered by role change.
9377: unless ($role =~ /^gr/) {
9378: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9379: $origstart,$selfenroll,$context);
9380: }
1.1172.2.9 raeburn 9381: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9382: $selfenroll,$context);
9383: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9384: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9385: ($role eq 'da')) {
1.1172.2.9 raeburn 9386: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9387: $context);
9388: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9389: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9390: $context);
9391: }
1.1053 raeburn 9392: if ($role eq 'cc') {
9393: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9394: }
1.349 www 9395: }
9396: return $answer;
1.169 harris41 9397: }
9398:
1.1053 raeburn 9399: sub autoupdate_coowners {
9400: my ($url,$end,$start,$uname,$udom) = @_;
9401: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9402: if (($cdom ne '') && ($cnum ne '')) {
9403: my $now = time;
9404: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9405: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9406: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9407: my $instcode = $coursehash{'internal.coursecode'};
9408: if ($instcode ne '') {
1.1056 raeburn 9409: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9410: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9411: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9412: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9413: if ($result eq 'valid') {
9414: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9415: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9416: push(@newcoowners,$coowner);
9417: }
9418: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9419: push(@newcoowners,$uname.':'.$udom);
9420: }
9421: @newcoowners = sort(@newcoowners);
9422: } else {
9423: push(@newcoowners,$uname.':'.$udom);
9424: }
9425: } else {
9426: if ($coursehash{'internal.co-owners'}) {
9427: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9428: unless ($coowner eq $uname.':'.$udom) {
9429: push(@newcoowners,$coowner);
9430: }
9431: }
9432: unless (@newcoowners > 0) {
9433: $delcoowners = 1;
9434: $coowners = '';
9435: }
9436: }
9437: }
9438: if (@newcoowners || $delcoowners) {
9439: &store_coowners($cdom,$cnum,$coursehash{'home'},
9440: $delcoowners,@newcoowners);
9441: }
9442: }
9443: }
9444: }
9445: }
9446: }
9447: }
9448:
9449: sub store_coowners {
9450: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9451: my $cid = $cdom.'_'.$cnum;
9452: my ($coowners,$delresult,$putresult);
9453: if (@newcoowners) {
9454: $coowners = join(',',@newcoowners);
9455: my %coownershash = (
9456: 'internal.co-owners' => $coowners,
9457: );
9458: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9459: if ($putresult eq 'ok') {
9460: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9461: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9462: }
9463: }
9464: }
9465: if ($delcoowners) {
9466: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9467: if ($delresult eq 'ok') {
9468: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9469: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9470: }
9471: }
9472: }
9473: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9474: my %crsinfo =
9475: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9476: if (ref($crsinfo{$cid}) eq 'HASH') {
9477: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9478: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9479: }
9480: }
9481: }
9482:
1.169 harris41 9483: # -------------------------------------------------- Modify user authentication
1.197 www 9484: # Overrides without validation
9485:
1.169 harris41 9486: sub modifyuserauth {
9487: my ($udom,$uname,$umode,$upass)=@_;
9488: my $uhome=&homeserver($uname,$udom);
1.197 www 9489: unless (&allowed('mau',$udom)) { return 'refused'; }
9490: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9491: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9492: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9493: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9494: &escape($upass),$uhome);
1.620 albertel 9495: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9496: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9497: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9498: &log($udom,,$uname,$uhome,
1.620 albertel 9499: 'Authentication changed by '.$env{'user.domain'}.', '.
9500: $env{'user.name'}.', '.$umode.
1.197 www 9501: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9502: unless ($reply eq 'ok') {
1.197 www 9503: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9504: return 'error: '.$reply;
9505: }
1.170 harris41 9506: return 'ok';
1.80 www 9507: }
9508:
1.81 www 9509: # --------------------------------------------------------------- Modify a user
1.80 www 9510:
1.81 www 9511: sub modifyuser {
1.206 matthew 9512: my ($udom, $uname, $uid,
9513: $umode, $upass, $first,
9514: $middle, $last, $gene,
1.1058 raeburn 9515: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9516: $udom= &LONCAPA::clean_domain($udom);
9517: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9518: my $showcandelete = 'none';
9519: if (ref($candelete) eq 'ARRAY') {
9520: if (@{$candelete} > 0) {
9521: $showcandelete = join(', ',@{$candelete});
9522: }
9523: }
1.81 www 9524: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9525: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9526: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9527: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9528: ' desiredhome not specified').
1.620 albertel 9529: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9530: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9531: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9532: my $newuser;
9533: if ($uhome eq 'no_host') {
9534: $newuser = 1;
9535: }
1.80 www 9536: # ----------------------------------------------------------------- Create User
1.406 albertel 9537: if (($uhome eq 'no_host') &&
9538: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9539: my $unhome='';
1.844 albertel 9540: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9541: $unhome = $desiredhome;
1.620 albertel 9542: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9543: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9544: } else { # load balancing routine for determining $unhome
1.81 www 9545: my $loadm=10000000;
1.841 albertel 9546: my %servers = &get_servers($udom,'library');
9547: foreach my $tryserver (keys(%servers)) {
9548: my $answer=reply('load',$tryserver);
9549: if (($answer=~/\d+/) && ($answer<$loadm)) {
9550: $loadm=$answer;
9551: $unhome=$tryserver;
9552: }
1.80 www 9553: }
9554: }
9555: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9556: return 'error: unable to find a home server for '.$uname.
9557: ' in domain '.$udom;
1.80 www 9558: }
9559: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9560: &escape($upass),$unhome);
9561: unless ($reply eq 'ok') {
9562: return 'error: '.$reply;
9563: }
1.230 stredwic 9564: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9565: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9566: return 'error: unable verify users home machine.';
1.80 www 9567: }
1.209 matthew 9568: } # End of creation of new user
1.80 www 9569: # ---------------------------------------------------------------------- Add ID
9570: if ($uid) {
9571: $uid=~tr/A-Z/a-z/;
9572: my %uidhash=&idrget($udom,$uname);
1.196 www 9573: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9574: && (!$forceid)) {
1.80 www 9575: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9576: return 'error: user id "'.$uid.'" does not match '.
9577: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9578: }
9579: } else {
9580: &idput($udom,($uname => $uid));
9581: }
9582: }
9583: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9584: my @tmp=&get('environment',
1.899 raeburn 9585: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9586: 'permanentemail','inststatus'],
1.134 albertel 9587: $udom,$uname);
1.1075 raeburn 9588: my (%names,%oldnames);
1.313 matthew 9589: if ($tmp[0] =~ m/^error:.*/) {
9590: %names=();
9591: } else {
9592: %names = @tmp;
1.1075 raeburn 9593: %oldnames = %names;
1.313 matthew 9594: }
1.388 www 9595: #
1.1058 raeburn 9596: # If name, email and/or uid are blank (e.g., because an uploaded file
9597: # of users did not contain them), do not overwrite existing values
9598: # unless field is in $candelete array ref.
9599: #
9600:
9601: my @fields = ('firstname','middlename','lastname','generation',
9602: 'permanentemail','id');
9603: my %newvalues;
9604: if (ref($candelete) eq 'ARRAY') {
9605: foreach my $field (@fields) {
9606: if (grep(/^\Q$field\E$/,@{$candelete})) {
9607: if ($field eq 'firstname') {
9608: $names{$field} = $first;
9609: } elsif ($field eq 'middlename') {
9610: $names{$field} = $middle;
9611: } elsif ($field eq 'lastname') {
9612: $names{$field} = $last;
9613: } elsif ($field eq 'generation') {
9614: $names{$field} = $gene;
9615: } elsif ($field eq 'permanentemail') {
9616: $names{$field} = $email;
9617: } elsif ($field eq 'id') {
9618: $names{$field} = $uid;
9619: }
9620: }
9621: }
9622: }
1.388 www 9623: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9624: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9625: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9626: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9627: if ($email) {
9628: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9629: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9630: }
1.899 raeburn 9631: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9632: if (defined($inststatus)) {
9633: $names{'inststatus'} = '';
9634: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9635: if (ref($usertypes) eq 'HASH') {
9636: my @okstatuses;
9637: foreach my $item (split(/:/,$inststatus)) {
9638: if (defined($usertypes->{$item})) {
9639: push(@okstatuses,$item);
9640: }
9641: }
9642: if (@okstatuses) {
9643: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9644: }
9645: }
9646: }
1.1075 raeburn 9647: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9648: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9649: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9650: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9651: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9652: } else {
9653: $logmsg .= ' during self creation';
9654: }
1.1075 raeburn 9655: my $changed;
9656: if ($newuser) {
9657: $changed = 1;
9658: } else {
9659: foreach my $field (@fields) {
9660: if ($names{$field} ne $oldnames{$field}) {
9661: $changed = 1;
9662: last;
9663: }
9664: }
9665: }
9666: unless ($changed) {
9667: $logmsg = 'No changes in user information needed for: '.$logmsg;
9668: &logthis($logmsg);
9669: return 'ok';
9670: }
9671: my $reply = &put('environment', \%names, $udom,$uname);
9672: if ($reply ne 'ok') {
9673: return 'error: '.$reply;
9674: }
1.1087 raeburn 9675: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9676: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9677: }
1.1075 raeburn 9678: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9679: &devalidate_cache_new('namescache',$uname.':'.$udom);
9680: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9681: &logthis($logmsg);
1.134 albertel 9682: return 'ok';
1.80 www 9683: }
9684:
1.81 www 9685: # -------------------------------------------------------------- Modify student
1.80 www 9686:
1.81 www 9687: sub modifystudent {
9688: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9689: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 9690: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9691: if (!$cid) {
1.620 albertel 9692: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9693: return 'not_in_class';
9694: }
1.80 www 9695: }
9696: # --------------------------------------------------------------- Make the user
1.81 www 9697: my $reply=&modifyuser
1.209 matthew 9698: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9699: $desiredhome,$email,$inststatus);
1.80 www 9700: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9701: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 9702: # student's environment
1.297 matthew 9703: $uid = undef if (!$forceid);
1.455 albertel 9704: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 9705: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 9706: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9707: return $reply;
9708: }
9709:
9710: sub modify_student_enrollment {
1.1172.2.23 raeburn 9711: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 9712: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9713: my ($cdom,$cnum,$chome);
9714: if (!$cid) {
1.620 albertel 9715: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9716: return 'not_in_class';
9717: }
1.620 albertel 9718: $cdom=$env{'course.'.$cid.'.domain'};
9719: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9720: } else {
9721: ($cdom,$cnum)=split(/_/,$cid);
9722: }
1.620 albertel 9723: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9724: if (!$chome) {
1.457 raeburn 9725: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9726: }
1.455 albertel 9727: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9728: # Make sure the user exists
1.81 www 9729: my $uhome=&homeserver($uname,$udom);
9730: if (($uhome eq '') || ($uhome eq 'no_host')) {
9731: return 'error: no such user';
9732: }
1.297 matthew 9733: # Get student data if we were not given enough information
9734: if (!defined($first) || $first eq '' ||
9735: !defined($last) || $last eq '' ||
9736: !defined($uid) || $uid eq '' ||
9737: !defined($middle) || $middle eq '' ||
9738: !defined($gene) || $gene eq '') {
1.294 matthew 9739: # They did not supply us with enough data to enroll the student, so
9740: # we need to pick up more information.
1.297 matthew 9741: my %tmp = &get('environment',
1.294 matthew 9742: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9743: ,$udom,$uname);
9744:
1.800 albertel 9745: #foreach my $key (keys(%tmp)) {
9746: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9747: #}
1.294 matthew 9748: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9749: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9750: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9751: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9752: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9753: }
1.556 albertel 9754: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9755: my $user = "$uname:$udom";
9756: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9757: my $reply=cput('classlist',
1.1148 raeburn 9758: {$user =>
1.1172.2.76 raeburn 9759: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9760: $cdom,$cnum);
1.1148 raeburn 9761: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9762: &devalidate_getsection_cache($udom,$uname,$cid);
9763: } else {
1.81 www 9764: return 'error: '.$reply;
9765: }
1.297 matthew 9766: # Add student role to user
1.83 www 9767: my $uurl='/'.$cid;
1.81 www 9768: $uurl=~s/\_/\//g;
9769: if ($usec) {
9770: $uurl.='/'.$usec;
9771: }
1.1148 raeburn 9772: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9773: $selfenroll,$context);
9774: if ($result ne 'ok') {
9775: if ($old_entry{$user} ne '') {
9776: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9777: } else {
9778: $reply = &del('classlist',[$user],$cdom,$cnum);
9779: }
9780: }
9781: return $result;
1.21 www 9782: }
9783:
1.556 albertel 9784: sub format_name {
9785: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9786: my $name;
9787: if ($first ne 'lastname') {
9788: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9789: } else {
9790: if ($lastname=~/\S/) {
9791: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9792: $name=~s/\s+,/,/;
9793: } else {
9794: $name.= $firstname.' '.$middlename.' '.$generation;
9795: }
9796: }
9797: $name=~s/^\s+//;
9798: $name=~s/\s+$//;
9799: $name=~s/\s+/ /g;
9800: return $name;
9801: }
9802:
1.84 www 9803: # ------------------------------------------------- Write to course preferences
9804:
9805: sub writecoursepref {
9806: my ($courseid,%prefs)=@_;
9807: $courseid=~s/^\///;
9808: $courseid=~s/\_/\//g;
9809: my ($cdomain,$cnum)=split(/\//,$courseid);
9810: my $chome=homeserver($cnum,$cdomain);
9811: if (($chome eq '') || ($chome eq 'no_host')) {
9812: return 'error: no such course';
9813: }
9814: my $cstring='';
1.800 albertel 9815: foreach my $pref (keys(%prefs)) {
9816: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9817: }
1.84 www 9818: $cstring=~s/\&$//;
9819: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9820: }
9821:
9822: # ---------------------------------------------------------- Make/modify course
9823:
9824: sub createcourse {
1.741 raeburn 9825: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9826: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9827: $url=&declutter($url);
9828: my $cid='';
1.1028 raeburn 9829: if ($context eq 'requestcourses') {
9830: my $can_create = 0;
9831: my ($ownername,$ownerdom) = split(':',$course_owner);
9832: if ($udom eq $ownerdom) {
9833: if (&usertools_access($ownername,$ownerdom,$category,undef,
9834: $context)) {
9835: $can_create = 1;
9836: }
9837: } else {
9838: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9839: $category);
9840: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9841: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9842: if (@curr > 0) {
9843: my @options = qw(approval validate autolimit);
9844: my $optregex = join('|',@options);
9845: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9846: $can_create = 1;
9847: }
9848: }
9849: }
9850: }
9851: if ($can_create) {
9852: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9853: unless (&allowed('ccc',$udom)) {
9854: return 'refused';
9855: }
1.1017 raeburn 9856: }
9857: } else {
9858: return 'refused';
9859: }
1.1028 raeburn 9860: } elsif (!&allowed('ccc',$udom)) {
9861: return 'refused';
1.84 www 9862: }
1.1011 raeburn 9863: # --------------------------------------------------------------- Get Unique ID
9864: my $uname;
9865: if ($cnum =~ /^$match_courseid$/) {
9866: my $chome=&homeserver($cnum,$udom,'true');
9867: if (($chome eq '') || ($chome eq 'no_host')) {
9868: $uname = $cnum;
9869: } else {
1.1038 raeburn 9870: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9871: }
9872: } else {
1.1038 raeburn 9873: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9874: }
9875: return $uname if ($uname =~ /^error/);
9876: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9877: if (!defined($course_server)) {
9878: if (defined(&domain($udom,'primary'))) {
9879: $course_server = &domain($udom,'primary');
9880: } else {
9881: $course_server = $env{'user.home'};
9882: }
9883: }
9884: my %host_servers =
9885: &Apache::lonnet::get_servers($udom,'library');
9886: unless ($host_servers{$course_server}) {
9887: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9888: }
1.84 www 9889: # ------------------------------------------------------------- Make the course
9890: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9891: $course_server);
1.84 www 9892: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9893: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9894: if (($uhome eq '') || ($uhome eq 'no_host')) {
9895: return 'error: no such course';
9896: }
1.271 www 9897: # ----------------------------------------------------------------- Course made
1.516 raeburn 9898: # log existence
1.1029 raeburn 9899: my $now = time;
1.918 raeburn 9900: my $newcourse = {
9901: $udom.'_'.$uname => {
1.921 raeburn 9902: description => $description,
9903: inst_code => $inst_code,
9904: owner => $course_owner,
9905: type => $crstype,
1.1029 raeburn 9906: creator => $env{'user.name'}.':'.
9907: $env{'user.domain'},
9908: created => $now,
9909: context => $context,
1.918 raeburn 9910: },
9911: };
1.921 raeburn 9912: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9913: # set toplevel url
1.271 www 9914: my $topurl=$url;
9915: unless ($nonstandard) {
9916: # ------------------------------------------ For standard courses, make top url
9917: my $mapurl=&clutter($url);
1.278 www 9918: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9919: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9920: <map>
9921: <resource id="1" type="start"></resource>
9922: <resource id="2" src="$mapurl"></resource>
9923: <resource id="3" type="finish"></resource>
9924: <link index="1" from="1" to="2"></link>
9925: <link index="2" from="2" to="3"></link>
9926: </map>
9927: ENDINITMAP
9928: $topurl=&declutter(
1.638 albertel 9929: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9930: );
9931: }
9932: # ----------------------------------------------------------- Write preferences
1.84 www 9933: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9934: ('description' => $description,
9935: 'url' => $topurl,
9936: 'internal.creator' => $env{'user.name'}.':'.
9937: $env{'user.domain'},
9938: 'internal.created' => $now,
9939: 'internal.creationcontext' => $context)
9940: );
1.84 www 9941: return '/'.$udom.'/'.$uname;
9942: }
9943:
1.1011 raeburn 9944: # ------------------------------------------------------------------- Create ID
9945: sub generate_coursenum {
1.1038 raeburn 9946: my ($udom,$crstype) = @_;
1.1011 raeburn 9947: my $domdesc = &domain($udom);
9948: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9949: my $first;
9950: if ($crstype eq 'Community') {
9951: $first = '0';
9952: } else {
9953: $first = int(1+rand(9));
9954: }
9955: my $uname=$first.
1.1011 raeburn 9956: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9957: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9958: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9959: # ----------------------------------------------- Make sure that does not exist
9960: my $uhome=&homeserver($uname,$udom,'true');
9961: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9962: if ($crstype eq 'Community') {
9963: $first = '0';
9964: } else {
9965: $first = int(1+rand(9));
9966: }
9967: $uname=$first.
1.1011 raeburn 9968: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9969: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9970: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9971: $uhome=&homeserver($uname,$udom,'true');
9972: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9973: return 'error: unable to generate unique course-ID';
9974: }
9975: }
9976: return $uname;
9977: }
9978:
1.813 albertel 9979: sub is_course {
1.1167 droeschl 9980: my ($cdom, $cnum) = scalar(@_) == 1 ?
9981: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9982:
9983: return unless $cdom and $cnum;
9984:
9985: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9986: '.');
9987:
1.1172.2.23 raeburn 9988: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9989: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9990: }
9991:
1.1015 raeburn 9992: sub store_userdata {
9993: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9994: my $result;
1.1016 raeburn 9995: if ($datakey ne '') {
1.1013 raeburn 9996: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9997: if ($udom eq '' || $uname eq '') {
9998: $udom = $env{'user.domain'};
9999: $uname = $env{'user.name'};
10000: }
10001: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10002: if (($uhome eq '') || ($uhome eq 'no_host')) {
10003: $result = 'error: no_host';
10004: } else {
10005: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10006: $storehash->{'host'} = $perlvar{'lonHostID'};
10007:
10008: my $namevalue='';
10009: foreach my $key (keys(%{$storehash})) {
10010: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10011: }
10012: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10013: unless ($namespace eq 'courserequests') {
10014: $datakey = &escape($datakey);
10015: }
1.1105 raeburn 10016: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10017: $namevalue,$uhome);
1.1013 raeburn 10018: }
10019: } else {
10020: $result = 'error: data to store was not a hash reference';
10021: }
10022: } else {
10023: $result= 'error: invalid requestkey';
10024: }
10025: return $result;
10026: }
10027:
1.21 www 10028: # ---------------------------------------------------------- Assign Custom Role
10029:
10030: sub assigncustomrole {
1.957 raeburn 10031: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10032: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10033: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10034: }
10035:
10036: # ----------------------------------------------------------------- Revoke Role
10037:
10038: sub revokerole {
1.957 raeburn 10039: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10040: my $now=time;
1.965 raeburn 10041: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10042: }
10043:
10044: # ---------------------------------------------------------- Revoke Custom Role
10045:
10046: sub revokecustomrole {
1.957 raeburn 10047: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10048: my $now=time;
1.357 www 10049: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10050: $deleteflag,$selfenroll,$context);
1.17 www 10051: }
10052:
1.533 banghart 10053: # ------------------------------------------------------------ Disk usage
1.535 albertel 10054: sub diskusage {
1.955 raeburn 10055: my ($udom,$uname,$directorypath,$getpropath)=@_;
10056: $directorypath =~ s/\/$//;
10057: my $listing=&reply('du2:'.&escape($directorypath).':'
10058: .&escape($getpropath).':'.&escape($uname).':'
10059: .&escape($udom),homeserver($uname,$udom));
10060: if ($listing eq 'unknown_cmd') {
10061: if ($getpropath) {
10062: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10063: }
10064: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10065: }
1.514 albertel 10066: return $listing;
1.512 banghart 10067: }
10068:
1.566 banghart 10069: sub is_locked {
1.1096 raeburn 10070: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10071: my @check;
10072: my $is_locked;
1.1093 raeburn 10073: push (@check,$file_name);
1.613 albertel 10074: my %locked = &get('file_permissions',\@check,
1.620 albertel 10075: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10076: my ($tmp)=keys(%locked);
10077: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10078:
1.566 banghart 10079: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10080: $is_locked = 'false';
10081: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10082: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10083: $is_locked = 'true';
1.1096 raeburn 10084: if (ref($which) eq 'ARRAY') {
10085: push(@{$which},$entry);
10086: } else {
10087: last;
10088: }
1.745 raeburn 10089: }
10090: }
1.566 banghart 10091: } else {
10092: $is_locked = 'false';
10093: }
1.1093 raeburn 10094: return $is_locked;
1.566 banghart 10095: }
10096:
1.759 albertel 10097: sub declutter_portfile {
10098: my ($file) = @_;
1.833 albertel 10099: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10100: return $file;
10101: }
10102:
1.559 banghart 10103: # ------------------------------------------------------------- Mark as Read Only
10104:
10105: sub mark_as_readonly {
10106: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10107: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10108: my ($tmp)=keys(%current_permissions);
10109: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10110: foreach my $file (@{$files}) {
1.759 albertel 10111: $file = &declutter_portfile($file);
1.561 banghart 10112: push(@{$current_permissions{$file}},$what);
1.559 banghart 10113: }
1.613 albertel 10114: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10115: return;
10116: }
10117:
1.572 banghart 10118: # ------------------------------------------------------------Save Selected Files
10119:
10120: sub save_selected_files {
10121: my ($user, $path, @files) = @_;
10122: my $filename = $user."savedfiles";
1.573 banghart 10123: my @other_files = &files_not_in_path($user, $path);
1.1172.2.93.4 7(raebur 10124:7): open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10125: foreach my $file (@files) {
1.620 albertel 10126: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10127: }
10128: foreach my $file (@other_files) {
1.574 banghart 10129: print (OUT $file."\n");
1.572 banghart 10130: }
1.574 banghart 10131: close (OUT);
1.572 banghart 10132: return 'ok';
10133: }
10134:
1.574 banghart 10135: sub clear_selected_files {
10136: my ($user) = @_;
10137: my $filename = $user."savedfiles";
1.1172.2.93.4 7(raebur 10138:7): open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10139: print (OUT undef);
10140: close (OUT);
10141: return ("ok");
10142: }
10143:
1.572 banghart 10144: sub files_in_path {
10145: my ($user, $path) = @_;
10146: my $filename = $user."savedfiles";
10147: my %return_files;
1.1172.2.93.4 7(raebur 10148:7): open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10149: while (my $line_in = <IN>) {
1.574 banghart 10150: chomp ($line_in);
10151: my @paths_and_file = split (m!/!, $line_in);
10152: my $file_part = pop (@paths_and_file);
10153: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10154: $path_part.='/';
10155: my $path_and_file = $path_part.$file_part;
10156: if ($path_part eq $path) {
10157: $return_files{$file_part}= 'selected';
10158: }
10159: }
1.574 banghart 10160: close (IN);
10161: return (\%return_files);
1.572 banghart 10162: }
10163:
10164: # called in portfolio select mode, to show files selected NOT in current directory
10165: sub files_not_in_path {
10166: my ($user, $path) = @_;
10167: my $filename = $user."savedfiles";
10168: my @return_files;
10169: my $path_part;
1.1172.2.93.4 7(raebur 10170:7): open(IN,'<',LONCAPA::tempdir().$filename);
1.800 albertel 10171: while (my $line = <IN>) {
1.572 banghart 10172: #ok, I know it's clunky, but I want it to work
1.800 albertel 10173: my @paths_and_file = split(m|/|, $line);
10174: my $file_part = pop(@paths_and_file);
10175: chomp($file_part);
10176: my $path_part = join('/', @paths_and_file);
1.572 banghart 10177: $path_part .= '/';
10178: my $path_and_file = $path_part.$file_part;
10179: if ($path_part ne $path) {
1.800 albertel 10180: push(@return_files, ($path_and_file));
1.572 banghart 10181: }
10182: }
1.800 albertel 10183: close(OUT);
1.574 banghart 10184: return (@return_files);
1.572 banghart 10185: }
10186:
1.745 raeburn 10187: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10188:
1.745 raeburn 10189: sub get_portfile_permissions {
10190: my ($domain,$user) = @_;
1.613 albertel 10191: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10192: my ($tmp)=keys(%current_permissions);
10193: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10194: return \%current_permissions;
10195: }
10196:
10197: #---------------------------------------------Get portfolio file access controls
10198:
1.749 raeburn 10199: sub get_access_controls {
1.745 raeburn 10200: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10201: my %access;
10202: my $real_file = $file;
10203: $file =~ s/\.meta$//;
1.745 raeburn 10204: if (defined($file)) {
1.749 raeburn 10205: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10206: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10207: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10208: }
10209: }
1.745 raeburn 10210: } else {
1.749 raeburn 10211: foreach my $key (keys(%{$current_permissions})) {
10212: if ($key =~ /\0accesscontrol$/) {
10213: if (defined($group)) {
10214: if ($key !~ m-^\Q$group\E/-) {
10215: next;
10216: }
10217: }
10218: my ($fullpath) = split(/\0/,$key);
10219: if (ref($$current_permissions{$key}) eq 'HASH') {
10220: foreach my $control (keys(%{$$current_permissions{$key}})) {
10221: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10222: }
10223: }
10224: }
10225: }
10226: }
10227: return %access;
10228: }
10229:
10230: sub modify_access_controls {
10231: my ($file_name,$changes,$domain,$user)=@_;
10232: my ($outcome,$deloutcome);
10233: my %store_permissions;
10234: my %new_values;
10235: my %new_control;
10236: my %translation;
10237: my @deletions = ();
10238: my $now = time;
10239: if (exists($$changes{'activate'})) {
10240: if (ref($$changes{'activate'}) eq 'HASH') {
10241: my @newitems = sort(keys(%{$$changes{'activate'}}));
10242: my $numnew = scalar(@newitems);
10243: for (my $i=0; $i<$numnew; $i++) {
10244: my $newkey = $newitems[$i];
10245: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10246: if ($newkey =~ /^\d+:/) {
10247: $newkey =~ s/^(\d+)/$newid/;
10248: $translation{$1} = $newid;
10249: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10250: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10251: $translation{$1} = $newid;
10252: }
1.749 raeburn 10253: $new_values{$file_name."\0".$newkey} =
10254: $$changes{'activate'}{$newitems[$i]};
10255: $new_control{$newkey} = $now;
10256: }
10257: }
10258: }
10259: my %todelete;
10260: my %changed_items;
10261: foreach my $action ('delete','update') {
10262: if (exists($$changes{$action})) {
10263: if (ref($$changes{$action}) eq 'HASH') {
10264: foreach my $key (keys(%{$$changes{$action}})) {
10265: my ($itemnum) = ($key =~ /^([^:]+):/);
10266: if ($action eq 'delete') {
10267: $todelete{$itemnum} = 1;
10268: } else {
10269: $changed_items{$itemnum} = $key;
10270: }
10271: }
1.745 raeburn 10272: }
10273: }
1.749 raeburn 10274: }
10275: # get lock on access controls for file.
10276: my $lockhash = {
10277: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10278: ':'.$env{'user.domain'},
10279: };
10280: my $tries = 0;
10281: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10282:
1.1172.2.79 raeburn 10283: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10284: $tries ++;
1.1172.2.79 raeburn 10285: sleep(0.1);
1.749 raeburn 10286: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10287: }
10288: if ($gotlock eq 'ok') {
10289: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10290: my ($tmp)=keys(%curr_permissions);
10291: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10292: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10293: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10294: if (ref($curr_controls) eq 'HASH') {
10295: foreach my $control_item (keys(%{$curr_controls})) {
10296: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10297: if (defined($todelete{$itemnum})) {
10298: push(@deletions,$file_name."\0".$control_item);
10299: } else {
10300: if (defined($changed_items{$itemnum})) {
10301: $new_control{$changed_items{$itemnum}} = $now;
10302: push(@deletions,$file_name."\0".$control_item);
10303: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10304: } else {
10305: $new_control{$control_item} = $$curr_controls{$control_item};
10306: }
10307: }
1.745 raeburn 10308: }
10309: }
10310: }
1.970 raeburn 10311: my ($group);
10312: if (&is_course($domain,$user)) {
10313: ($group,my $file) = split(/\//,$file_name,2);
10314: }
1.749 raeburn 10315: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10316: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10317: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10318: # remove lock
10319: my @del_lock = ($file_name."\0".'locked_access_records');
10320: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10321: my $sqlresult =
1.970 raeburn 10322: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10323: $group);
1.749 raeburn 10324: } else {
10325: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10326: }
1.749 raeburn 10327: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10328: }
10329:
1.827 raeburn 10330: sub make_public_indefinitely {
10331: my ($requrl) = @_;
10332: my $now = time;
10333: my $action = 'activate';
10334: my $aclnum = 0;
10335: if (&is_portfolio_url($requrl)) {
10336: my (undef,$udom,$unum,$file_name,$group) =
10337: &parse_portfolio_url($requrl);
10338: my $current_perms = &get_portfile_permissions($udom,$unum);
10339: my %access_controls = &get_access_controls($current_perms,
10340: $group,$file_name);
10341: foreach my $key (keys(%{$access_controls{$file_name}})) {
10342: my ($num,$scope,$end,$start) =
10343: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10344: if ($scope eq 'public') {
10345: if ($start <= $now && $end == 0) {
10346: $action = 'none';
10347: } else {
10348: $action = 'update';
10349: $aclnum = $num;
10350: }
10351: last;
10352: }
10353: }
10354: if ($action eq 'none') {
10355: return 'ok';
10356: } else {
10357: my %changes;
10358: my $newend = 0;
10359: my $newstart = $now;
10360: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10361: $changes{$action}{$newkey} = {
10362: type => 'public',
10363: time => {
10364: start => $newstart,
10365: end => $newend,
10366: },
10367: };
10368: my ($outcome,$deloutcome,$new_values,$translation) =
10369: &modify_access_controls($file_name,\%changes,$udom,$unum);
10370: return $outcome;
10371: }
10372: } else {
10373: return 'invalid';
10374: }
10375: }
10376:
1.745 raeburn 10377: #------------------------------------------------------Get Marked as Read Only
10378:
10379: sub get_marked_as_readonly {
10380: my ($domain,$user,$what,$group) = @_;
10381: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10382: my @readonly_files;
1.629 banghart 10383: my $cmp1=$what;
10384: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10385: while (my ($file_name,$value) = each(%{$current_permissions})) {
10386: if (defined($group)) {
10387: if ($file_name !~ m-^\Q$group\E/-) {
10388: next;
10389: }
10390: }
1.561 banghart 10391: if (ref($value) eq "ARRAY"){
10392: foreach my $stored_what (@{$value}) {
1.629 banghart 10393: my $cmp2=$stored_what;
1.759 albertel 10394: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10395: $cmp2=join('',@{$stored_what});
1.745 raeburn 10396: }
1.629 banghart 10397: if ($cmp1 eq $cmp2) {
1.561 banghart 10398: push(@readonly_files, $file_name);
1.745 raeburn 10399: last;
1.563 banghart 10400: } elsif (!defined($what)) {
10401: push(@readonly_files, $file_name);
1.745 raeburn 10402: last;
1.561 banghart 10403: }
10404: }
1.745 raeburn 10405: }
1.561 banghart 10406: }
10407: return @readonly_files;
10408: }
1.577 banghart 10409: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10410:
1.577 banghart 10411: sub get_marked_as_readonly_hash {
1.745 raeburn 10412: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10413: my %readonly_files;
1.745 raeburn 10414: while (my ($file_name,$value) = each(%{$current_permissions})) {
10415: if (defined($group)) {
10416: if ($file_name !~ m-^\Q$group\E/-) {
10417: next;
10418: }
10419: }
1.577 banghart 10420: if (ref($value) eq "ARRAY"){
10421: foreach my $stored_what (@{$value}) {
1.745 raeburn 10422: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10423: foreach my $lock_descriptor(@{$stored_what}) {
10424: if ($lock_descriptor eq 'graded') {
10425: $readonly_files{$file_name} = 'graded';
10426: } elsif ($lock_descriptor eq 'handback') {
10427: $readonly_files{$file_name} = 'handback';
10428: } else {
10429: if (!exists($readonly_files{$file_name})) {
10430: $readonly_files{$file_name} = 'locked';
10431: }
10432: }
1.745 raeburn 10433: }
1.750 banghart 10434: }
1.577 banghart 10435: }
10436: }
10437: }
10438: return %readonly_files;
10439: }
1.559 banghart 10440: # ------------------------------------------------------------ Unmark as Read Only
10441:
10442: sub unmark_as_readonly {
1.629 banghart 10443: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10444: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10445: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10446: $file_name = &declutter_portfile($file_name);
1.634 albertel 10447: my $symb_crs = $what;
10448: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10449: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10450: my ($tmp)=keys(%current_permissions);
10451: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10452: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10453: foreach my $file (@readonly_files) {
1.759 albertel 10454: my $clean_file = &declutter_portfile($file);
10455: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10456: my $current_locks = $current_permissions{$file};
1.563 banghart 10457: my @new_locks;
10458: my @del_keys;
10459: if (ref($current_locks) eq "ARRAY"){
10460: foreach my $locker (@{$current_locks}) {
1.632 albertel 10461: my $compare=$locker;
1.749 raeburn 10462: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10463: $compare=join('',@{$locker});
1.746 raeburn 10464: if ($compare ne $symb_crs) {
10465: push(@new_locks, $locker);
10466: }
1.563 banghart 10467: }
10468: }
1.650 albertel 10469: if (scalar(@new_locks) > 0) {
1.563 banghart 10470: $current_permissions{$file} = \@new_locks;
10471: } else {
10472: push(@del_keys, $file);
1.613 albertel 10473: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10474: delete($current_permissions{$file});
1.563 banghart 10475: }
10476: }
1.561 banghart 10477: }
1.613 albertel 10478: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10479: return;
10480: }
1.512 banghart 10481:
1.17 www 10482: # ------------------------------------------------------------ Directory lister
10483:
10484: sub dirlist {
1.955 raeburn 10485: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10486: $uri=~s/^\///;
10487: $uri=~s/\/$//;
1.253 stredwic 10488: my ($udom, $uname);
1.955 raeburn 10489: if ($getuserdir) {
1.253 stredwic 10490: $udom = $userdomain;
10491: $uname = $username;
1.955 raeburn 10492: } else {
10493: (undef,$udom,$uname)=split(/\//,$uri);
10494: if(defined($userdomain)) {
10495: $udom = $userdomain;
10496: }
10497: if(defined($username)) {
10498: $uname = $username;
10499: }
1.253 stredwic 10500: }
1.955 raeburn 10501: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10502:
1.955 raeburn 10503: $dirRoot = $perlvar{'lonDocRoot'};
10504: if (defined($getpropath)) {
10505: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10506: $dirRoot =~ s/\/$//;
1.955 raeburn 10507: } elsif (defined($getuserdir)) {
10508: my $subdir=$uname.'__';
10509: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10510: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10511: ."/$udom/$subdir/$uname";
10512: } elsif (defined($alternateRoot)) {
10513: $dirRoot = $alternateRoot;
1.751 banghart 10514: }
1.253 stredwic 10515:
10516: if($udom) {
10517: if($uname) {
1.1135 raeburn 10518: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10519: if ($uhome eq 'no_host') {
10520: return ([],'no_host');
10521: }
1.955 raeburn 10522: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10523: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10524: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10525: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10526: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10527: } else {
10528: @listing_results = map { &unescape($_); } split(/:/,$listing);
10529: }
1.605 matthew 10530: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10531: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10532: @listing_results = split(/:/,$listing);
10533: } else {
10534: @listing_results = map { &unescape($_); } split(/:/,$listing);
10535: }
1.1135 raeburn 10536: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10537: ($listing eq 'rejected') || ($listing eq 'refused') ||
10538: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10539: return ([],$listing);
10540: } else {
10541: return (\@listing_results);
1.1135 raeburn 10542: }
1.955 raeburn 10543: } elsif(!$alternateRoot) {
1.1136 raeburn 10544: my (%allusers,%listerror);
1.841 albertel 10545: my %servers = &get_servers($udom,'library');
1.955 raeburn 10546: foreach my $tryserver (keys(%servers)) {
10547: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10548: &escape($udom),$tryserver);
10549: if ($listing eq 'unknown_cmd') {
10550: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10551: $udom, $tryserver);
10552: } else {
10553: @listing_results = map { &unescape($_); } split(/:/,$listing);
10554: }
1.841 albertel 10555: if ($listing eq 'unknown_cmd') {
10556: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10557: $udom, $tryserver);
10558: @listing_results = split(/:/,$listing);
10559: } else {
10560: @listing_results =
10561: map { &unescape($_); } split(/:/,$listing);
10562: }
1.1136 raeburn 10563: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10564: ($listing eq 'rejected') || ($listing eq 'refused') ||
10565: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10566: $listerror{$tryserver} = $listing;
10567: } else {
1.841 albertel 10568: foreach my $line (@listing_results) {
10569: my ($entry) = split(/&/,$line,2);
10570: $allusers{$entry} = 1;
10571: }
10572: }
1.253 stredwic 10573: }
1.1136 raeburn 10574: my @alluserslist=();
1.800 albertel 10575: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10576: push(@alluserslist,$user.'&user');
1.253 stredwic 10577: }
1.1172.2.80 raeburn 10578: if (!%listerror) {
10579: # no errors
10580: return (\@alluserslist);
10581: } elsif (scalar(keys(%servers)) == 1) {
10582: # one library server, one error
10583: my ($key) = keys(%listerror);
10584: return (\@alluserslist, $listerror{$key});
10585: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10586: # con_lost indicates that we might miss data from at least one
10587: # library server
10588: return (\@alluserslist, 'con_lost');
10589: } else {
10590: # multiple library servers and no con_lost -> data should be
10591: # complete.
10592: return (\@alluserslist);
10593: }
10594:
1.253 stredwic 10595: } else {
1.1136 raeburn 10596: return ([],'missing username');
1.253 stredwic 10597: }
1.955 raeburn 10598: } elsif(!defined($getpropath)) {
1.1136 raeburn 10599: my $path = $perlvar{'lonDocRoot'}.'/res/';
10600: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10601: return (\@all_domains);
1.955 raeburn 10602: } else {
1.1136 raeburn 10603: return ([],'missing domain');
1.275 stredwic 10604: }
10605: }
10606:
10607: # --------------------------------------------- GetFileTimestamp
10608: # This function utilizes dirlist and returns the date stamp for
10609: # when it was last modified. It will also return an error of -1
10610: # if an error occurs
10611:
10612: sub GetFileTimestamp {
1.955 raeburn 10613: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10614: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10615: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10616: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10617: undef,$getuserdir);
10618: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10619: return -1;
10620: }
10621: if (ref($fileref) eq 'ARRAY') {
10622: my @stats = split('&',$fileref->[0]);
1.375 matthew 10623: # @stats contains first the filename, then the stat output
10624: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10625: } else {
10626: return -1;
1.253 stredwic 10627: }
1.26 www 10628: }
10629:
1.712 albertel 10630: sub stat_file {
10631: my ($uri) = @_;
1.787 albertel 10632: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10633:
1.955 raeburn 10634: my ($udom,$uname,$file);
1.712 albertel 10635: if ($uri =~ m-^/(uploaded|editupload)/-) {
10636: ($udom,$uname,$file) =
1.811 albertel 10637: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10638: $file = 'userfiles/'.$file;
10639: }
10640: if ($uri =~ m-^/res/-) {
10641: ($udom,$uname) =
1.807 albertel 10642: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10643: $file = $uri;
10644: }
10645:
10646: if (!$udom || !$uname || !$file) {
10647: # unable to handle the uri
10648: return ();
10649: }
1.956 raeburn 10650: my $getpropath;
10651: if ($file =~ /^userfiles\//) {
10652: $getpropath = 1;
10653: }
1.1136 raeburn 10654: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10655: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10656: return ();
10657: } else {
10658: if (ref($listref) eq 'ARRAY') {
10659: my @stats = split('&',$listref->[0]);
10660: shift(@stats); #filename is first
10661: return @stats;
10662: }
1.712 albertel 10663: }
10664: return ();
10665: }
10666:
1.26 www 10667: # -------------------------------------------------------- Value of a Condition
10668:
1.713 albertel 10669: # gets the value of a specific preevaluated condition
10670: # stored in the string $env{user.state.<cid>}
10671: # or looks up a condition reference in the bighash and if if hasn't
10672: # already been evaluated recurses into docondval to get the value of
10673: # the condition, then memoizing it to
10674: # $env{user.state.<cid>.<condition>}
1.40 www 10675: sub directcondval {
10676: my $number=shift;
1.620 albertel 10677: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10678: &Apache::lonuserstate::evalstate();
10679: }
1.713 albertel 10680: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10681: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10682: } elsif ($number =~ /^_/) {
10683: my $sub_condition;
10684: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10685: &GDBM_READER(),0640)) {
10686: $sub_condition=$bighash{'conditions'.$number};
10687: untie(%bighash);
10688: }
10689: my $value = &docondval($sub_condition);
1.949 raeburn 10690: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10691: return $value;
10692: }
1.620 albertel 10693: if ($env{'user.state.'.$env{'request.course.id'}}) {
10694: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10695: } else {
10696: return 2;
10697: }
10698: }
10699:
1.713 albertel 10700: # get the collection of conditions for this resource
1.26 www 10701: sub condval {
10702: my $condidx=shift;
1.54 www 10703: my $allpathcond='';
1.713 albertel 10704: foreach my $cond (split(/\|/,$condidx)) {
10705: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10706: $allpathcond.=
10707: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10708: }
1.191 harris41 10709: }
1.54 www 10710: $allpathcond=~s/\|$//;
1.713 albertel 10711: return &docondval($allpathcond);
10712: }
10713:
10714: #evaluates an expression of conditions
10715: sub docondval {
10716: my ($allpathcond) = @_;
10717: my $result=0;
10718: if ($env{'request.course.id'}
10719: && defined($allpathcond)) {
10720: my $operand='|';
10721: my @stack;
10722: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10723: if ($chunk eq '(') {
10724: push @stack,($operand,$result);
10725: } elsif ($chunk eq ')') {
10726: my $before=pop @stack;
10727: if (pop @stack eq '&') {
10728: $result=$result>$before?$before:$result;
10729: } else {
10730: $result=$result>$before?$result:$before;
10731: }
10732: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10733: $operand=$chunk;
10734: } else {
10735: my $new=directcondval($chunk);
10736: if ($operand eq '&') {
10737: $result=$result>$new?$new:$result;
10738: } else {
10739: $result=$result>$new?$result:$new;
10740: }
10741: }
10742: }
1.26 www 10743: }
10744: return $result;
1.421 albertel 10745: }
10746:
10747: # ---------------------------------------------------- Devalidate courseresdata
10748:
10749: sub devalidatecourseresdata {
10750: my ($coursenum,$coursedomain)=@_;
10751: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10752: &devalidate_cache_new('courseres',$hashid);
1.28 www 10753: }
10754:
1.763 www 10755:
1.200 www 10756: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10757: #
10758: # Parameters:
10759: # $coursenum - Number of the course.
10760: # $coursedomain - Domain at which the course was created.
10761: # Returns:
10762: # A hash of the course parameters along (I think) with timestamps
10763: # and version info.
1.877 foxr 10764:
1.624 albertel 10765: sub get_courseresdata {
10766: my ($coursenum,$coursedomain)=@_;
1.200 www 10767: my $coursehom=&homeserver($coursenum,$coursedomain);
10768: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10769: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10770: my %dumpreply;
1.417 albertel 10771: unless (defined($cached)) {
1.624 albertel 10772: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10773: $result=\%dumpreply;
1.251 albertel 10774: my ($tmp) = keys(%dumpreply);
10775: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10776: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10777: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10778: return $tmp;
1.416 albertel 10779: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10780: $result=undef;
1.599 albertel 10781: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10782: }
10783: }
1.624 albertel 10784: return $result;
10785: }
10786:
1.633 albertel 10787: sub devalidateuserresdata {
10788: my ($uname,$udom)=@_;
10789: my $hashid="$udom:$uname";
10790: &devalidate_cache_new('userres',$hashid);
10791: }
10792:
1.624 albertel 10793: sub get_userresdata {
10794: my ($uname,$udom)=@_;
10795: #most student don\'t have any data set, check if there is some data
10796: if (&EXT_cache_status($udom,$uname)) { return undef; }
10797:
10798: my $hashid="$udom:$uname";
10799: my ($result,$cached)=&is_cached_new('userres',$hashid);
10800: if (!defined($cached)) {
10801: my %resourcedata=&dump('resourcedata',$udom,$uname);
10802: $result=\%resourcedata;
10803: &do_cache_new('userres',$hashid,$result,600);
10804: }
10805: my ($tmp)=keys(%$result);
10806: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10807: return $result;
10808: }
10809: #error 2 occurs when the .db doesn't exist
10810: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10811: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10812: &logthis("<font color=\"blue\">WARNING:".
10813: " Trying to get resource data for ".
10814: $uname." at ".$udom.": ".
10815: $tmp."</font>");
10816: }
1.624 albertel 10817: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10818: #&EXT_cache_set($udom,$uname);
10819: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10820: undef($tmp); # not really an error so don't send it back
1.624 albertel 10821: }
10822: return $tmp;
10823: }
1.879 foxr 10824: #----------------------------------------------- resdata - return resource data
10825: # Purpose:
10826: # Return resource data for either users or for a course.
10827: # Parameters:
10828: # $name - Course/user name.
10829: # $domain - Name of the domain the user/course is registered on.
1.1172.2.93.4 1(raebur 10830:7): # $type - Type of thing $name is (must be 'course' or 'user')
1.879 foxr 10831: # @which - Array of names of resources desired.
10832: # Returns:
10833: # The value of the first reasource in @which that is found in the
10834: # resource hash.
10835: # Exceptional Conditions:
10836: # If the $type passed in is not valid (not the string 'course' or
10837: # 'user', an undefined reference is returned.
10838: # If none of the resources are found, an undef is returned
1.624 albertel 10839: sub resdata {
10840: my ($name,$domain,$type,@which)=@_;
10841: my $result;
10842: if ($type eq 'course') {
10843: $result=&get_courseresdata($name,$domain);
10844: } elsif ($type eq 'user') {
10845: $result=&get_userresdata($name,$domain);
10846: }
10847: if (!ref($result)) { return $result; }
1.251 albertel 10848: foreach my $item (@which) {
1.1172.2.93.4 1(raebur 10849:7): if (ref($item) eq 'ARRAY') {
10850:7): if (defined($result->{$item->[0]})) {
10851:7): return [$result->{$item->[0]},$item->[1]];
10852:7): }
10853:7): }
1.250 albertel 10854: }
1.291 albertel 10855: return undef;
1.200 www 10856: }
10857:
1.1172.2.93.4 2(raebur 10858:7): sub get_domain_ltitools {
10859:7): my ($cdom) = @_;
10860:7): my %ltitools;
10861:7): my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10862:7): if (defined($cached)) {
10863:7): if (ref($result) eq 'HASH') {
10864:7): %ltitools = %{$result};
10865:7): }
10866:7): } else {
10867:7): my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10868:7): if (ref($domconfig{'ltitools'}) eq 'HASH') {
10869:7): %ltitools = %{$domconfig{'ltitools'}};
10870:7): my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
10871:7): if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
10872:7): foreach my $id (keys(%ltitools)) {
10873:7): if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
10874:7): foreach my $item ('key','secret') {
10875:7): $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
10876:7): }
10877:7): }
10878:7): }
10879:7): }
10880:7): }
10881:7): my $cachetime = 24*60*60;
10882:7): &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10883:7): }
10884:7): return %ltitools;
10885:7): }
10886:7):
1.1172.2.31 raeburn 10887: sub get_numsuppfiles {
10888: my ($cnum,$cdom,$ignorecache)=@_;
10889: my $hashid=$cnum.':'.$cdom;
10890: my ($suppcount,$cached);
10891: unless ($ignorecache) {
10892: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10893: }
10894: unless (defined($cached)) {
10895: my $chome=&homeserver($cnum,$cdom);
10896: unless ($chome eq 'no_host') {
10897: ($suppcount,my $errors) = (0,0);
10898: my $suppmap = 'supplemental.sequence';
10899: ($suppcount,$errors) =
10900: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10901: }
10902: &do_cache_new('suppcount',$hashid,$suppcount,600);
10903: }
10904: return $suppcount;
10905: }
10906:
1.379 matthew 10907: #
10908: # EXT resource caching routines
10909: #
10910:
10911: sub clear_EXT_cache_status {
1.383 albertel 10912: &delenv('cache.EXT.');
1.379 matthew 10913: }
10914:
10915: sub EXT_cache_status {
10916: my ($target_domain,$target_user) = @_;
1.383 albertel 10917: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10918: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10919: # We know already the user has no data
10920: return 1;
10921: } else {
10922: return 0;
10923: }
10924: }
10925:
10926: sub EXT_cache_set {
10927: my ($target_domain,$target_user) = @_;
1.383 albertel 10928: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10929: #&appenv({$cachename => time});
1.379 matthew 10930: }
10931:
1.28 www 10932: # --------------------------------------------------------- Value of a Variable
1.58 www 10933: sub EXT {
1.715 albertel 10934:
1.1172.2.28 raeburn 10935: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10936: unless ($varname) { return ''; }
1.218 albertel 10937: #get real user name/domain, courseid and symb
10938: my $courseid;
1.359 albertel 10939: my $publicuser;
1.427 www 10940: if ($symbparm) {
10941: $symbparm=&get_symb_from_alias($symbparm);
10942: }
1.218 albertel 10943: if (!($uname && $udom)) {
1.790 albertel 10944: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10945: if (!$symbparm) { $symbparm=$cursymb; }
10946: } else {
1.620 albertel 10947: $courseid=$env{'request.course.id'};
1.218 albertel 10948: }
1.48 www 10949: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10950: my $rest;
1.320 albertel 10951: if (defined($therest[0])) {
1.48 www 10952: $rest=join('.',@therest);
10953: } else {
10954: $rest='';
10955: }
1.320 albertel 10956:
1.57 www 10957: my $qualifierrest=$qualifier;
10958: if ($rest) { $qualifierrest.='.'.$rest; }
10959: my $spacequalifierrest=$space;
10960: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10961: if ($realm eq 'user') {
1.48 www 10962: # --------------------------------------------------------------- user.resource
10963: if ($space eq 'resource') {
1.651 albertel 10964: if ( (defined($Apache::lonhomework::parsing_a_problem)
10965: || defined($Apache::lonhomework::parsing_a_task))
10966: &&
1.744 albertel 10967: ($symbparm eq &symbread()) ) {
10968: # if we are in the middle of processing the resource the
10969: # get the value we are planning on committing
10970: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10971: return $Apache::lonhomework::results{$qualifierrest};
10972: } else {
10973: return $Apache::lonhomework::history{$qualifierrest};
10974: }
1.335 albertel 10975: } else {
1.359 albertel 10976: my %restored;
1.620 albertel 10977: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10978: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10979: } else {
10980: %restored=&restore($symbparm,$courseid,$udom,$uname);
10981: }
1.335 albertel 10982: return $restored{$qualifierrest};
10983: }
1.48 www 10984: # ----------------------------------------------------------------- user.access
10985: } elsif ($space eq 'access') {
1.218 albertel 10986: # FIXME - not supporting calls for a specific user
1.48 www 10987: return &allowed($qualifier,$rest);
10988: # ------------------------------------------ user.preferences, user.environment
10989: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10990: if (($uname eq $env{'user.name'}) &&
10991: ($udom eq $env{'user.domain'})) {
10992: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10993: } else {
1.359 albertel 10994: my %returnhash;
10995: if (!$publicuser) {
10996: %returnhash=&userenvironment($udom,$uname,
10997: $qualifierrest);
10998: }
1.218 albertel 10999: return $returnhash{$qualifierrest};
11000: }
1.48 www 11001: # ----------------------------------------------------------------- user.course
11002: } elsif ($space eq 'course') {
1.218 albertel 11003: # FIXME - not supporting calls for a specific user
1.620 albertel 11004: return $env{join('.',('request.course',$qualifier))};
1.48 www 11005: # ------------------------------------------------------------------- user.role
11006: } elsif ($space eq 'role') {
1.218 albertel 11007: # FIXME - not supporting calls for a specific user
1.620 albertel 11008: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11009: if ($qualifier eq 'value') {
11010: return $role;
11011: } elsif ($qualifier eq 'extent') {
11012: return $where;
11013: }
11014: # ----------------------------------------------------------------- user.domain
11015: } elsif ($space eq 'domain') {
1.218 albertel 11016: return $udom;
1.48 www 11017: # ------------------------------------------------------------------- user.name
11018: } elsif ($space eq 'name') {
1.218 albertel 11019: return $uname;
1.48 www 11020: # ---------------------------------------------------- Any other user namespace
1.29 www 11021: } else {
1.359 albertel 11022: my %reply;
11023: if (!$publicuser) {
11024: %reply=&get($space,[$qualifierrest],$udom,$uname);
11025: }
11026: return $reply{$qualifierrest};
1.48 www 11027: }
1.236 www 11028: } elsif ($realm eq 'query') {
11029: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11030: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11031: [$spacequalifierrest]);
1.620 albertel 11032: return $env{'form.'.$spacequalifierrest};
1.236 www 11033: } elsif ($realm eq 'request') {
1.48 www 11034: # ------------------------------------------------------------- request.browser
11035: if ($space eq 'browser') {
1.1145 bisitz 11036: return $env{'browser.'.$qualifier};
1.57 www 11037: # ------------------------------------------------------------ request.filename
11038: } else {
1.620 albertel 11039: return $env{'request.'.$spacequalifierrest};
1.29 www 11040: }
1.28 www 11041: } elsif ($realm eq 'course') {
1.48 www 11042: # ---------------------------------------------------------- course.description
1.620 albertel 11043: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11044: } elsif ($realm eq 'resource') {
1.165 www 11045:
1.620 albertel 11046: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11047: if (!$symbparm) { $symbparm=&symbread(); }
11048: }
1.693 albertel 11049:
1.1172.2.30 raeburn 11050: if ($qualifier eq '') {
11051: if ($space eq 'title') {
11052: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11053: return &gettitle($symbparm);
11054: }
1.693 albertel 11055:
1.1172.2.30 raeburn 11056: if ($space eq 'map') {
11057: my ($map) = &decode_symb($symbparm);
11058: return &symbread($map);
11059: }
11060: if ($space eq 'maptitle') {
11061: my ($map) = &decode_symb($symbparm);
11062: return &gettitle($map);
11063: }
11064: if ($space eq 'filename') {
11065: if ($symbparm) {
11066: return &clutter((&decode_symb($symbparm))[2]);
11067: }
11068: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11069: }
1.1172.2.30 raeburn 11070:
11071: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11072: if ($space eq 'visibleparts') {
11073: my $navmap = Apache::lonnavmaps::navmap->new();
11074: my $item;
11075: if (ref($navmap)) {
11076: my $res = $navmap->getBySymb($symbparm);
11077: my $parts = $res->parts();
11078: if (ref($parts) eq 'ARRAY') {
11079: $item = join(',',@{$parts});
11080: }
11081: undef($navmap);
11082: }
11083: return $item;
11084: }
11085: }
11086: }
1.693 albertel 11087:
11088: my ($section, $group, @groups);
1.593 albertel 11089: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11090: if (($courseid eq '') && ($cid)) {
11091: $courseid = $cid;
11092: }
11093: if (($symbparm && $courseid) &&
11094: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11095:
1.218 albertel 11096: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11097:
1.60 www 11098: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11099: my $symbp=$symbparm;
1.735 albertel 11100: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11101:
11102: my $symbparm=$symbp.'.'.$spacequalifierrest;
11103: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11104:
1.620 albertel 11105: if (($env{'user.name'} eq $uname) &&
11106: ($env{'user.domain'} eq $udom)) {
11107: $section=$env{'request.course.sec'};
1.733 raeburn 11108: @groups = split(/:/,$env{'request.course.groups'});
11109: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11110: } else {
1.539 albertel 11111: if (! defined($usection)) {
1.551 albertel 11112: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11113: } else {
11114: $section = $usection;
11115: }
1.733 raeburn 11116: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11117: }
11118:
11119: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11120: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11121: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11122:
1.593 albertel 11123: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11124: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11125: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11126:
1.60 www 11127: # ----------------------------------------------------------- first, check user
1.624 albertel 11128:
11129: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11130: ([$courselevelr,'resource'],
11131: [$courselevelm,'map' ],
11132: [$courselevel, 'course' ]));
1.931 albertel 11133: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11134:
1.594 albertel 11135: # ------------------------------------------------ second, check some of course
1.684 raeburn 11136: my $coursereply;
1.691 raeburn 11137: if (@groups > 0) {
11138: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11139: $mapparm,$spacequalifierrest);
1.927 albertel 11140: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11141: }
1.96 www 11142:
1.684 raeburn 11143: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11144: $env{'course.'.$courseid.'.domain'},
11145: 'course',
11146: ([$seclevelr, 'resource'],
11147: [$seclevelm, 'map' ],
11148: [$seclevel, 'course' ],
11149: [$courselevelr,'resource']));
11150: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11151:
1.60 www 11152: # ------------------------------------------------------ third, check map parms
1.218 albertel 11153: my %parmhash=();
11154: my $thisparm='';
11155: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11156: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11157: &GDBM_READER(),0640)) {
1.218 albertel 11158: $thisparm=$parmhash{$symbparm};
11159: untie(%parmhash);
11160: }
1.927 albertel 11161: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11162: }
1.594 albertel 11163: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11164:
1.218 albertel 11165: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11166: my $filename;
11167: if (!$symbparm) { $symbparm=&symbread(); }
11168: if ($symbparm) {
1.409 www 11169: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11170: } else {
1.620 albertel 11171: $filename=$env{'request.filename'};
1.282 albertel 11172: }
11173: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11174: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11175: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11176: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11177:
1.927 albertel 11178: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11179: if ($symbparm && defined($courseid) &&
1.620 albertel 11180: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11181: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11182: $env{'course.'.$courseid.'.domain'},
11183: 'course',
1.927 albertel 11184: ([$courselevelm,'map' ],
11185: [$courselevel, 'course']));
11186: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11187: }
1.145 www 11188: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11189: unless ($space eq '0') {
1.336 albertel 11190: my @parts=split(/_/,$space);
11191: my $id=pop(@parts);
11192: my $part=join('_',@parts);
11193: if ($part eq '') { $part='0'; }
1.927 albertel 11194: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11195: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11196: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11197: }
1.395 albertel 11198: if ($recurse) { return undef; }
11199: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11200: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11201: # ---------------------------------------------------- Any other user namespace
11202: } elsif ($realm eq 'environment') {
11203: # ----------------------------------------------------------------- environment
1.620 albertel 11204: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11205: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11206: } else {
1.770 albertel 11207: if ($uname eq 'anonymous' && $udom eq '') {
11208: return '';
11209: }
1.219 albertel 11210: my %returnhash=&userenvironment($udom,$uname,
11211: $spacequalifierrest);
11212: return $returnhash{$spacequalifierrest};
11213: }
1.28 www 11214: } elsif ($realm eq 'system') {
1.48 www 11215: # ----------------------------------------------------------------- system.time
11216: if ($space eq 'time') {
11217: return time;
11218: }
1.696 albertel 11219: } elsif ($realm eq 'server') {
11220: # ----------------------------------------------------------------- system.time
11221: if ($space eq 'name') {
11222: return $ENV{'SERVER_NAME'};
11223: }
1.28 www 11224: }
1.48 www 11225: return '';
1.61 www 11226: }
11227:
1.927 albertel 11228: sub get_reply {
11229: my ($reply_value) = @_;
1.940 raeburn 11230: if (ref($reply_value) eq 'ARRAY') {
11231: if (wantarray) {
11232: return @$reply_value;
11233: }
11234: return $reply_value->[0];
11235: } else {
11236: return $reply_value;
1.927 albertel 11237: }
11238: }
11239:
1.691 raeburn 11240: sub check_group_parms {
11241: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11242: my @groupitems = ();
11243: my $resultitem;
1.927 albertel 11244: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11245: foreach my $group (@{$groups}) {
11246: foreach my $level (@levels) {
1.927 albertel 11247: my $item = $courseid.'.['.$group.'].'.$level->[0];
11248: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11249: }
11250: }
11251: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11252: $env{'course.'.$courseid.'.domain'},
11253: 'course',@groupitems);
11254: return $coursereply;
11255: }
11256:
11257: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11258: my ($courseid,@groups) = @_;
11259: @groups = sort(@groups);
1.691 raeburn 11260: return @groups;
11261: }
11262:
1.395 albertel 11263: sub packages_tab_default {
11264: my ($uri,$varname)=@_;
11265: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11266:
11267: my (@extension,@specifics,$do_default);
11268: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11269: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11270: if ($pack_type eq 'default') {
11271: $do_default=1;
11272: } elsif ($pack_type eq 'extension') {
11273: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11274: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11275: # only look at packages defaults for packages that this id is
1.738 albertel 11276: push(@specifics,[$package,$pack_type,$pack_part]);
11277: }
11278: }
11279: # first look for a package that matches the requested part id
11280: foreach my $package (@specifics) {
11281: my (undef,$pack_type,$pack_part)=@{$package};
11282: next if ($pack_part ne $part);
11283: if (defined($packagetab{"$pack_type&$name&default"})) {
11284: return $packagetab{"$pack_type&$name&default"};
11285: }
11286: }
11287: # look for any possible matching non extension_ package
11288: foreach my $package (@specifics) {
11289: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11290: if (defined($packagetab{"$pack_type&$name&default"})) {
11291: return $packagetab{"$pack_type&$name&default"};
11292: }
1.585 albertel 11293: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11294: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11295: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11296: }
11297: }
1.738 albertel 11298: # look for any posible extension_ match
11299: foreach my $package (@extension) {
11300: my ($package,$pack_type)=@{$package};
11301: if (defined($packagetab{"$pack_type&$name&default"})) {
11302: return $packagetab{"$pack_type&$name&default"};
11303: }
11304: if (defined($packagetab{$package."&$name&default"})) {
11305: return $packagetab{$package."&$name&default"};
11306: }
11307: }
11308: # look for a global default setting
11309: if ($do_default && defined($packagetab{"default&$name&default"})) {
11310: return $packagetab{"default&$name&default"};
11311: }
1.395 albertel 11312: return undef;
11313: }
11314:
1.334 albertel 11315: sub add_prefix_and_part {
11316: my ($prefix,$part)=@_;
11317: my $keyroot;
11318: if (defined($prefix) && $prefix !~ /^__/) {
11319: # prefix that has a part already
11320: $keyroot=$prefix;
11321: } elsif (defined($prefix)) {
11322: # prefix that is missing a part
11323: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11324: } else {
11325: # no prefix at all
11326: if (defined($part)) { $keyroot='_'.$part; }
11327: }
11328: return $keyroot;
11329: }
11330:
1.71 www 11331: # ---------------------------------------------------------------- Get metadata
11332:
1.599 albertel 11333: my %metaentry;
1.1070 www 11334: my %importedpartids;
1.1172.2.93.4 8(raebur 11335:8): my %importedrespids;
1.71 www 11336: sub metadata {
1.176 www 11337: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11338: $uri=&declutter($uri);
1.288 albertel 11339: # if it is a non metadata possible uri return quickly
1.529 albertel 11340: if (($uri eq '') ||
11341: (($uri =~ m|^/*adm/|) &&
1.1172.2.93.4 2(raebur 11342:7): ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 11343: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11344: return undef;
11345: }
1.1172.2.49 raeburn 11346: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11347: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11348: return undef;
1.288 albertel 11349: }
1.73 www 11350: my $filename=$uri;
11351: $uri=~s/\.meta$//;
1.172 www 11352: #
11353: # Is the metadata already cached?
1.177 www 11354: # Look at timestamp of caching
1.172 www 11355: # Everything is cached by the main uri, libraries are never directly cached
11356: #
1.428 albertel 11357: if (!defined($liburi)) {
1.599 albertel 11358: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11359: if (defined($cached)) { return $result->{':'.$what}; }
11360: }
11361: {
1.1069 www 11362: # Imported parts would go here
1.1172.2.93.4 8(raebur 11363:8): my @origfiletagids=();
1.1069 www 11364: my $importedparts=0;
1.1172.2.93.4 8(raebur 11365:8):
11366:8): # Imported responseids would go here
11367:8): my $importedresponses=0;
1.172 www 11368: #
11369: # Is this a recursive call for a library?
11370: #
1.599 albertel 11371: # if (! exists($metacache{$uri})) {
11372: # $metacache{$uri}={};
11373: # }
1.924 albertel 11374: my $cachetime = 60*60;
1.171 www 11375: if ($liburi) {
11376: $liburi=&declutter($liburi);
11377: $filename=$liburi;
1.401 bowersj2 11378: } else {
1.599 albertel 11379: &devalidate_cache_new('meta',$uri);
11380: undef(%metaentry);
1.401 bowersj2 11381: }
1.140 www 11382: my %metathesekeys=();
1.73 www 11383: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11384: my $metastring;
1.1140 www 11385: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11386: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11387: $metastring =
1.929 albertel 11388: &Apache::lonnet::ssi_body($which,
1.924 albertel 11389: ('grade_target' => 'meta'));
11390: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11391: } elsif (($uri !~ m -^(editupload)/-) &&
11392: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11393: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11394: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11395: $metastring=&getfile($file);
1.489 albertel 11396: }
1.208 albertel 11397: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11398: my $token;
1.140 www 11399: undef %metathesekeys;
1.71 www 11400: while ($token=$parser->get_token) {
1.339 albertel 11401: if ($token->[0] eq 'S') {
11402: if (defined($token->[2]->{'package'})) {
1.172 www 11403: #
11404: # This is a package - get package info
11405: #
1.339 albertel 11406: my $package=$token->[2]->{'package'};
11407: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11408: if (defined($token->[2]->{'id'})) {
11409: $keyroot.='_'.$token->[2]->{'id'};
11410: }
1.599 albertel 11411: if ($metaentry{':packages'}) {
11412: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11413: } else {
1.599 albertel 11414: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11415: }
1.736 albertel 11416: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11417: my $part=$keyroot;
11418: $part=~s/^\_//;
1.736 albertel 11419: if ($pack_entry=~/^\Q$package\E\&/ ||
11420: $pack_entry=~/^\Q$package\E_0\&/) {
11421: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11422: # ignore package.tab specified default values
11423: # here &package_tab_default() will fetch those
11424: if ($subp eq 'default') { next; }
1.736 albertel 11425: my $value=$packagetab{$pack_entry};
1.432 albertel 11426: my $unikey;
11427: if ($pack =~ /_0$/) {
11428: $unikey='parameter_0_'.$name;
11429: $part=0;
11430: } else {
11431: $unikey='parameter'.$keyroot.'_'.$name;
11432: }
1.339 albertel 11433: if ($subp eq 'display') {
11434: $value.=' [Part: '.$part.']';
11435: }
1.599 albertel 11436: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11437: $metathesekeys{$unikey}=1;
1.599 albertel 11438: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11439: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11440: }
1.599 albertel 11441: if (defined($metaentry{':'.$unikey.'.default'})) {
11442: $metaentry{':'.$unikey}=
11443: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11444: }
1.339 albertel 11445: }
11446: }
11447: } else {
1.172 www 11448: #
11449: # This is not a package - some other kind of start tag
1.339 albertel 11450: #
11451: my $entry=$token->[1];
1.1068 www 11452: my $unikey='';
1.175 www 11453:
1.339 albertel 11454: if ($entry eq 'import') {
1.175 www 11455: #
11456: # Importing a library here
1.339 albertel 11457: #
1.1067 www 11458: my $location=$parser->get_text('/import');
11459: my $dir=$filename;
11460: $dir=~s|[^/]*$||;
11461: $location=&filelocation($dir,$location);
1.1172.2.93.4 8(raebur 11462:8):
11463:8): my $importid=$token->[2]->{'id'};
1.1068 www 11464: my $importmode=$token->[2]->{'importmode'};
1.1172.2.93.4 8(raebur 11465:8): #
11466:8): # Check metadata for imported file to
11467:8): # see if it contained response items
11468:8): #
9(raebur 11469:8): my %currmetaentry = %metaentry;
8(raebur 11470:8): my $libresponseorder = &metadata($location,'responseorder');
11471:8): my $origfile;
11472:8): if ($libresponseorder ne '') {
11473:8): if ($#origfiletagids<0) {
11474:8): undef(%importedrespids);
11475:8): undef(%importedpartids);
11476:8): }
11477:8): @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11478:8): if (@{$importedrespids{$importid}} > 0) {
11479:8): $importedresponses = 1;
11480:8): # We need to get the original file and the imported file to get the response order correct
11481:8): # Load and inspect original file
11482:8): if ($#origfiletagids<0) {
11483:8): my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11484:8): $origfile=&getfile($origfilelocation);
11485:8): @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11486:8): }
11487:8): }
11488:8): }
9(raebur 11489:8): # Do not overwrite contents of %metaentry hash for resource itself with
11490:8): # hash populated for imported library file
11491:8): %metaentry = %currmetaentry;
11492:8): undef(%currmetaentry);
1.1068 www 11493: if ($importmode eq 'problem') {
1.1069 www 11494: # Import as problem/response
1.1068 www 11495: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11496: } elsif ($importmode eq 'part') {
11497: # Import as part(s)
1.1069 www 11498: $importedparts=1;
11499: # We need to get the original file and the imported file to get the part order correct
11500: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.93.4 8(raebur 11501:8): # Load and inspect original file if we didn't do that already
9(raebur 11502:8): if ($#origfiletagids<0) {
8(raebur 11503:8): undef(%importedrespids);
11504:8): undef(%importedpartids);
11505:8): if ($origfile eq '') {
11506:8): my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11507:8): $origfile=&getfile($origfilelocation);
11508:8): @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11509:8): }
1.1070 www 11510: }
11511:
1.1069 www 11512: # Load and inspect imported file
11513: my $impfile=&getfile($location);
11514: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11515: if ($#impfilepartids>=0) {
11516: # This problem had parts
1.1070 www 11517: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11518: } else {
11519: # Importing by turning a single problem into a problem part
11520: # It gets the import-tags ID as part-ID
11521: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11522: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11523: }
1.1068 www 11524: } else {
11525: # Normal import
11526: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11527: if (defined($token->[2]->{'id'})) {
11528: $unikey.='_'.$token->[2]->{'id'};
11529: }
1.1067 www 11530: }
11531:
1.339 albertel 11532: if ($depthcount<20) {
1.736 albertel 11533: my $metadata =
11534: &metadata($uri,'keys', $location,$unikey,
11535: $depthcount+1);
11536: foreach my $meta (split(',',$metadata)) {
11537: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11538: $metathesekeys{$meta}=1;
1.339 albertel 11539: }
1.1068 www 11540:
11541: }
1.1067 www 11542: } else {
11543: #
11544: # Not importing, some other kind of non-package, non-library start tag
11545: #
11546: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11547: if (defined($token->[2]->{'id'})) {
11548: $unikey.='_'.$token->[2]->{'id'};
11549: }
1.339 albertel 11550: if (defined($token->[2]->{'name'})) {
11551: $unikey.='_'.$token->[2]->{'name'};
11552: }
11553: $metathesekeys{$unikey}=1;
1.736 albertel 11554: foreach my $param (@{$token->[3]}) {
11555: $metaentry{':'.$unikey.'.'.$param} =
11556: $token->[2]->{$param};
1.339 albertel 11557: }
11558: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11559: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11560: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11561: # only ws inside the tag, and not in default, so use default
11562: # as value
1.599 albertel 11563: $metaentry{':'.$unikey}=$default;
1.908 albertel 11564: } elsif ( $internaltext =~ /\S/ ) {
11565: # something interesting inside the tag
11566: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11567: } else {
1.908 albertel 11568: # no interesting values, don't set a default
1.339 albertel 11569: }
1.172 www 11570: # end of not-a-package not-a-library import
1.339 albertel 11571: }
1.172 www 11572: # end of not-a-package start tag
1.339 albertel 11573: }
1.172 www 11574: # the next is the end of "start tag"
1.339 albertel 11575: }
11576: }
1.483 albertel 11577: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11578: $extension = lc($extension);
11579: if ($extension eq 'htm') { $extension='html'; }
11580:
1.737 albertel 11581: foreach my $key (keys(%packagetab)) {
1.483 albertel 11582: #no specific packages #how's our extension
11583: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11584: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11585: \%metathesekeys);
11586: }
1.883 albertel 11587:
11588: if (!exists($metaentry{':packages'})
11589: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11590: foreach my $key (keys(%packagetab)) {
1.483 albertel 11591: #no specific packages well let's get default then
11592: if ($key!~/^default&/) { next; }
1.488 albertel 11593: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11594: \%metathesekeys);
11595: }
11596: }
1.338 www 11597: # are there custom rights to evaluate
1.599 albertel 11598: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11599:
1.338 www 11600: #
11601: # Importing a rights file here
1.339 albertel 11602: #
11603: unless ($depthcount) {
1.599 albertel 11604: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11605: my $dir=$filename;
11606: $dir=~s|[^/]*$||;
11607: $location=&filelocation($dir,$location);
1.736 albertel 11608: my $rights_metadata =
11609: &metadata($uri,'keys',$location,'_rights',
11610: $depthcount+1);
11611: foreach my $rights (split(',',$rights_metadata)) {
11612: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11613: $metathesekeys{$rights}=1;
1.339 albertel 11614: }
11615: }
11616: }
1.737 albertel 11617: # uniqifiy package listing
11618: my %seen;
11619: my @uniq_packages =
11620: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11621: $metaentry{':packages'} = join(',',@uniq_packages);
11622:
1.1172.2.93.4 8(raebur 11623:8): if (($importedresponses) || ($importedparts)) {
11624:8): if ($importedparts) {
1.1070 www 11625: # We had imported parts and need to rebuild partorder
1.1172.2.93.4 8(raebur 11626:8): $metaentry{':partorder'}='';
11627:8): $metathesekeys{'partorder'}=1;
11628:8): }
11629:8): if ($importedresponses) {
11630:8): # We had imported responses and need to rebuild responseorder
11631:8): $metaentry{':responseorder'}='';
11632:8): $metathesekeys{'responseorder'}=1;
11633:8): }
11634:8): for (my $index=0;$index<$#origfiletagids;$index+=2) {
11635:8): my $origid = $origfiletagids[$index+1];
11636:8): if ($origfiletagids[$index] eq 'part') {
11637:8): # Original part, part of the problem
11638:8): if ($importedparts) {
11639:8): $metaentry{':partorder'}.=','.$origid;
11640:8): }
11641:8): } elsif ($origfiletagids[$index] eq 'import') {
11642:8): if ($importedparts) {
11643:8): # We have imported parts at this position
11644:8): $metaentry{':partorder'}.=','.$importedpartids{$origid};
11645:8): }
11646:8): if ($importedresponses) {
11647:8): # We have imported responses at this position
11648:8): if (ref($importedrespids{$origid}) eq 'ARRAY') {
11649:8): $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
11650:8): }
11651:8): }
11652:8): } else {
11653:8): # Original response item, part of the problem
11654:8): if ($importedresponses) {
11655:8): $metaentry{':responseorder'}.=','.$origid;
11656:8): }
11657:8): }
11658:8): }
11659:8): if ($importedparts) {
11660:8): $metaentry{':partorder'}=~s/^\,//;
11661:8): }
11662:8): if ($importedresponses) {
11663:8): $metaentry{':responseorder'}=~s/^\,//;
11664:8): }
1.1070 www 11665: }
11666:
1.737 albertel 11667: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11668: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 11669: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11670: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11671: # this is the end of "was not already recently cached
1.71 www 11672: }
1.599 albertel 11673: return $metaentry{':'.$what};
1.261 albertel 11674: }
11675:
1.488 albertel 11676: sub metadata_create_package_def {
1.483 albertel 11677: my ($uri,$key,$package,$metathesekeys)=@_;
11678: my ($pack,$name,$subp)=split(/\&/,$key);
11679: if ($subp eq 'default') { next; }
11680:
1.599 albertel 11681: if (defined($metaentry{':packages'})) {
11682: $metaentry{':packages'}.=','.$package;
1.483 albertel 11683: } else {
1.599 albertel 11684: $metaentry{':packages'}=$package;
1.483 albertel 11685: }
11686: my $value=$packagetab{$key};
11687: my $unikey;
11688: $unikey='parameter_0_'.$name;
1.599 albertel 11689: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11690: $$metathesekeys{$unikey}=1;
1.599 albertel 11691: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11692: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11693: }
1.599 albertel 11694: if (defined($metaentry{':'.$unikey.'.default'})) {
11695: $metaentry{':'.$unikey}=
11696: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11697: }
11698: }
11699:
1.261 albertel 11700: sub metadata_generate_part0 {
11701: my ($metadata,$metacache,$uri) = @_;
11702: my %allnames;
1.737 albertel 11703: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11704: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11705: my $part=$$metacache{':'.$metakey.'.part'};
11706: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11707: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11708: $allnames{$name}=$part;
11709: }
11710: }
11711: }
11712: foreach my $name (keys(%allnames)) {
11713: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11714: my $key=":parameter_0_$name";
1.261 albertel 11715: $$metacache{"$key.part"}='0';
11716: $$metacache{"$key.name"}=$name;
1.428 albertel 11717: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11718: $allnames{$name}.'_'.$name.
11719: '.type'};
1.428 albertel 11720: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11721: '.display'};
1.644 www 11722: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11723: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11724: $$metacache{"$key.display"}=$olddis;
11725: }
1.71 www 11726: }
11727:
1.764 albertel 11728: # ------------------------------------------------------ Devalidate title cache
11729:
11730: sub devalidate_title_cache {
11731: my ($url)=@_;
11732: if (!$env{'request.course.id'}) { return; }
11733: my $symb=&symbread($url);
11734: if (!$symb) { return; }
11735: my $key=$env{'request.course.id'}."\0".$symb;
11736: &devalidate_cache_new('title',$key);
11737: }
11738:
1.1014 droeschl 11739: # ------------------------------------------------- Get the title of a course
11740:
11741: sub current_course_title {
11742: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11743: }
1.301 www 11744: # ------------------------------------------------- Get the title of a resource
11745:
11746: sub gettitle {
11747: my $urlsymb=shift;
11748: my $symb=&symbread($urlsymb);
1.534 albertel 11749: if ($symb) {
1.620 albertel 11750: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11751: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11752: if (defined($cached)) {
11753: return $result;
11754: }
1.534 albertel 11755: my ($map,$resid,$url)=&decode_symb($symb);
11756: my $title='';
1.907 albertel 11757: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11758: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11759: } else {
11760: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11761: &GDBM_READER(),0640)) {
11762: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11763: $title=$bighash{'title_'.$mapid.'.'.$resid};
11764: untie(%bighash);
11765: }
1.534 albertel 11766: }
11767: $title=~s/\&colon\;/\:/gs;
11768: if ($title) {
1.1159 www 11769: # Remember both $symb and $title for dynamic metadata
11770: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11771: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11772: # Cache this title and then return it
1.599 albertel 11773: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11774: }
11775: $urlsymb=$url;
11776: }
11777: my $title=&metadata($urlsymb,'title');
11778: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11779: return $title;
1.301 www 11780: }
1.613 albertel 11781:
1.614 albertel 11782: sub get_slot {
11783: my ($which,$cnum,$cdom)=@_;
11784: if (!$cnum || !$cdom) {
1.790 albertel 11785: (undef,my $courseid)=&whichuser();
1.620 albertel 11786: $cdom=$env{'course.'.$courseid.'.domain'};
11787: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11788: }
1.703 albertel 11789: my $key=join("\0",'slots',$cdom,$cnum,$which);
11790: my %slotinfo;
11791: if (exists($remembered{$key})) {
11792: $slotinfo{$which} = $remembered{$key};
11793: } else {
11794: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11795: &Apache::lonhomework::showhash(%slotinfo);
11796: my ($tmp)=keys(%slotinfo);
11797: if ($tmp=~/^error:/) { return (); }
11798: $remembered{$key} = $slotinfo{$which};
11799: }
1.616 albertel 11800: if (ref($slotinfo{$which}) eq 'HASH') {
11801: return %{$slotinfo{$which}};
11802: }
11803: return $slotinfo{$which};
1.614 albertel 11804: }
1.1150 raeburn 11805:
11806: sub get_reservable_slots {
11807: my ($cnum,$cdom,$uname,$udom) = @_;
11808: my $now = time;
11809: my $reservable_info;
11810: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11811: if (exists($remembered{$key})) {
11812: $reservable_info = $remembered{$key};
11813: } else {
11814: my %resv;
11815: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11816: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11817: $reservable_info = \%resv;
11818: $remembered{$key} = $reservable_info;
11819: }
11820: return $reservable_info;
11821: }
11822:
11823: sub get_course_slots {
11824: my ($cnum,$cdom) = @_;
11825: my $hashid=$cnum.':'.$cdom;
11826: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11827: if (defined($cached)) {
11828: if (ref($result) eq 'HASH') {
11829: return %{$result};
11830: }
11831: } else {
11832: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11833: my ($tmp) = keys(%slots);
11834: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11835: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11836: return %slots;
11837: }
11838: }
11839: return;
11840: }
11841:
11842: sub devalidate_slots_cache {
11843: my ($cnum,$cdom)=@_;
11844: my $hashid=$cnum.':'.$cdom;
11845: &devalidate_cache_new('allslots',$hashid);
11846: }
11847:
1.1172.2.8 raeburn 11848: sub get_coursechange {
11849: my ($cdom,$cnum) = @_;
11850: if ($cdom eq '' || $cnum eq '') {
11851: return unless ($env{'request.course.id'});
11852: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11853: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11854: }
11855: my $hashid=$cdom.'_'.$cnum;
11856: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11857: if ((defined($cached)) && ($change ne '')) {
11858: return $change;
11859: } else {
11860: my %crshash;
11861: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11862: if ($crshash{'internal.contentchange'} eq '') {
11863: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11864: if ($change eq '') {
11865: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11866: $change = $crshash{'internal.created'};
11867: }
11868: } else {
11869: $change = $crshash{'internal.contentchange'};
11870: }
11871: my $cachetime = 600;
11872: &do_cache_new('crschange',$hashid,$change,$cachetime);
11873: }
11874: return $change;
11875: }
11876:
11877: sub devalidate_coursechange_cache {
11878: my ($cnum,$cdom)=@_;
11879: my $hashid=$cnum.':'.$cdom;
11880: &devalidate_cache_new('crschange',$hashid);
11881: }
11882:
1.31 www 11883: # ------------------------------------------------- Update symbolic store links
11884:
11885: sub symblist {
11886: my ($mapname,%newhash)=@_;
1.438 www 11887: $mapname=&deversion(&declutter($mapname));
1.31 www 11888: my %hash;
1.620 albertel 11889: if (($env{'request.course.fn'}) && (%newhash)) {
11890: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11891: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11892: foreach my $url (keys(%newhash)) {
1.711 albertel 11893: next if ($url eq 'last_known'
11894: && $env{'form.no_update_last_known'});
11895: $hash{declutter($url)}=&encode_symb($mapname,
11896: $newhash{$url}->[1],
11897: $newhash{$url}->[0]);
1.191 harris41 11898: }
1.31 www 11899: if (untie(%hash)) {
11900: return 'ok';
11901: }
11902: }
11903: }
11904: return 'error';
1.212 www 11905: }
11906:
11907: # --------------------------------------------------------------- Verify a symb
11908:
11909: sub symbverify {
1.1172.2.11 raeburn 11910: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11911: my $thisfn=$thisurl;
1.439 www 11912: $thisfn=&declutter($thisfn);
1.215 www 11913: # direct jump to resource in page or to a sequence - will construct own symbs
11914: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11915: # check URL part
1.409 www 11916: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11917:
1.431 www 11918: unless ($url eq $thisfn) { return 0; }
1.213 www 11919:
1.216 www 11920: $symb=&symbclean($symb);
1.510 www 11921: $thisurl=&deversion($thisurl);
1.439 www 11922: $thisfn=&deversion($thisfn);
1.213 www 11923:
11924: my %bighash;
11925: my $okay=0;
1.431 www 11926:
1.620 albertel 11927: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11928: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11929: my $noclutter;
1.1032 raeburn 11930: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11931: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11932: if ($map =~ m{^uploaded/.+\.page$}) {
11933: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11934: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11935: $noclutter = 1;
11936: }
11937: }
11938: my $ids;
11939: if ($noclutter) {
11940: $ids=$bighash{'ids_'.$thisurl};
11941: } else {
11942: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11943: }
1.1102 raeburn 11944: unless ($ids) {
1.1172.2.13 raeburn 11945: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11946: $ids=$bighash{$idkey};
1.216 www 11947: }
11948: if ($ids) {
11949: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11950: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11951: $symb =~ s/\?.+$//;
11952: }
1.800 albertel 11953: foreach my $id (split(/\,/,$ids)) {
11954: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11955: if (
11956: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11957: eq $symb) {
1.1172.2.11 raeburn 11958: if (ref($encstate)) {
11959: $$encstate = $bighash{'encrypted_'.$id};
11960: }
1.1172.2.13 raeburn 11961: if (($env{'request.role.adv'}) ||
11962: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11963: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11964: $okay=1;
11965: last;
11966: }
11967: }
11968: }
1.216 www 11969: }
1.213 www 11970: untie(%bighash);
11971: }
11972: return $okay;
1.31 www 11973: }
11974:
1.210 www 11975: # --------------------------------------------------------------- Clean-up symb
11976:
11977: sub symbclean {
11978: my $symb=shift;
1.568 albertel 11979: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11980: # remove version from map
11981: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11982:
1.210 www 11983: # remove version from URL
11984: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11985:
1.507 www 11986: # remove wrapper
11987:
1.510 www 11988: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11989: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11990: return $symb;
1.409 www 11991: }
11992:
11993: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11994:
11995: sub encode_symb {
11996: my ($map,$resid,$url)=@_;
11997: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11998: }
1.409 www 11999:
12000: sub decode_symb {
1.568 albertel 12001: my $symb=shift;
12002: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12003: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12004: return (&fixversion($map),$resid,&fixversion($url));
12005: }
12006:
12007: sub fixversion {
12008: my $fn=shift;
1.609 banghart 12009: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12010: my %bighash;
12011: my $uri=&clutter($fn);
1.620 albertel 12012: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12013: # is this cached?
1.599 albertel 12014: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12015: if (defined($cached)) { return $result; }
12016: # unfortunately not cached, or expired
1.620 albertel 12017: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12018: &GDBM_READER(),0640)) {
12019: if ($bighash{'version_'.$uri}) {
12020: my $version=$bighash{'version_'.$uri};
1.444 www 12021: unless (($version eq 'mostrecent') ||
12022: ($version==&getversion($uri))) {
1.440 www 12023: $uri=~s/\.(\w+)$/\.$version\.$1/;
12024: }
12025: }
12026: untie %bighash;
1.413 www 12027: }
1.599 albertel 12028: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12029: }
12030:
12031: sub deversion {
12032: my $url=shift;
12033: $url=~s/\.\d+\.(\w+)$/\.$1/;
12034: return $url;
1.210 www 12035: }
12036:
1.31 www 12037: # ------------------------------------------------------ Return symb list entry
12038:
12039: sub symbread {
1.1172.2.66 raeburn 12040: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 12041: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 12042: if (defined($env{$cache_str})) {
12043: if ($ignorecachednull) {
12044: return $env{$cache_str} unless ($env{$cache_str} eq '');
12045: } else {
12046: return $env{$cache_str};
12047: }
12048: }
1.242 www 12049: # no filename provided? try from environment
1.1172.2.54 raeburn 12050: unless ($thisfn) {
1.620 albertel 12051: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 12052: return $env{$cache_str}=&symbclean($env{'request.symb'});
12053: }
12054: $thisfn=$env{'request.filename'};
1.44 www 12055: }
1.569 albertel 12056: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12057: # is that filename actually a symb? Verify, clean, and return
12058: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12059: if (&symbverify($thisfn,$1)) {
1.620 albertel 12060: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12061: }
1.242 www 12062: }
1.44 www 12063: $thisfn=declutter($thisfn);
1.31 www 12064: my %hash;
1.37 www 12065: my %bighash;
12066: my $syval='';
1.620 albertel 12067: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12068: my $targetfn = $thisfn;
1.609 banghart 12069: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12070: $targetfn = 'adm/wrapper/'.$thisfn;
12071: }
1.687 albertel 12072: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12073: $targetfn=$1;
12074: }
1.620 albertel 12075: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12076: &GDBM_READER(),0640)) {
1.481 raeburn 12077: $syval=$hash{$targetfn};
1.37 www 12078: untie(%hash);
12079: }
12080: # ---------------------------------------------------------- There was an entry
12081: if ($syval) {
1.601 albertel 12082: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12083: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12084: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12085: #return $env{$cache_str}='';
1.601 albertel 12086: #}
12087: #$syval.=$1;
12088: #}
1.37 www 12089: } else {
12090: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12091: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12092: &GDBM_READER(),0640)) {
1.37 www 12093: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12094: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12095: unless ($ids) {
12096: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12097: }
12098: unless ($ids) {
12099: # alias?
12100: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12101: }
1.37 www 12102: if ($ids) {
12103: # ------------------------------------------------------------------- Has ID(s)
12104: my @possibilities=split(/\,/,$ids);
1.39 www 12105: if ($#possibilities==0) {
12106: # ----------------------------------------------- There is only one possibility
1.37 www 12107: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12108: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12109: $resid,$thisfn);
1.1172.2.66 raeburn 12110: if (ref($possibles) eq 'HASH') {
12111: $possibles->{$syval} = 1;
12112: }
12113: if ($checkforblock) {
12114: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12115: if (@blockers) {
12116: $syval = '';
12117: return;
12118: }
12119: }
12120: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12121: # ------------------------------------------ There is more than one possibility
12122: my $realpossible=0;
1.800 albertel 12123: foreach my $id (@possibilities) {
12124: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12125: my $canaccess;
12126: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12127: $canaccess = 1;
12128: } else {
12129: $canaccess = &allowed('bre',$file);
12130: }
12131: if ($canaccess) {
12132: my ($mapid,$resid)=split(/\./,$id);
12133: if ($bighash{'map_type_'.$mapid} ne 'page') {
12134: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12135: $resid,$thisfn);
12136: if (ref($possibles) eq 'HASH') {
12137: $possibles->{$syval} = 1;
12138: }
12139: if ($checkforblock) {
12140: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12141: unless (@blockers > 0) {
12142: $syval = $poss_syval;
12143: $realpossible++;
12144: }
12145: } else {
12146: $syval = $poss_syval;
12147: $realpossible++;
12148: }
12149: }
1.39 www 12150: }
1.191 harris41 12151: }
1.39 www 12152: if ($realpossible!=1) { $syval=''; }
1.249 www 12153: } else {
12154: $syval='';
1.37 www 12155: }
12156: }
1.1172.2.66 raeburn 12157: untie(%bighash);
1.481 raeburn 12158: }
1.31 www 12159: }
1.62 www 12160: if ($syval) {
1.620 albertel 12161: return $env{$cache_str}=$syval;
1.62 www 12162: }
1.31 www 12163: }
1.949 raeburn 12164: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12165: return $env{$cache_str}='';
1.31 www 12166: }
12167:
12168: # ---------------------------------------------------------- Return random seed
12169:
1.32 www 12170: sub numval {
12171: my $txt=shift;
12172: $txt=~tr/A-J/0-9/;
12173: $txt=~tr/a-j/0-9/;
12174: $txt=~tr/K-T/0-9/;
12175: $txt=~tr/k-t/0-9/;
12176: $txt=~tr/U-Z/0-5/;
12177: $txt=~tr/u-z/0-5/;
12178: $txt=~s/\D//g;
1.564 albertel 12179: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12180: return int($txt);
1.368 albertel 12181: }
12182:
1.484 albertel 12183: sub numval2 {
12184: my $txt=shift;
12185: $txt=~tr/A-J/0-9/;
12186: $txt=~tr/a-j/0-9/;
12187: $txt=~tr/K-T/0-9/;
12188: $txt=~tr/k-t/0-9/;
12189: $txt=~tr/U-Z/0-5/;
12190: $txt=~tr/u-z/0-5/;
12191: $txt=~s/\D//g;
12192: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12193: my $total;
12194: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12195: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12196: return int($total);
12197: }
12198:
1.575 albertel 12199: sub numval3 {
12200: use integer;
12201: my $txt=shift;
12202: $txt=~tr/A-J/0-9/;
12203: $txt=~tr/a-j/0-9/;
12204: $txt=~tr/K-T/0-9/;
12205: $txt=~tr/k-t/0-9/;
12206: $txt=~tr/U-Z/0-5/;
12207: $txt=~tr/u-z/0-5/;
12208: $txt=~s/\D//g;
12209: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12210: my $total;
12211: foreach my $val (@txts) { $total+=$val; }
12212: if ($_64bit) { $total=(($total<<32)>>32); }
12213: return $total;
12214: }
12215:
1.675 albertel 12216: sub digest {
12217: my ($data)=@_;
12218: my $digest=&Digest::MD5::md5($data);
12219: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12220: my ($e,$f);
12221: {
12222: use integer;
12223: $e=($a+$b);
12224: $f=($c+$d);
12225: if ($_64bit) {
12226: $e=(($e<<32)>>32);
12227: $f=(($f<<32)>>32);
12228: }
12229: }
12230: if (wantarray) {
12231: return ($e,$f);
12232: } else {
12233: my $g;
12234: {
12235: use integer;
12236: $g=($e+$f);
12237: if ($_64bit) {
12238: $g=(($g<<32)>>32);
12239: }
12240: }
12241: return $g;
12242: }
12243: }
12244:
1.368 albertel 12245: sub latest_rnd_algorithm_id {
1.675 albertel 12246: return '64bit5';
1.366 albertel 12247: }
1.32 www 12248:
1.503 albertel 12249: sub get_rand_alg {
12250: my ($courseid)=@_;
1.790 albertel 12251: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12252: if ($courseid) {
1.620 albertel 12253: return $env{"course.$courseid.rndseed"};
1.503 albertel 12254: }
12255: return &latest_rnd_algorithm_id();
12256: }
12257:
1.562 albertel 12258: sub validCODE {
12259: my ($CODE)=@_;
12260: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12261: return 0;
12262: }
12263:
1.491 albertel 12264: sub getCODE {
1.620 albertel 12265: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12266: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12267: defined($Apache::lonhomework::parsing_a_task) ) &&
12268: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12269: return $Apache::lonhomework::history{'resource.CODE'};
12270: }
12271: return undef;
12272: }
1.1133 foxr 12273: #
12274: # Determines the random seed for a specific context:
12275: #
12276: # parameters:
12277: # symb - in course context the symb for the seed.
12278: # course_id - The course id of the form domain_coursenum.
12279: # domain - Domain for the user.
12280: # course - Course for the user.
12281: # cenv - environment of the course.
12282: #
12283: # NOTE:
12284: # All parameters are picked out of the environment if missing
12285: # or not defined.
12286: # If a symb cannot be determined the current time is used instead.
12287: #
12288: # For a given well defined symb, courside, domain, username,
12289: # and course environment, the seed is reproducible.
12290: #
1.31 www 12291: sub rndseed {
1.1133 foxr 12292: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12293: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12294: if (!defined($symb)) {
1.366 albertel 12295: unless ($symb=$wsymb) { return time; }
12296: }
1.1146 foxr 12297: if (!defined $courseid) {
12298: $courseid=$wcourseid;
12299: }
12300: if (!defined $domain) { $domain=$wdomain; }
12301: if (!defined $username) { $username=$wusername }
1.1133 foxr 12302:
12303: my $which;
12304: if (defined($cenv->{'rndseed'})) {
12305: $which = $cenv->{'rndseed'};
12306: } else {
12307: $which =&get_rand_alg($courseid);
12308: }
1.491 albertel 12309: if (defined(&getCODE())) {
1.675 albertel 12310: if ($which eq '64bit5') {
12311: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12312: } elsif ($which eq '64bit4') {
1.575 albertel 12313: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12314: } else {
12315: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12316: }
1.675 albertel 12317: } elsif ($which eq '64bit5') {
12318: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12319: } elsif ($which eq '64bit4') {
12320: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12321: } elsif ($which eq '64bit3') {
12322: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12323: } elsif ($which eq '64bit2') {
12324: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12325: } elsif ($which eq '64bit') {
12326: return &rndseed_64bit($symb,$courseid,$domain,$username);
12327: }
12328: return &rndseed_32bit($symb,$courseid,$domain,$username);
12329: }
12330:
12331: sub rndseed_32bit {
12332: my ($symb,$courseid,$domain,$username)=@_;
12333: {
12334: use integer;
12335: my $symbchck=unpack("%32C*",$symb) << 27;
12336: my $symbseed=numval($symb) << 22;
12337: my $namechck=unpack("%32C*",$username) << 17;
12338: my $nameseed=numval($username) << 12;
12339: my $domainseed=unpack("%32C*",$domain) << 7;
12340: my $courseseed=unpack("%32C*",$courseid);
12341: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12342: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12343: #&logthis("rndseed :$num:$symb");
1.564 albertel 12344: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12345: return $num;
12346: }
12347: }
12348:
12349: sub rndseed_64bit {
12350: my ($symb,$courseid,$domain,$username)=@_;
12351: {
12352: use integer;
12353: my $symbchck=unpack("%32S*",$symb) << 21;
12354: my $symbseed=numval($symb) << 10;
12355: my $namechck=unpack("%32S*",$username);
12356:
12357: my $nameseed=numval($username) << 21;
12358: my $domainseed=unpack("%32S*",$domain) << 10;
12359: my $courseseed=unpack("%32S*",$courseid);
12360:
12361: my $num1=$symbchck+$symbseed+$namechck;
12362: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12363: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12364: #&logthis("rndseed :$num:$symb");
1.564 albertel 12365: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12366: return "$num1,$num2";
1.155 albertel 12367: }
1.366 albertel 12368: }
12369:
1.443 albertel 12370: sub rndseed_64bit2 {
12371: my ($symb,$courseid,$domain,$username)=@_;
12372: {
12373: use integer;
12374: # strings need to be an even # of cahracters long, it it is odd the
12375: # last characters gets thrown away
12376: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12377: my $symbseed=numval($symb) << 10;
12378: my $namechck=unpack("%32S*",$username.' ');
12379:
12380: my $nameseed=numval($username) << 21;
1.501 albertel 12381: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12382: my $courseseed=unpack("%32S*",$courseid.' ');
12383:
12384: my $num1=$symbchck+$symbseed+$namechck;
12385: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12386: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12387: #&logthis("rndseed :$num:$symb");
1.803 albertel 12388: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12389: return "$num1,$num2";
12390: }
12391: }
12392:
12393: sub rndseed_64bit3 {
12394: my ($symb,$courseid,$domain,$username)=@_;
12395: {
12396: use integer;
12397: # strings need to be an even # of cahracters long, it it is odd the
12398: # last characters gets thrown away
12399: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12400: my $symbseed=numval2($symb) << 10;
12401: my $namechck=unpack("%32S*",$username.' ');
12402:
12403: my $nameseed=numval2($username) << 21;
1.443 albertel 12404: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12405: my $courseseed=unpack("%32S*",$courseid.' ');
12406:
12407: my $num1=$symbchck+$symbseed+$namechck;
12408: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12409: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12410: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12411: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12412:
1.503 albertel 12413: return "$num1:$num2";
1.443 albertel 12414: }
12415: }
12416:
1.575 albertel 12417: sub rndseed_64bit4 {
12418: my ($symb,$courseid,$domain,$username)=@_;
12419: {
12420: use integer;
12421: # strings need to be an even # of cahracters long, it it is odd the
12422: # last characters gets thrown away
12423: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12424: my $symbseed=numval3($symb) << 10;
12425: my $namechck=unpack("%32S*",$username.' ');
12426:
12427: my $nameseed=numval3($username) << 21;
12428: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12429: my $courseseed=unpack("%32S*",$courseid.' ');
12430:
12431: my $num1=$symbchck+$symbseed+$namechck;
12432: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12433: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12434: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12435: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12436:
1.575 albertel 12437: return "$num1:$num2";
12438: }
12439: }
12440:
1.675 albertel 12441: sub rndseed_64bit5 {
12442: my ($symb,$courseid,$domain,$username)=@_;
12443: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12444: return "$num1:$num2";
12445: }
12446:
1.366 albertel 12447: sub rndseed_CODE_64bit {
12448: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12449: {
1.366 albertel 12450: use integer;
1.443 albertel 12451: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12452: my $symbseed=numval2($symb);
1.491 albertel 12453: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12454: my $CODEseed=numval(&getCODE());
1.443 albertel 12455: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12456: my $num1=$symbseed+$CODEchck;
12457: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12458: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12459: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12460: if ($_64bit) { $num1=(($num1<<32)>>32); }
12461: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12462: return "$num1:$num2";
1.366 albertel 12463: }
12464: }
12465:
1.575 albertel 12466: sub rndseed_CODE_64bit4 {
12467: my ($symb,$courseid,$domain,$username)=@_;
12468: {
12469: use integer;
12470: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12471: my $symbseed=numval3($symb);
12472: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12473: my $CODEseed=numval3(&getCODE());
12474: my $courseseed=unpack("%32S*",$courseid.' ');
12475: my $num1=$symbseed+$CODEchck;
12476: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12477: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12478: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12479: if ($_64bit) { $num1=(($num1<<32)>>32); }
12480: if ($_64bit) { $num2=(($num2<<32)>>32); }
12481: return "$num1:$num2";
12482: }
12483: }
12484:
1.675 albertel 12485: sub rndseed_CODE_64bit5 {
12486: my ($symb,$courseid,$domain,$username)=@_;
12487: my $code = &getCODE();
12488: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12489: return "$num1:$num2";
12490: }
12491:
1.366 albertel 12492: sub setup_random_from_rndseed {
12493: my ($rndseed)=@_;
1.503 albertel 12494: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 12495: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12496: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12497: &Math::Random::random_set_seed_from_phrase($rndseed);
12498: } else {
12499: &Math::Random::random_set_seed($num1,$num2);
12500: }
1.366 albertel 12501: } else {
12502: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12503: }
1.36 albertel 12504: }
12505:
1.474 albertel 12506: sub latest_receipt_algorithm_id {
1.835 albertel 12507: return 'receipt3';
1.474 albertel 12508: }
12509:
1.480 www 12510: sub recunique {
12511: my $fucourseid=shift;
12512: my $unique;
1.835 albertel 12513: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12514: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12515: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12516: } else {
12517: $unique=$perlvar{'lonReceipt'};
12518: }
12519: return unpack("%32C*",$unique);
12520: }
12521:
12522: sub recprefix {
12523: my $fucourseid=shift;
12524: my $prefix;
1.835 albertel 12525: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12526: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12527: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12528: } else {
12529: $prefix=$perlvar{'lonHostID'};
12530: }
12531: return unpack("%32C*",$prefix);
12532: }
12533:
1.76 www 12534: sub ireceipt {
1.474 albertel 12535: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12536:
12537: my $return =&recprefix($fucourseid).'-';
12538:
12539: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12540: $env{'request.state'} eq 'construct') {
12541: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12542: return $return;
12543: }
12544:
1.76 www 12545: my $cuname=unpack("%32C*",$funame);
12546: my $cudom=unpack("%32C*",$fudom);
12547: my $cucourseid=unpack("%32C*",$fucourseid);
12548: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12549: my $cunique=&recunique($fucourseid);
1.474 albertel 12550: my $cpart=unpack("%32S*",$part);
1.835 albertel 12551: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12552:
1.790 albertel 12553: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12554:
12555: $return.= ($cunique%$cuname+
12556: $cunique%$cudom+
12557: $cusymb%$cuname+
12558: $cusymb%$cudom+
12559: $cucourseid%$cuname+
12560: $cucourseid%$cudom+
12561: $cpart%$cuname+
12562: $cpart%$cudom);
12563: } else {
12564: $return.= ($cunique%$cuname+
12565: $cunique%$cudom+
12566: $cusymb%$cuname+
12567: $cusymb%$cudom+
12568: $cucourseid%$cuname+
12569: $cucourseid%$cudom);
12570: }
12571: return $return;
1.76 www 12572: }
12573:
12574: sub receipt {
1.474 albertel 12575: my ($part)=@_;
1.790 albertel 12576: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12577: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12578: }
1.260 ng 12579:
1.790 albertel 12580: sub whichuser {
12581: my ($passedsymb)=@_;
12582: my ($symb,$courseid,$domain,$name,$publicuser);
12583: if (defined($env{'form.grade_symb'})) {
12584: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12585: my $allowed=&allowed('vgr',$tmp_courseid);
12586: if (!$allowed &&
12587: exists($env{'request.course.sec'}) &&
12588: $env{'request.course.sec'} !~ /^\s*$/) {
12589: $allowed=&allowed('vgr',$tmp_courseid.
12590: '/'.$env{'request.course.sec'});
12591: }
12592: if ($allowed) {
12593: ($symb)=&get_env_multiple('form.grade_symb');
12594: $courseid=$tmp_courseid;
12595: ($domain)=&get_env_multiple('form.grade_domain');
12596: ($name)=&get_env_multiple('form.grade_username');
12597: return ($symb,$courseid,$domain,$name,$publicuser);
12598: }
12599: }
12600: if (!$passedsymb) {
12601: $symb=&symbread();
12602: } else {
12603: $symb=$passedsymb;
12604: }
12605: $courseid=$env{'request.course.id'};
12606: $domain=$env{'user.domain'};
12607: $name=$env{'user.name'};
12608: if ($name eq 'public' && $domain eq 'public') {
12609: if (!defined($env{'form.username'})) {
12610: $env{'form.username'}.=time.rand(10000000);
12611: }
12612: $name.=$env{'form.username'};
12613: }
12614: return ($symb,$courseid,$domain,$name,$publicuser);
12615:
12616: }
12617:
1.36 albertel 12618: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12619: # returns either the contents of the file or
12620: # -1 if the file doesn't exist
1.481 raeburn 12621: #
12622: # if the target is a file that was uploaded via DOCS,
12623: # a check will be made to see if a current copy exists on the local server,
12624: # if it does this will be served, otherwise a copy will be retrieved from
12625: # the home server for the course and stored in /home/httpd/html/userfiles on
12626: # the local server.
1.472 albertel 12627:
1.36 albertel 12628: sub getfile {
1.538 albertel 12629: my ($file) = @_;
1.609 banghart 12630: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12631: &repcopy($file);
12632: return &readfile($file);
12633: }
12634:
12635: sub repcopy_userfile {
12636: my ($file)=@_;
1.1142 raeburn 12637: my $londocroot = $perlvar{'lonDocRoot'};
12638: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12639: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12640: my ($cdom,$cnum,$filename) =
1.811 albertel 12641: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12642: my $uri="/uploaded/$cdom/$cnum/$filename";
12643: if (-e "$file") {
1.828 www 12644: # we already have a local copy, check it out
1.538 albertel 12645: my @fileinfo = stat($file);
1.828 www 12646: my $rtncode;
12647: my $info;
1.538 albertel 12648: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12649: if ($lwpresp ne 'ok') {
1.828 www 12650: # there is no such file anymore, even though we had a local copy
1.482 albertel 12651: if ($rtncode eq '404') {
1.538 albertel 12652: unlink($file);
1.482 albertel 12653: }
12654: return -1;
12655: }
12656: if ($info < $fileinfo[9]) {
1.828 www 12657: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12658: return 'ok';
1.828 www 12659: } else {
12660: # the file is outdated, get rid of it
12661: unlink($file);
1.482 albertel 12662: }
1.828 www 12663: }
12664: # one way or the other, at this point, we don't have the file
12665: # construct the correct path for the file
12666: my @parts = ($cdom,$cnum);
12667: if ($filename =~ m|^(.+)/[^/]+$|) {
12668: push @parts, split(/\//,$1);
12669: }
12670: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12671: foreach my $part (@parts) {
12672: $path .= '/'.$part;
12673: if (!-e $path) {
12674: mkdir($path,0770);
1.482 albertel 12675: }
12676: }
1.828 www 12677: # now the path exists for sure
12678: # get a user agent
12679: my $ua=new LWP::UserAgent;
12680: my $transferfile=$file.'.in.transfer';
12681: # FIXME: this should flock
12682: if (-e $transferfile) { return 'ok'; }
12683: my $request;
12684: $uri=~s/^\///;
1.980 raeburn 12685: my $homeserver = &homeserver($cnum,$cdom);
12686: my $protocol = $protocol{$homeserver};
12687: $protocol = 'http' if ($protocol ne 'https');
12688: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12689: my $response=$ua->request($request,$transferfile);
12690: # did it work?
12691: if ($response->is_error()) {
12692: unlink($transferfile);
12693: &logthis("Userfile repcopy failed for $uri");
12694: return -1;
12695: }
12696: # worked, rename the transfer file
12697: rename($transferfile,$file);
1.607 raeburn 12698: return 'ok';
1.481 raeburn 12699: }
12700:
1.517 albertel 12701: sub tokenwrapper {
12702: my $uri=shift;
1.980 raeburn 12703: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12704: $uri=~s|^/||;
1.620 albertel 12705: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12706: my $token=$1;
1.552 albertel 12707: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12708: if ($udom && $uname && $file) {
12709: $file=~s|(\?\.*)*$||;
1.949 raeburn 12710: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12711: my $homeserver = &homeserver($uname,$udom);
12712: my $protocol = $protocol{$homeserver};
12713: $protocol = 'http' if ($protocol ne 'https');
12714: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12715: (($uri=~/\?/)?'&':'?').'token='.$token.
12716: '&tokenissued='.$perlvar{'lonHostID'};
12717: } else {
12718: return '/adm/notfound.html';
12719: }
12720: }
12721:
1.828 www 12722: # call with reqtype HEAD: get last modification time
12723: # call with reqtype GET: get the file contents
12724: # Do not call this with reqtype GET for large files! It loads everything into memory
12725: #
1.481 raeburn 12726: sub getuploaded {
12727: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12728: $uri=~s/^\///;
1.980 raeburn 12729: my $homeserver = &homeserver($cnum,$cdom);
12730: my $protocol = $protocol{$homeserver};
12731: $protocol = 'http' if ($protocol ne 'https');
12732: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12733: my $ua=new LWP::UserAgent;
12734: my $request=new HTTP::Request($reqtype,$uri);
12735: my $response=$ua->request($request);
12736: $$rtncode = $response->code;
1.482 albertel 12737: if (! $response->is_success()) {
12738: return 'failed';
12739: }
12740: if ($reqtype eq 'HEAD') {
1.486 www 12741: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12742: } elsif ($reqtype eq 'GET') {
12743: $$info = $response->content;
1.472 albertel 12744: }
1.482 albertel 12745: return 'ok';
1.36 albertel 12746: }
12747:
1.481 raeburn 12748: sub readfile {
12749: my $file = shift;
12750: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12751: my $fh;
1.1172.2.93.4 7(raebur 12752:7): open($fh,"<",$file);
1.481 raeburn 12753: my $a='';
1.800 albertel 12754: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12755: return $a;
12756: }
12757:
1.36 albertel 12758: sub filelocation {
1.590 banghart 12759: my ($dir,$file) = @_;
12760: my $location;
12761: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12762:
12763: if ($file =~ m-^/adm/-) {
12764: $file=~s-^/adm/wrapper/-/-;
12765: $file=~s-^/adm/coursedocs/showdoc/-/-;
12766: }
1.882 albertel 12767:
1.1139 www 12768: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12769: $location = $file;
1.609 banghart 12770: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12771: my ($udom,$uname,$filename)=
1.811 albertel 12772: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12773: my $home=&homeserver($uname,$udom);
12774: my $is_me=0;
12775: my @ids=¤t_machine_ids();
12776: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12777: if ($is_me) {
1.1117 foxr 12778: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12779: } else {
12780: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12781: $udom.'/'.$uname.'/'.$filename;
12782: }
1.882 albertel 12783: } elsif ($file =~ m-^/adm/-) {
12784: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12785: } else {
12786: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12787: $file=~s:^/(res|priv)/:/:;
12788: my $space=$1;
1.590 banghart 12789: if ( !( $file =~ m:^/:) ) {
12790: $location = $dir. '/'.$file;
12791: } else {
1.1142 raeburn 12792: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12793: }
1.59 albertel 12794: }
1.590 banghart 12795: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12796: while ($location=~m{/\.\./}) {
12797: if ($location =~ m{/[^/]+/\.\./}) {
12798: $location=~ s{/[^/]+/\.\./}{/}g;
12799: } else {
12800: $location=~ s{/\.\./}{/}g;
12801: }
12802: } #remove dir/..
1.590 banghart 12803: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12804: return $location;
1.46 www 12805: }
1.36 albertel 12806:
1.46 www 12807: sub hreflocation {
12808: my ($dir,$file)=@_;
1.980 raeburn 12809: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12810: $file=filelocation($dir,$file);
1.700 albertel 12811: } elsif ($file=~m-^/adm/-) {
12812: $file=~s-^/adm/wrapper/-/-;
12813: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12814: }
12815: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12816: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12817: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12818: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12819: {/uploaded/$1/$2/}x;
1.46 www 12820: }
1.913 albertel 12821: if ($file=~ m{^/userfiles/}) {
12822: $file =~ s{^/userfiles/}{/uploaded/};
12823: }
1.462 albertel 12824: return $file;
1.465 albertel 12825: }
12826:
1.1139 www 12827:
12828:
12829:
12830:
1.465 albertel 12831: sub current_machine_domains {
1.853 albertel 12832: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12833: }
12834:
12835: sub machine_domains {
12836: my ($hostname) = @_;
1.465 albertel 12837: my @domains;
1.838 albertel 12838: my %hostname = &all_hostnames();
1.465 albertel 12839: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12840: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12841: if ($hostname eq $name) {
1.844 albertel 12842: push(@domains,&host_domain($id));
1.465 albertel 12843: }
12844: }
12845: return @domains;
12846: }
12847:
12848: sub current_machine_ids {
1.853 albertel 12849: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12850: }
12851:
12852: sub machine_ids {
12853: my ($hostname) = @_;
12854: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12855: my @ids;
1.888 albertel 12856: my %name_to_host = &all_names();
1.889 albertel 12857: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12858: return @{ $name_to_host{$hostname} };
12859: }
12860: return;
1.31 www 12861: }
12862:
1.824 raeburn 12863: sub additional_machine_domains {
12864: my @domains;
1.1172.2.93.4 7(raebur 12865:7): open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 12866: while( my $line = <$fh>) {
12867: $line =~ s/\s//g;
12868: push(@domains,$line);
12869: }
12870: return @domains;
12871: }
12872:
12873: sub default_login_domain {
12874: my $domain = $perlvar{'lonDefDomain'};
12875: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12876: foreach my $posdom (¤t_machine_domains(),
12877: &additional_machine_domains()) {
12878: if (lc($posdom) eq lc($testdomain)) {
12879: $domain=$posdom;
12880: last;
12881: }
12882: }
12883: return $domain;
12884: }
12885:
1.31 www 12886: # ------------------------------------------------------------- Declutters URLs
12887:
12888: sub declutter {
12889: my $thisfn=shift;
1.569 albertel 12890: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12891: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12892: $thisfn=~s{^/home/httpd/html}{};
12893: }
1.31 www 12894: $thisfn=~s/^\///;
1.697 albertel 12895: $thisfn=~s|^adm/wrapper/||;
12896: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12897: $thisfn=~s/^res\///;
1.1172 bisitz 12898: $thisfn=~s/^priv\///;
1.1032 raeburn 12899: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12900: $thisfn=~s/\?.+$//;
12901: }
1.268 www 12902: return $thisfn;
12903: }
12904:
12905: # ------------------------------------------------------------- Clutter up URLs
12906:
12907: sub clutter {
12908: my $thisfn='/'.&declutter(shift);
1.887 albertel 12909: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12910: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12911: $thisfn='/res'.$thisfn;
12912: }
1.1031 raeburn 12913: if ($thisfn !~m|^/adm|) {
12914: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12915: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12916: } else {
12917: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12918: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12919: if ($embstyle eq 'ssi'
12920: || ($embstyle eq 'hdn')
12921: || ($embstyle eq 'rat')
12922: || ($embstyle eq 'prv')
12923: || ($embstyle eq 'ign')) {
12924: #do nothing with these
12925: } elsif (($embstyle eq 'img')
1.695 albertel 12926: || ($embstyle eq 'emb')
12927: || ($embstyle eq 'wrp')) {
12928: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12929: } elsif ($embstyle eq 'unk'
12930: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12931: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12932: } else {
1.718 www 12933: # &logthis("Got a blank emb style");
1.695 albertel 12934: }
1.694 albertel 12935: }
1.1172.2.93.4 2(raebur 12936:7): } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
12937:7): $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12938: }
1.31 www 12939: return $thisfn;
1.12 www 12940: }
12941:
1.787 albertel 12942: sub clutter_with_no_wrapper {
12943: my $uri = &clutter(shift);
12944: if ($uri =~ m-^/adm/-) {
12945: $uri =~ s-^/adm/wrapper/-/-;
12946: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12947: }
12948: return $uri;
12949: }
12950:
1.557 albertel 12951: sub freeze_escape {
12952: my ($value)=@_;
12953: if (ref($value)) {
12954: $value=&nfreeze($value);
12955: return '__FROZEN__'.&escape($value);
12956: }
12957: return &escape($value);
12958: }
12959:
1.11 www 12960:
1.557 albertel 12961: sub thaw_unescape {
12962: my ($value)=@_;
12963: if ($value =~ /^__FROZEN__/) {
12964: substr($value,0,10,undef);
12965: $value=&unescape($value);
12966: return &thaw($value);
12967: }
12968: return &unescape($value);
12969: }
12970:
1.436 albertel 12971: sub correct_line_ends {
12972: my ($result)=@_;
12973: $$result =~s/\r\n/\n/mg;
12974: $$result =~s/\r/\n/mg;
1.415 albertel 12975: }
1.1 albertel 12976: # ================================================================ Main Program
12977:
1.184 www 12978: sub goodbye {
1.204 albertel 12979: &logthis("Starting Shut down");
1.443 albertel 12980: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12981: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12982: #converted
1.599 albertel 12983: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12984: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12985: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12986: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12987: #1.1 only
1.870 albertel 12988: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12989: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12990: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12991: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12992: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12993: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12994: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12995: &flushcourselogs();
12996: &logthis("Shutting down");
12997: }
12998:
1.852 albertel 12999: sub get_dns {
1.1172.2.17 raeburn 13000: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13001: if (!$ignore_cache) {
13002: my ($content,$cached)=
13003: &Apache::lonnet::is_cached_new('dns',$url);
13004: if ($cached) {
1.1172.2.17 raeburn 13005: &$func($content,$hashref);
1.869 albertel 13006: return;
13007: }
13008: }
13009:
13010: my %alldns;
1.1172.2.93.4 7(raebur 13011:7): open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 13012: foreach my $dns (<$config>) {
13013: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 13014: my $line = $1;
13015: my ($host,$protocol) = split(/:/,$line);
13016: if ($protocol ne 'https') {
13017: $protocol = 'http';
13018: }
13019: $alldns{$host} = $protocol;
1.869 albertel 13020: }
13021: while (%alldns) {
1.1172.2.52 raeburn 13022: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 13023: my $ua=new LWP::UserAgent;
1.1134 raeburn 13024: $ua->timeout(30);
1.979 raeburn 13025: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 13026: my $response=$ua->request($request);
1.979 raeburn 13027: delete($alldns{$dns});
1.852 albertel 13028: next if ($response->is_error());
13029: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 13030: unless ($nocache) {
1.1172.2.23 raeburn 13031: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 13032: }
13033: &$func(\@content,$hashref);
1.869 albertel 13034: return;
1.852 albertel 13035: }
13036: close($config);
1.871 albertel 13037: my $which = (split('/',$url))[3];
13038: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.93.4 7(raebur 13039:7): open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 13040: my @content = <$config>;
1.1172.2.17 raeburn 13041: &$func(\@content,$hashref);
13042: return;
13043: }
13044:
13045: # ------------------------------------------------------Get DNS checksums file
13046: sub parse_dns_checksums_tab {
13047: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 13048: my $lonhost = $perlvar{'lonHostID'};
13049: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 13050: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 13051: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13052: my $webconfdir = '/etc/httpd/conf';
13053: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13054: $webconfdir = '/etc/apache2';
13055: } elsif ($distro =~ /^sles(\d+)$/) {
13056: if ($1 >= 10) {
13057: $webconfdir = '/etc/apache2';
13058: }
13059: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13060: if ($1 >= 10.0) {
13061: $webconfdir = '/etc/apache2';
13062: }
13063: }
1.1172.2.17 raeburn 13064: my ($release,$timestamp) = split(/\-/,$loncaparev);
13065: my (%chksum,%revnum);
13066: if (ref($lines) eq 'ARRAY') {
13067: chomp(@{$lines});
1.1172.2.34 raeburn 13068: my $version = shift(@{$lines});
13069: if ($version eq $release) {
1.1172.2.17 raeburn 13070: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 13071: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 13072: if ($file =~ m{^/etc/httpd/conf}) {
13073: if ($webconfdir eq '/etc/apache2') {
13074: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13075: }
13076: }
1.1172.2.34 raeburn 13077: $chksum{$file} = $shasum;
13078: $revnum{$file} = $version;
1.1172.2.17 raeburn 13079: }
13080: if (ref($hashref) eq 'HASH') {
13081: %{$hashref} = (
13082: sums => \%chksum,
13083: versions => \%revnum,
13084: );
13085: }
13086: }
13087: }
1.869 albertel 13088: return;
1.852 albertel 13089: }
1.1172.2.17 raeburn 13090:
13091: sub fetch_dns_checksums {
13092: my %checksums;
1.1172.2.34 raeburn 13093: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 13094: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 13095: my ($release,$timestamp) = split(/\-/,$loncaparev);
13096: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 13097: \%checksums);
13098: return \%checksums;
13099: }
13100:
1.327 albertel 13101: # ------------------------------------------------------------ Read domain file
13102: {
1.852 albertel 13103: my $loaded;
1.846 albertel 13104: my %domain;
13105:
1.852 albertel 13106: sub parse_domain_tab {
13107: my ($lines) = @_;
13108: foreach my $line (@$lines) {
13109: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13110:
1.846 albertel 13111: chomp($line);
1.852 albertel 13112: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13113: my %this_domain;
13114: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13115: 'lang_def', 'city', 'longi', 'lati',
13116: 'primary') {
13117: $this_domain{$field} = shift(@elements);
13118: }
13119: $domain{$name} = \%this_domain;
1.852 albertel 13120: }
13121: }
1.864 albertel 13122:
13123: sub reset_domain_info {
13124: undef($loaded);
13125: undef(%domain);
13126: }
13127:
1.852 albertel 13128: sub load_domain_tab {
1.1172.2.70 raeburn 13129: my ($ignore_cache,$nocache) = @_;
13130: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13131: my $fh;
1.1172.2.93.4 7(raebur 13132:7): if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 13133: my @lines = <$fh>;
13134: &parse_domain_tab(\@lines);
1.448 albertel 13135: }
1.852 albertel 13136: close($fh);
13137: $loaded = 1;
1.327 albertel 13138: }
1.846 albertel 13139:
13140: sub domain {
1.852 albertel 13141: &load_domain_tab() if (!$loaded);
13142:
1.846 albertel 13143: my ($name,$what) = @_;
13144: return if ( !exists($domain{$name}) );
13145:
13146: if (!$what) {
13147: return $domain{$name}{'description'};
13148: }
13149: return $domain{$name}{$what};
13150: }
1.974 raeburn 13151:
13152: sub domain_info {
13153: &load_domain_tab() if (!$loaded);
13154: return %domain;
13155: }
13156:
1.327 albertel 13157: }
13158:
13159:
1.1 albertel 13160: # ------------------------------------------------------------- Read hosts file
13161: {
1.838 albertel 13162: my %hostname;
1.844 albertel 13163: my %hostdom;
1.845 albertel 13164: my %libserv;
1.852 albertel 13165: my $loaded;
1.888 albertel 13166: my %name_to_host;
1.1074 raeburn 13167: my %internetdom;
1.1107 raeburn 13168: my %LC_dns_serv;
1.852 albertel 13169:
13170: sub parse_hosts_tab {
13171: my ($file) = @_;
13172: foreach my $configline (@$file) {
13173: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13174: chomp($configline);
13175: if ($configline =~ /^\^/) {
13176: if ($configline =~ /^\^([\w.\-]+)/) {
13177: $LC_dns_serv{$1} = 1;
13178: }
13179: next;
13180: }
1.1074 raeburn 13181: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13182: $name=~s/\s//g;
13183: if ($id && $domain && $role && $name) {
1.1172.2.93.4 3(raebur 13184:7): if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13185:7): my $curr = $hostname{$id};
13186:7): my $skip;
13187:7): if (ref($name_to_host{$curr}) eq 'ARRAY') {
13188:7): if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13189:7): $skip = 1;
13190:7): } else {
13191:7): @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13192:7): }
13193:7): }
13194:7): unless ($skip) {
13195:7): push(@{$name_to_host{$name}},$id);
13196:7): }
13197:7): } else {
13198:7): push(@{$name_to_host{$name}},$id);
13199:7): }
1.852 albertel 13200: $hostname{$id}=$name;
13201: $hostdom{$id}=$domain;
13202: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13203: if (defined($protocol)) {
13204: if ($protocol eq 'https') {
13205: $protocol{$id} = $protocol;
13206: } else {
13207: $protocol{$id} = 'http';
13208: }
1.968 raeburn 13209: } else {
1.969 raeburn 13210: $protocol{$id} = 'http';
1.968 raeburn 13211: }
1.1074 raeburn 13212: if (defined($intdom)) {
13213: $internetdom{$id} = $intdom;
13214: }
1.852 albertel 13215: }
13216: }
13217: }
1.864 albertel 13218:
13219: sub reset_hosts_info {
1.897 albertel 13220: &purge_remembered();
1.864 albertel 13221: &reset_domain_info();
13222: &reset_hosts_ip_info();
1.892 albertel 13223: undef(%name_to_host);
1.864 albertel 13224: undef(%hostname);
13225: undef(%hostdom);
13226: undef(%libserv);
13227: undef($loaded);
13228: }
1.1 albertel 13229:
1.852 albertel 13230: sub load_hosts_tab {
1.1172.2.70 raeburn 13231: my ($ignore_cache,$nocache) = @_;
13232: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.93.4 7(raebur 13233:7): open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 13234: my @config = <$config>;
13235: &parse_hosts_tab(\@config);
13236: close($config);
13237: $loaded=1;
1.1 albertel 13238: }
1.852 albertel 13239:
1.838 albertel 13240: sub hostname {
1.852 albertel 13241: &load_hosts_tab() if (!$loaded);
13242:
1.838 albertel 13243: my ($lonid) = @_;
13244: return $hostname{$lonid};
13245: }
1.845 albertel 13246:
1.838 albertel 13247: sub all_hostnames {
1.852 albertel 13248: &load_hosts_tab() if (!$loaded);
13249:
1.838 albertel 13250: return %hostname;
13251: }
1.845 albertel 13252:
1.888 albertel 13253: sub all_names {
1.1172.2.70 raeburn 13254: my ($ignore_cache,$nocache) = @_;
13255: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13256:
13257: return %name_to_host;
13258: }
13259:
1.974 raeburn 13260: sub all_host_domain {
13261: &load_hosts_tab() if (!$loaded);
13262: return %hostdom;
13263: }
13264:
1.845 albertel 13265: sub is_library {
1.852 albertel 13266: &load_hosts_tab() if (!$loaded);
13267:
1.845 albertel 13268: return exists($libserv{$_[0]});
13269: }
13270:
13271: sub all_library {
1.852 albertel 13272: &load_hosts_tab() if (!$loaded);
13273:
1.845 albertel 13274: return %libserv;
13275: }
13276:
1.1062 droeschl 13277: sub unique_library {
13278: #2x reverse removes all hostnames that appear more than once
13279: my %unique = reverse &all_library();
13280: return reverse %unique;
13281: }
13282:
1.841 albertel 13283: sub get_servers {
1.852 albertel 13284: &load_hosts_tab() if (!$loaded);
13285:
1.841 albertel 13286: my ($domain,$type) = @_;
13287: my %possible_hosts = ($type eq 'library') ? %libserv
13288: : %hostname;
13289: my %result;
1.842 albertel 13290: if (ref($domain) eq 'ARRAY') {
13291: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13292: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13293: $result{$host} = $hostname;
13294: }
13295: }
13296: } else {
13297: while ( my ($host,$hostname) = each(%possible_hosts)) {
13298: if ($hostdom{$host} eq $domain) {
13299: $result{$host} = $hostname;
13300: }
1.841 albertel 13301: }
13302: }
13303: return %result;
13304: }
1.845 albertel 13305:
1.1062 droeschl 13306: sub get_unique_servers {
13307: my %unique = reverse &get_servers(@_);
13308: return reverse %unique;
13309: }
13310:
1.844 albertel 13311: sub host_domain {
1.852 albertel 13312: &load_hosts_tab() if (!$loaded);
13313:
1.844 albertel 13314: my ($lonid) = @_;
13315: return $hostdom{$lonid};
13316: }
13317:
1.841 albertel 13318: sub all_domains {
1.852 albertel 13319: &load_hosts_tab() if (!$loaded);
13320:
1.841 albertel 13321: my %seen;
13322: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13323: return @uniq;
13324: }
1.1074 raeburn 13325:
13326: sub internet_dom {
13327: &load_hosts_tab() if (!$loaded);
13328:
13329: my ($lonid) = @_;
13330: return $internetdom{$lonid};
13331: }
1.1107 raeburn 13332:
13333: sub is_LC_dns {
13334: &load_hosts_tab() if (!$loaded);
13335:
13336: my ($hostname) = @_;
13337: return exists($LC_dns_serv{$hostname});
13338: }
13339:
1.1 albertel 13340: }
13341:
1.847 albertel 13342: {
13343: my %iphost;
1.856 albertel 13344: my %name_to_ip;
13345: my %lonid_to_ip;
1.869 albertel 13346:
1.847 albertel 13347: sub get_hosts_from_ip {
13348: my ($ip) = @_;
13349: my %iphosts = &get_iphost();
13350: if (ref($iphosts{$ip})) {
13351: return @{$iphosts{$ip}};
13352: }
13353: return;
1.839 albertel 13354: }
1.864 albertel 13355:
13356: sub reset_hosts_ip_info {
13357: undef(%iphost);
13358: undef(%name_to_ip);
13359: undef(%lonid_to_ip);
13360: }
1.856 albertel 13361:
13362: sub get_host_ip {
13363: my ($lonid) = @_;
13364: if (exists($lonid_to_ip{$lonid})) {
13365: return $lonid_to_ip{$lonid};
13366: }
13367: my $name=&hostname($lonid);
13368: my $ip = gethostbyname($name);
13369: return if (!$ip || length($ip) ne 4);
13370: $ip=inet_ntoa($ip);
13371: $name_to_ip{$name} = $ip;
13372: $lonid_to_ip{$lonid} = $ip;
13373: return $ip;
13374: }
1.847 albertel 13375:
13376: sub get_iphost {
1.1172.2.70 raeburn 13377: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13378:
1.869 albertel 13379: if (!$ignore_cache) {
13380: if (%iphost) {
13381: return %iphost;
13382: }
13383: my ($ip_info,$cached)=
13384: &Apache::lonnet::is_cached_new('iphost','iphost');
13385: if ($cached) {
13386: %iphost = %{$ip_info->[0]};
13387: %name_to_ip = %{$ip_info->[1]};
13388: %lonid_to_ip = %{$ip_info->[2]};
13389: return %iphost;
13390: }
13391: }
1.894 albertel 13392:
13393: # get yesterday's info for fallback
13394: my %old_name_to_ip;
13395: my ($ip_info,$cached)=
13396: &Apache::lonnet::is_cached_new('iphost','iphost');
13397: if ($cached) {
13398: %old_name_to_ip = %{$ip_info->[1]};
13399: }
13400:
1.1172.2.70 raeburn 13401: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13402: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13403: my $ip;
13404: if (!exists($name_to_ip{$name})) {
13405: $ip = gethostbyname($name);
13406: if (!$ip || length($ip) ne 4) {
1.894 albertel 13407: if (defined($old_name_to_ip{$name})) {
13408: $ip = $old_name_to_ip{$name};
13409: &logthis("Can't find $name defaulting to old $ip");
13410: } else {
13411: &logthis("Name $name no IP found");
13412: next;
13413: }
13414: } else {
13415: $ip=inet_ntoa($ip);
1.847 albertel 13416: }
13417: $name_to_ip{$name} = $ip;
13418: } else {
13419: $ip = $name_to_ip{$name};
1.653 albertel 13420: }
1.888 albertel 13421: foreach my $id (@{ $name_to_host{$name} }) {
13422: $lonid_to_ip{$id} = $ip;
13423: }
13424: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13425: }
1.1172.2.70 raeburn 13426: unless ($nocache) {
13427: &do_cache_new('iphost','iphost',
13428: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13429: 48*60*60);
13430: }
1.869 albertel 13431:
1.847 albertel 13432: return %iphost;
1.598 albertel 13433: }
13434:
1.992 raeburn 13435: #
13436: # Given a DNS returns the loncapa host name for that DNS
13437: #
13438: sub host_from_dns {
13439: my ($dns) = @_;
13440: my @hosts;
13441: my $ip;
13442:
1.993 raeburn 13443: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13444: $ip = $name_to_ip{$dns};
13445: }
13446: if (!$ip) {
13447: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13448: if (length($ip) == 4) {
13449: $ip = &IO::Socket::inet_ntoa($ip);
13450: }
13451: }
13452: if ($ip) {
13453: @hosts = get_hosts_from_ip($ip);
13454: return $hosts[0];
13455: }
13456: return undef;
1.986 foxr 13457: }
1.992 raeburn 13458:
1.1074 raeburn 13459: sub get_internet_names {
13460: my ($lonid) = @_;
13461: return if ($lonid eq '');
13462: my ($idnref,$cached)=
13463: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13464: if ($cached) {
13465: return $idnref;
13466: }
13467: my $ip = &get_host_ip($lonid);
13468: my @hosts = &get_hosts_from_ip($ip);
13469: my %iphost = &get_iphost();
13470: my (@idns,%seen);
13471: foreach my $id (@hosts) {
13472: my $dom = &host_domain($id);
13473: my $prim_id = &domain($dom,'primary');
13474: my $prim_ip = &get_host_ip($prim_id);
13475: next if ($seen{$prim_ip});
13476: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13477: foreach my $id (@{$iphost{$prim_ip}}) {
13478: my $intdom = &internet_dom($id);
13479: unless (grep(/^\Q$intdom\E$/,@idns)) {
13480: push(@idns,$intdom);
13481: }
13482: }
13483: }
13484: $seen{$prim_ip} = 1;
13485: }
1.1172.2.23 raeburn 13486: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13487: }
13488:
1.986 foxr 13489: }
13490:
1.1079 raeburn 13491: sub all_loncaparevs {
1.1172.2.39 raeburn 13492: 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 13493: }
13494:
1.1172.2.27 raeburn 13495: # ------------------------------------------------------- Read loncaparev table
13496: {
13497: sub load_loncaparevs {
13498: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.93.4 7(raebur 13499:7): if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 13500: while (my $configline=<$config>) {
13501: chomp($configline);
13502: my ($hostid,$loncaparev)=split(/:/,$configline);
13503: $loncaparevs{$hostid}=$loncaparev;
13504: }
13505: close($config);
13506: }
13507: }
13508: }
13509: }
13510:
13511: # ----------------------------------------------------- Read serverhostID table
13512: {
13513: sub load_serverhomeIDs {
13514: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.93.4 7(raebur 13515:7): if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 13516: while (my $configline=<$config>) {
13517: chomp($configline);
13518: my ($name,$id)=split(/:/,$configline);
13519: $serverhomeIDs{$name}=$id;
13520: }
13521: close($config);
13522: }
13523: }
13524: }
13525: }
13526:
13527:
1.862 albertel 13528: BEGIN {
13529:
13530: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13531: unless ($readit) {
13532: {
13533: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13534: %perlvar = (%perlvar,%{$configvars});
13535: }
13536:
13537:
1.1 albertel 13538: # ------------------------------------------------------ Read spare server file
13539: {
1.1172.2.93.4 7(raebur 13540:7): open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13541:
13542: while (my $configline=<$config>) {
13543: chomp($configline);
1.284 matthew 13544: if ($configline) {
1.784 albertel 13545: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13546: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13547: push(@{ $spareid{$type} }, $host);
1.1 albertel 13548: }
13549: }
1.448 albertel 13550: close($config);
1.1 albertel 13551: }
1.11 www 13552: # ------------------------------------------------------------ Read permissions
13553: {
1.1172.2.93.4 7(raebur 13554:7): open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13555:
13556: while (my $configline=<$config>) {
1.448 albertel 13557: chomp($configline);
13558: if ($configline) {
13559: my ($role,$perm)=split(/ /,$configline);
13560: if ($perm ne '') { $pr{$role}=$perm; }
13561: }
1.11 www 13562: }
1.448 albertel 13563: close($config);
1.11 www 13564: }
13565:
13566: # -------------------------------------------- Read plain texts for permissions
13567: {
1.1172.2.93.4 7(raebur 13568:7): open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13569:
13570: while (my $configline=<$config>) {
1.448 albertel 13571: chomp($configline);
13572: if ($configline) {
1.742 raeburn 13573: my ($short,@plain)=split(/:/,$configline);
13574: %{$prp{$short}} = ();
13575: if (@plain > 0) {
13576: $prp{$short}{'std'} = $plain[0];
13577: for (my $i=1; $i<@plain; $i++) {
13578: $prp{$short}{'alt'.$i} = $plain[$i];
13579: }
13580: }
1.448 albertel 13581: }
1.135 www 13582: }
1.448 albertel 13583: close($config);
1.135 www 13584: }
13585:
13586: # ---------------------------------------------------------- Read package table
13587: {
1.1172.2.93.4 7(raebur 13588:7): open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13589:
13590: while (my $configline=<$config>) {
1.483 albertel 13591: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13592: chomp($configline);
13593: my ($short,$plain)=split(/:/,$configline);
13594: my ($pack,$name)=split(/\&/,$short);
13595: if ($plain ne '') {
13596: $packagetab{$pack.'&'.$name.'&name'}=$name;
13597: $packagetab{$short}=$plain;
13598: }
1.11 www 13599: }
1.448 albertel 13600: close($config);
1.329 matthew 13601: }
13602:
1.1172.2.27 raeburn 13603: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 13604:
1.1172.2.27 raeburn 13605: &load_loncaparevs();
13606:
13607: # ------------------------------------------------------- Read serverhostID table
13608:
13609: &load_serverhomeIDs();
1.1074 raeburn 13610:
1.1172.2.27 raeburn 13611: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13612: {
13613: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13614: if (-e $file) {
13615: my $parser = HTML::LCParser->new($file);
13616: while (my $token = $parser->get_token()) {
13617: if ($token->[0] eq 'S') {
13618: my $item = $token->[1];
13619: my $name = $token->[2]{'name'};
13620: my $value = $token->[2]{'value'};
13621: if ($item ne '' && $name ne '' && $value ne '') {
13622: my $release = $parser->get_text();
13623: $release =~ s/(^\s*|\s*$ )//gx;
13624: $needsrelease{$item.':'.$name.':'.$value} = $release;
13625: }
13626: }
13627: }
13628: }
1.1073 raeburn 13629: }
13630:
1.1138 raeburn 13631: # ---------------------------------------------------------- Read managers table
13632: {
13633: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.93.4 7(raebur 13634:7): if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 13635: while (my $configline=<$config>) {
13636: chomp($configline);
13637: next if ($configline =~ /^\#/);
13638: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13639: $managerstab{$configline} = 1;
13640: }
13641: }
13642: close($config);
13643: }
13644: }
13645: }
13646:
1.329 matthew 13647: # ------------- set up temporary directory
13648: {
1.1117 foxr 13649: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13650:
1.11 www 13651: }
13652:
1.794 albertel 13653: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13654: 'compress_threshold'=> 20_000,
13655: });
1.185 www 13656:
1.281 www 13657: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13658: $dumpcount=0;
1.958 www 13659: $locknum=0;
1.22 www 13660:
1.163 harris41 13661: &logtouch();
1.672 albertel 13662: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13663: $readit=1;
1.564 albertel 13664: {
13665: use integer;
13666: my $test=(2**32)+1;
1.568 albertel 13667: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13668: &logthis(" Detected 64bit platform ($_64bit)");
13669: }
1.195 www 13670: }
1.1 albertel 13671: }
1.179 www 13672:
1.1 albertel 13673: 1;
1.191 harris41 13674: __END__
13675:
1.243 albertel 13676: =pod
13677:
1.191 harris41 13678: =head1 NAME
13679:
1.243 albertel 13680: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13681:
13682: =head1 SYNOPSIS
13683:
1.243 albertel 13684: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13685:
13686: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13687:
1.243 albertel 13688: Common parameters:
13689:
13690: =over 4
13691:
13692: =item *
13693:
13694: $uname : an internal username (if $cname expecting a course Id specifically)
13695:
13696: =item *
13697:
13698: $udom : a domain (if $cdom expecting a course's domain specifically)
13699:
13700: =item *
13701:
13702: $symb : a resource instance identifier
13703:
13704: =item *
13705:
13706: $namespace : the name of a .db file that contains the data needed or
13707: being set.
13708:
13709: =back
13710:
1.394 bowersj2 13711: =head1 OVERVIEW
1.191 harris41 13712:
1.394 bowersj2 13713: lonnet provides subroutines which interact with the
13714: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13715: about classes, users, and resources.
1.243 albertel 13716:
13717: For many of these objects you can also use this to store data about
13718: them or modify them in various ways.
1.191 harris41 13719:
1.394 bowersj2 13720: =head2 Symbs
1.191 harris41 13721:
1.394 bowersj2 13722: To identify a specific instance of a resource, LON-CAPA uses symbols
13723: or "symbs"X<symb>. These identifiers are built from the URL of the
13724: map, the resource number of the resource in the map, and the URL of
13725: the resource itself. The latter is somewhat redundant, but might help
13726: if maps change.
13727:
13728: An example is
13729:
13730: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13731:
13732: The respective map entry is
13733:
13734: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13735: title="Problem 2">
13736: </resource>
13737:
13738: Symbs are used by the random number generator, as well as to store and
13739: restore data specific to a certain instance of for example a problem.
13740:
13741: =head2 Storing And Retrieving Data
13742:
13743: X<store()>X<cstore()>X<restore()>Three of the most important functions
13744: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13745: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13746: is is the non-critical message twin of cstore. These functions are for
13747: handlers to store a perl hash to a user's permanent data space in an
13748: easy manner, and to retrieve it again on another call. It is expected
13749: that a handler would use this once at the beginning to retrieve data,
13750: and then again once at the end to send only the new data back.
13751:
13752: The data is stored in the user's data directory on the user's
13753: homeserver under the ID of the course.
13754:
13755: The hash that is returned by restore will have all of the previous
13756: value for all of the elements of the hash.
13757:
13758: Example:
13759:
13760: #creating a hash
13761: my %hash;
13762: $hash{'foo'}='bar';
13763:
13764: #storing it
13765: &Apache::lonnet::cstore(\%hash);
13766:
13767: #changing a value
13768: $hash{'foo'}='notbar';
13769:
13770: #adding a new value
13771: $hash{'bar'}='foo';
13772: &Apache::lonnet::cstore(\%hash);
13773:
13774: #retrieving the hash
13775: my %history=&Apache::lonnet::restore();
13776:
13777: #print the hash
13778: foreach my $key (sort(keys(%history))) {
13779: print("\%history{$key} = $history{$key}");
13780: }
13781:
13782: Will print out:
1.191 harris41 13783:
1.394 bowersj2 13784: %history{1:foo} = bar
13785: %history{1:keys} = foo:timestamp
13786: %history{1:timestamp} = 990455579
13787: %history{2:bar} = foo
13788: %history{2:foo} = notbar
13789: %history{2:keys} = foo:bar:timestamp
13790: %history{2:timestamp} = 990455580
13791: %history{bar} = foo
13792: %history{foo} = notbar
13793: %history{timestamp} = 990455580
13794: %history{version} = 2
13795:
13796: Note that the special hash entries C<keys>, C<version> and
13797: C<timestamp> were added to the hash. C<version> will be equal to the
13798: total number of versions of the data that have been stored. The
13799: C<timestamp> attribute will be the UNIX time the hash was
13800: stored. C<keys> is available in every historical section to list which
13801: keys were added or changed at a specific historical revision of a
13802: hash.
13803:
13804: B<Warning>: do not store the hash that restore returns directly. This
13805: will cause a mess since it will restore the historical keys as if the
13806: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13807:
1.394 bowersj2 13808: Calling convention:
1.191 harris41 13809:
1.1172.2.27 raeburn 13810: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 13811: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13812:
1.394 bowersj2 13813: For more detailed information, see lonnet specific documentation.
1.191 harris41 13814:
1.394 bowersj2 13815: =head1 RETURN MESSAGES
1.191 harris41 13816:
1.394 bowersj2 13817: =over 4
1.191 harris41 13818:
1.394 bowersj2 13819: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13820:
1.394 bowersj2 13821: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13822: when the connection is brought back up
1.191 harris41 13823:
1.394 bowersj2 13824: =item * B<con_failed>: unable to contact remote host and unable to save message
13825: for later delivery
1.191 harris41 13826:
1.967 bisitz 13827: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13828:
1.394 bowersj2 13829: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13830: that was requested
1.191 harris41 13831:
1.243 albertel 13832: =back
1.191 harris41 13833:
1.243 albertel 13834: =head1 PUBLIC SUBROUTINES
1.191 harris41 13835:
1.243 albertel 13836: =head2 Session Environment Functions
1.191 harris41 13837:
1.243 albertel 13838: =over 4
1.191 harris41 13839:
1.394 bowersj2 13840: =item *
13841: X<appenv()>
1.949 raeburn 13842: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13843: the user envirnoment file, and will be restored for each access this
1.620 albertel 13844: user makes during this session, also modifies the %env for the current
1.949 raeburn 13845: process. Optional rolesarrayref - if defined contains a reference to an array
13846: of roles which are exempt from the restriction on modifying user.role entries
13847: in the user's environment.db and in %env.
1.191 harris41 13848:
13849: =item *
1.394 bowersj2 13850: X<delenv()>
1.987 raeburn 13851: B<delenv($delthis,$regexp)>: removes all items from the session
13852: environment file that begin with $delthis. If the
13853: optional second arg - $regexp - is true, $delthis is treated as a
13854: regular expression, otherwise \Q$delthis\E is used.
13855: The values are also deleted from the current processes %env.
1.191 harris41 13856:
1.795 albertel 13857: =item * get_env_multiple($name)
13858:
13859: gets $name from the %env hash, it seemlessly handles the cases where multiple
13860: values may be defined and end up as an array ref.
13861:
13862: returns an array of values
13863:
1.243 albertel 13864: =back
13865:
13866: =head2 User Information
1.191 harris41 13867:
1.243 albertel 13868: =over 4
1.191 harris41 13869:
13870: =item *
1.394 bowersj2 13871: X<queryauthenticate()>
13872: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13873: authentication scheme
13874:
13875: =item *
1.394 bowersj2 13876: X<authenticate()>
1.1073 raeburn 13877: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13878: authenticate user from domain's lib servers (first use the current
13879: one). C<$upass> should be the users password.
1.1073 raeburn 13880: $checkdefauth is optional (value is 1 if a check should be made to
13881: authenticate user using default authentication method, and allow
13882: account creation if username does not have account in the domain).
13883: $clientcancheckhost is optional (value is 1 if checking whether the
13884: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13885:
13886: =item *
1.394 bowersj2 13887: X<homeserver()>
13888: B<homeserver($uname,$udom)>: find the server which has
13889: the user's directory and files (there must be only one), this caches
13890: the answer, and also caches if there is a borken connection.
1.191 harris41 13891:
13892: =item *
1.394 bowersj2 13893: X<idget()>
13894: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13895: (IDs are a unique resource in a domain, there must be only 1 ID per
13896: username, and only 1 username per ID in a specific domain) (returns
13897: hash: id=>name,id=>name)
1.191 harris41 13898:
13899: =item *
1.394 bowersj2 13900: X<idrget()>
13901: B<idrget($udom,@unames)>: find the IDs behind a list of
13902: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13903:
13904: =item *
1.394 bowersj2 13905: X<idput()>
13906: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13907:
13908: =item *
1.394 bowersj2 13909: X<rolesinit()>
1.1169 droeschl 13910: B<rolesinit($udom,$username)>: get user privileges.
13911: returns user role, first access and timer interval hashes
1.243 albertel 13912:
13913: =item *
1.1171 droeschl 13914: X<privileged()>
13915: B<privileged($username,$domain)>: returns a true if user has a
13916: privileged and active role (i.e. su or dc), false otherwise.
13917:
13918: =item *
1.551 albertel 13919: X<getsection()>
13920: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13921: course $cname, return section name/number or '' for "not in course"
13922: and '-1' for "no section"
13923:
13924: =item *
1.394 bowersj2 13925: X<userenvironment()>
13926: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13927: passed in @what from the requested user's environment, returns a hash
13928:
1.858 raeburn 13929: =item *
13930: X<userlog_query()>
1.859 albertel 13931: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13932: activity.log file. %filters defines filters applied when parsing the
13933: log file. These can be start or end timestamps, or the type of action
13934: - log to look for Login or Logout events, check for Checkin or
13935: Checkout, role for role selection. The response is in the form
13936: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13937: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13938:
1.243 albertel 13939: =back
13940:
13941: =head2 User Roles
13942:
13943: =over 4
13944:
13945: =item *
13946:
1.1172.2.65 raeburn 13947: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13948: returns codes for allowed actions.
13949:
13950: The first argument is required, all others are optional.
13951:
13952: $priv is the privilege being checked.
13953: $uri contains additional information about what is being checked for access (e.g.,
13954: URL, course ID etc.).
13955: $symb is the unique resource instance identifier in a course; if needed,
13956: but not provided, it will be retrieved via a call to &symbread().
13957: $role is the role for which a priv is being checked (only used if priv is evb).
13958: $clientip is the user's IP address (only used when checking for access to portfolio
13959: files).
13960: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13961: prevents recursive calls to &allowed.
13962:
1.243 albertel 13963: F: full access
13964: U,I,K: authentication modes (cxx only)
13965: '': forbidden
13966: 1: user needs to choose course
13967: 2: browse allowed
1.766 albertel 13968: A: passphrase authentication needed
1.1172.2.65 raeburn 13969: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13970:
13971: =item *
13972:
1.1172.2.13 raeburn 13973: constructaccess($url,$setpriv) : check for access to construction space URL
13974:
13975: See if the owner domain and name in the URL match those in the
13976: expected environment. If so, return three element list
13977: ($ownername,$ownerdomain,$ownerhome).
13978:
13979: Otherwise return the null string.
13980:
13981: If second argument 'setpriv' is true, it assigns the privileges,
13982: and returns the same three element list, unless the owner has
13983: blocked "ad hoc" Domain Coordinator access to the Author Space,
13984: in which case the null string is returned.
13985:
13986: =item *
13987:
1.1172.2.84 raeburn 13988: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13989: define a custom role rolename set privileges in format of lonTabs/roles.tab
13990: for system, domain, and course level. $uname and $udom are optional (current
13991: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13992:
13993: =item *
13994:
1.988 raeburn 13995: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13996: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13997: $type is Course (default) or Community.
1.988 raeburn 13998: If $forcedefault evaluates to true, text returned will be default
13999: text for $type. Otherwise, if this is a course, the text returned
14000: will be a custom name for the role (if defined in the course's
14001: environment). If no custom name is defined the default is returned.
14002:
1.832 raeburn 14003: =item *
14004:
1.1172.2.23 raeburn 14005: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14006: All arguments are optional. Returns a hash of a roles, either for
14007: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14008: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14009: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14010: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14011: For each key, value is set to colon-separated start and end times for
14012: the role. If no username and domain are specified, will default to
1.934 raeburn 14013: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14014: of role statuses (active, future or previous), roles
14015: (e.g., cc,in, st etc.) and domains of the roles which can be used
14016: to restrict the list of roles reported. If no array ref is
14017: provided for types, will default to return only active roles.
1.834 albertel 14018:
1.1172.2.13 raeburn 14019: =item *
14020:
14021: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14022: user: $uname:$udom has a role in the course: $cdom_$cnum.
14023:
14024: Additional optional arguments are: $type (if role checking is to be restricted
14025: to certain user status types -- previous (expired roles), active (currently
14026: available roles) or future (roles available in the future), and
14027: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 14028: have active Domain Coordinator role in course's domain or in additional
14029: domains (specified in 'Domains to check for privileged users' in course
14030: environment -- set via: Course Settings -> Classlists and staff listing).
14031:
14032: =item *
14033:
14034: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14035: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14036: $possdomains and $possroles are optional array refs -- to domains to check and
14037: roles to check. If $possdomains is not specified, a dump will be done of the
14038: users' roles.db to check for a dc or su role in any domain. This can be
14039: time consuming if &privileged is called repeatedly (e.g., when displaying a
14040: classlist), so in such cases, supplying a $possdomains array is preferred, as
14041: this then allows &privileged_by_domain() to be used, which caches the identity
14042: of privileged users, eliminating the need for repeated calls to &dump().
14043:
14044: =item *
14045:
14046: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14047: where the outer hash keys are domains specified in the $possdomains array ref,
14048: next inner hash keys are privileged roles specified in the $roles array ref,
14049: and the innermost hash contains key = value pairs for username:domain = end:start
14050: for active or future "privileged" users with that role in that domain. To avoid
14051: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14052: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 14053:
1.243 albertel 14054: =back
14055:
14056: =head2 User Modification
14057:
14058: =over 4
14059:
14060: =item *
14061:
1.957 raeburn 14062: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14063: user for the level given by URL. Optional start and end dates (leave empty
14064: string or zero for "no date")
1.191 harris41 14065:
14066: =item *
14067:
1.243 albertel 14068: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14069: change a users, password, possible return values are: ok,
14070: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14071: refused
1.191 harris41 14072:
14073: =item *
14074:
1.243 albertel 14075: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14076:
14077: =item *
14078:
1.1058 raeburn 14079: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14080: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14081:
14082: will update user information (firstname,middlename,lastname,generation,
14083: permanentemail), and if forceid is true, student/employee ID also.
14084: A user's institutional affiliation(s) can also be updated.
14085: User information fields will not be overwritten with empty entries
14086: unless the field is included in the $candelete array reference.
14087: This array is included when a single user is modified via "Manage Users",
14088: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14089:
14090: =item *
14091:
1.286 matthew 14092: modifystudent
14093:
1.957 raeburn 14094: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 14095: The course id is resolved based on the current user's environment.
14096: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14097: associated with a course.
14098:
1.297 matthew 14099: This call is essentially a wrapper for lonnet::modifyuser and
14100: lonnet::modify_student_enrollment
1.286 matthew 14101:
14102: Inputs:
14103:
14104: =over 4
14105:
1.957 raeburn 14106: =item B<$udom> Student's loncapa domain
1.286 matthew 14107:
1.957 raeburn 14108: =item B<$uname> Student's loncapa login name
1.286 matthew 14109:
1.964 bisitz 14110: =item B<$uid> Student/Employee ID
1.286 matthew 14111:
1.957 raeburn 14112: =item B<$umode> Student's authentication mode
1.286 matthew 14113:
1.957 raeburn 14114: =item B<$upass> Student's password
1.286 matthew 14115:
1.957 raeburn 14116: =item B<$first> Student's first name
1.286 matthew 14117:
1.957 raeburn 14118: =item B<$middle> Student's middle name
1.286 matthew 14119:
1.957 raeburn 14120: =item B<$last> Student's last name
1.286 matthew 14121:
1.957 raeburn 14122: =item B<$gene> Student's generation
1.286 matthew 14123:
1.957 raeburn 14124: =item B<$usec> Student's section in course
1.286 matthew 14125:
14126: =item B<$end> Unix time of the roles expiration
14127:
14128: =item B<$start> Unix time of the roles start date
14129:
14130: =item B<$forceid> If defined, allow $uid to be changed
14131:
14132: =item B<$desiredhome> server to use as home server for student
14133:
1.957 raeburn 14134: =item B<$email> Student's permanent e-mail address
14135:
14136: =item B<$type> Type of enrollment (auto or manual)
14137:
1.963 raeburn 14138: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14139:
14140: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14141:
1.963 raeburn 14142: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14143:
1.963 raeburn 14144: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14145:
1.1172.2.19 raeburn 14146: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14147:
14148: =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 14149:
1.286 matthew 14150: =back
1.297 matthew 14151:
14152: =item *
14153:
14154: modify_student_enrollment
14155:
1.1172.2.31 raeburn 14156: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14157: 'role.request.course' must be defined for this function to proceed.
14158:
14159: Inputs:
14160:
14161: =over 4
14162:
1.1172.2.31 raeburn 14163: =item $udom, student's domain
1.297 matthew 14164:
1.1172.2.31 raeburn 14165: =item $uname, student's name
1.297 matthew 14166:
1.1172.2.31 raeburn 14167: =item $uid, student's user id
1.297 matthew 14168:
1.1172.2.31 raeburn 14169: =item $first, student's first name
1.297 matthew 14170:
14171: =item $middle
14172:
14173: =item $last
14174:
14175: =item $gene
14176:
14177: =item $usec
14178:
14179: =item $end
14180:
14181: =item $start
14182:
1.957 raeburn 14183: =item $type
14184:
14185: =item $locktype
14186:
14187: =item $cid
14188:
14189: =item $selfenroll
14190:
14191: =item $context
14192:
1.1172.2.19 raeburn 14193: =item $credits, number of credits student will earn from this class
14194:
1.1172.2.76 raeburn 14195: =item $instsec, institutional course section code for student
14196:
1.297 matthew 14197: =back
14198:
1.191 harris41 14199:
14200: =item *
14201:
1.243 albertel 14202: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14203: custom role; give a custom role to a user for the level given by URL. Specify
14204: name and domain of role author, and role name
1.191 harris41 14205:
14206: =item *
14207:
1.243 albertel 14208: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14209:
14210: =item *
14211:
1.243 albertel 14212: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14213:
14214: =back
14215:
14216: =head2 Course Infomation
14217:
14218: =over 4
1.191 harris41 14219:
14220: =item *
14221:
1.1118 foxr 14222: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14223: specified course id, including all environment settings for the
14224: course, the description of the course will be in the hash under the
14225: key 'description'
1.191 harris41 14226:
1.1118 foxr 14227: $options is an optional parameter that if supplied is a hash reference that controls
14228: what how this function works. It has the following key/values:
14229:
14230: =over 4
14231:
14232: =item freshen_cache
14233:
14234: If defined, and the environment cache for the course is valid, it is
14235: returned in the returned hash.
14236:
14237: =item one_time
14238:
14239: If defined, the last cache time is set to _now_
14240:
14241: =item user
14242:
14243: If defined, the supplied username is used instead of the current user.
14244:
14245:
14246: =back
14247:
1.191 harris41 14248: =item *
14249:
1.624 albertel 14250: resdata($name,$domain,$type,@which) : request for current parameter
14251: setting for a specific $type, where $type is either 'course' or 'user',
14252: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 14253: answers for 10 minutes.
1.243 albertel 14254:
1.877 foxr 14255: =item *
14256:
14257: get_courseresdata($courseid, $domain) : dump the entire course resource
14258: data base, returning a hash that is keyed by the resource name and has
14259: values that are the resource value. I believe that the timestamps and
14260: versions are also returned.
14261:
1.1172.2.31 raeburn 14262: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14263: supplemental content area. This routine caches the number of files for
14264: 10 minutes.
14265:
1.243 albertel 14266: =back
14267:
14268: =head2 Course Modification
14269:
14270: =over 4
1.191 harris41 14271:
14272: =item *
14273:
1.243 albertel 14274: writecoursepref($courseid,%prefs) : write preferences (environment
14275: database) for a course
1.191 harris41 14276:
14277: =item *
14278:
1.1011 raeburn 14279: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14280:
14281: =item *
14282:
1.1038 raeburn 14283: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14284:
1.1167 droeschl 14285: =item *
14286:
14287: is_course($courseid), is_course($cdom, $cnum)
14288:
14289: Accepts either a combined $courseid (in the form of domain_courseid) or the
14290: two component version $cdom, $cnum. It checks if the specified course exists.
14291:
14292: Returns:
14293: undef if the course doesn't exist, otherwise
14294: in scalar context the combined courseid.
14295: in list context the two components of the course identifier, domain and
14296: courseid.
14297:
1.243 albertel 14298: =back
14299:
1.1172.2.93.4 12(raebu 14300:19): =head2 Bubblesheet Configuration
14301:19):
14302:19): =over 4
14303:19):
14304:19): =item *
14305:19):
14306:19): get_scantron_config($which)
14307:19):
14308:19): $which - the name of the configuration to parse from the file.
14309:19):
14310:19): Parses and returns the bubblesheet configuration line selected as a
14311:19): hash of configuration file fields.
14312:19):
14313:19):
14314:19): Returns:
14315:19): If the named configuration is not in the file, an empty
14316:19): hash is returned.
14317:19):
14318:19): a hash with the fields
14319:19): name - internal name for the this configuration setup
14320:19): description - text to display to operator that describes this config
14321:19): CODElocation - if 0 or the string 'none'
14322:19): - no CODE exists for this config
14323:19): if -1 || the string 'letter'
14324:19): - a CODE exists for this config and is
14325:19): a string of letters
14326:19): Unsupported value (but planned for future support)
14327:19): if a positive integer
14328:19): - The CODE exists as the first n items from
14329:19): the question section of the form
14330:19): if the string 'number'
14331:19): - The CODE exists for this config and is
14332:19): a string of numbers
14333:19): CODEstart - (only matter if a CODE exists) column in the line where
14334:19): the CODE starts
14335:19): CODElength - length of the CODE
14336:19): IDstart - column where the student/employee ID starts
14337:19): IDlength - length of the student/employee ID info
14338:19): Qstart - column where the information from the bubbled
14339:19): 'questions' start
14340:19): Qlength - number of columns comprising a single bubble line from
14341:19): the sheet. (usually either 1 or 10)
14342:19): Qon - either a single character representing the character used
14343:19): to signal a bubble was chosen in the positional setup, or
14344:19): the string 'letter' if the letter of the chosen bubble is
14345:19): in the final, or 'number' if a number representing the
14346:19): chosen bubble is in the file (1->A 0->J)
14347:19): Qoff - the character used to represent that a bubble was
14348:19): left blank
14349:19): PaperID - if the scanning process generates a unique number for each
14350:19): sheet scanned the column that this ID number starts in
14351:19): PaperIDlength - number of columns that comprise the unique ID number
14352:19): for the sheet of paper
14353:19): FirstName - column that the first name starts in
14354:19): FirstNameLength - number of columns that the first name spans
14355:19): LastName - column that the last name starts in
14356:19): LastNameLength - number of columns that the last name spans
14357:19): BubblesPerRow - number of bubbles available in each row used to
14358:19): bubble an answer. (If not specified, 10 assumed).
14359:19):
14360:19):
14361:19): =item *
14362:19):
14363:19): get_scantronformat_file($cdom)
14364:19):
14365:19): $cdom - the course's domain (optional); if not supplied, uses
14366:19): domain for current $env{'request.course.id'}.
14367:19):
14368:19): Returns an array containing lines from the scantron format file for
14369:19): the domain of the course.
14370:19):
14371:19): If a url for a custom.tab file is listed in domain's configuration.db,
14372:19): lines are from this file.
14373:19):
14374:19): Otherwise, if a default.tab has been published in RES space by the
14375:19): domainconfig user, lines are from this file.
14376:19):
14377:19): Otherwise, fall back to getting lines from the legacy file on the
14378:19): local server: /home/httpd/lonTabs/default_scantronformat.tab
14379:19):
14380:19): =back
14381:19):
1.243 albertel 14382: =head2 Resource Subroutines
14383:
14384: =over 4
1.191 harris41 14385:
14386: =item *
14387:
1.243 albertel 14388: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14389:
14390: =item *
14391:
1.243 albertel 14392: repcopy($filename) : subscribes to the requested file, and attempts to
14393: replicate from the owning library server, Might return
1.607 raeburn 14394: 'unavailable', 'not_found', 'forbidden', 'ok', or
14395: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14396: resource. Expects the local filesystem pathname
14397: (/home/httpd/html/res/....)
14398:
14399: =back
14400:
14401: =head2 Resource Information
14402:
14403: =over 4
1.191 harris41 14404:
14405: =item *
14406:
1.1172.2.28 raeburn 14407: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14408: and returns the value of a variety of different possible values,
14409: $varname should be a request string, and the other parameters can be
14410: used to specify who and what one is asking about. Ordinarily, $cid
14411: does not need to be specified, as it is retrived from
14412: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14413: within lonuserstate::loadmap() when initializing a course, before
14414: $env{'request.course.id'} has been set, so it needs to be provided
14415: in that one case.
1.243 albertel 14416:
14417: Possible values for $varname are environment.lastname (or other item
14418: from the envirnment hash), user.name (or someother aspect about the
14419: user), resource.0.maxtries (or some other part and parameter of a
14420: resource)
1.204 albertel 14421:
14422: =item *
14423:
1.243 albertel 14424: directcondval($number) : get current value of a condition; reads from a state
14425: string
1.204 albertel 14426:
14427: =item *
14428:
1.243 albertel 14429: condval($condidx) : value of condition index based on state
1.204 albertel 14430:
14431: =item *
14432:
1.243 albertel 14433: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14434: resource's metadata, $what should be either a specific key, or either
14435: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14436: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14437:
14438: this function automatically caches all requests
1.191 harris41 14439:
14440: =item *
14441:
1.243 albertel 14442: metadata_query($query,$custom,$customshow) : make a metadata query against the
14443: network of library servers; returns file handle of where SQL and regex results
14444: will be stored for query
1.191 harris41 14445:
14446: =item *
14447:
1.1172.2.66 raeburn 14448: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14449: return symbolic list entry (all arguments optional).
14450:
14451: Args: filename is the filename (including path) for the file for which a symb
14452: is required; donotrecurse, if true will prevent calls to allowed() being made
14453: to check access status if more than one resource was found in the bighash
14454: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14455: a randompick); ignorecachednull, if true will prevent a symb of '' being
14456: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14457: cause possible symbs to be checked to determine if they are subject to content
14458: blocking, if so they will not be included as possible symbs; possibles is a
14459: ref to a hash, which, as a side effect, will be populated with all possible
14460: symbs (content blocking not tested).
14461:
1.243 albertel 14462: returns the data handle
1.191 harris41 14463:
14464: =item *
14465:
1.1172.2.17 raeburn 14466: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 14467: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14468: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 14469: on failure, user must be in a course, as it assumes the existence of
14470: the course initial hash, and uses $env('request.course.id'}. The third
14471: arg is an optional reference to a scalar. If this arg is passed in the
14472: call to symbverify, it will be set to 1 if the symb has been set to be
14473: encrypted; otherwise it will be null.
1.243 albertel 14474:
1.191 harris41 14475: =item *
14476:
1.243 albertel 14477: symbclean($symb) : removes versions numbers from a symb, returns the
14478: cleaned symb
1.191 harris41 14479:
14480: =item *
14481:
1.243 albertel 14482: is_on_map($uri) : checks if the $uri is somewhere on the current
14483: course map, user must be in a course for it to work.
1.191 harris41 14484:
14485: =item *
14486:
1.243 albertel 14487: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14488:
14489: =item *
14490:
1.243 albertel 14491: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14492: a random seed, all arguments are optional, if they aren't sent it uses the
14493: environment to derive them. Note: if symb isn't sent and it can't get one
14494: from &symbread it will use the current time as its return value
1.191 harris41 14495:
14496: =item *
14497:
1.243 albertel 14498: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14499: unfakeable, receipt
1.191 harris41 14500:
14501: =item *
14502:
1.620 albertel 14503: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14504:
14505: =item *
14506:
1.243 albertel 14507: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14508:
14509: =item *
14510:
1.243 albertel 14511: 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 14512:
14513: =item *
14514:
1.243 albertel 14515: 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 14516:
14517: =item *
14518:
1.243 albertel 14519: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14520:
14521: =item *
14522:
1.243 albertel 14523: devalidate($symb) : devalidate temporary spreadsheet calculations,
14524: forcing spreadsheet to reevaluate the resource scores next time.
14525:
1.1172.2.13 raeburn 14526: =item *
14527:
14528: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14529: when viewing in course context.
14530:
14531: input: six args -- filename (decluttered), course number, course domain,
14532: url, symb (if registered) and group (if this is a
14533: group item -- e.g., bulletin board, group page etc.).
14534:
14535: output: array of five scalars --
14536: $cfile -- url for file editing if editable on current server
14537: $home -- homeserver of resource (i.e., for author if published,
14538: or course if uploaded.).
14539: $switchserver -- 1 if server switch will be needed.
14540: $forceedit -- 1 if icon/link should be to go to edit mode
14541: $forceview -- 1 if icon/link should be to go to view mode
14542:
14543: =item *
14544:
14545: is_course_upload($file,$cnum,$cdom)
14546:
14547: Used in course context to determine if current file was uploaded to
14548: the course (i.e., would be found in /userfiles/docs on the course's
14549: homeserver.
14550:
14551: input: 3 args -- filename (decluttered), course number and course domain.
14552: output: boolean -- 1 if file was uploaded.
14553:
1.243 albertel 14554: =back
14555:
14556: =head2 Storing/Retreiving Data
14557:
14558: =over 4
1.191 harris41 14559:
14560: =item *
14561:
1.1172.2.64 raeburn 14562: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14563: permanently for this url; hashref needs to be given and should be a \%hashname;
14564: the remaining args aren't required and if they aren't passed or are '' they will
14565: be derived from the env (with the exception of $laststore, which is an
14566: optional arg used when a user's submission is stored in grading).
14567: $laststore is $version=$timestamp, where $version is the most recent version
14568: number retrieved for the corresponding $symb in the $namespace db file, and
14569: $timestamp is the timestamp for that transaction (UNIX time).
14570: $laststore is currently only passed when cstore() is called by
14571: structuretags::finalize_storage().
1.191 harris41 14572:
14573: =item *
14574:
1.1172.2.64 raeburn 14575: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14576: but uses critical subroutine
1.191 harris41 14577:
14578: =item *
14579:
1.243 albertel 14580: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14581: all args are optional
1.191 harris41 14582:
14583: =item *
14584:
1.717 albertel 14585: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14586: dumps the complete (or key matching regexp) namespace into a hash
14587: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14588: normally &store()ed into
14589:
14590: $range should be either an integer '100' (give me the first 100
14591: matching records)
14592: or be two integers sperated by a - with no spaces
14593: '30-50' (give me the 30th through the 50th matching
14594: records)
14595:
14596:
14597: =item *
14598:
1.1172.2.59 raeburn 14599: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14600: replaces a &store() version of data with a replacement set of data
14601: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 14602: reference. If $tolog is true, the transaction is logged in the courselog
14603: with an action=PUTSTORE.
1.717 albertel 14604:
14605: =item *
14606:
1.243 albertel 14607: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14608: works very similar to store/cstore, but all data is stored in a
14609: temporary location and can be reset using tmpreset, $storehash should
14610: be a hash reference, returns nothing on success
1.191 harris41 14611:
14612: =item *
14613:
1.243 albertel 14614: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14615: similar to restore, but all data is stored in a temporary location and
14616: can be reset using tmpreset. Returns a hash of values on success,
14617: error string otherwise.
1.191 harris41 14618:
14619: =item *
14620:
1.243 albertel 14621: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14622: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14623:
14624: =item *
14625:
1.243 albertel 14626: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14627: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14628:
14629: =item *
14630:
1.243 albertel 14631: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14632: namesp ($udom and $uname are optional)
1.191 harris41 14633:
14634: =item *
14635:
1.702 albertel 14636: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14637: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14638: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14639:
1.702 albertel 14640: $range should be either an integer '100' (give me the first 100
14641: matching records)
14642: or be two integers sperated by a - with no spaces
14643: '30-50' (give me the 30th through the 50th matching
14644: records)
1.449 matthew 14645: =item *
14646:
14647: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14648: $store can be a scalar, an array reference, or if the amount to be
14649: incremented is > 1, a hash reference.
14650:
14651: ($udom and $uname are optional)
1.191 harris41 14652:
14653: =item *
14654:
1.243 albertel 14655: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14656: ($udom and $uname are optional)
1.191 harris41 14657:
14658: =item *
14659:
1.243 albertel 14660: cput($namespace,$storehash,$udom,$uname) : critical put
14661: ($udom and $uname are optional)
1.191 harris41 14662:
14663: =item *
14664:
1.748 albertel 14665: newput($namespace,$storehash,$udom,$uname) :
14666:
14667: Attempts to store the items in the $storehash, but only if they don't
14668: currently exist, if this succeeds you can be certain that you have
14669: successfully created a new key value pair in the $namespace db.
14670:
14671:
14672: Args:
14673: $namespace: name of database to store values to
14674: $storehash: hashref to store to the db
14675: $udom: (optional) domain of user containing the db
14676: $uname: (optional) name of user caontaining the db
14677:
14678: Returns:
14679: 'ok' -> succeeded in storing all keys of $storehash
14680: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14681: least <key> already existed in the db (other
14682: requested keys may also already exist)
1.967 bisitz 14683: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14684: 'con_lost' -> unable to contact request server
14685: 'refused' -> action was not allowed by remote machine
14686:
14687:
14688: =item *
14689:
1.243 albertel 14690: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14691: reference filled in from namesp (encrypts the return communication)
14692: ($udom and $uname are optional)
1.191 harris41 14693:
14694: =item *
14695:
1.243 albertel 14696: log($udom,$name,$home,$message) : write to permanent log for user; use
14697: critical subroutine
14698:
1.806 raeburn 14699: =item *
14700:
1.860 raeburn 14701: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14702: array reference filled in from namespace found in domain level on either
14703: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14704:
14705: =item *
14706:
1.860 raeburn 14707: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14708: domain level either on specified domain server ($uhome) or primary domain
14709: server ($udom and $uhome are optional)
1.806 raeburn 14710:
1.943 raeburn 14711: =item *
14712:
1.1172.2.35 raeburn 14713: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14714: for: authentication, language, quotas, timezone, date locale, and portal URL in
14715: the target domain.
14716:
14717: May also include additional key => value pairs for the following groups:
14718:
14719: =over
14720:
14721: =item
14722: disk quotas (MB allocated by default to portfolios and authoring spaces).
14723:
14724: =over
14725:
14726: =item defaultquota, authorquota
14727:
14728: =back
14729:
14730: =item
14731: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14732: portfolio for users).
14733:
14734: =over
14735:
14736: =item
14737: aboutme, blog, webdav, portfolio
14738:
14739: =back
14740:
14741: =item
14742: requestcourses: ability to request courses, and how requests are processed.
14743:
14744: =over
14745:
14746: =item
1.1172.2.37 raeburn 14747: official, unofficial, community, textbook
1.1172.2.35 raeburn 14748:
14749: =back
14750:
14751: =item
14752: inststatus: types of institutional affiliation, and order in which they are displayed.
14753:
14754: =over
14755:
14756: =item
1.1172.2.44 raeburn 14757: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 14758:
14759: =back
14760:
14761: =item
14762: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14763: for course's uploaded content.
14764:
14765: =over
14766:
14767: =item
1.1172.2.68 raeburn 14768: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
14769: communityquota, textbookquota
1.1172.2.35 raeburn 14770:
14771: =back
14772:
14773: =item
14774: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14775: on your servers.
14776:
14777: =over
14778:
14779: =item
14780: remotesessions, hostedsessions
14781:
14782: =back
14783:
14784: =back
14785:
14786: In cases where a domain coordinator has never used the "Set Domain Configuration"
14787: utility to create a configuration.db file on a domain's primary library server
14788: only the following domain defaults: auth_def, auth_arg_def, lang_def
14789: -- corresponding values are authentication type (internal, krb4, krb5,
14790: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14791: will be available. Values are retrieved from cache (if current), unless the
14792: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14793: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14794:
14795: Typical usage:
1.943 raeburn 14796:
1.1172.2.35 raeburn 14797: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14798:
1.243 albertel 14799: =back
14800:
14801: =head2 Network Status Functions
14802:
14803: =over 4
1.191 harris41 14804:
14805: =item *
14806:
1.1137 raeburn 14807: dirlist() : return directory list based on URI (first arg).
14808:
14809: Inputs: 1 required, 5 optional.
14810:
14811: =over
14812:
14813: =item
14814: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14815:
14816: =item
14817: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14818:
14819: =item
14820: $username - username of user/course to be listed. Extracted from $uri if absent.
14821:
14822: =item
14823: $getpropath - boolean: 1 if prepend path using &propath().
14824:
14825: =item
14826: $getuserdir - boolean: 1 if prepend path for "userfiles".
14827:
14828: =item
14829: $alternateRoot - path to prepend in place of path from $uri.
14830:
14831: =back
14832:
14833: Returns: Array of up to two items.
14834:
14835: =over
14836:
14837: a reference to an array of files/subdirectories
14838:
14839: =over
14840:
14841: Each element in the array of files/subdirectories is a & separated list of
14842: item name and the result of running stat on the item. If dirlist was requested
14843: for a file instead of a directory, the item name will be ''. For a directory
14844: listing, if the item is a metadata file, the element will end &N&M
14845: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14846: default copyright set (1).
14847:
14848: =back
14849:
14850: a scalar containing error condition (if encountered).
14851:
14852: =over
14853:
14854: =item
14855: no_host (no homeserver identified for $username:$domain).
14856:
14857: =item
14858: no_such_host (server contacted for listing not identified as valid host).
14859:
14860: =item
14861: con_lost (connection to remote server failed).
14862:
14863: =item
14864: refused (invalid $username:$domain received on lond side).
14865:
14866: =item
14867: no_such_dir (directory at specified path on lond side does not exist).
14868:
14869: =item
14870: empty (directory at specified path on lond side is empty).
14871:
14872: =over
14873:
14874: This is currently not encountered because the &ls3, &ls2,
14875: &ls (_handler) routines on the lond side do not filter out
14876: . and .. from a directory listing.
14877:
14878: =back
14879:
14880: =back
14881:
14882: =back
1.191 harris41 14883:
14884: =item *
14885:
1.243 albertel 14886: spareserver() : find server with least workload from spare.tab
14887:
1.986 foxr 14888:
14889: =item *
14890:
14891: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14892: if there is no corresponding loncapa host.
14893:
1.243 albertel 14894: =back
14895:
1.986 foxr 14896:
1.243 albertel 14897: =head2 Apache Request
14898:
14899: =over 4
1.191 harris41 14900:
14901: =item *
14902:
1.243 albertel 14903: ssi($url,%hash) : server side include, does a complete request cycle on url to
14904: localhost, posts hash
14905:
14906: =back
14907:
14908: =head2 Data to String to Data
14909:
14910: =over 4
1.191 harris41 14911:
14912: =item *
14913:
1.243 albertel 14914: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14915: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14916:
14917: =item *
14918:
1.243 albertel 14919: hashref2str($hashref) : convert a hashref into a string complete with
14920: escaping and '=' and '&' separators, supports elements that are
14921: arrayrefs and hashrefs
1.191 harris41 14922:
14923: =item *
14924:
1.243 albertel 14925: arrayref2str($arrayref) : convert an arrayref into a string complete
14926: with escaping and '&' separators, supports elements that are arrayrefs
14927: and hashrefs
1.191 harris41 14928:
14929: =item *
14930:
1.243 albertel 14931: str2hash($string) : convert string to hash using unescaping and
14932: splitting on '=' and '&', supports elements that are arrayrefs and
14933: hashrefs
1.191 harris41 14934:
14935: =item *
14936:
1.243 albertel 14937: str2array($string) : convert string to hash using unescaping and
14938: splitting on '&', supports elements that are arrayrefs and hashrefs
14939:
14940: =back
14941:
14942: =head2 Logging Routines
14943:
14944:
14945: These routines allow one to make log messages in the lonnet.log and
14946: lonnet.perm logfiles.
1.191 harris41 14947:
1.1119 foxr 14948: =over 4
14949:
1.191 harris41 14950: =item *
14951:
1.243 albertel 14952: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14953:
14954: =item *
14955:
1.243 albertel 14956: logthis() : append message to the normal lonnet.log file, it gets
14957: preiodically rolled over and deleted.
1.191 harris41 14958:
14959: =item *
14960:
1.243 albertel 14961: logperm() : append a permanent message to lonnet.perm.log, this log
14962: file never gets deleted by any automated portion of the system, only
14963: messages of critical importance should go in here.
14964:
1.1119 foxr 14965:
1.243 albertel 14966: =back
14967:
14968: =head2 General File Helper Routines
14969:
14970: =over 4
1.191 harris41 14971:
14972: =item *
14973:
1.481 raeburn 14974: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14975: (a) files in /uploaded
14976: (i) If a local copy of the file exists -
14977: compares modification date of local copy with last-modified date for
14978: definitive version stored on home server for course. If local copy is
14979: stale, requests a new version from the home server and stores it.
14980: If the original has been removed from the home server, then local copy
14981: is unlinked.
14982: (ii) If local copy does not exist -
14983: requests the file from the home server and stores it.
14984:
14985: If $caller is 'uploadrep':
14986: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14987: for request for files originally uploaded via DOCS.
14988: - returns 'ok' if fresh local copy now available, -1 otherwise.
14989:
14990: Otherwise:
14991: This indicates a call from the content generation phase of the request.
14992: - returns the entire contents of the file or -1.
14993:
14994: (b) files in /res
14995: - returns the entire contents of a file or -1;
14996: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14997:
1.712 albertel 14998:
14999: =item *
15000:
15001: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15002: reference
15003:
15004: returns either a stat() list of data about the file or an empty list
15005: if the file doesn't exist or couldn't find out about it (connection
15006: problems or user unknown)
15007:
1.191 harris41 15008: =item *
15009:
1.243 albertel 15010: filelocation($dir,$file) : returns file system location of a file
15011: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15012: directory that relative $file lookups are to looked in ($dir of /a/dir
15013: and a file of ../bob will become /a/bob)
1.191 harris41 15014:
15015: =item *
15016:
15017: hreflocation($dir,$file) : returns file system location or a URL; same as
15018: filelocation except for hrefs
15019:
15020: =item *
15021:
1.1172.2.49 raeburn 15022: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15023: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15024:
1.243 albertel 15025: =back
15026:
1.608 albertel 15027: =head2 Usererfile file routines (/uploaded*)
15028:
15029: =over 4
15030:
15031: =item *
15032:
15033: userfileupload(): main rotine for putting a file in a user or course's
15034: filespace, arguments are,
15035:
1.620 albertel 15036: formname - required - this is the name of the element in $env where the
1.608 albertel 15037: filename, and the contents of the file to create/modifed exist
1.620 albertel 15038: the filename is in $env{'form.'.$formname.'.filename'} and the
15039: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15040: context - if coursedoc, store the file in the course of the active role
15041: of the current user;
15042: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15043: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15044: subdir - required - subdirectory to put the file in under ../userfiles/
15045: if undefined, it will be placed in "unknown"
15046:
15047: (This routine calls clean_filename() to remove any dangerous
15048: characters from the filename, and then calls finuserfileupload() to
15049: complete the transaction)
15050:
15051: returns either the url of the uploaded file (/uploaded/....) if successful
15052: and /adm/notfound.html if unsuccessful
15053:
15054: =item *
15055:
15056: clean_filename(): routine for cleaing a filename up for storage in
15057: userfile space, argument is:
15058:
15059: filename - proposed filename
15060:
15061: returns: the new clean filename
15062:
15063: =item *
15064:
1.1090 raeburn 15065: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15066: userspace, probably shouldn't be called directly
15067:
15068: docuname: username or courseid of destination for the file
15069: docudom: domain of user/course of destination for the file
15070: formname: same as for userfileupload()
1.1090 raeburn 15071: fname: filename (including subdirectories) for the file
15072: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.93.4 12(raebu 15073:19): if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 15074: allfiles: reference to hash used to store objects found by parser
15075: codebase: reference to hash used for codebases of java objects found by parser
15076: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15077: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15078: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15079: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15080: context: if 'overwrite', will move the uploaded file from its temporary location to
15081: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15082: mimetype: reference to scalar to accommodate mime type determined
15083: from File::MMagic if $parser = parse.
1.608 albertel 15084:
15085: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15086: and /adm/notfound.html if unsuccessful (or an error message if context
15087: was 'overwrite').
15088:
1.608 albertel 15089:
15090: =item *
15091:
15092: renameuserfile(): renames an existing userfile to a new name
15093:
15094: Args:
15095: docuname: username or courseid of destination for the file
15096: docudom: domain of user/course of destination for the file
15097: old: current file name (including any subdirs under userfiles)
15098: new: desired file name (including any subdirs under userfiles)
15099:
15100: =item *
15101:
15102: mkdiruserfile(): creates a directory is a userfiles dir
15103:
15104: Args:
15105: docuname: username or courseid of destination for the file
15106: docudom: domain of user/course of destination for the file
15107: dir: dir to create (including any subdirs under userfiles)
15108:
15109: =item *
15110:
15111: removeuserfile(): removes a file that exists in userfiles
15112:
15113: Args:
15114: docuname: username or courseid of destination for the file
15115: docudom: domain of user/course of destination for the file
15116: fname: filname to delete (including any subdirs under userfiles)
15117:
15118: =item *
15119:
15120: removeuploadedurl(): convience function for removeuserfile()
15121:
15122: Args:
15123: url: a full /uploaded/... url to delete
15124:
1.747 albertel 15125: =item *
15126:
15127: get_portfile_permissions():
15128: Args:
15129: domain: domain of user or course contain the portfolio files
15130: user: name of user or num of course contain the portfolio files
15131: Returns:
15132: hashref of a dump of the proper file_permissions.db
15133:
15134:
15135: =item *
15136:
15137: get_access_controls():
15138:
15139: Args:
15140: current_permissions: the hash ref returned from get_portfile_permissions()
15141: group: (optional) the group you want the files associated with
15142: file: (optional) the file you want access info on
15143:
15144: Returns:
1.749 raeburn 15145: a hash (keys are file names) of hashes containing
15146: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15147: values are XML containing access control settings (see below)
1.747 albertel 15148:
15149: Internal notes:
15150:
1.749 raeburn 15151: access controls are stored in file_permissions.db as key=value pairs.
15152: key -> path to file/file_name\0uniqueID:scope_end_start
15153: where scope -> public,guest,course,group,domains or users.
15154: end -> UNIX time for end of access (0 -> no end date)
15155: start -> UNIX time for start of access
15156:
15157: value -> XML description of access control
15158: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15159: <start></start>
15160: <end></end>
15161:
15162: <password></password> for scope type = guest
15163:
15164: <domain></domain> for scope type = course or group
15165: <number></number>
15166: <roles id="">
15167: <role></role>
15168: <access></access>
15169: <section></section>
15170: <group></group>
15171: </roles>
15172:
15173: <dom></dom> for scope type = domains
15174:
15175: <users> for scope type = users
15176: <user>
15177: <uname></uname>
15178: <udom></udom>
15179: </user>
15180: </users>
15181: </scope>
15182:
15183: Access data is also aggregated for each file in an additional key=value pair:
15184: key -> path to file/file_name\0accesscontrol
15185: value -> reference to hash
15186: hash contains key = value pairs
15187: where key = uniqueID:scope_end_start
15188: value = UNIX time record was last updated
15189:
15190: Used to improve speed of look-ups of access controls for each file.
15191:
15192: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15193:
1.1172.2.13 raeburn 15194: =item *
15195:
1.749 raeburn 15196: modify_access_controls():
15197:
15198: Modifies access controls for a portfolio file
15199: Args
15200: 1. file name
15201: 2. reference to hash of required changes,
15202: 3. domain
15203: 4. username
15204: where domain,username are the domain of the portfolio owner
15205: (either a user or a course)
15206:
15207: Returns:
15208: 1. result of additions or updates ('ok' or 'error', with error message).
15209: 2. result of deletions ('ok' or 'error', with error message).
15210: 3. reference to hash of any new or updated access controls.
15211: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15212: key = integer (inbound ID)
1.1172.2.13 raeburn 15213: value = uniqueID
15214:
15215: =item *
15216:
15217: get_timebased_id():
15218:
15219: Attempts to get a unique timestamp-based suffix for use with items added to a
15220: course via the Course Editor (e.g., folders, composite pages,
15221: group bulletin boards).
15222:
15223: Args: (first three required; six others optional)
15224:
15225: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15226: docssequence, or name of group
15227:
15228: 2. keyid (alphanumeric): name of temporary locking key in hash,
15229: e.g., num, boardids
15230:
15231: 3. namespace: name of gdbm file used to store suffixes already assigned;
15232: file will be named nohist_namespace.db
15233:
15234: 4. cdom: domain of course; default is current course domain from %env
15235:
15236: 5. cnum: course number; default is current course number from %env
15237:
15238: 6. idtype: set to concat if an additional digit is to be appended to the
15239: unix timestamp to form the suffix, if the plain timestamp is already
15240: in use. Default is to not do this, but simply increment the unix
15241: timestamp by 1 until a unique key is obtained.
15242:
15243: 7. who: holder of locking key; defaults to user:domain for user.
15244:
15245: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15246: retrying); default is 3.
15247:
15248: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15249:
15250: Returns:
15251:
15252: 1. suffix obtained (numeric)
15253:
15254: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15255:
15256: 3. error: contains (localized) error message if an error occurred.
15257:
1.747 albertel 15258:
1.608 albertel 15259: =back
15260:
1.243 albertel 15261: =head2 HTTP Helper Routines
15262:
15263: =over 4
15264:
1.191 harris41 15265: =item *
15266:
15267: escape() : unpack non-word characters into CGI-compatible hex codes
15268:
15269: =item *
15270:
15271: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15272:
1.243 albertel 15273: =back
15274:
15275: =head1 PRIVATE SUBROUTINES
15276:
15277: =head2 Underlying communication routines (Shouldn't call)
15278:
15279: =over 4
15280:
15281: =item *
15282:
15283: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15284:
15285: =item *
15286:
15287: reply() : uses subreply to send a message to remote machine, logs all failures
15288:
15289: =item *
15290:
15291: critical() : passes a critical message to another server; if cannot
15292: get through then place message in connection buffer directory and
15293: returns con_delayed, if incapable of saving message, returns
15294: con_failed
15295:
15296: =item *
15297:
15298: reconlonc() : tries to reconnect lonc client processes.
15299:
15300: =back
15301:
15302: =head2 Resource Access Logging
15303:
15304: =over 4
15305:
15306: =item *
15307:
15308: flushcourselogs() : flush (save) buffer logs and access logs
15309:
15310: =item *
15311:
15312: courselog($what) : save message for course in hash
15313:
15314: =item *
15315:
15316: courseacclog($what) : save message for course using &courselog(). Perform
15317: special processing for specific resource types (problems, exams, quizzes, etc).
15318:
1.191 harris41 15319: =item *
15320:
15321: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15322: as a PerlChildExitHandler
1.243 albertel 15323:
15324: =back
15325:
15326: =head2 Other
15327:
15328: =over 4
15329:
15330: =item *
15331:
15332: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15333:
15334: =back
15335:
15336: =cut
1.877 foxr 15337:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>