Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1310
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1310 ! raeburn 4: # $Id: lonnet.pm,v 1.1309 2016/05/30 03:16:33 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1245 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.1289 damieng 95: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.1288 damieng 108: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1187 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1187 raeburn 119: sub write_log {
1.1188 raeburn 120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1184 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 143: }
144: }
1.1 albertel 145:
1.163 harris41 146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
1.1 albertel 156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
1.448 albertel 161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
1.448 albertel 164: close($fh);
165: }
1.1 albertel 166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
1.448 albertel 174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
1.1 albertel 178: return 1;
179: }
180:
1.850 albertel 181: sub create_connection {
1.853 albertel 182: my ($hostname,$lonid) = @_;
1.851 albertel 183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
1.890 albertel 187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
1.983 raeburn 194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
1.850 albertel 208:
1.1106 raeburn 209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
1.993 raeburn 232: sub get_server_loncaparev {
1.1073 raeburn 233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
1.1073 raeburn 248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
1.1082 raeburn 267: $ua->timeout(4);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
1.1241 raeburn 359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 364: return $response;
365: }
366:
1.1 albertel 367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
1.838 albertel 370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 378: sleep(0.1);
1.549 foxr 379: }
380: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 381: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 382: #
1.550 foxr 383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
1.869 albertel 391: if ($client) {
1.550 foxr 392: last; # Connected!
1.850 albertel 393: } else {
1.853 albertel 394: &create_connection(&hostname($server),$server);
1.550 foxr 395: }
1.1289 damieng 396: sleep(0.1); # Try again later if failed connection.
1.550 foxr 397: }
398: my $answer;
399: if ($client) {
1.704 albertel 400: print $client "sethost:$server:$cmd\n";
1.550 foxr 401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
1.1 albertel 407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
1.838 albertel 412: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 413: my $answer=subreply($cmd,$server);
1.65 www 414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 415: &logthis("<font color=\"blue\">WARNING:".
1.12 www 416: " $cmd to $server returned $answer</font>");
417: }
1.1 albertel 418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
1.891 albertel 424: my ($lonid) = @_;
425: if ($lonid) {
1.1295 raeburn 426: my $hostname = &hostname($lonid);
1.891 albertel 427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
1.836 www 442: &logthis("Trying to reconnect lonc");
1.1 albertel 443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 444: if (open(my $fh,"<$loncfile")) {
1.1 albertel 445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
1.1295 raeburn 451: } else {
1.12 www 452: &logthis(
1.672 albertel 453: "<font color=\"blue\">WARNING:".
1.12 www 454: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 455: }
456: } else {
1.836 www 457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
1.12 www 462:
1.1 albertel 463: sub critical {
464: my ($cmd,$server)=@_;
1.838 albertel 465: unless (&hostname($server)) {
1.672 albertel 466: &logthis("<font color=\"blue\">WARNING:".
1.89 www 467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
1.1 albertel 470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
1.1295 raeburn 472: &reconlonc($server);
1.589 albertel 473: my $answer=reply($cmd,$server);
1.1 albertel 474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
1.5 www 477: $middlename=substr($middlename,0,16);
1.1 albertel 478: $middlename=~s/\W//g;
479: my $dfilename=
1.305 www 480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
1.1 albertel 482: {
1.448 albertel 483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
1.1 albertel 488: }
1.1288 damieng 489: sleep 1;
1.1 albertel 490: my $wcmd='';
491: {
1.448 albertel 492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
1.1 albertel 497: }
498: chomp($wcmd);
1.7 www 499: if ($wcmd eq $cmd) {
1.672 albertel 500: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 501: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
1.672 albertel 505: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 506: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
1.405 albertel 513: }
514:
1.755 albertel 515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
1.756 albertel 519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
1.783 albertel 526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
1.917 albertel 530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
1.915 albertel 532: return 0;
533: }
1.783 albertel 534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
1.786 albertel 540: if ($line !~ m/=/) {
541: return 0;
542: }
1.783 albertel 543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
1.786 albertel 554: return 1;
1.783 albertel 555: }
556:
1.374 www 557: # ------------------------------------------- Transfer profile into environment
1.780 albertel 558: my $env_loaded;
559: sub transfer_profile_to_env {
1.788 albertel 560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
1.374 www 562:
1.720 albertel 563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
1.786 albertel 570: my $convert;
571: {
1.917 albertel 572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
1.915 albertel 574: return;
575: }
1.786 albertel 576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
1.374 www 589: }
1.783 albertel 590:
1.786 albertel 591: my %remove;
1.783 albertel 592: while ( my $envname = each(%env) ) {
1.433 matthew 593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
1.783 albertel 595: $remove{$key}++;
1.433 matthew 596: }
597: }
598: }
1.783 albertel 599:
1.619 albertel 600: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 601: $env_loaded=1;
1.783 albertel 602: foreach my $expired_key (keys(%remove)) {
1.433 matthew 603: &delenv($expired_key);
1.374 www 604: }
1.1 albertel 605: }
606:
1.916 albertel 607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
1.1245 raeburn 609: my ($r,$name,$userhashref) = @_;
1.916 albertel 610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
1.916 albertel 615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
1.916 albertel 624: return undef if (!-e "$lonidsdir/$handle.id");
625:
1.917 albertel 626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
1.916 albertel 628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
1.1245 raeburn 640:
641: if (ref($userhashref) eq 'HASH') {
642: $userhashref->{'name'} = $disk_env{'user.name'};
643: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 644: }
1.1245 raeburn 645:
1.916 albertel 646: return $handle;
647: }
648:
1.830 albertel 649: sub timed_flock {
650: my ($file,$lock_type) = @_;
651: my $failed=0;
652: eval {
653: local $SIG{__DIE__}='DEFAULT';
654: local $SIG{ALRM}=sub {
655: $failed=1;
656: die("failed lock");
657: };
658: alarm(13);
659: flock($file,$lock_type);
660: alarm(0);
661: };
662: if ($failed) {
663: return undef;
664: } else {
665: return 1;
666: }
667: }
668:
1.5 www 669: # ---------------------------------------------------------- Append Environment
670:
671: sub appenv {
1.949 raeburn 672: my ($newenv,$roles) = @_;
673: if (ref($newenv) eq 'HASH') {
674: foreach my $key (keys(%{$newenv})) {
675: my $refused = 0;
676: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
677: $refused = 1;
678: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 679: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 680: if (grep(/^\Q$role\E$/,@{$roles})) {
681: $refused = 0;
682: }
683: }
684: }
685: if ($refused) {
686: &logthis("<font color=\"blue\">WARNING: ".
687: "Attempt to modify environment ".$key." to ".$newenv->{$key}
688: .'</font>');
689: delete($newenv->{$key});
690: } else {
691: $env{$key}=$newenv->{$key};
692: }
693: }
694: my $opened = open(my $env_file,'+<',$env{'user.environment'});
695: if ($opened
696: && &timed_flock($env_file,LOCK_EX)
697: &&
698: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
699: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
700: while (my ($key,$value) = each(%{$newenv})) {
701: $disk_env{$key} = $value;
702: }
703: untie(%disk_env);
1.35 www 704: }
1.191 harris41 705: }
1.56 www 706: return 'ok';
707: }
708: # ----------------------------------------------------- Delete from Environment
709:
710: sub delenv {
1.1104 raeburn 711: my ($delthis,$regexp,$roles) = @_;
712: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
713: my $refused = 1;
714: if (ref($roles) eq 'ARRAY') {
715: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
716: if (grep(/^\Q$role\E$/,@{$roles})) {
717: $refused = 0;
718: }
719: }
720: if ($refused) {
721: &logthis("<font color=\"blue\">WARNING: ".
722: "Attempt to delete from environment ".$delthis);
723: return 'error';
724: }
1.56 www 725: }
1.917 albertel 726: my $opened = open(my $env_file,'+<',$env{'user.environment'});
727: if ($opened
1.915 albertel 728: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 729: &&
730: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
731: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 732: foreach my $key (keys(%disk_env)) {
1.987 raeburn 733: if ($regexp) {
734: if ($key=~/^$delthis/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: } else {
739: if ($key=~/^\Q$delthis\E/) {
740: delete($env{$key});
741: delete($disk_env{$key});
742: }
743: }
1.448 albertel 744: }
1.783 albertel 745: untie(%disk_env);
1.5 www 746: }
747: return 'ok';
1.369 albertel 748: }
749:
1.790 albertel 750: sub get_env_multiple {
751: my ($name) = @_;
752: my @values;
753: if (defined($env{$name})) {
754: # exists is it an array
755: if (ref($env{$name})) {
756: @values=@{ $env{$name} };
757: } else {
758: $values[0]=$env{$name};
759: }
760: }
761: return(@values);
762: }
763:
1.958 www 764: # ------------------------------------------------------------------- Locking
765:
766: sub set_lock {
767: my ($text)=@_;
768: $locknum++;
769: my $id=$$.'-'.$locknum;
770: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
771: 'session.lock.'.$id => $text});
772: return $id;
773: }
774:
775: sub get_locks {
776: my $num=0;
777: my %texts=();
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if ($lock=~/\w/) {
780: $num++;
781: $texts{$lock}=$env{'session.lock.'.$lock};
782: }
783: }
784: return ($num,%texts);
785: }
786:
787: sub remove_lock {
788: my ($id)=@_;
789: my $newlocks='';
790: foreach my $lock (split(/\,/,$env{'session.locks'})) {
791: if (($lock=~/\w/) && ($lock ne $id)) {
792: $newlocks.=','.$lock;
793: }
794: }
795: &appenv({'session.locks' => $newlocks});
796: &delenv('session.lock.'.$id);
797: }
798:
799: sub remove_all_locks {
800: my $activelocks=$env{'session.locks'};
801: foreach my $lock (split(/\,/,$env{'session.locks'})) {
802: if ($lock=~/\w/) {
803: &remove_lock($lock);
804: }
805: }
806: }
807:
808:
1.369 albertel 809: # ------------------------------------------ Find out current server userload
810: sub userload {
811: my $numusers=0;
812: {
813: opendir(LONIDS,$perlvar{'lonIDsDir'});
814: my $filename;
815: my $curtime=time;
816: while ($filename=readdir(LONIDS)) {
1.925 albertel 817: next if ($filename eq '.' || $filename eq '..');
818: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 819: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 820: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 821: }
822: closedir(LONIDS);
823: }
824: my $userloadpercent=0;
825: my $maxuserload=$perlvar{'lonUserLoadLim'};
826: if ($maxuserload) {
1.371 albertel 827: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 828: }
1.372 albertel 829: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 830: return $userloadpercent;
1.283 www 831: }
832:
1.1 albertel 833: # ------------------------------ Find server with least workload from spare.tab
1.11 www 834:
1.1 albertel 835: sub spareserver {
1.1083 raeburn 836: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 837: my $spare_server;
1.370 albertel 838: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 839: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
840: : $userloadpercent;
1.1083 raeburn 841: my ($uint_dom,$remotesessions);
842: if (($udom ne '') && (&domain($udom) ne '')) {
843: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
844: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
845: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
846: $remotesessions = $udomdefaults{'remotesessions'};
847: }
1.1123 raeburn 848: my $spareshash = &this_host_spares($udom);
849: if (ref($spareshash) eq 'HASH') {
850: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 852: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
853: $try_server));
1.1123 raeburn 854: ($spare_server, $lowest_load) =
855: &compare_server_load($try_server, $spare_server, $lowest_load);
856: }
1.1083 raeburn 857: }
1.784 albertel 858:
1.1123 raeburn 859: my $found_server = ($spare_server ne '' && $lowest_load < 100);
860:
861: if (!$found_server) {
862: if (ref($spareshash->{'default'}) eq 'ARRAY') {
863: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 864: next unless (&spare_can_host($udom,$uint_dom,
865: $remotesessions,$try_server));
1.1123 raeburn 866: ($spare_server, $lowest_load) =
867: &compare_server_load($try_server, $spare_server, $lowest_load);
868: }
869: }
870: }
1.784 albertel 871: }
872:
873: if (!$want_server_name) {
1.968 raeburn 874: my $protocol = 'http';
875: if ($protocol{$spare_server} eq 'https') {
876: $protocol = $protocol{$spare_server};
877: }
1.1001 raeburn 878: if (defined($spare_server)) {
879: my $hostname = &hostname($spare_server);
1.1083 raeburn 880: if (defined($hostname)) {
1.1001 raeburn 881: $spare_server = $protocol.'://'.$hostname;
882: }
883: }
1.784 albertel 884: }
885: return $spare_server;
886: }
887:
888: sub compare_server_load {
1.1253 raeburn 889: my ($try_server, $spare_server, $lowest_load, $required) = @_;
890:
891: if ($required) {
892: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
893: my $remoterev = &get_server_loncaparev(undef,$try_server);
894: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
895: if (($major eq '' && $minor eq '') ||
896: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
897: return ($spare_server,$lowest_load);
898: }
899: }
1.784 albertel 900:
901: my $loadans = &reply('load', $try_server);
902: my $userloadans = &reply('userload',$try_server);
903:
904: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 905: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 906: }
907:
908: my $load;
909: if ($loadans =~ /\d/) {
910: if ($userloadans =~ /\d/) {
911: #both are numbers, pick the bigger one
912: $load = ($loadans > $userloadans) ? $loadans
913: : $userloadans;
1.411 albertel 914: } else {
1.784 albertel 915: $load = $loadans;
1.411 albertel 916: }
1.784 albertel 917: } else {
918: $load = $userloadans;
919: }
920:
921: if (($load =~ /\d/) && ($load < $lowest_load)) {
922: $spare_server = $try_server;
923: $lowest_load = $load;
1.370 albertel 924: }
1.784 albertel 925: return ($spare_server,$lowest_load);
1.202 matthew 926: }
1.914 albertel 927:
928: # --------------------------- ask offload servers if user already has a session
929: sub find_existing_session {
930: my ($udom,$uname) = @_;
1.1123 raeburn 931: my $spareshash = &this_host_spares($udom);
932: if (ref($spareshash) eq 'HASH') {
933: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'primary'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
938: if (ref($spareshash->{'default'}) eq 'ARRAY') {
939: foreach my $try_server (@{ $spareshash->{'default'} }) {
940: return $try_server if (&has_user_session($try_server, $udom, $uname));
941: }
942: }
1.914 albertel 943: }
944: return;
945: }
946:
947: # -------------------------------- ask if server already has a session for user
948: sub has_user_session {
949: my ($lonid,$udom,$uname) = @_;
950: my $result = &reply(join(':','userhassession',
951: map {&escape($_)} ($udom,$uname)),$lonid);
952: return 1 if ($result eq 'ok');
953:
954: return 0;
955: }
956:
1.1076 raeburn 957: # --------- determine least loaded server in a user's domain which allows login
958:
959: sub choose_server {
1.1259 raeburn 960: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 961: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 962: my %servers = &get_servers($udom);
1.1076 raeburn 963: my $lowest_load = 30000;
1.1259 raeburn 964: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
965: if ($skiploadbal) {
966: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
967: unless (defined($cached)) {
968: my $cachetime = 60*60*24;
969: my %domconfig =
970: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
971: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
972: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
973: $cachetime);
974: }
975: }
976: }
1.1076 raeburn 977: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 978: if ($skiploadbal) {
979: if (ref($balancers) eq 'HASH') {
980: next if (exists($balancers->{$lonhost}));
981: }
982: }
1.1115 raeburn 983: my $loginvia;
984: if ($checkloginvia) {
985: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 986: if ($loginvia) {
987: my ($server,$path) = split(/:/,$loginvia);
988: ($login_host, $lowest_load) =
1.1253 raeburn 989: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 990: if ($login_host eq $server) {
991: $portal_path = $path;
1.1151 raeburn 992: $isredirect = 1;
1.1116 raeburn 993: }
994: } else {
995: ($login_host, $lowest_load) =
1.1253 raeburn 996: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 997: if ($login_host eq $lonhost) {
998: $portal_path = '';
1.1151 raeburn 999: $isredirect = '';
1.1116 raeburn 1000: }
1001: }
1002: } else {
1.1076 raeburn 1003: ($login_host, $lowest_load) =
1.1253 raeburn 1004: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1005: }
1006: }
1007: if ($login_host ne '') {
1.1116 raeburn 1008: $hostname = &hostname($login_host);
1.1076 raeburn 1009: }
1.1151 raeburn 1010: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1011: }
1012:
1.202 matthew 1013: # --------------------------------------------- Try to change a user's password
1014:
1015: sub changepass {
1.799 raeburn 1016: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1017: $currentpass = &escape($currentpass);
1018: $newpass = &escape($newpass);
1.1030 raeburn 1019: my $lonhost = $perlvar{'lonHostID'};
1020: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1021: $server);
1022: if (! $answer) {
1023: &logthis("No reply on password change request to $server ".
1024: "by $uname in domain $udom.");
1025: } elsif ($answer =~ "^ok") {
1026: &logthis("$uname in $udom successfully changed their password ".
1027: "on $server.");
1028: } elsif ($answer =~ "^pwchange_failure") {
1029: &logthis("$uname in $udom was unable to change their password ".
1030: "on $server. The action was blocked by either lcpasswd ".
1031: "or pwchange");
1032: } elsif ($answer =~ "^non_authorized") {
1033: &logthis("$uname in $udom did not get their password correct when ".
1034: "attempting to change it on $server.");
1035: } elsif ($answer =~ "^auth_mode_error") {
1036: &logthis("$uname in $udom attempted to change their password despite ".
1037: "not being locally or internally authenticated on $server.");
1038: } elsif ($answer =~ "^unknown_user") {
1039: &logthis("$uname in $udom attempted to change their password ".
1040: "on $server but were unable to because $server is not ".
1041: "their home server.");
1042: } elsif ($answer =~ "^refused") {
1043: &logthis("$server refused to change $uname in $udom password because ".
1044: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1045: } elsif ($answer =~ "invalid_client") {
1046: &logthis("$server refused to change $uname in $udom password because ".
1047: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1048: }
1049: return $answer;
1.1 albertel 1050: }
1051:
1.169 harris41 1052: # ----------------------- Try to determine user's current authentication scheme
1053:
1054: sub queryauthenticate {
1055: my ($uname,$udom)=@_;
1.456 albertel 1056: my $uhome=&homeserver($uname,$udom);
1057: if (!$uhome) {
1058: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1059: return 'no_host';
1060: }
1061: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1062: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1063: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1064: }
1.456 albertel 1065: return $answer;
1.169 harris41 1066: }
1067:
1.1 albertel 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1069:
1.1 albertel 1070: sub authenticate {
1.1073 raeburn 1071: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1072: $upass=&escape($upass);
1073: $uname= &LONCAPA::clean_username($uname);
1.836 www 1074: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1075: my $newhome;
1.836 www 1076: if ((!$uhome) || ($uhome eq 'no_host')) {
1077: # Maybe the machine was offline and only re-appeared again recently?
1078: &reconlonc();
1079: # One more
1.952 raeburn 1080: $uhome=&homeserver($uname,$udom,1);
1081: if (($uhome eq 'no_host') && $checkdefauth) {
1082: if (defined(&domain($udom,'primary'))) {
1083: $newhome=&domain($udom,'primary');
1084: }
1085: if ($newhome ne '') {
1086: $uhome = $newhome;
1087: }
1088: }
1.836 www 1089: if ((!$uhome) || ($uhome eq 'no_host')) {
1090: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1091: return 'no_host';
1092: }
1.1 albertel 1093: }
1.1073 raeburn 1094: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1095: if ($answer eq 'authorized') {
1.952 raeburn 1096: if ($newhome) {
1097: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1098: return 'no_account_on_host';
1099: } else {
1100: &logthis("User $uname at $udom authorized by $uhome");
1101: return $uhome;
1102: }
1.471 albertel 1103: }
1104: if ($answer eq 'non_authorized') {
1105: &logthis("User $uname at $udom rejected by $uhome");
1106: return 'no_host';
1.9 www 1107: }
1.471 albertel 1108: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1109: return 'no_host';
1110: }
1111:
1.1073 raeburn 1112: sub can_host_session {
1.1074 raeburn 1113: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1114: my $canhost = 1;
1.1074 raeburn 1115: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1116: if (ref($remotesessions) eq 'HASH') {
1117: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1118: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1119: $canhost = 0;
1120: } else {
1121: $canhost = 1;
1122: }
1123: }
1124: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1125: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1126: $canhost = 1;
1127: } else {
1128: $canhost = 0;
1129: }
1130: }
1131: if ($canhost) {
1132: if ($remotesessions->{'version'} ne '') {
1133: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1134: if ($reqmajor ne '' && $reqminor ne '') {
1135: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1136: my $major = $1;
1137: my $minor = $2;
1138: if (($major < $reqmajor ) ||
1139: (($major == $reqmajor) && ($minor < $reqminor))) {
1140: $canhost = 0;
1141: }
1142: } else {
1143: $canhost = 0;
1144: }
1145: }
1146: }
1147: }
1148: }
1149: if ($canhost) {
1150: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1151: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1152: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1153: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1154: if (($uint_dom ne '') &&
1155: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1156: $canhost = 0;
1157: } else {
1158: $canhost = 1;
1159: }
1160: }
1161: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1162: if (($uint_dom ne '') &&
1163: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1164: $canhost = 1;
1165: } else {
1166: $canhost = 0;
1167: }
1168: }
1169: }
1170: }
1171: return $canhost;
1172: }
1173:
1.1083 raeburn 1174: sub spare_can_host {
1175: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1176: my $canhost=1;
1.1279 raeburn 1177: my $try_server_hostname = &hostname($try_server);
1178: my $serverhomeID = &get_server_homeID($try_server_hostname);
1179: my $serverhomedom = &host_domain($serverhomeID);
1180: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1181: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1182: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1183: $canhost = 0;
1184: }
1185: }
1186: if (($canhost) && ($uint_dom)) {
1187: my @intdoms;
1188: my $internet_names = &get_internet_names($try_server);
1189: if (ref($internet_names) eq 'ARRAY') {
1190: @intdoms = @{$internet_names};
1191: }
1192: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1193: my $remoterev = &get_server_loncaparev(undef,$try_server);
1194: $canhost = &can_host_session($udom,$try_server,$remoterev,
1195: $remotesessions,
1196: $defdomdefaults{'hostedsessions'});
1197: }
1.1083 raeburn 1198: }
1199: return $canhost;
1200: }
1201:
1.1123 raeburn 1202: sub this_host_spares {
1203: my ($dom) = @_;
1.1126 raeburn 1204: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1205: my @hosts = ¤t_machine_ids();
1206: foreach my $lonhost (@hosts) {
1207: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1208: $dom_in_use = $dom;
1209: $lonhost_in_use = $lonhost;
1.1123 raeburn 1210: last;
1211: }
1212: }
1.1126 raeburn 1213: if ($dom_in_use ne '') {
1214: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1215: }
1216: if (ref($result) ne 'HASH') {
1217: $lonhost_in_use = $perlvar{'lonHostID'};
1218: $dom_in_use = &host_domain($lonhost_in_use);
1219: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1220: if (ref($result) ne 'HASH') {
1221: $result = \%spareid;
1222: }
1223: }
1224: return $result;
1225: }
1226:
1227: sub spares_for_offload {
1228: my ($dom_in_use,$lonhost_in_use) = @_;
1229: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1230: if (defined($cached)) {
1231: return $result;
1232: } else {
1.1126 raeburn 1233: my $cachetime = 60*60*24;
1234: my %domconfig =
1235: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1236: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1237: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1238: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1239: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1240: }
1241: }
1242: }
1243: }
1.1126 raeburn 1244: return;
1.1123 raeburn 1245: }
1246:
1.1129 raeburn 1247: sub get_lonbalancer_config {
1248: my ($servers) = @_;
1249: my ($currbalancer,$currtargets);
1250: if (ref($servers) eq 'HASH') {
1251: foreach my $server (keys(%{$servers})) {
1252: my %what = (
1253: spareid => 1,
1254: perlvar => 1,
1255: );
1256: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1257: if ($result eq 'ok') {
1258: if (ref($returnhash) eq 'HASH') {
1259: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1260: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1261: $currbalancer = $server;
1262: $currtargets = {};
1263: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1264: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1265: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1266: }
1267: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1268: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1269: }
1270: }
1271: last;
1272: }
1273: }
1274: }
1275: }
1276: }
1277: }
1278: return ($currbalancer,$currtargets);
1279: }
1280:
1281: sub check_loadbalancing {
1282: my ($uname,$udom) = @_;
1.1191 raeburn 1283: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1284: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1285: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1286: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1287: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1288: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1289: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1290: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1291: my $domneedscache;
1.1129 raeburn 1292: my $cachetime = 60*60*24;
1293:
1294: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1295: $dom_in_use = $udom;
1296: $homeintdom = 1;
1297: } else {
1298: $dom_in_use = $serverhomedom;
1299: }
1300: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1301: unless (defined($cached)) {
1302: my %domconfig =
1303: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1304: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1305: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1306: } else {
1307: $domneedscache = $dom_in_use;
1.1129 raeburn 1308: }
1309: }
1310: if (ref($result) eq 'HASH') {
1.1191 raeburn 1311: ($is_balancer,$currtargets,$currrules) =
1312: &check_balancer_result($result,@hosts);
1.1129 raeburn 1313: if ($is_balancer) {
1314: if (ref($currrules) eq 'HASH') {
1315: if ($homeintdom) {
1316: if ($uname ne '') {
1317: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1318: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1319: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1320: $rule_in_effect = $currrules->{'_LC_author'};
1321: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1322: $rule_in_effect = $currrules->{'_LC_adv'}
1323: }
1324: }
1325: if ($rule_in_effect eq '') {
1326: my %userenv = &userenvironment($udom,$uname,'inststatus');
1327: if ($userenv{'inststatus'} ne '') {
1328: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1329: my ($othertitle,$usertypes,$types) =
1330: &Apache::loncommon::sorted_inst_types($udom);
1331: if (ref($types) eq 'ARRAY') {
1332: foreach my $type (@{$types}) {
1333: if (grep(/^\Q$type\E$/,@statuses)) {
1334: if (exists($currrules->{$type})) {
1335: $rule_in_effect = $currrules->{$type};
1336: }
1337: }
1338: }
1339: }
1340: } else {
1341: if (exists($currrules->{'default'})) {
1342: $rule_in_effect = $currrules->{'default'};
1343: }
1344: }
1345: }
1346: } else {
1347: if (exists($currrules->{'default'})) {
1348: $rule_in_effect = $currrules->{'default'};
1349: }
1350: }
1351: } else {
1352: if ($currrules->{'_LC_external'} ne '') {
1353: $rule_in_effect = $currrules->{'_LC_external'};
1354: }
1355: }
1356: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1357: $uname,$udom);
1358: }
1359: }
1360: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1361: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1362: unless (defined($cached)) {
1363: my %domconfig =
1364: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1365: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1366: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1367: } else {
1368: $domneedscache = $serverhomedom;
1.1129 raeburn 1369: }
1370: }
1371: if (ref($result) eq 'HASH') {
1.1191 raeburn 1372: ($is_balancer,$currtargets,$currrules) =
1373: &check_balancer_result($result,@hosts);
1374: if ($is_balancer) {
1.1129 raeburn 1375: if (ref($currrules) eq 'HASH') {
1376: if ($currrules->{'_LC_internetdom'} ne '') {
1377: $rule_in_effect = $currrules->{'_LC_internetdom'};
1378: }
1379: }
1380: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1381: $uname,$udom);
1382: }
1383: } else {
1384: if ($perlvar{'lonBalancer'} eq 'yes') {
1385: $is_balancer = 1;
1386: $offloadto = &this_host_spares($dom_in_use);
1387: }
1.1307 raeburn 1388: unless (defined($cached)) {
1389: $domneedscache = $serverhomedom;
1390: }
1.1129 raeburn 1391: }
1392: } else {
1393: if ($perlvar{'lonBalancer'} eq 'yes') {
1394: $is_balancer = 1;
1395: $offloadto = &this_host_spares($dom_in_use);
1396: }
1.1307 raeburn 1397: unless (defined($cached)) {
1398: $domneedscache = $serverhomedom;
1399: }
1400: }
1401: if ($domneedscache) {
1402: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1403: }
1.1176 raeburn 1404: if ($is_balancer) {
1405: my $lowest_load = 30000;
1406: if (ref($offloadto) eq 'HASH') {
1407: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1408: foreach my $try_server (@{$offloadto->{'primary'}}) {
1409: ($otherserver,$lowest_load) =
1410: &compare_server_load($try_server,$otherserver,$lowest_load);
1411: }
1.1129 raeburn 1412: }
1.1176 raeburn 1413: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1414:
1.1176 raeburn 1415: if (!$found_server) {
1416: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1417: foreach my $try_server (@{$offloadto->{'default'}}) {
1418: ($otherserver,$lowest_load) =
1419: &compare_server_load($try_server,$otherserver,$lowest_load);
1420: }
1421: }
1422: }
1423: } elsif (ref($offloadto) eq 'ARRAY') {
1424: if (@{$offloadto} == 1) {
1425: $otherserver = $offloadto->[0];
1426: } elsif (@{$offloadto} > 1) {
1427: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1428: ($otherserver,$lowest_load) =
1429: &compare_server_load($try_server,$otherserver,$lowest_load);
1430: }
1431: }
1432: }
1.1176 raeburn 1433: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1434: $is_balancer = 0;
1435: if ($uname ne '' && $udom ne '') {
1436: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1437:
1438: &appenv({'user.loadbalexempt' => $lonhost,
1439: 'user.loadbalcheck.time' => time});
1440: }
1.1129 raeburn 1441: }
1442: }
1443: }
1444: return ($is_balancer,$otherserver);
1445: }
1446:
1.1191 raeburn 1447: sub check_balancer_result {
1448: my ($result,@hosts) = @_;
1449: my ($is_balancer,$currtargets,$currrules);
1450: if (ref($result) eq 'HASH') {
1451: if ($result->{'lonhost'} ne '') {
1452: my $currbalancer = $result->{'lonhost'};
1453: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1454: $is_balancer = 1;
1455: $currtargets = $result->{'targets'};
1456: $currrules = $result->{'rules'};
1457: }
1458: } else {
1459: foreach my $key (keys(%{$result})) {
1460: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1461: (ref($result->{$key}) eq 'HASH')) {
1462: $is_balancer = 1;
1463: $currrules = $result->{$key}{'rules'};
1464: $currtargets = $result->{$key}{'targets'};
1465: last;
1466: }
1467: }
1468: }
1469: }
1470: return ($is_balancer,$currtargets,$currrules);
1471: }
1472:
1.1129 raeburn 1473: sub get_loadbalancer_targets {
1474: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1475: my $offloadto;
1.1175 raeburn 1476: if ($rule_in_effect eq 'none') {
1477: return [$perlvar{'lonHostID'}];
1478: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1479: $offloadto = $currtargets;
1480: } else {
1481: if ($rule_in_effect eq 'homeserver') {
1482: my $homeserver = &homeserver($uname,$udom);
1483: if ($homeserver ne 'no_host') {
1484: $offloadto = [$homeserver];
1485: }
1486: } elsif ($rule_in_effect eq 'externalbalancer') {
1487: my %domconfig =
1488: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1489: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1490: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1491: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1492: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1493: }
1494: }
1495: } else {
1.1178 raeburn 1496: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1497: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1498: if (&hostname($remotebalancer) ne '') {
1499: $offloadto = [$remotebalancer];
1500: }
1501: }
1502: } elsif (&hostname($rule_in_effect) ne '') {
1503: $offloadto = [$rule_in_effect];
1504: }
1505: }
1506: return $offloadto;
1507: }
1508:
1.1127 raeburn 1509: sub internet_dom_servers {
1510: my ($dom) = @_;
1511: my (%uniqservers,%servers);
1512: my $primaryserver = &hostname(&domain($dom,'primary'));
1513: my @machinedoms = &machine_domains($primaryserver);
1514: foreach my $mdom (@machinedoms) {
1515: my %currservers = %servers;
1516: my %server = &get_servers($mdom);
1517: %servers = (%currservers,%server);
1518: }
1519: my %by_hostname;
1520: foreach my $id (keys(%servers)) {
1521: push(@{$by_hostname{$servers{$id}}},$id);
1522: }
1523: foreach my $hostname (sort(keys(%by_hostname))) {
1524: if (@{$by_hostname{$hostname}} > 1) {
1525: my $match = 0;
1526: foreach my $id (@{$by_hostname{$hostname}}) {
1527: if (&host_domain($id) eq $dom) {
1528: $uniqservers{$id} = $hostname;
1529: $match = 1;
1530: }
1531: }
1532: unless ($match) {
1533: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1534: }
1535: } else {
1536: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1537: }
1538: }
1539: return %uniqservers;
1540: }
1541:
1.1 albertel 1542: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1543:
1.599 albertel 1544: my %homecache;
1.1 albertel 1545: sub homeserver {
1.230 stredwic 1546: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1547: my $index="$uname:$udom";
1.426 albertel 1548:
1.599 albertel 1549: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1550:
1551: my %servers = &get_servers($udom,'library');
1552: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1553: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1554: exists($badServerCache{$tryserver}));
1.841 albertel 1555:
1556: my $answer=reply("home:$udom:$uname",$tryserver);
1557: if ($answer eq 'found') {
1558: delete($badServerCache{$tryserver});
1559: return $homecache{$index}=$tryserver;
1560: } elsif ($answer eq 'no_host') {
1561: $badServerCache{$tryserver}=1;
1562: }
1.1 albertel 1563: }
1564: return 'no_host';
1.70 www 1565: }
1566:
1.1300 raeburn 1567: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1568:
1569: sub idget {
1.1300 raeburn 1570: my ($udom,$idsref,$namespace)=@_;
1.70 www 1571: my %returnhash=();
1.1300 raeburn 1572: my @ids=();
1573: if (ref($idsref) eq 'ARRAY') {
1574: @ids = @{$idsref};
1575: } else {
1576: return %returnhash;
1577: }
1578: if ($namespace eq '') {
1579: $namespace = 'ids';
1580: }
1.70 www 1581:
1.841 albertel 1582: my %servers = &get_servers($udom,'library');
1583: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1584: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1585: if ($namespace eq 'ids') {
1586: $idlist=~tr/A-Z/a-z/;
1587: }
1588: my $reply;
1589: if ($namespace eq 'ids') {
1590: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1591: } else {
1592: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1593: }
1.841 albertel 1594: my @answer=();
1595: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1596: @answer=split(/\&/,$reply);
1597: } ;
1598: my $i;
1599: for ($i=0;$i<=$#ids;$i++) {
1600: if ($answer[$i]) {
1.1299 raeburn 1601: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1602: }
1.841 albertel 1603: }
1.1300 raeburn 1604: }
1.70 www 1605: return %returnhash;
1606: }
1607:
1608: # ------------------------------------- Find the IDs behind a list of usernames
1609:
1610: sub idrget {
1611: my ($udom,@unames)=@_;
1612: my %returnhash=();
1.800 albertel 1613: foreach my $uname (@unames) {
1614: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1615: }
1.70 www 1616: return %returnhash;
1617: }
1618:
1.1300 raeburn 1619: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1620:
1621: sub idput {
1.1300 raeburn 1622: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1623: my %servers=();
1.1300 raeburn 1624: my %ids=();
1625: my %byid = ();
1626: if (ref($idsref) eq 'HASH') {
1627: %ids=%{$idsref};
1628: }
1629: if ($namespace eq '') {
1630: $namespace = 'ids';
1631: }
1.800 albertel 1632: foreach my $uname (keys(%ids)) {
1633: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1634: if ($uhom eq '') {
1635: $uhom=&homeserver($uname,$udom);
1636: }
1.70 www 1637: if ($uhom ne 'no_host') {
1.800 albertel 1638: my $esc_unam=&escape($uname);
1.1300 raeburn 1639: if ($namespace eq 'ids') {
1640: my $id=&escape($ids{$uname});
1641: $id=~tr/A-Z/a-z/;
1642: my $esc_unam=&escape($uname);
1643: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1644: } else {
1.1300 raeburn 1645: my @currids = split(/,/,$ids{$uname});
1646: foreach my $id (@currids) {
1647: $byid{$uhom}{$id} .= $uname.',';
1648: }
1649: }
1650: }
1651: }
1652: if ($namespace eq 'clickers') {
1653: foreach my $server (keys(%byid)) {
1654: if (ref($byid{$server}) eq 'HASH') {
1655: foreach my $id (keys(%{$byid{$server}})) {
1656: $byid{$server} =~ s/,$//;
1657: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1658: }
1.70 www 1659: }
1660: }
1.191 harris41 1661: }
1.800 albertel 1662: foreach my $server (keys(%servers)) {
1.1300 raeburn 1663: $servers{$server} =~ s/\&$//;
1664: if ($namespace eq 'ids') {
1665: &critical('idput:'.$udom.':'.$servers{$server},$server);
1666: } else {
1667: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1668: }
1.191 harris41 1669: }
1.344 www 1670: }
1671:
1.1300 raeburn 1672: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1673:
1674: sub iddel {
1.1300 raeburn 1675: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1676: my %result=();
1.1300 raeburn 1677: my %ids=();
1678: my %byid = ();
1679: if (ref($idshashref) eq 'HASH') {
1680: %ids=%{$idshashref};
1681: } else {
1.1231 raeburn 1682: return %result;
1683: }
1.1300 raeburn 1684: if ($namespace eq '') {
1685: $namespace = 'ids';
1686: }
1.1231 raeburn 1687: my %servers=();
1.1300 raeburn 1688: while (my ($id,$unamestr) = each(%ids)) {
1689: if ($namespace eq 'ids') {
1690: my $uhom = $uhome;
1691: if ($uhom eq '') {
1692: $uhom=&homeserver($unamestr,$udom);
1693: }
1694: if ($uhom ne 'no_host') {
1695: $servers{$uhom}.='&'.&escape($id);
1696: }
1697: } else {
1698: my @curritems = split(/,/,$ids{$id});
1699: foreach my $uname (@curritems) {
1700: my $uhom = $uhome;
1701: if ($uhom eq '') {
1702: $uhom=&homeserver($uname,$udom);
1703: }
1704: if ($uhom ne 'no_host') {
1705: $byid{$uhom}{$id} .= $uname.',';
1706: }
1707: }
1.1231 raeburn 1708: }
1.1300 raeburn 1709: }
1710: if ($namespace eq 'clickers') {
1711: foreach my $server (keys(%byid)) {
1712: if (ref($byid{$server}) eq 'HASH') {
1713: foreach my $id (keys(%{$byid{$server}})) {
1714: $byid{$server}{$id} =~ s/,$//;
1715: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1716: }
1.1231 raeburn 1717: }
1718: }
1719: }
1720: foreach my $server (keys(%servers)) {
1.1300 raeburn 1721: $servers{$server} =~ s/\&$//;
1722: if ($namespace eq 'ids') {
1723: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1724: } elsif ($namespace eq 'clickers') {
1725: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1726: }
1.1231 raeburn 1727: }
1728: return %result;
1729: }
1730:
1.1300 raeburn 1731: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1732:
1733: sub updateclickers {
1734: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1735: my %clickers;
1736: if (ref($idshashref) eq 'HASH') {
1737: %clickers=%{$idshashref};
1738: } else {
1739: return;
1740: }
1741: my $items='';
1742: foreach my $item (keys(%clickers)) {
1743: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1744: }
1745: $items=~s/\&$//;
1746: my $request = "updateclickers:$udom:$action:$items";
1747: if ($critical) {
1748: return &critical($request,$uhome);
1749: } else {
1750: return &reply($request,$uhome);
1751: }
1752: }
1753:
1.1023 raeburn 1754: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1755: sub dump_dom {
1.1165 droeschl 1756: my ($namespace, $udom, $regexp) = @_;
1757:
1758: $udom ||= $env{'user.domain'};
1759:
1760: return () unless $udom;
1761:
1762: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1763: }
1764:
1.1023 raeburn 1765: # ------------------------------------------ get items from domain db files
1.806 raeburn 1766:
1767: sub get_dom {
1.860 raeburn 1768: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1769: return if ($udom eq 'public');
1.806 raeburn 1770: my $items='';
1771: foreach my $item (@$storearr) {
1772: $items.=&escape($item).'&';
1773: }
1774: $items=~s/\&$//;
1.860 raeburn 1775: if (!$udom) {
1776: $udom=$env{'user.domain'};
1.1267 raeburn 1777: return if ($udom eq 'public');
1.860 raeburn 1778: if (defined(&domain($udom,'primary'))) {
1779: $uhome=&domain($udom,'primary');
1780: } else {
1.874 albertel 1781: undef($uhome);
1.860 raeburn 1782: }
1783: } else {
1784: if (!$uhome) {
1785: if (defined(&domain($udom,'primary'))) {
1786: $uhome=&domain($udom,'primary');
1787: }
1788: }
1789: }
1790: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1791: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1792: my %returnhash;
1.875 albertel 1793: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1794: return %returnhash;
1795: }
1.806 raeburn 1796: my @pairs=split(/\&/,$rep);
1797: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1798: return @pairs;
1799: }
1800: my $i=0;
1801: foreach my $item (@$storearr) {
1802: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1803: $i++;
1804: }
1805: return %returnhash;
1806: } else {
1.880 banghart 1807: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1808: }
1809: }
1810:
1811: # -------------------------------------------- put items in domain db files
1812:
1813: sub put_dom {
1.860 raeburn 1814: my ($namespace,$storehash,$udom,$uhome)=@_;
1815: if (!$udom) {
1816: $udom=$env{'user.domain'};
1817: if (defined(&domain($udom,'primary'))) {
1818: $uhome=&domain($udom,'primary');
1819: } else {
1.874 albertel 1820: undef($uhome);
1.860 raeburn 1821: }
1822: } else {
1823: if (!$uhome) {
1824: if (defined(&domain($udom,'primary'))) {
1825: $uhome=&domain($udom,'primary');
1826: }
1827: }
1828: }
1829: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1830: my $items='';
1831: foreach my $item (keys(%$storehash)) {
1832: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1833: }
1834: $items=~s/\&$//;
1835: return &reply("putdom:$udom:$namespace:$items",$uhome);
1836: } else {
1.860 raeburn 1837: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1838: }
1839: }
1840:
1.1023 raeburn 1841: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1842: sub newput_dom {
1.1023 raeburn 1843: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1844: my $result;
1845: if (!$udom) {
1846: $udom=$env{'user.domain'};
1847: }
1.1023 raeburn 1848: if ($udom) {
1849: my $uname = &get_domainconfiguser($udom);
1850: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1851: }
1852: return $result;
1853: }
1854:
1.1023 raeburn 1855: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1856: sub del_dom {
1.1023 raeburn 1857: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1858: if (ref($storearr) eq 'ARRAY') {
1859: if (!$udom) {
1860: $udom=$env{'user.domain'};
1861: }
1.1023 raeburn 1862: if ($udom) {
1863: my $uname = &get_domainconfiguser($udom);
1864: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1865: }
1866: }
1867: }
1868:
1.1023 raeburn 1869: # ----------------------------------construct domainconfig user for a domain
1870: sub get_domainconfiguser {
1871: my ($udom) = @_;
1872: return $udom.'-domainconfig';
1873: }
1874:
1.837 raeburn 1875: sub retrieve_inst_usertypes {
1876: my ($udom) = @_;
1877: my (%returnhash,@order);
1.989 raeburn 1878: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1879: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1880: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1881: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1882: } else {
1883: if (defined(&domain($udom,'primary'))) {
1884: my $uhome=&domain($udom,'primary');
1885: my $rep=&reply("inst_usertypes:$udom",$uhome);
1886: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1887: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1888: return (\%returnhash,\@order);
1889: }
1890: my ($hashitems,$orderitems) = split(/:/,$rep);
1891: my @pairs=split(/\&/,$hashitems);
1892: foreach my $item (@pairs) {
1893: my ($key,$value)=split(/=/,$item,2);
1894: $key = &unescape($key);
1895: next if ($key =~ /^error: 2 /);
1896: $returnhash{$key}=&thaw_unescape($value);
1897: }
1898: my @esc_order = split(/\&/,$orderitems);
1899: foreach my $item (@esc_order) {
1900: push(@order,&unescape($item));
1901: }
1902: } else {
1.1256 raeburn 1903: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1904: }
1.1256 raeburn 1905: return (\%returnhash,\@order);
1.837 raeburn 1906: }
1907: }
1908:
1.868 raeburn 1909: sub is_domainimage {
1910: my ($url) = @_;
1.1306 raeburn 1911: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1912: if (&domain($1) ne '') {
1913: return '1';
1914: }
1915: }
1916: return;
1917: }
1918:
1.899 raeburn 1919: sub inst_directory_query {
1920: my ($srch) = @_;
1921: my $udom = $srch->{'srchdomain'};
1922: my %results;
1923: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1924: my $outcome;
1.899 raeburn 1925: if ($homeserver ne '') {
1.904 albertel 1926: my $queryid=&reply("querysend:instdirsearch:".
1927: &escape($srch->{'srchby'}).':'.
1928: &escape($srch->{'srchterm'}).':'.
1929: &escape($srch->{'srchtype'}),$homeserver);
1930: my $host=&hostname($homeserver);
1931: if ($queryid !~/^\Q$host\E\_/) {
1932: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1933: return;
1934: }
1935: my $response = &get_query_reply($queryid);
1936: my $maxtries = 5;
1937: my $tries = 1;
1938: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1939: $response = &get_query_reply($queryid);
1940: $tries ++;
1941: }
1942:
1943: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1944: if ($response eq 'unavailable') {
1945: $outcome = $response;
1946: } else {
1947: $outcome = 'ok';
1948: my @matches = split(/\n/,$response);
1949: foreach my $match (@matches) {
1950: my ($key,$value) = split(/=/,$match);
1951: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1952: }
1.899 raeburn 1953: }
1954: }
1955: }
1.909 raeburn 1956: return ($outcome,%results);
1.899 raeburn 1957: }
1958:
1959: sub usersearch {
1960: my ($srch) = @_;
1961: my $dom = $srch->{'srchdomain'};
1962: my %results;
1963: my %libserv = &all_library();
1964: my $query = 'usersearch';
1965: foreach my $tryserver (keys(%libserv)) {
1966: if (&host_domain($tryserver) eq $dom) {
1967: my $host=&hostname($tryserver);
1968: my $queryid=
1.911 raeburn 1969: &reply("querysend:".&escape($query).':'.
1970: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1971: &escape($srch->{'srchtype'}).':'.
1972: &escape($srch->{'srchterm'}),$tryserver);
1973: if ($queryid !~/^\Q$host\E\_/) {
1974: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1975: next;
1.899 raeburn 1976: }
1977: my $reply = &get_query_reply($queryid);
1978: my $maxtries = 1;
1979: my $tries = 1;
1980: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1981: $reply = &get_query_reply($queryid);
1982: $tries ++;
1983: }
1984: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1985: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1986: } else {
1.911 raeburn 1987: my @matches;
1988: if ($reply =~ /\n/) {
1989: @matches = split(/\n/,$reply);
1990: } else {
1991: @matches = split(/\&/,$reply);
1992: }
1.899 raeburn 1993: foreach my $match (@matches) {
1994: my ($uname,$udom,%userhash);
1.911 raeburn 1995: foreach my $entry (split(/:/,$match)) {
1996: my ($key,$value) =
1997: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1998: $userhash{$key} = $value;
1999: if ($key eq 'username') {
2000: $uname = $value;
2001: } elsif ($key eq 'domain') {
2002: $udom = $value;
1.911 raeburn 2003: }
1.899 raeburn 2004: }
2005: $results{$uname.':'.$udom} = \%userhash;
2006: }
2007: }
2008: }
2009: }
2010: return %results;
2011: }
2012:
1.912 raeburn 2013: sub get_instuser {
2014: my ($udom,$uname,$id) = @_;
2015: my $homeserver = &domain($udom,'primary');
2016: my ($outcome,%results);
2017: if ($homeserver ne '') {
2018: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2019: &escape($id).':'.&escape($udom),$homeserver);
2020: my $host=&hostname($homeserver);
2021: if ($queryid !~/^\Q$host\E\_/) {
2022: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2023: return;
2024: }
2025: my $response = &get_query_reply($queryid);
2026: my $maxtries = 5;
2027: my $tries = 1;
2028: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2029: $response = &get_query_reply($queryid);
2030: $tries ++;
2031: }
2032: if (!&error($response) && $response ne 'refused') {
2033: if ($response eq 'unavailable') {
2034: $outcome = $response;
2035: } else {
2036: $outcome = 'ok';
2037: my @matches = split(/\n/,$response);
2038: foreach my $match (@matches) {
2039: my ($key,$value) = split(/=/,$match);
2040: $results{&unescape($key)} = &thaw_unescape($value);
2041: }
2042: }
2043: }
2044: }
2045: my %userinfo;
2046: if (ref($results{$uname}) eq 'HASH') {
2047: %userinfo = %{$results{$uname}};
2048: }
2049: return ($outcome,%userinfo);
2050: }
2051:
1.1290 raeburn 2052: sub get_multiple_instusers {
2053: my ($udom,$users,$caller) = @_;
2054: my ($outcome,$results);
2055: if (ref($users) eq 'HASH') {
2056: my $count = keys(%{$users});
2057: my $requested = &freeze_escape($users);
2058: my $homeserver = &domain($udom,'primary');
2059: if ($homeserver ne '') {
2060: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2061: my $host=&hostname($homeserver);
2062: if ($queryid !~/^\Q$host\E\_/) {
2063: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2064: ' for host: '.$homeserver.'in domain '.$udom);
2065: return ($outcome,$results);
2066: }
2067: my $response = &get_query_reply($queryid);
2068: my $maxtries = 5;
2069: if ($count > 100) {
2070: $maxtries = 1+int($count/20);
2071: }
2072: my $tries = 1;
2073: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2074: $response = &get_query_reply($queryid);
2075: $tries ++;
2076: }
2077: if ($response eq '') {
2078: $results = {};
2079: foreach my $key (keys(%{$users})) {
2080: my ($uname,$id);
2081: if ($caller eq 'id') {
2082: $id = $key;
2083: } else {
2084: $uname = $key;
2085: }
2086: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2087: $outcome = $resp;
1.1290 raeburn 2088: if ($resp eq 'ok') {
2089: %{$results} = (%{$results}, %info);
2090: } else {
2091: last;
2092: }
2093: }
2094: } elsif(!&error($response) && ($response ne 'refused')) {
2095: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2096: $outcome = $response;
2097: } else {
1.1291 raeburn 2098: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2099: if ($outcome eq 'ok') {
2100: $results = &thaw_unescape($userdata);
2101: }
2102: }
2103: }
2104: }
2105: }
2106: return ($outcome,$results);
2107: }
2108:
1.912 raeburn 2109: sub inst_rulecheck {
1.923 raeburn 2110: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2111: my %returnhash;
2112: if ($udom ne '') {
2113: if (ref($rules) eq 'ARRAY') {
2114: @{$rules} = map {&escape($_);} (@{$rules});
2115: my $rulestr = join(':',@{$rules});
2116: my $homeserver=&domain($udom,'primary');
2117: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2118: my $response;
2119: if ($item eq 'username') {
2120: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2121: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2122: $homeserver));
1.923 raeburn 2123: } elsif ($item eq 'id') {
2124: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2125: ':'.&escape($id).':'.$rulestr,
2126: $homeserver));
1.945 raeburn 2127: } elsif ($item eq 'selfcreate') {
2128: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2129: &escape($udom).':'.&escape($uname).
2130: ':'.$rulestr,$homeserver));
1.923 raeburn 2131: }
1.912 raeburn 2132: if ($response ne 'refused') {
2133: my @pairs=split(/\&/,$response);
2134: foreach my $item (@pairs) {
2135: my ($key,$value)=split(/=/,$item,2);
2136: $key = &unescape($key);
2137: next if ($key =~ /^error: 2 /);
2138: $returnhash{$key}=&thaw_unescape($value);
2139: }
2140: }
2141: }
2142: }
2143: }
2144: return %returnhash;
2145: }
2146:
2147: sub inst_userrules {
1.923 raeburn 2148: my ($udom,$check) = @_;
1.912 raeburn 2149: my (%ruleshash,@ruleorder);
2150: if ($udom ne '') {
2151: my $homeserver=&domain($udom,'primary');
2152: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2153: my $response;
2154: if ($check eq 'id') {
2155: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2156: $homeserver);
1.943 raeburn 2157: } elsif ($check eq 'email') {
2158: $response=&reply('instemailrules:'.&escape($udom),
2159: $homeserver);
1.923 raeburn 2160: } else {
2161: $response=&reply('instuserrules:'.&escape($udom),
2162: $homeserver);
2163: }
1.912 raeburn 2164: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2165: ($response ne 'unknown_cmd') &&
1.912 raeburn 2166: ($response ne 'no_such_host')) {
2167: my ($hashitems,$orderitems) = split(/:/,$response);
2168: my @pairs=split(/\&/,$hashitems);
2169: foreach my $item (@pairs) {
2170: my ($key,$value)=split(/=/,$item,2);
2171: $key = &unescape($key);
2172: next if ($key =~ /^error: 2 /);
2173: $ruleshash{$key}=&thaw_unescape($value);
2174: }
2175: my @esc_order = split(/\&/,$orderitems);
2176: foreach my $item (@esc_order) {
2177: push(@ruleorder,&unescape($item));
2178: }
2179: }
2180: }
2181: }
2182: return (\%ruleshash,\@ruleorder);
2183: }
2184:
1.976 raeburn 2185: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2186:
2187: sub get_domain_defaults {
1.1240 raeburn 2188: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2189: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2190: my $cachetime = 60*60*24;
1.1240 raeburn 2191: unless ($ignore_cache) {
2192: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2193: if (defined($cached)) {
2194: if (ref($result) eq 'HASH') {
2195: return %{$result};
2196: }
1.943 raeburn 2197: }
2198: }
2199: my %domdefaults;
2200: my %domconfig =
1.989 raeburn 2201: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2202: 'requestcourses','inststatus',
1.1183 raeburn 2203: 'coursedefaults','usersessions',
1.1258 raeburn 2204: 'requestauthor','selfenrollment',
2205: 'coursecategories'],$domain);
1.1305 raeburn 2206: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2207: if (ref($domconfig{'defaults'}) eq 'HASH') {
2208: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2209: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2210: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2211: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2212: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2213: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2214: } else {
2215: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2216: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2217: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2218: }
1.976 raeburn 2219: if (ref($domconfig{'quotas'}) eq 'HASH') {
2220: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2221: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2222: } else {
2223: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2224: }
1.1177 raeburn 2225: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2226: foreach my $item (@usertools) {
2227: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2228: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2229: }
2230: }
1.1229 raeburn 2231: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2232: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2233: }
1.976 raeburn 2234: }
1.985 raeburn 2235: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2236: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2237: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2238: }
2239: }
1.1183 raeburn 2240: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2241: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2242: }
1.989 raeburn 2243: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2244: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2245: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2246: }
2247: }
1.1047 raeburn 2248: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2249: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2250: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2251: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2252: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2253: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2254: }
1.1254 raeburn 2255: foreach my $type (@coursetypes) {
2256: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2257: unless ($type eq 'community') {
2258: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2259: }
2260: }
2261: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2262: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2263: }
1.1277 raeburn 2264: if ($domdefaults{'postsubmit'} eq 'on') {
2265: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2266: $domdefaults{$type.'postsubtimeout'} =
2267: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2268: }
2269: }
1.1230 raeburn 2270: }
1.1286 raeburn 2271: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2272: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2273: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2274: if (@clonecodes) {
2275: $domdefaults{'canclone'} = join('+',@clonecodes);
2276: }
2277: }
2278: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2279: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2280: }
1.1047 raeburn 2281: }
1.1073 raeburn 2282: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2283: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2284: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2285: }
2286: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2287: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2288: }
1.1279 raeburn 2289: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2290: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2291: }
1.1073 raeburn 2292: }
1.1254 raeburn 2293: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2294: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2295: my @settings = ('types','registered','enroll_dates','access_dates','section',
2296: 'approval','limit');
2297: foreach my $type (@coursetypes) {
2298: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2299: my @mgrdc = ();
2300: foreach my $item (@settings) {
2301: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2302: push(@mgrdc,$item);
2303: }
2304: }
2305: if (@mgrdc) {
2306: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2307: }
2308: }
2309: }
2310: }
2311: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2312: foreach my $type (@coursetypes) {
2313: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2314: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2315: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2316: }
2317: }
2318: }
2319: }
2320: }
1.1258 raeburn 2321: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2322: $domdefaults{'catauth'} = 'std';
2323: $domdefaults{'catunauth'} = 'std';
2324: if ($domconfig{'coursecategories'}{'auth'}) {
2325: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2326: }
2327: if ($domconfig{'coursecategories'}{'unauth'}) {
2328: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2329: }
2330: }
1.1219 raeburn 2331: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2332: return %domdefaults;
2333: }
2334:
1.344 www 2335: # --------------------------------------------------- Assign a key to a student
2336:
2337: sub assign_access_key {
1.364 www 2338: #
2339: # a valid key looks like uname:udom#comments
2340: # comments are being appended
2341: #
1.498 www 2342: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2343: $kdom=
1.620 albertel 2344: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2345: $knum=
1.620 albertel 2346: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2347: $cdom=
1.620 albertel 2348: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2349: $cnum=
1.620 albertel 2350: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2351: $udom=$env{'user.name'} unless (defined($udom));
2352: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2353: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2354: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2355: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2356: # assigned to this person
2357: # - this should not happen,
1.345 www 2358: # unless something went wrong
2359: # the first time around
2360: # ready to assign
1.364 www 2361: $logentry=$1.'; '.$logentry;
1.496 www 2362: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2363: $kdom,$knum) eq 'ok') {
1.345 www 2364: # key now belongs to user
1.346 www 2365: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2366: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2367: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2368: return 'ok';
2369: } else {
2370: return
2371: 'error: Count not permanently assign key, will need to be re-entered later.';
2372: }
2373: } else {
2374: return 'error: Could not assign key, try again later.';
2375: }
1.364 www 2376: } elsif (!$existing{$ckey}) {
1.345 www 2377: # the key does not exist
2378: return 'error: The key does not exist';
2379: } else {
2380: # the key is somebody else's
2381: return 'error: The key is already in use';
2382: }
1.344 www 2383: }
2384:
1.364 www 2385: # ------------------------------------------ put an additional comment on a key
2386:
2387: sub comment_access_key {
2388: #
2389: # a valid key looks like uname:udom#comments
2390: # comments are being appended
2391: #
2392: my ($ckey,$cdom,$cnum,$logentry)=@_;
2393: $cdom=
1.620 albertel 2394: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2395: $cnum=
1.620 albertel 2396: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2397: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2398: if ($existing{$ckey}) {
2399: $existing{$ckey}.='; '.$logentry;
2400: # ready to assign
1.367 www 2401: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2402: $cdom,$cnum) eq 'ok') {
2403: return 'ok';
2404: } else {
2405: return 'error: Count not store comment.';
2406: }
2407: } else {
2408: # the key does not exist
2409: return 'error: The key does not exist';
2410: }
2411: }
2412:
1.344 www 2413: # ------------------------------------------------------ Generate a set of keys
2414:
2415: sub generate_access_keys {
1.364 www 2416: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2417: $cdom=
1.620 albertel 2418: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2419: $cnum=
1.620 albertel 2420: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2421: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2422: unless (($cdom) && ($cnum)) { return 0; }
2423: if ($number>10000) { return 0; }
2424: sleep(2); # make sure don't get same seed twice
2425: srand(time()^($$+($$<<15))); # from "Programming Perl"
2426: my $total=0;
2427: for (my $i=1;$i<=$number;$i++) {
2428: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2429: sprintf("%lx",int(100000*rand)).'-'.
2430: sprintf("%lx",int(100000*rand));
2431: $newkey=~s/1/g/g; # folks mix up 1 and l
2432: $newkey=~s/0/h/g; # and also 0 and O
2433: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2434: if ($existing{$newkey}) {
2435: $i--;
2436: } else {
1.364 www 2437: if (&put('accesskeys',
2438: { $newkey => '# generated '.localtime().
1.620 albertel 2439: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2440: '; '.$logentry },
2441: $cdom,$cnum) eq 'ok') {
1.344 www 2442: $total++;
2443: }
2444: }
2445: }
1.620 albertel 2446: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2447: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2448: return $total;
2449: }
2450:
2451: # ------------------------------------------------------- Validate an accesskey
2452:
2453: sub validate_access_key {
2454: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2455: $cdom=
1.620 albertel 2456: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2457: $cnum=
1.620 albertel 2458: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2459: $udom=$env{'user.domain'} unless (defined($udom));
2460: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2461: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2462: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2463: }
2464:
2465: # ------------------------------------- Find the section of student in a course
1.652 albertel 2466: sub devalidate_getsection_cache {
2467: my ($udom,$unam,$courseid)=@_;
2468: my $hashid="$udom:$unam:$courseid";
2469: &devalidate_cache_new('getsection',$hashid);
2470: }
1.298 matthew 2471:
1.815 albertel 2472: sub courseid_to_courseurl {
2473: my ($courseid) = @_;
2474: #already url style courseid
2475: return $courseid if ($courseid =~ m{^/});
2476:
2477: if (exists($env{'course.'.$courseid.'.num'})) {
2478: my $cnum = $env{'course.'.$courseid.'.num'};
2479: my $cdom = $env{'course.'.$courseid.'.domain'};
2480: return "/$cdom/$cnum";
2481: }
2482:
2483: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2484: if (exists($courseinfo{'num'})) {
2485: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2486: }
2487:
2488: return undef;
2489: }
2490:
1.298 matthew 2491: sub getsection {
2492: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2493: my $cachetime=1800;
1.551 albertel 2494:
2495: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2496: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2497: if (defined($cached)) { return $result; }
2498:
1.298 matthew 2499: my %Pending;
2500: my %Expired;
2501: #
2502: # Each role can either have not started yet (pending), be active,
2503: # or have expired.
2504: #
2505: # If there is an active role, we are done.
2506: #
2507: # If there is more than one role which has not started yet,
2508: # choose the one which will start sooner
2509: # If there is one role which has not started yet, return it.
2510: #
2511: # If there is more than one expired role, choose the one which ended last.
2512: # If there is a role which has expired, return it.
2513: #
1.815 albertel 2514: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2515: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2516: foreach my $key (keys(%roleshash)) {
1.479 albertel 2517: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2518: my $section=$1;
2519: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2520: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2521: my $now=time;
1.548 albertel 2522: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2523: $Expired{$end}=$section;
2524: next;
2525: }
1.548 albertel 2526: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2527: $Pending{$start}=$section;
2528: next;
2529: }
1.599 albertel 2530: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2531: }
2532: #
2533: # Presumedly there will be few matching roles from the above
2534: # loop and the sorting time will be negligible.
2535: if (scalar(keys(%Pending))) {
2536: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2537: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2538: }
2539: if (scalar(keys(%Expired))) {
2540: my @sorted = sort {$a <=> $b} keys(%Expired);
2541: my $time = pop(@sorted);
1.599 albertel 2542: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2543: }
1.599 albertel 2544: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2545: }
1.70 www 2546:
1.599 albertel 2547: sub save_cache {
2548: &purge_remembered();
1.722 albertel 2549: #&Apache::loncommon::validate_page();
1.620 albertel 2550: undef(%env);
1.780 albertel 2551: undef($env_loaded);
1.599 albertel 2552: }
1.452 albertel 2553:
1.599 albertel 2554: my $to_remember=-1;
2555: my %remembered;
2556: my %accessed;
2557: my $kicks=0;
2558: my $hits=0;
1.849 albertel 2559: sub make_key {
2560: my ($name,$id) = @_;
1.872 albertel 2561: if (length($id) > 65
2562: && length(&escape($id)) > 200) {
2563: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2564: }
1.849 albertel 2565: return &escape($name.':'.$id);
2566: }
2567:
1.599 albertel 2568: sub devalidate_cache_new {
2569: my ($name,$id,$debug) = @_;
2570: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2571: $id=&make_key($name,$id);
1.599 albertel 2572: $memcache->delete($id);
2573: delete($remembered{$id});
2574: delete($accessed{$id});
2575: }
2576:
2577: sub is_cached_new {
2578: my ($name,$id,$debug) = @_;
1.849 albertel 2579: $id=&make_key($name,$id);
1.599 albertel 2580: if (exists($remembered{$id})) {
1.1133 foxr 2581: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2582: $accessed{$id}=[&gettimeofday()];
2583: $hits++;
2584: return ($remembered{$id},1);
2585: }
2586: my $value = $memcache->get($id);
2587: if (!(defined($value))) {
2588: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2589: return (undef,undef);
1.416 albertel 2590: }
1.599 albertel 2591: if ($value eq '__undef__') {
2592: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2593: $value=undef;
2594: }
2595: &make_room($id,$value,$debug);
2596: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2597: return ($value,1);
2598: }
2599:
2600: sub do_cache_new {
2601: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2602: $id=&make_key($name,$id);
1.599 albertel 2603: my $setvalue=$value;
2604: if (!defined($setvalue)) {
2605: $setvalue='__undef__';
2606: }
1.623 albertel 2607: if (!defined($time) ) {
2608: $time=600;
2609: }
1.599 albertel 2610: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2611: my $result = $memcache->set($id,$setvalue,$time);
2612: if (! $result) {
1.872 albertel 2613: &logthis("caching of id -> $id failed");
1.910 albertel 2614: $memcache->disconnect_all();
1.872 albertel 2615: }
1.600 albertel 2616: # need to make a copy of $value
1.919 albertel 2617: &make_room($id,$value,$debug);
1.599 albertel 2618: return $value;
2619: }
2620:
2621: sub make_room {
2622: my ($id,$value,$debug)=@_;
1.919 albertel 2623:
2624: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2625: : $value;
1.599 albertel 2626: if ($to_remember<0) { return; }
2627: $accessed{$id}=[&gettimeofday()];
2628: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2629: my $to_kick;
2630: my $max_time=0;
2631: foreach my $other (keys(%accessed)) {
2632: if (&tv_interval($accessed{$other}) > $max_time) {
2633: $to_kick=$other;
2634: $max_time=&tv_interval($accessed{$other});
2635: }
2636: }
2637: delete($remembered{$to_kick});
2638: delete($accessed{$to_kick});
2639: $kicks++;
2640: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2641: return;
2642: }
2643:
1.599 albertel 2644: sub purge_remembered {
1.604 albertel 2645: #&logthis("Tossing ".scalar(keys(%remembered)));
2646: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2647: undef(%remembered);
2648: undef(%accessed);
1.428 albertel 2649: }
1.70 www 2650: # ------------------------------------- Read an entry from a user's environment
2651:
2652: sub userenvironment {
2653: my ($udom,$unam,@what)=@_;
1.976 raeburn 2654: my $items;
2655: foreach my $item (@what) {
2656: $items.=&escape($item).'&';
2657: }
2658: $items=~s/\&$//;
1.70 www 2659: my %returnhash=();
1.1009 raeburn 2660: my $uhome = &homeserver($unam,$udom);
2661: unless ($uhome eq 'no_host') {
2662: my @answer=split(/\&/,
2663: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2664: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2665: return %returnhash;
2666: }
1.1009 raeburn 2667: my $i;
2668: for ($i=0;$i<=$#what;$i++) {
2669: $returnhash{$what[$i]}=&unescape($answer[$i]);
2670: }
1.70 www 2671: }
2672: return %returnhash;
1.1 albertel 2673: }
2674:
1.617 albertel 2675: # ---------------------------------------------------------- Get a studentphoto
2676: sub studentphoto {
2677: my ($udom,$unam,$ext) = @_;
2678: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2679: if (defined($env{'request.course.id'})) {
1.708 raeburn 2680: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2681: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2682: return(&retrievestudentphoto($udom,$unam,$ext));
2683: } else {
2684: my ($result,$perm_reqd)=
1.707 albertel 2685: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2686: if ($result eq 'ok') {
2687: if (!($perm_reqd eq 'yes')) {
2688: return(&retrievestudentphoto($udom,$unam,$ext));
2689: }
2690: }
2691: }
2692: }
2693: } else {
2694: my ($result,$perm_reqd) =
1.707 albertel 2695: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2696: if ($result eq 'ok') {
2697: if (!($perm_reqd eq 'yes')) {
2698: return(&retrievestudentphoto($udom,$unam,$ext));
2699: }
2700: }
2701: }
2702: return '/adm/lonKaputt/lonlogo_broken.gif';
2703: }
2704:
2705: sub retrievestudentphoto {
2706: my ($udom,$unam,$ext,$type) = @_;
2707: my $home=&Apache::lonnet::homeserver($unam,$udom);
2708: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2709: if ($ret eq 'ok') {
2710: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2711: if ($type eq 'thumbnail') {
2712: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2713: }
2714: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2715: return $tokenurl;
2716: } else {
2717: if ($type eq 'thumbnail') {
2718: return '/adm/lonKaputt/genericstudent_tn.gif';
2719: } else {
2720: return '/adm/lonKaputt/lonlogo_broken.gif';
2721: }
1.617 albertel 2722: }
2723: }
2724:
1.263 www 2725: # -------------------------------------------------------------------- New chat
2726:
2727: sub chatsend {
1.724 raeburn 2728: my ($newentry,$anon,$group)=@_;
1.620 albertel 2729: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2730: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2731: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2732: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2733: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2734: &escape($newentry)).':'.$group,$chome);
1.292 www 2735: }
2736:
2737: # ------------------------------------------ Find current version of a resource
2738:
2739: sub getversion {
2740: my $fname=&clutter(shift);
1.1189 raeburn 2741: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2742: return ¤tversion(&filelocation('',$fname));
2743: }
2744:
2745: sub currentversion {
2746: my $fname=shift;
2747: my $author=$fname;
2748: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2749: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2750: my $home=&homeserver($uname,$udom);
1.292 www 2751: if ($home eq 'no_host') {
2752: return -1;
2753: }
1.1112 www 2754: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2755: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2756: return -1;
2757: }
1.1112 www 2758: return $answer;
1.263 www 2759: }
2760:
1.1111 www 2761: #
2762: # Return special version number of resource if set by override, empty otherwise
2763: #
2764: sub usedversion {
2765: my $fname=shift;
2766: unless ($fname) { $fname=$env{'request.uri'}; }
2767: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2768: if ($urlversion) { return $urlversion; }
2769: return '';
2770: }
2771:
1.1 albertel 2772: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2773:
1.1 albertel 2774: sub subscribe {
2775: my $fname=shift;
1.761 raeburn 2776: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2777: $fname=~s/[\n\r]//g;
1.1 albertel 2778: my $author=$fname;
2779: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2780: my ($udom,$uname)=split(/\//,$author);
2781: my $home=homeserver($uname,$udom);
1.335 albertel 2782: if ($home eq 'no_host') {
2783: return 'not_found';
1.1 albertel 2784: }
2785: my $answer=reply("sub:$fname",$home);
1.64 www 2786: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2787: $answer.=' by '.$home;
2788: }
1.1 albertel 2789: return $answer;
2790: }
2791:
1.8 www 2792: # -------------------------------------------------------------- Replicate file
2793:
2794: sub repcopy {
2795: my $filename=shift;
1.23 www 2796: $filename=~s/\/+/\//g;
1.1142 raeburn 2797: my $londocroot = $perlvar{'lonDocRoot'};
2798: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2799: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2800: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2801: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2802: return &repcopy_userfile($filename);
2803: }
1.532 albertel 2804: $filename=~s/[\n\r]//g;
1.8 www 2805: my $transname="$filename.in.transfer";
1.828 www 2806: # FIXME: this should flock
1.607 raeburn 2807: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2808: my $remoteurl=subscribe($filename);
1.64 www 2809: if ($remoteurl =~ /^con_lost by/) {
2810: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2811: return 'unavailable';
1.8 www 2812: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2813: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2814: return 'not_found';
1.64 www 2815: } elsif ($remoteurl =~ /^rejected by/) {
2816: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2817: return 'forbidden';
1.20 www 2818: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2819: return 'ok';
1.8 www 2820: } else {
1.290 www 2821: my $author=$filename;
2822: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2823: my ($udom,$uname)=split(/\//,$author);
2824: my $home=homeserver($uname,$udom);
2825: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2826: my @parts=split(/\//,$filename);
2827: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2828: if ($path ne "$londocroot/res") {
1.8 www 2829: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2830: return 'bad_request';
1.8 www 2831: }
2832: my $count;
2833: for ($count=5;$count<$#parts;$count++) {
2834: $path.="/$parts[$count]";
2835: if ((-e $path)!=1) {
2836: mkdir($path,0777);
2837: }
2838: }
2839: my $ua=new LWP::UserAgent;
2840: my $request=new HTTP::Request('GET',"$remoteurl");
2841: my $response=$ua->request($request,$transname);
2842: if ($response->is_error()) {
2843: unlink($transname);
2844: my $message=$response->status_line;
1.672 albertel 2845: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2846: ." LWP get: $message: $filename</font>");
1.607 raeburn 2847: return 'unavailable';
1.8 www 2848: } else {
1.16 www 2849: if ($remoteurl!~/\.meta$/) {
2850: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2851: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2852: if ($mresponse->is_error()) {
2853: unlink($filename.'.meta');
2854: &logthis(
1.672 albertel 2855: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2856: }
2857: }
1.8 www 2858: rename($transname,$filename);
1.607 raeburn 2859: return 'ok';
1.8 www 2860: }
1.290 www 2861: }
1.8 www 2862: }
1.330 www 2863: }
2864:
2865: # ------------------------------------------------ Get server side include body
2866: sub ssi_body {
1.381 albertel 2867: my ($filelink,%form)=@_;
1.606 matthew 2868: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2869: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2870: }
1.953 www 2871: my $output='';
2872: my $response;
1.980 raeburn 2873: if ($filelink=~/^https?\:/) {
1.954 raeburn 2874: ($output,$response)=&externalssi($filelink);
1.953 www 2875: } else {
1.1004 droeschl 2876: $filelink .= $filelink=~/\?/ ? '&' : '?';
2877: $filelink .= 'inhibitmenu=yes';
1.953 www 2878: ($output,$response)=&ssi($filelink,%form);
2879: }
1.778 albertel 2880: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2881: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2882: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2883: if (wantarray) {
2884: return ($output, $response);
2885: } else {
2886: return $output;
2887: }
1.8 www 2888: }
2889:
1.15 www 2890: # --------------------------------------------------------- Server Side Include
2891:
1.782 albertel 2892: sub absolute_url {
2893: my ($host_name) = @_;
2894: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2895: if ($host_name eq '') {
2896: $host_name = $ENV{'SERVER_NAME'};
2897: }
2898: return $protocol.$host_name;
2899: }
2900:
1.942 foxr 2901: #
2902: # Server side include.
2903: # Parameters:
2904: # fn Possibly encrypted resource name/id.
2905: # form Hash that describes how the rendering should be done
2906: # and other things.
1.944 foxr 2907: # Returns:
1.950 raeburn 2908: # Scalar context: The content of the response.
2909: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2910: #
1.15 www 2911: sub ssi {
2912:
1.944 foxr 2913: my ($fn,%form)=@_;
1.15 www 2914: my $ua=new LWP::UserAgent;
1.23 www 2915: my $request;
1.711 albertel 2916:
2917: $form{'no_update_last_known'}=1;
1.895 albertel 2918: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2919: if (%form) {
1.782 albertel 2920: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 2921: $request->content(join('&',map {
2922: my $name = escape($_);
2923: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2924: ? join("&$name=", map {escape($_) } @{$form{$_}})
2925: : &escape($form{$_}) );
2926: } keys(%form)));
1.23 www 2927: } else {
1.782 albertel 2928: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2929: }
2930:
1.15 www 2931: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2932: my $response= $ua->request($request);
1.1182 foxr 2933: my $content = $response->content;
2934:
2935:
1.944 foxr 2936: if (wantarray) {
1.1173 foxr 2937: return ($content, $response);
1.944 foxr 2938: } else {
1.1173 foxr 2939: return $content;
1.942 foxr 2940: }
1.324 www 2941: }
2942:
2943: sub externalssi {
2944: my ($url)=@_;
2945: my $ua=new LWP::UserAgent;
2946: my $request=new HTTP::Request('GET',$url);
2947: my $response=$ua->request($request);
1.954 raeburn 2948: if (wantarray) {
2949: return ($response->content, $response);
2950: } else {
2951: return $response->content;
2952: }
1.15 www 2953: }
1.254 www 2954:
1.492 albertel 2955: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2956:
2957: sub allowuploaded {
2958: my ($srcurl,$url)=@_;
2959: $url=&clutter(&declutter($url));
2960: my $dir=$url;
2961: $dir=~s/\/[^\/]+$//;
2962: my %httpref=();
2963: my $httpurl=&hreflocation('',$url);
2964: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2965: &Apache::lonnet::appenv(\%httpref);
1.254 www 2966: }
1.477 raeburn 2967:
1.1193 raeburn 2968: #
2969: # Determine if the current user should be able to edit a particular resource,
2970: # when viewing in course context.
2971: # (a) When viewing resource used to determine if "Edit" item is included in
2972: # Functions.
2973: # (b) When displaying folder contents in course editor, used to determine if
2974: # "Edit" link will be displayed alongside resource.
2975: #
1.1196 raeburn 2976: # input: six args -- filename (decluttered), course number, course domain,
2977: # url, symb (if registered) and group (if this is a group
2978: # item -- e.g., bulletin board, group page etc.).
2979: # output: array of five scalars --
1.1193 raeburn 2980: # $cfile -- url for file editing if editable on current server
2981: # $home -- homeserver of resource (i.e., for author if published,
2982: # or course if uploaded.).
2983: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2984: # $forceedit -- 1 if icon/link should be to go to edit mode
2985: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2986: #
2987:
2988: sub can_edit_resource {
1.1194 raeburn 2989: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2990: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2991: #
2992: # For aboutme pages user can only edit his/her own.
2993: #
1.1199 raeburn 2994: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2995: my ($sdom,$sname) = ($1,$2);
2996: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2997: $home = $env{'user.home'};
2998: $cfile = $resurl;
2999: if ($env{'form.forceedit'}) {
3000: $forceview = 1;
3001: } else {
3002: $forceedit = 1;
3003: }
3004: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3005: } else {
3006: return;
3007: }
3008: }
3009:
3010: if ($env{'request.course.id'}) {
3011: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3012: if ($group ne '') {
3013: # if this is a group homepage or group bulletin board, check group privs
3014: my $allowed = 0;
1.1197 raeburn 3015: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3016: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3017: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3018: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3019: $allowed = 1;
3020: }
1.1197 raeburn 3021: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3022: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3023: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3024: $allowed = 1;
3025: }
3026: }
3027: if ($allowed) {
3028: $home=&homeserver($cnum,$cdom);
3029: if ($env{'form.forceedit'}) {
3030: $forceview = 1;
3031: } else {
3032: $forceedit = 1;
3033: }
3034: $cfile = $resurl;
3035: } else {
3036: return;
3037: }
3038: } else {
1.1208 raeburn 3039: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3040: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3041: return;
3042: }
3043: } elsif (!$crsedit) {
1.1194 raeburn 3044: #
3045: # No edit allowed where CC has switched to student role.
3046: #
3047: return;
3048: }
3049: }
3050: }
3051:
1.1193 raeburn 3052: if ($file ne '') {
3053: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3054: if (&is_course_upload($file,$cnum,$cdom)) {
3055: $uploaded = 1;
3056: $incourse = 1;
1.1193 raeburn 3057: if ($file =~/\.(htm|html|css|js|txt)$/) {
3058: $cfile = &hreflocation('',$file);
1.1201 raeburn 3059: if ($env{'form.forceedit'}) {
3060: $forceview = 1;
3061: } else {
3062: $forceedit = 1;
3063: }
1.1194 raeburn 3064: }
3065: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3066: $incourse = 1;
3067: if ($env{'form.forceedit'}) {
3068: $forceview = 1;
3069: } else {
3070: $forceedit = 1;
3071: }
3072: $cfile = $resurl;
3073: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3074: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3075: $incourse = 1;
3076: if ($env{'form.forceedit'}) {
3077: $forceview = 1;
3078: } else {
3079: $forceedit = 1;
3080: }
3081: $cfile = $resurl;
1.1199 raeburn 3082: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3083: $incourse = 1;
3084: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3085: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3086: $incourse = 1;
1.1199 raeburn 3087: if ($env{'form.forceedit'}) {
3088: $forceview = 1;
3089: } else {
3090: $forceedit = 1;
3091: }
3092: $cfile = $resurl;
1.1298 raeburn 3093: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
3094: $incourse = 1;
3095: if ($env{'form.forceedit'}) {
3096: $forceview = 1;
3097: } else {
3098: $forceedit = 1;
3099: }
3100: $cfile = $resurl;
1.1208 raeburn 3101: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3102: $incourse = 1;
3103: if ($env{'form.forceedit'}) {
3104: $forceview = 1;
3105: } else {
3106: $forceedit = 1;
3107: }
3108: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3109: }
3110: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3111: my $template = '/res/lib/templates/simpleproblem.problem';
3112: if (&is_on_map($template)) {
3113: $incourse = 1;
3114: $forceview = 1;
3115: $cfile = $template;
1.1193 raeburn 3116: }
1.1199 raeburn 3117: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3118: $incourse = 1;
3119: if ($env{'form.forceedit'}) {
3120: $forceview = 1;
3121: } else {
3122: $forceedit = 1;
3123: }
3124: $cfile = $resurl;
1.1298 raeburn 3125: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3126: $incourse = 1;
3127: if ($env{'form.forceedit'}) {
3128: $forceview = 1;
3129: } else {
3130: $forceedit = 1;
3131: }
3132: $cfile = $resurl;
1.1199 raeburn 3133: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3134: $incourse = 1;
3135: $forceview = 1;
3136: if ($symb) {
3137: my ($map,$id,$res)=&decode_symb($symb);
3138: $env{'request.symb'} = $symb;
3139: $cfile = &clutter($res);
3140: } else {
3141: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3142: my $escfile = &unescape($cfile);
3143: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
3144: $cfile = '/adm/wrapper'.$escfile;
3145: } else {
3146: $escfile =~ s{^http://}{};
3147: $cfile = &escape("/adm/wrapper/ext/$escfile");
3148: }
1.1199 raeburn 3149: }
1.1234 raeburn 3150: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3151: if ($env{'form.forceedit'}) {
3152: $forceview = 1;
3153: } else {
3154: $forceedit = 1;
3155: }
3156: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3157: }
3158: }
1.1194 raeburn 3159: if ($uploaded || $incourse) {
3160: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3161: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3162: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3163: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3164: # Check that the user has permission to edit this resource
3165: my $setpriv = 1;
3166: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3167: if (defined($cfudom)) {
3168: $home=&homeserver($cfuname,$cfudom);
3169: $cfile=$file;
3170: }
3171: }
1.1194 raeburn 3172: if (($cfile ne '') && (!$incourse || $uploaded) &&
3173: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3174: my @ids=¤t_machine_ids();
3175: unless (grep(/^\Q$home\E$/,@ids)) {
3176: $switchserver=1;
3177: }
3178: }
3179: }
1.1194 raeburn 3180: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3181: }
3182:
3183: sub is_course_upload {
3184: my ($file,$cnum,$cdom) = @_;
3185: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3186: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3187: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3188: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3189: return 1;
3190: }
3191: return;
3192: }
3193:
1.1194 raeburn 3194: sub in_course {
1.1195 raeburn 3195: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3196: if ($hideprivileged) {
3197: my $skipuser;
1.1219 raeburn 3198: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3199: my @possdoms = ($cdom);
3200: if ($coursehash{'checkforpriv'}) {
3201: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3202: }
3203: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3204: $skipuser = 1;
3205: if ($coursehash{'nothideprivileged'}) {
3206: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3207: my $user;
3208: if ($item =~ /:/) {
3209: $user = $item;
3210: } else {
3211: $user = join(':',split(/[\@]/,$item));
3212: }
3213: if ($user eq $uname.':'.$udom) {
3214: undef($skipuser);
3215: last;
3216: }
3217: }
3218: }
3219: if ($skipuser) {
3220: return 0;
3221: }
3222: }
3223: }
1.1194 raeburn 3224: $type ||= 'any';
3225: if (!defined($cdom) || !defined($cnum)) {
3226: my $cid = $env{'request.course.id'};
3227: $cdom = $env{'course.'.$cid.'.domain'};
3228: $cnum = $env{'course.'.$cid.'.num'};
3229: }
3230: my $typesref;
1.1195 raeburn 3231: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3232: $typesref = ['active','previous','future'];
3233: } elsif ($type eq 'previous' || $type eq 'future') {
3234: $typesref = [$type];
3235: }
3236: my %roles = &get_my_roles($uname,$udom,'userroles',
3237: $typesref,undef,[$cdom]);
3238: my ($tmp) = keys(%roles);
3239: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3240: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3241: if (@course_roles > 0) {
3242: return 1;
3243: }
3244: return 0;
3245: }
3246:
1.478 albertel 3247: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3248: # input: action, courseID, current domain, intended
1.637 raeburn 3249: # path to file, source of file, instruction to parse file for objects,
3250: # ref to hash for embedded objects,
3251: # ref to hash for codebase of java objects.
1.1095 raeburn 3252: # reference to scalar to accommodate mime type determined
3253: # from File::MMagic if $parser = parse.
1.637 raeburn 3254: #
1.485 raeburn 3255: # output: url to file (if action was uploaddoc),
3256: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3257: #
1.478 albertel 3258: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3259: # course.
1.477 raeburn 3260: #
1.478 albertel 3261: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3262: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3263: # course's home server.
1.477 raeburn 3264: #
1.478 albertel 3265: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3266: # be copied from $source (current location) to
3267: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3268: # and will then be copied to
3269: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3270: # course's home server.
1.485 raeburn 3271: #
1.481 raeburn 3272: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3273: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3274: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3275: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3276: # in course's home server.
1.637 raeburn 3277: #
1.477 raeburn 3278:
3279: sub process_coursefile {
1.1095 raeburn 3280: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3281: $mimetype)=@_;
1.477 raeburn 3282: my $fetchresult;
1.638 albertel 3283: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3284: if ($action eq 'propagate') {
1.638 albertel 3285: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3286: $home);
1.481 raeburn 3287: } else {
1.477 raeburn 3288: my $fpath = '';
3289: my $fname = $file;
1.478 albertel 3290: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3291: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3292: my $filepath = &build_filepath($fpath);
1.481 raeburn 3293: if ($action eq 'copy') {
3294: if ($source eq '') {
3295: $fetchresult = 'no source file';
3296: return $fetchresult;
3297: } else {
3298: my $destination = $filepath.'/'.$fname;
3299: rename($source,$destination);
3300: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3301: $home);
1.481 raeburn 3302: }
3303: } elsif ($action eq 'uploaddoc') {
3304: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3305: print $fh $env{'form.'.$source};
1.481 raeburn 3306: close($fh);
1.637 raeburn 3307: if ($parser eq 'parse') {
1.1024 raeburn 3308: my $mm = new File::MMagic;
1.1095 raeburn 3309: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3310: if ($type eq 'text/html') {
1.1024 raeburn 3311: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3312: unless ($parse_result eq 'ok') {
3313: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3314: }
1.637 raeburn 3315: }
1.1095 raeburn 3316: if (ref($mimetype)) {
3317: $$mimetype = $type;
3318: }
1.637 raeburn 3319: }
1.477 raeburn 3320: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3321: $home);
1.481 raeburn 3322: if ($fetchresult eq 'ok') {
3323: return '/uploaded/'.$fpath.'/'.$fname;
3324: } else {
3325: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3326: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3327: return '/adm/notfound.html';
3328: }
1.477 raeburn 3329: }
3330: }
1.485 raeburn 3331: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3332: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3333: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3334: }
3335: return $fetchresult;
3336: }
3337:
1.637 raeburn 3338: sub build_filepath {
3339: my ($fpath) = @_;
3340: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3341: unless ($fpath eq '') {
3342: my @parts=split('/',$fpath);
3343: foreach my $part (@parts) {
3344: $filepath.= '/'.$part;
3345: if ((-e $filepath)!=1) {
3346: mkdir($filepath,0777);
3347: }
3348: }
3349: }
3350: return $filepath;
3351: }
3352:
3353: sub store_edited_file {
1.638 albertel 3354: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3355: my $file = $primary_url;
3356: $file =~ s#^/uploaded/$docudom/$docuname/##;
3357: my $fpath = '';
3358: my $fname = $file;
3359: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3360: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3361: my $filepath = &build_filepath($fpath);
3362: open(my $fh,'>'.$filepath.'/'.$fname);
3363: print $fh $content;
3364: close($fh);
1.638 albertel 3365: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3366: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3367: $home);
1.637 raeburn 3368: if ($$fetchresult eq 'ok') {
3369: return '/uploaded/'.$fpath.'/'.$fname;
3370: } else {
1.638 albertel 3371: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3372: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3373: return '/adm/notfound.html';
3374: }
3375: }
3376:
1.531 albertel 3377: sub clean_filename {
1.831 albertel 3378: my ($fname,$args)=@_;
1.315 www 3379: # Replace Windows backslashes by forward slashes
1.257 www 3380: $fname=~s/\\/\//g;
1.831 albertel 3381: if (!$args->{'keep_path'}) {
3382: # Get rid of everything but the actual filename
3383: $fname=~s/^.*\/([^\/]+)$/$1/;
3384: }
1.315 www 3385: # Replace spaces by underscores
3386: $fname=~s/\s+/\_/g;
3387: # Replace all other weird characters by nothing
1.831 albertel 3388: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3389: # Replace all .\d. sequences with _\d. so they no longer look like version
3390: # numbers
3391: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3392: return $fname;
3393: }
1.1051 raeburn 3394: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3395: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3396: # image with the same aspect ratio as the original, but with dimensions which do
3397: # not exceed $resizewidth and $resizeheight.
3398:
1.984 neumanie 3399: sub resizeImage {
1.1051 raeburn 3400: my ($img_path,$resizewidth,$resizeheight) = @_;
3401: my $ima = Image::Magick->new;
3402: my $resized;
3403: if (-e $img_path) {
3404: $ima->Read($img_path);
3405: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3406: my $width = $ima->Get('width');
3407: my $height = $ima->Get('height');
3408: if ($width > $resizewidth) {
3409: my $factor = $width/$resizewidth;
3410: my $newheight = $height/$factor;
3411: $ima->Scale(width=>$resizewidth,height=>$newheight);
3412: $resized = 1;
3413: }
3414: }
3415: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3416: my $width = $ima->Get('width');
3417: my $height = $ima->Get('height');
3418: if ($height > $resizeheight) {
3419: my $factor = $height/$resizeheight;
3420: my $newwidth = $width/$factor;
3421: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3422: $resized = 1;
3423: }
3424: }
3425: if ($resized) {
3426: $ima->Write($img_path);
3427: }
3428: }
3429: return;
1.977 amueller 3430: }
3431:
1.608 albertel 3432: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3433: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3434: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3435: # $context - possible values: coursedoc, existingfile, overwrite,
3436: # canceloverwrite, or ''.
3437: # if 'coursedoc': upload to the current course
3438: # if 'existingfile': write file to tmp/overwrites directory
3439: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3440: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3441: # $subdir - directory in userfile to store the file into
1.858 raeburn 3442: # $parser - instruction to parse file for objects ($parser = parse)
3443: # $allfiles - reference to hash for embedded objects
3444: # $codebase - reference to hash for codebase of java objects
3445: # $desuname - username for permanent storage of uploaded file
3446: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3447: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3448: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3449: # $resizewidth - width (pixels) to which to resize uploaded image
3450: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3451: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3452: # from File::MMagic.
1.858 raeburn 3453: #
1.686 albertel 3454: # output: url of file in userspace, or error: <message>
3455: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3456:
1.531 albertel 3457: sub userfileupload {
1.1090 raeburn 3458: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3459: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3460: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3461: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3462: $fname=&clean_filename($fname);
1.1090 raeburn 3463: # See if there is anything left
1.257 www 3464: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3465: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3466: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3467: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3468: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3469: my $now = time;
1.1090 raeburn 3470: my $filepath;
1.1095 raeburn 3471: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3472: $filepath = 'tmp/helprequests/'.$now;
3473: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3474: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3475: '_'.$env{'user.domain'}.'/pending';
3476: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3477: my ($docuname,$docudom);
3478: if ($destudom) {
3479: $docudom = $destudom;
3480: } else {
3481: $docudom = $env{'user.domain'};
3482: }
3483: if ($destuname) {
3484: $docuname = $destuname;
3485: } else {
3486: $docuname = $env{'user.name'};
3487: }
3488: if (exists($env{'form.group'})) {
3489: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3490: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3491: }
3492: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3493: if ($context eq 'canceloverwrite') {
3494: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3495: if (-e $tempfile) {
3496: my @info = stat($tempfile);
3497: if ($info[9] eq $env{'form.timestamp'}) {
3498: unlink($tempfile);
3499: }
3500: }
3501: return;
1.523 raeburn 3502: }
3503: }
1.1090 raeburn 3504: # Create the directory if not present
1.741 raeburn 3505: my @parts=split(/\//,$filepath);
3506: my $fullpath = $perlvar{'lonDaemons'};
3507: for (my $i=0;$i<@parts;$i++) {
3508: $fullpath .= '/'.$parts[$i];
3509: if ((-e $fullpath)!=1) {
3510: mkdir($fullpath,0777);
3511: }
3512: }
3513: open(my $fh,'>'.$fullpath.'/'.$fname);
3514: print $fh $env{'form.'.$formname};
3515: close($fh);
1.1090 raeburn 3516: if ($context eq 'existingfile') {
3517: my @info = stat($fullpath.'/'.$fname);
3518: return ($fullpath.'/'.$fname,$info[9]);
3519: } else {
3520: return $fullpath.'/'.$fname;
3521: }
1.523 raeburn 3522: }
1.995 raeburn 3523: if ($subdir eq 'scantron') {
3524: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3525: } else {
1.995 raeburn 3526: $fname="$subdir/$fname";
3527: }
1.1090 raeburn 3528: if ($context eq 'coursedoc') {
1.638 albertel 3529: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3530: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3531: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3532: return &finishuserfileupload($docuname,$docudom,
3533: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3534: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3535: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3536: } else {
1.1218 raeburn 3537: if ($env{'form.folder'}) {
3538: $fname=$env{'form.folder'}.'/'.$fname;
3539: }
1.638 albertel 3540: return &process_coursefile('uploaddoc',$docuname,$docudom,
3541: $fname,$formname,$parser,
1.1095 raeburn 3542: $allfiles,$codebase,$mimetype);
1.481 raeburn 3543: }
1.719 banghart 3544: } elsif (defined($destuname)) {
3545: my $docuname=$destuname;
3546: my $docudom=$destudom;
1.860 raeburn 3547: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3548: $parser,$allfiles,$codebase,
1.1051 raeburn 3549: $thumbwidth,$thumbheight,
1.1095 raeburn 3550: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3551: } else {
1.638 albertel 3552: my $docuname=$env{'user.name'};
3553: my $docudom=$env{'user.domain'};
1.1220 raeburn 3554: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3555: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3556: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3557: }
1.860 raeburn 3558: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3559: $parser,$allfiles,$codebase,
1.1051 raeburn 3560: $thumbwidth,$thumbheight,
1.1095 raeburn 3561: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3562: }
1.271 www 3563: }
3564:
3565: sub finishuserfileupload {
1.860 raeburn 3566: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3567: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3568: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3569: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3570:
1.860 raeburn 3571: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3572: $file=$fname;
3573: if ($fname=~m|/|) {
3574: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3575: $path.=$fnamepath.'/';
3576: }
1.259 www 3577: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3578: my $count;
3579: for ($count=4;$count<=$#parts;$count++) {
3580: $filepath.="/$parts[$count]";
3581: if ((-e $filepath)!=1) {
3582: mkdir($filepath,0777);
3583: }
3584: }
1.984 neumanie 3585:
1.258 www 3586: # Save the file
3587: {
1.701 albertel 3588: if (!open(FH,'>'.$filepath.'/'.$file)) {
3589: &logthis('Failed to create '.$filepath.'/'.$file);
3590: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3591: return '/adm/notfound.html';
3592: }
1.1090 raeburn 3593: if ($context eq 'overwrite') {
1.1117 foxr 3594: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3595: my $target = $filepath.'/'.$file;
3596: if (-e $source) {
3597: my @info = stat($source);
3598: if ($info[9] eq $env{'form.timestamp'}) {
3599: unless (&File::Copy::move($source,$target)) {
3600: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3601: return "Moving from $source failed";
3602: }
3603: } else {
3604: return "Temporary file: $source had unexpected date/time for last modification";
3605: }
3606: } else {
3607: return "Temporary file: $source missing";
3608: }
3609: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3610: &logthis('Failed to write to '.$filepath.'/'.$file);
3611: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3612: return '/adm/notfound.html';
3613: }
1.570 albertel 3614: close(FH);
1.1051 raeburn 3615: if ($resizewidth && $resizeheight) {
3616: my $mm = new File::MMagic;
3617: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3618: if ($mime_type =~ m{^image/}) {
3619: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3620: }
1.977 amueller 3621: }
1.258 www 3622: }
1.1152 raeburn 3623: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3624: if (ref($mimetype)) {
3625: if ($$mimetype eq '') {
3626: my $mm = new File::MMagic;
3627: my $type = $mm->checktype_filename($filepath.'/'.$file);
3628: $$mimetype = $type;
3629: }
3630: }
3631: }
1.637 raeburn 3632: if ($parser eq 'parse') {
1.1152 raeburn 3633: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3634: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3635: $allfiles,$codebase);
3636: unless ($parse_result eq 'ok') {
3637: &logthis('Failed to parse '.$filepath.$file.
3638: ' for embedded media: '.$parse_result);
3639: }
1.637 raeburn 3640: }
3641: }
1.860 raeburn 3642: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3643: my $input = $filepath.'/'.$file;
3644: my $output = $filepath.'/'.'tn-'.$file;
3645: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3646: system("convert -sample $thumbsize $input $output");
3647: if (-e $filepath.'/'.'tn-'.$file) {
3648: $fetchthumb = 1;
3649: }
3650: }
1.858 raeburn 3651:
1.259 www 3652: # Notify homeserver to grep it
3653: #
1.984 neumanie 3654: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3655: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3656: if ($fetchresult eq 'ok') {
1.860 raeburn 3657: if ($fetchthumb) {
3658: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3659: if ($thumbresult ne 'ok') {
3660: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3661: $docuhome.': '.$thumbresult);
3662: }
3663: }
1.259 www 3664: #
1.258 www 3665: # Return the URL to it
1.494 albertel 3666: return '/uploaded/'.$path.$file;
1.263 www 3667: } else {
1.494 albertel 3668: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3669: ': '.$fetchresult);
1.263 www 3670: return '/adm/notfound.html';
1.858 raeburn 3671: }
1.493 albertel 3672: }
3673:
1.637 raeburn 3674: sub extract_embedded_items {
1.961 raeburn 3675: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3676: my @state = ();
1.1164 raeburn 3677: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3678: my %javafiles = (
3679: codebase => '',
3680: code => '',
3681: archive => ''
3682: );
3683: my %mediafiles = (
3684: src => '',
3685: movie => '',
3686: );
1.648 raeburn 3687: my $p;
3688: if ($content) {
3689: $p = HTML::LCParser->new($content);
3690: } else {
1.961 raeburn 3691: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3692: }
1.641 albertel 3693: while (my $t=$p->get_token()) {
1.640 albertel 3694: if ($t->[0] eq 'S') {
3695: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3696: push(@state, $tagname);
1.648 raeburn 3697: if (lc($tagname) eq 'allow') {
3698: &add_filetype($allfiles,$attr->{'src'},'src');
3699: }
1.640 albertel 3700: if (lc($tagname) eq 'img') {
3701: &add_filetype($allfiles,$attr->{'src'},'src');
3702: }
1.886 albertel 3703: if (lc($tagname) eq 'a') {
1.1222 raeburn 3704: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3705: &add_filetype($allfiles,$attr->{'href'},'href');
3706: }
1.886 albertel 3707: }
1.645 raeburn 3708: if (lc($tagname) eq 'script') {
1.1164 raeburn 3709: my $src;
1.645 raeburn 3710: if ($attr->{'archive'} =~ /\.jar$/i) {
3711: &add_filetype($allfiles,$attr->{'archive'},'archive');
3712: } else {
1.1164 raeburn 3713: if ($attr->{'src'} ne '') {
3714: $src = $attr->{'src'};
3715: &add_filetype($allfiles,$src,'src');
3716: }
3717: }
3718: my $text = $p->get_trimmed_text();
3719: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3720: my @swfargs = split(/,/,$1);
3721: foreach my $item (@swfargs) {
3722: $item =~ s/["']//g;
3723: $item =~ s/^\s+//;
3724: $item =~ s/\s+$//;
3725: }
3726: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3727: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3728: push(@{$related{$swfargs[0]}},$swfargs[2]);
3729: } else {
3730: $related{$swfargs[0]} = [$swfargs[2]];
3731: }
3732: }
1.645 raeburn 3733: }
3734: }
3735: if (lc($tagname) eq 'link') {
3736: if (lc($attr->{'rel'}) eq 'stylesheet') {
3737: &add_filetype($allfiles,$attr->{'href'},'href');
3738: }
3739: }
1.640 albertel 3740: if (lc($tagname) eq 'object' ||
3741: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3742: foreach my $item (keys(%javafiles)) {
3743: $javafiles{$item} = '';
3744: }
1.1164 raeburn 3745: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3746: $lastids{lc($tagname)} = $attr->{'id'};
3747: }
1.640 albertel 3748: }
3749: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3750: my $name = lc($attr->{'name'});
3751: foreach my $item (keys(%javafiles)) {
3752: if ($name eq $item) {
3753: $javafiles{$item} = $attr->{'value'};
3754: last;
3755: }
3756: }
1.1164 raeburn 3757: my $pathfrom;
1.640 albertel 3758: foreach my $item (keys(%mediafiles)) {
3759: if ($name eq $item) {
1.1164 raeburn 3760: $pathfrom = $attr->{'value'};
3761: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3762: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3763: last;
3764: }
3765: }
1.1164 raeburn 3766: if ($name eq 'flashvars') {
3767: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3768: }
3769: if ($pathfrom ne '') {
3770: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3771: $pathfrom);
3772: }
1.640 albertel 3773: }
3774: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3775: foreach my $item (keys(%javafiles)) {
3776: if ($attr->{$item}) {
3777: $javafiles{$item} = $attr->{$item};
3778: last;
3779: }
3780: }
3781: foreach my $item (keys(%mediafiles)) {
3782: if ($attr->{$item}) {
3783: &add_filetype($allfiles,$attr->{$item},$item);
3784: last;
3785: }
3786: }
1.1164 raeburn 3787: if (lc($tagname) eq 'embed') {
3788: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3789: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3790: $attr->{'src'});
3791: }
3792: }
1.640 albertel 3793: }
1.1243 raeburn 3794: if (lc($tagname) eq 'iframe') {
3795: my $src = $attr->{'src'} ;
3796: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3797: &add_filetype($allfiles,$src,'src');
3798: } elsif ($src =~ m{^/}) {
3799: if ($env{'request.course.id'}) {
3800: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3801: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3802: my $url = &hreflocation('',$fullpath);
3803: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3804: my $relpath = $1;
3805: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3806: &add_filetype($allfiles,$1,'src');
3807: }
3808: }
3809: }
3810: }
3811: }
1.1164 raeburn 3812: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3813: pop(@state);
1.1164 raeburn 3814: }
1.640 albertel 3815: } elsif ($t->[0] eq 'E') {
3816: my ($tagname) = ($t->[1]);
3817: if ($javafiles{'codebase'} ne '') {
3818: $javafiles{'codebase'} .= '/';
3819: }
3820: if (lc($tagname) eq 'applet' ||
3821: lc($tagname) eq 'object' ||
3822: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3823: ) {
3824: foreach my $item (keys(%javafiles)) {
3825: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3826: my $file=$javafiles{'codebase'}.$javafiles{$item};
3827: &add_filetype($allfiles,$file,$item);
3828: }
3829: }
3830: }
3831: pop @state;
3832: }
3833: }
1.1164 raeburn 3834: foreach my $id (sort(keys(%flashvars))) {
3835: if ($shockwave{$id} ne '') {
3836: my @pairs = split(/\&/,$flashvars{$id});
3837: foreach my $pair (@pairs) {
3838: my ($key,$value) = split(/\=/,$pair);
3839: if ($key eq 'thumb') {
3840: &add_filetype($allfiles,$value,$key);
3841: } elsif ($key eq 'content') {
3842: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3843: my ($ext) = ($value =~ /\.([^.]+)$/);
3844: if ($ext ne '') {
3845: &add_filetype($allfiles,$path.$value,$ext);
3846: }
3847: }
3848: }
3849: }
3850: }
1.637 raeburn 3851: return 'ok';
3852: }
3853:
1.639 albertel 3854: sub add_filetype {
3855: my ($allfiles,$file,$type)=@_;
3856: if (exists($allfiles->{$file})) {
3857: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3858: push(@{$allfiles->{$file}}, &escape($type));
3859: }
3860: } else {
3861: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3862: }
3863: }
3864:
1.1164 raeburn 3865: sub embedded_dependency {
3866: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3867: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3868: if (($identifier ne '') &&
3869: (ref($related->{$identifier}) eq 'ARRAY') &&
3870: ($pathfrom ne '')) {
3871: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3872: foreach my $dep (@{$related->{$identifier}}) {
3873: &add_filetype($allfiles,$path.$dep,'object');
3874: }
3875: }
3876: }
3877: return;
3878: }
3879:
1.493 albertel 3880: sub removeuploadedurl {
1.984 neumanie 3881: my ($url)=@_;
3882: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3883: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3884: }
3885:
3886: sub removeuserfile {
3887: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3888: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3889: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3890: if ($result eq 'ok') {
1.798 raeburn 3891: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3892: my $metafile = $fname.'.meta';
3893: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3894: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3895: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3896: my $sqlresult =
1.823 albertel 3897: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3898: 'portfolio_metadata',$group,
3899: 'delete');
1.798 raeburn 3900: }
3901: }
3902: return $result;
1.257 www 3903: }
1.15 www 3904:
1.530 albertel 3905: sub mkdiruserfile {
3906: my ($docuname,$docudom,$dir)=@_;
3907: my $home=&homeserver($docuname,$docudom);
3908: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3909: }
3910:
1.531 albertel 3911: sub renameuserfile {
3912: my ($docuname,$docudom,$old,$new)=@_;
3913: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3914: my $result = &reply("renameuserfile:$docudom:$docuname:".
3915: &escape("$old").':'.&escape("$new"),$home);
3916: if ($result eq 'ok') {
3917: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3918: my $oldmeta = $old.'.meta';
3919: my $newmeta = $new.'.meta';
3920: my $metaresult =
3921: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3922: my $url = "/uploaded/$docudom/$docuname/$old";
3923: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3924: my $sqlresult =
1.823 albertel 3925: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3926: 'portfolio_metadata',$group,
3927: 'delete');
1.798 raeburn 3928: }
3929: }
3930: return $result;
1.531 albertel 3931: }
3932:
1.14 www 3933: # ------------------------------------------------------------------------- Log
3934:
3935: sub log {
3936: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3937: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3938: }
3939:
3940: # ------------------------------------------------------------------ Course Log
1.352 www 3941: #
3942: # This routine flushes several buffers of non-mission-critical nature
3943: #
1.157 www 3944:
3945: sub flushcourselogs {
1.352 www 3946: &logthis('Flushing log buffers');
3947: #
3948: # course logs
3949: # This is a log of all transactions in a course, which can be used
3950: # for data mining purposes
3951: #
3952: # It also collects the courseid database, which lists last transaction
3953: # times and course titles for all courseids
3954: #
3955: my %courseidbuffer=();
1.921 raeburn 3956: foreach my $crsid (keys(%courselogs)) {
1.352 www 3957: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3958: &escape($courselogs{$crsid}),
3959: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3960: delete $courselogs{$crsid};
3961: } else {
3962: &logthis('Failed to flush log buffer for '.$crsid);
3963: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3964: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3965: " exceeded maximum size, deleting.</font>");
3966: delete $courselogs{$crsid};
3967: }
1.352 www 3968: }
1.920 raeburn 3969: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3970: 'description' => $coursedescrbuf{$crsid},
3971: 'inst_code' => $courseinstcodebuf{$crsid},
3972: 'type' => $coursetypebuf{$crsid},
3973: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3974: };
1.191 harris41 3975: }
1.352 www 3976: #
3977: # Write course id database (reverse lookup) to homeserver of courses
3978: # Is used in pickcourse
3979: #
1.840 albertel 3980: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3981: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3982: $courseidbuffer{$crs_home},
3983: $crs_home,'timeonly');
1.352 www 3984: }
3985: #
3986: # File accesses
3987: # Writes to the dynamic metadata of resources to get hit counts, etc.
3988: #
1.449 matthew 3989: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3990: if ($entry =~ /___count$/) {
3991: my ($dom,$name);
1.807 albertel 3992: ($dom,$name,undef)=
1.811 albertel 3993: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3994: if (! defined($dom) || $dom eq '' ||
3995: ! defined($name) || $name eq '') {
1.620 albertel 3996: my $cid = $env{'request.course.id'};
3997: $dom = $env{'request.'.$cid.'.domain'};
3998: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3999: }
1.450 matthew 4000: my $value = $accesshash{$entry};
4001: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4002: my %temphash=($url => $value);
1.449 matthew 4003: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4004: if ($result eq 'ok') {
4005: delete $accesshash{$entry};
4006: }
4007: } else {
1.811 albertel 4008: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4009: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4010: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4011: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4012: delete $accesshash{$entry};
4013: }
1.185 www 4014: }
1.191 harris41 4015: }
1.352 www 4016: #
4017: # Roles
4018: # Reverse lookup of user roles for course faculty/staff and co-authorship
4019: #
1.800 albertel 4020: foreach my $entry (keys(%userrolehash)) {
1.351 www 4021: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4022: split(/\:/,$entry);
4023: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4024: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4025: $rudom,$runame) eq 'ok') {
4026: delete $userrolehash{$entry};
4027: }
4028: }
1.662 raeburn 4029: #
4030: # Reverse lookup of domain roles (dc, ad, li, sc, au)
4031: #
4032: my %domrolebuffer = ();
1.1000 raeburn 4033: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4034: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4035: if ($domrolebuffer{$rudom}) {
4036: $domrolebuffer{$rudom}.='&'.&escape($entry).
4037: '='.&escape($domainrolehash{$entry});
4038: } else {
4039: $domrolebuffer{$rudom}.=&escape($entry).
4040: '='.&escape($domainrolehash{$entry});
4041: }
4042: delete $domainrolehash{$entry};
4043: }
4044: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 4045: my %servers = &get_servers($dom,'library');
4046: foreach my $tryserver (keys(%servers)) {
4047: unless (&reply('domroleput:'.$dom.':'.
4048: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4049: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4050: }
1.662 raeburn 4051: }
4052: }
1.186 www 4053: $dumpcount++;
1.157 www 4054: }
4055:
4056: sub courselog {
4057: my $what=shift;
1.158 www 4058: $what=time.':'.$what;
1.620 albertel 4059: unless ($env{'request.course.id'}) { return ''; }
4060: $coursedombuf{$env{'request.course.id'}}=
4061: $env{'course.'.$env{'request.course.id'}.'.domain'};
4062: $coursenumbuf{$env{'request.course.id'}}=
4063: $env{'course.'.$env{'request.course.id'}.'.num'};
4064: $coursehombuf{$env{'request.course.id'}}=
4065: $env{'course.'.$env{'request.course.id'}.'.home'};
4066: $coursedescrbuf{$env{'request.course.id'}}=
4067: $env{'course.'.$env{'request.course.id'}.'.description'};
4068: $courseinstcodebuf{$env{'request.course.id'}}=
4069: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4070: $courseownerbuf{$env{'request.course.id'}}=
4071: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4072: $coursetypebuf{$env{'request.course.id'}}=
4073: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4074: if (defined $courselogs{$env{'request.course.id'}}) {
4075: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4076: } else {
1.620 albertel 4077: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4078: }
1.620 albertel 4079: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4080: &flushcourselogs();
4081: }
1.158 www 4082: }
4083:
4084: sub courseacclog {
4085: my $fnsymb=shift;
1.620 albertel 4086: unless ($env{'request.course.id'}) { return ''; }
4087: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4088: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4089: $what.=':POST';
1.583 matthew 4090: # FIXME: Probably ought to escape things....
1.800 albertel 4091: foreach my $key (keys(%env)) {
4092: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4093: my $formitem = $1;
4094: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4095: $what.=':'.$formitem.'='.$env{$key};
4096: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4097: $what.=':'.$formitem.'='.$env{$key};
4098: }
1.158 www 4099: }
1.191 harris41 4100: }
1.583 matthew 4101: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4102: # FIXME: We should not be depending on a form parameter that someone
4103: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4104: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4105: $what.= ':POST';
4106: # FIXME: Probably ought to escape things....
4107: foreach my $element ('courseexp','crsfulltext','crsrelated',
4108: 'crsdiscuss') {
1.620 albertel 4109: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4110: }
4111: }
1.158 www 4112: }
4113: &courselog($what);
1.149 www 4114: }
4115:
1.185 www 4116: sub countacc {
4117: my $url=&declutter(shift);
1.458 matthew 4118: return if (! defined($url) || $url eq '');
1.620 albertel 4119: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4120: #
4121: # Mark that this url was used in this course
4122: #
1.620 albertel 4123: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4124: #
4125: # Increase the access count for this resource in this child process
4126: #
1.281 www 4127: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4128: $accesshash{$key}++;
1.185 www 4129: }
1.349 www 4130:
1.361 www 4131: sub linklog {
4132: my ($from,$to)=@_;
4133: $from=&declutter($from);
4134: $to=&declutter($to);
4135: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4136: $accesshash{$to.'___'.$from.'___goto'}=1;
4137: }
1.1160 www 4138:
4139: sub statslog {
4140: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4141: if ($users<2) { return; }
4142: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4143: 'course' => $env{'request.course.id'},
4144: 'sections' => '"all"',
4145: 'num_students' => $users,
4146: 'part' => $part,
4147: 'symb' => $symb,
4148: 'mean_tries' => $av_attempts,
4149: 'deg_of_diff' => $degdiff});
4150: foreach my $key (keys(%dynstore)) {
4151: $accesshash{$key}=$dynstore{$key};
4152: }
4153: }
1.361 www 4154:
1.349 www 4155: sub userrolelog {
4156: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4157: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4158: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4159: $userrolehash
4160: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4161: =$tend.':'.$tstart;
1.662 raeburn 4162: }
1.1169 droeschl 4163: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4164: $userrolehash
4165: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4166: =$tend.':'.$tstart;
4167: }
1.1169 droeschl 4168: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 4169: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4170: $domainrolehash
4171: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4172: = $tend.':'.$tstart;
4173: }
1.351 www 4174: }
4175:
1.957 raeburn 4176: sub courserolelog {
4177: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4178: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4179: my $cdom = $1;
4180: my $cnum = $2;
4181: my $sec = $3;
4182: my $namespace = 'rolelog';
4183: my %storehash = (
4184: role => $trole,
4185: start => $tstart,
4186: end => $tend,
4187: selfenroll => $selfenroll,
4188: context => $context,
4189: );
4190: if ($trole eq 'gr') {
4191: $namespace = 'groupslog';
4192: $storehash{'group'} = $sec;
4193: } else {
4194: $storehash{'section'} = $sec;
4195: }
1.1188 raeburn 4196: &write_log('course',$namespace,\%storehash,$delflag,$username,
4197: $domain,$cnum,$cdom);
1.1184 raeburn 4198: if (($trole ne 'st') || ($sec ne '')) {
4199: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4200: }
4201: }
4202: return;
4203: }
4204:
1.1184 raeburn 4205: sub domainrolelog {
4206: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4207: if ($area =~ m{^/($match_domain)/$}) {
4208: my $cdom = $1;
4209: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4210: my $namespace = 'rolelog';
4211: my %storehash = (
4212: role => $trole,
4213: start => $tstart,
4214: end => $tend,
4215: context => $context,
4216: );
1.1188 raeburn 4217: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4218: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4219: }
4220: return;
4221:
4222: }
4223:
4224: sub coauthorrolelog {
4225: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4226: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4227: my $audom = $1;
4228: my $auname = $2;
4229: my $namespace = 'rolelog';
4230: my %storehash = (
4231: role => $trole,
4232: start => $tstart,
4233: end => $tend,
4234: context => $context,
4235: );
1.1188 raeburn 4236: &write_log('author',$namespace,\%storehash,$delflag,$username,
4237: $domain,$auname,$audom);
1.1184 raeburn 4238: }
4239: return;
4240: }
4241:
1.351 www 4242: sub get_course_adv_roles {
1.948 raeburn 4243: my ($cid,$codes) = @_;
1.620 albertel 4244: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4245: my %coursehash=&coursedescription($cid);
1.988 raeburn 4246: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4247: my %nothide=();
1.800 albertel 4248: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4249: if ($user !~ /:/) {
4250: $nothide{join(':',split(/[\@]/,$user))}=1;
4251: } else {
4252: $nothide{$user}=1;
4253: }
1.470 www 4254: }
1.1219 raeburn 4255: my @possdoms = ($coursehash{'domain'});
4256: if ($coursehash{'checkforpriv'}) {
4257: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4258: }
1.351 www 4259: my %returnhash=();
4260: my %dumphash=
4261: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4262: my $now=time;
1.997 raeburn 4263: my %privileged;
1.1000 raeburn 4264: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4265: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4266: if (($tstart) && ($tstart<0)) { next; }
4267: if (($tend) && ($tend<$now)) { next; }
4268: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4269: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4270: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4271: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4272: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4273: if ($role eq 'cr') { next; }
1.948 raeburn 4274: if ($codes) {
4275: if ($section) { $role .= ':'.$section; }
4276: if ($returnhash{$role}) {
4277: $returnhash{$role}.=','.$username.':'.$domain;
4278: } else {
4279: $returnhash{$role}=$username.':'.$domain;
4280: }
1.351 www 4281: } else {
1.988 raeburn 4282: my $key=&plaintext($role,$crstype);
1.973 bisitz 4283: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4284: if ($returnhash{$key}) {
4285: $returnhash{$key}.=','.$username.':'.$domain;
4286: } else {
4287: $returnhash{$key}=$username.':'.$domain;
4288: }
1.351 www 4289: }
1.948 raeburn 4290: }
1.400 www 4291: return %returnhash;
4292: }
4293:
4294: sub get_my_roles {
1.937 raeburn 4295: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4296: unless (defined($uname)) { $uname=$env{'user.name'}; }
4297: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4298: my (%dumphash,%nothide);
1.1086 raeburn 4299: if ($context eq 'userroles') {
1.1166 raeburn 4300: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4301: } else {
1.1219 raeburn 4302: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4303: if ($hidepriv) {
4304: my %coursehash=&coursedescription($udom.'_'.$uname);
4305: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4306: if ($user !~ /:/) {
4307: $nothide{join(':',split(/[\@]/,$user))} = 1;
4308: } else {
4309: $nothide{$user} = 1;
4310: }
4311: }
4312: }
1.858 raeburn 4313: }
1.400 www 4314: my %returnhash=();
4315: my $now=time;
1.999 raeburn 4316: my %privileged;
1.800 albertel 4317: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4318: my ($role,$tend,$tstart);
4319: if ($context eq 'userroles') {
1.1149 raeburn 4320: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4321: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4322: } else {
4323: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4324: }
1.400 www 4325: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4326: my $status = 'active';
1.939 raeburn 4327: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4328: $status = 'previous';
4329: }
4330: if (($tstart) && ($now<$tstart)) {
4331: $status = 'future';
4332: }
4333: if (ref($types) eq 'ARRAY') {
4334: if (!grep(/^\Q$status\E$/,@{$types})) {
4335: next;
4336: }
4337: } else {
4338: if ($status ne 'active') {
4339: next;
4340: }
4341: }
1.867 raeburn 4342: my ($rolecode,$username,$domain,$section,$area);
4343: if ($context eq 'userroles') {
1.1186 raeburn 4344: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4345: (undef,$domain,$username,$section) = split(/\//,$area);
4346: } else {
4347: ($role,$username,$domain,$section) = split(/\:/,$entry);
4348: }
1.832 raeburn 4349: if (ref($roledoms) eq 'ARRAY') {
4350: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4351: next;
4352: }
4353: }
4354: if (ref($roles) eq 'ARRAY') {
4355: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4356: if ($role =~ /^cr\//) {
4357: if (!grep(/^cr$/,@{$roles})) {
4358: next;
4359: }
1.1104 raeburn 4360: } elsif ($role =~ /^gr\//) {
4361: if (!grep(/^gr$/,@{$roles})) {
4362: next;
4363: }
1.922 raeburn 4364: } else {
4365: next;
4366: }
1.832 raeburn 4367: }
1.867 raeburn 4368: }
1.937 raeburn 4369: if ($hidepriv) {
1.1219 raeburn 4370: my @privroles = ('dc','su');
1.999 raeburn 4371: if ($context eq 'userroles') {
1.1219 raeburn 4372: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4373: } else {
1.1219 raeburn 4374: my $possdoms = [$domain];
4375: if (ref($roledoms) eq 'ARRAY') {
4376: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4377: }
1.1219 raeburn 4378: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4379: if (!$nothide{$username.':'.$domain}) {
4380: next;
4381: }
4382: }
1.937 raeburn 4383: }
4384: }
1.933 raeburn 4385: if ($withsec) {
4386: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4387: $tstart.':'.$tend;
4388: } else {
4389: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4390: }
1.832 raeburn 4391: }
1.373 www 4392: return %returnhash;
1.399 www 4393: }
4394:
4395: # ----------------------------------------------------- Frontpage Announcements
4396: #
4397: #
4398:
4399: sub postannounce {
4400: my ($server,$text)=@_;
1.844 albertel 4401: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4402: unless ($text=~/\w/) { $text=''; }
4403: return &reply('setannounce:'.&escape($text),$server);
4404: }
4405:
4406: sub getannounce {
1.448 albertel 4407:
4408: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4409: my $announcement='';
1.800 albertel 4410: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4411: close($fh);
1.399 www 4412: if ($announcement=~/\w/) {
4413: return
4414: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4415: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4416: } else {
4417: return '';
4418: }
4419: } else {
4420: return '';
4421: }
1.351 www 4422: }
1.353 www 4423:
4424: # ---------------------------------------------------------- Course ID routines
4425: # Deal with domain's nohist_courseid.db files
4426: #
4427:
4428: sub courseidput {
1.921 raeburn 4429: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4430: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4431: my $outcome;
4432: if ($caller eq 'timeonly') {
4433: my $cids = '';
4434: foreach my $item (keys(%$storehash)) {
4435: $cids.=&escape($item).'&';
4436: }
4437: $cids=~s/\&$//;
4438: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4439: $coursehome);
4440: } else {
4441: my $items = '';
4442: foreach my $item (keys(%$storehash)) {
4443: $items.= &escape($item).'='.
4444: &freeze_escape($$storehash{$item}).'&';
4445: }
4446: $items=~s/\&$//;
4447: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4448: $coursehome);
1.918 raeburn 4449: }
4450: if ($outcome eq 'unknown_cmd') {
4451: my $what;
4452: foreach my $cid (keys(%$storehash)) {
4453: $what .= &escape($cid).'=';
1.921 raeburn 4454: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4455: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4456: }
4457: $what =~ s/\:$/&/;
4458: }
4459: $what =~ s/\&$//;
4460: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4461: } else {
4462: return $outcome;
4463: }
1.353 www 4464: }
4465:
4466: sub courseiddump {
1.921 raeburn 4467: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4468: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4469: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4470: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4471: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4472: my $as_hash = 1;
4473: my %returnhash;
4474: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4475: my %libserv = &all_library();
4476: foreach my $tryserver (keys(%libserv)) {
4477: if ( ( $hostidflag == 1
4478: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4479: || (!defined($hostidflag)) ) {
4480:
1.918 raeburn 4481: if (($domfilter eq '') ||
4482: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4483: my $rep;
4484: if (grep { $_ eq $tryserver } current_machine_ids()) {
4485: $rep = LONCAPA::Lond::dump_course_id_handler(
4486: join(":", (&host_domain($tryserver), $sincefilter,
4487: &escape($descfilter), &escape($instcodefilter),
4488: &escape($ownerfilter), &escape($coursefilter),
4489: &escape($typefilter), &escape($regexp_ok),
4490: $as_hash, &escape($selfenrollonly),
4491: &escape($catfilter), $showhidden, $caller,
4492: &escape($cloner), &escape($cc_clone), $cloneonly,
4493: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4494: &escape($creationcontext),$domcloner,$hasuniquecode,
4495: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4496: } else {
4497: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4498: $sincefilter.':'.&escape($descfilter).':'.
4499: &escape($instcodefilter).':'.&escape($ownerfilter).
4500: ':'.&escape($coursefilter).':'.&escape($typefilter).
4501: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4502: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4503: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4504: &escape($cc_clone).':'.$cloneonly.':'.
4505: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4506: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4507: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4508: }
4509:
1.918 raeburn 4510: my @pairs=split(/\&/,$rep);
4511: foreach my $item (@pairs) {
4512: my ($key,$value)=split(/\=/,$item,2);
4513: $key = &unescape($key);
4514: next if ($key =~ /^error: 2 /);
4515: my $result = &thaw_unescape($value);
4516: if (ref($result) eq 'HASH') {
4517: $returnhash{$key}=$result;
4518: } else {
1.921 raeburn 4519: my @responses = split(/:/,$value);
4520: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4521: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4522: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4523: }
1.1008 raeburn 4524: }
1.353 www 4525: }
4526: }
4527: }
4528: }
4529: return %returnhash;
4530: }
4531:
1.1055 raeburn 4532: sub courselastaccess {
4533: my ($cdom,$cnum,$hostidref) = @_;
4534: my %returnhash;
4535: if ($cdom && $cnum) {
4536: my $chome = &homeserver($cnum,$cdom);
4537: if ($chome ne 'no_host') {
4538: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4539: &extract_lastaccess(\%returnhash,$rep);
4540: }
4541: } else {
4542: if (!$cdom) { $cdom=''; }
4543: my %libserv = &all_library();
4544: foreach my $tryserver (keys(%libserv)) {
4545: if (ref($hostidref) eq 'ARRAY') {
4546: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4547: }
4548: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4549: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4550: &extract_lastaccess(\%returnhash,$rep);
4551: }
4552: }
4553: }
4554: return %returnhash;
4555: }
4556:
4557: sub extract_lastaccess {
4558: my ($returnhash,$rep) = @_;
4559: if (ref($returnhash) eq 'HASH') {
4560: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4561: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4562: $rep eq '') {
4563: my @pairs=split(/\&/,$rep);
4564: foreach my $item (@pairs) {
4565: my ($key,$value)=split(/\=/,$item,2);
4566: $key = &unescape($key);
4567: next if ($key =~ /^error: 2 /);
4568: $returnhash->{$key} = &thaw_unescape($value);
4569: }
4570: }
4571: }
4572: return;
4573: }
4574:
1.658 raeburn 4575: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4576:
4577: sub dcmailput {
1.685 raeburn 4578: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4579: my $status = &Apache::lonnet::critical(
1.740 www 4580: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4581: &escape($message),$server);
1.662 raeburn 4582: return $status;
4583: }
4584:
1.658 raeburn 4585: sub dcmaildump {
4586: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4587: my %returnhash=();
1.846 albertel 4588:
4589: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4590: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4591: &escape($enddate).':';
4592: my @esc_senders=map { &escape($_)} @$senders;
4593: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4594: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4595: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4596: if (($key) && ($value)) {
4597: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4598: }
4599: }
4600: }
4601: return %returnhash;
4602: }
1.662 raeburn 4603: # ---------------------------------------------------------- Domain roles
4604:
4605: sub get_domain_roles {
4606: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4607: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4608: $startdate = '.';
4609: }
1.1018 raeburn 4610: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4611: $enddate = '.';
4612: }
1.922 raeburn 4613: my $rolelist;
4614: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4615: $rolelist = join('&',@{$roles});
1.922 raeburn 4616: }
1.662 raeburn 4617: my %personnel = ();
1.841 albertel 4618:
4619: my %servers = &get_servers($dom,'library');
4620: foreach my $tryserver (keys(%servers)) {
4621: %{$personnel{$tryserver}}=();
4622: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4623: &escape($startdate).':'.
4624: &escape($enddate).':'.
4625: &escape($rolelist), $tryserver))) {
4626: my ($key,$value) = split(/\=/,$line,2);
4627: if (($key) && ($value)) {
4628: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4629: }
4630: }
1.662 raeburn 4631: }
4632: return %personnel;
4633: }
1.658 raeburn 4634:
1.1057 www 4635: # ----------------------------------------------------------- Interval timing
1.149 www 4636:
1.1153 www 4637: {
4638: # Caches needed for speedup of navmaps
4639: # We don't want to cache this for very long at all (5 seconds at most)
4640: #
4641: # The user for whom we cache
4642: my $cachedkey='';
4643: # The cached times for this user
4644: my %cachedtimes=();
4645: # When this was last done
1.1282 raeburn 4646: my $cachedtime='';
1.1153 www 4647:
4648: sub load_all_first_access {
1.1308 raeburn 4649: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 4650: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 4651: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
4652: (!$ignorecache)) {
1.1154 raeburn 4653: return;
4654: }
4655: $cachedtime=time;
4656: $cachedkey=$uname.':'.$udom;
4657: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4658: }
4659:
1.504 albertel 4660: sub get_first_access {
1.1308 raeburn 4661: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 4662: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4663: if ($argsymb) { $symb=$argsymb; }
4664: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4665: if ($argmap) { $map = $argmap; }
1.926 albertel 4666: if ($type eq 'course') {
4667: $res='course';
4668: } elsif ($type eq 'map') {
1.588 albertel 4669: $res=&symbread($map);
4670: } else {
4671: $res=$symb;
4672: }
1.1308 raeburn 4673: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 4674: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4675: }
4676:
4677: sub set_first_access {
1.1162 raeburn 4678: my ($type,$interval)=@_;
1.790 albertel 4679: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4680: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4681: if ($type eq 'course') {
4682: $res='course';
4683: } elsif ($type eq 'map') {
1.588 albertel 4684: $res=&symbread($map);
4685: } else {
4686: $res=$symb;
4687: }
1.1153 www 4688: $cachedkey='';
1.1162 raeburn 4689: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4690: if (!$firstaccess) {
1.1162 raeburn 4691: my $start = time;
4692: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4693: $udom,$uname);
4694: if ($putres eq 'ok') {
4695: &put('timerinterval',{"$courseid\0$res"=>$interval},
4696: $udom,$uname);
4697: &appenv(
4698: {
4699: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4700: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4701: }
4702: );
4703: }
4704: return $putres;
1.505 albertel 4705: }
4706: return 'already_set';
1.504 albertel 4707: }
1.1153 www 4708: }
1.1282 raeburn 4709:
1.110 www 4710: # --------------------------------------------- Set Expire Date for Spreadsheet
4711:
4712: sub expirespread {
4713: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4714: my $cid=$env{'request.course.id'};
1.110 www 4715: if ($cid) {
4716: my $now=time;
4717: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4718: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4719: $env{'course.'.$cid.'.num'}.
1.110 www 4720: ':nohist_expirationdates:'.
4721: &escape($key).'='.$now,
1.620 albertel 4722: $env{'course.'.$cid.'.home'})
1.110 www 4723: }
4724: return 'ok';
1.14 www 4725: }
4726:
1.109 www 4727: # ----------------------------------------------------- Devalidate Spreadsheets
4728:
4729: sub devalidate {
1.325 www 4730: my ($symb,$uname,$udom)=@_;
1.620 albertel 4731: my $cid=$env{'request.course.id'};
1.109 www 4732: if ($cid) {
1.391 matthew 4733: # delete the stored spreadsheets for
4734: # - the student level sheet of this user in course's homespace
4735: # - the assessment level sheet for this resource
4736: # for this user in user's homespace
1.553 albertel 4737: # - current conditional state info
1.325 www 4738: my $key=$uname.':'.$udom.':';
1.109 www 4739: my $status=
1.299 matthew 4740: &del('nohist_calculatedsheets',
1.391 matthew 4741: [$key.'studentcalc:'],
1.620 albertel 4742: $env{'course.'.$cid.'.domain'},
4743: $env{'course.'.$cid.'.num'})
1.133 albertel 4744: .' '.
4745: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4746: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4747: unless ($status eq 'ok ok') {
4748: &logthis('Could not devalidate spreadsheet '.
1.325 www 4749: $uname.' at '.$udom.' for '.
1.109 www 4750: $symb.': '.$status);
1.133 albertel 4751: }
1.553 albertel 4752: &delenv('user.state.'.$cid);
1.109 www 4753: }
4754: }
4755:
1.265 albertel 4756: sub get_scalar {
4757: my ($string,$end) = @_;
4758: my $value;
4759: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4760: $value = $1;
4761: } elsif ($$string =~ s/^([^&]*?)&//) {
4762: $value = $1;
4763: }
4764: return &unescape($value);
4765: }
4766:
4767: sub array2str {
4768: my (@array) = @_;
4769: my $result=&arrayref2str(\@array);
4770: $result=~s/^__ARRAY_REF__//;
4771: $result=~s/__END_ARRAY_REF__$//;
4772: return $result;
4773: }
4774:
1.204 albertel 4775: sub arrayref2str {
4776: my ($arrayref) = @_;
1.265 albertel 4777: my $result='__ARRAY_REF__';
1.204 albertel 4778: foreach my $elem (@$arrayref) {
1.265 albertel 4779: if(ref($elem) eq 'ARRAY') {
4780: $result.=&arrayref2str($elem).'&';
4781: } elsif(ref($elem) eq 'HASH') {
4782: $result.=&hashref2str($elem).'&';
4783: } elsif(ref($elem)) {
4784: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4785: } else {
4786: $result.=&escape($elem).'&';
4787: }
4788: }
4789: $result=~s/\&$//;
1.265 albertel 4790: $result .= '__END_ARRAY_REF__';
1.204 albertel 4791: return $result;
4792: }
4793:
1.168 albertel 4794: sub hash2str {
1.204 albertel 4795: my (%hash) = @_;
4796: my $result=&hashref2str(\%hash);
1.265 albertel 4797: $result=~s/^__HASH_REF__//;
4798: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4799: return $result;
4800: }
4801:
4802: sub hashref2str {
4803: my ($hashref)=@_;
1.265 albertel 4804: my $result='__HASH_REF__';
1.800 albertel 4805: foreach my $key (sort(keys(%$hashref))) {
4806: if (ref($key) eq 'ARRAY') {
4807: $result.=&arrayref2str($key).'=';
4808: } elsif (ref($key) eq 'HASH') {
4809: $result.=&hashref2str($key).'=';
4810: } elsif (ref($key)) {
1.265 albertel 4811: $result.='=';
1.800 albertel 4812: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4813: } else {
1.1132 raeburn 4814: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4815: }
4816:
1.800 albertel 4817: if(ref($hashref->{$key}) eq 'ARRAY') {
4818: $result.=&arrayref2str($hashref->{$key}).'&';
4819: } elsif(ref($hashref->{$key}) eq 'HASH') {
4820: $result.=&hashref2str($hashref->{$key}).'&';
4821: } elsif(ref($hashref->{$key})) {
1.265 albertel 4822: $result.='&';
1.800 albertel 4823: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4824: } else {
1.800 albertel 4825: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4826: }
4827: }
1.168 albertel 4828: $result=~s/\&$//;
1.265 albertel 4829: $result .= '__END_HASH_REF__';
1.168 albertel 4830: return $result;
4831: }
4832:
4833: sub str2hash {
1.265 albertel 4834: my ($string)=@_;
4835: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4836: return %$hash;
4837: }
4838:
4839: sub str2hashref {
1.168 albertel 4840: my ($string) = @_;
1.265 albertel 4841:
4842: my %hash;
4843:
4844: if($string !~ /^__HASH_REF__/) {
4845: if (! ($string eq '' || !defined($string))) {
4846: $hash{'error'}='Not hash reference';
4847: }
4848: return (\%hash, $string);
4849: }
4850:
4851: $string =~ s/^__HASH_REF__//;
4852:
4853: while($string !~ /^__END_HASH_REF__/) {
4854: #key
4855: my $key='';
4856: if($string =~ /^__HASH_REF__/) {
4857: ($key, $string)=&str2hashref($string);
4858: if(defined($key->{'error'})) {
4859: $hash{'error'}='Bad data';
4860: return (\%hash, $string);
4861: }
4862: } elsif($string =~ /^__ARRAY_REF__/) {
4863: ($key, $string)=&str2arrayref($string);
4864: if($key->[0] eq 'Array reference error') {
4865: $hash{'error'}='Bad data';
4866: return (\%hash, $string);
4867: }
4868: } else {
4869: $string =~ s/^(.*?)=//;
1.267 albertel 4870: $key=&unescape($1);
1.265 albertel 4871: }
4872: $string =~ s/^=//;
4873:
4874: #value
4875: my $value='';
4876: if($string =~ /^__HASH_REF__/) {
4877: ($value, $string)=&str2hashref($string);
4878: if(defined($value->{'error'})) {
4879: $hash{'error'}='Bad data';
4880: return (\%hash, $string);
4881: }
4882: } elsif($string =~ /^__ARRAY_REF__/) {
4883: ($value, $string)=&str2arrayref($string);
4884: if($value->[0] eq 'Array reference error') {
4885: $hash{'error'}='Bad data';
4886: return (\%hash, $string);
4887: }
4888: } else {
4889: $value=&get_scalar(\$string,'__END_HASH_REF__');
4890: }
4891: $string =~ s/^&//;
4892:
4893: $hash{$key}=$value;
1.204 albertel 4894: }
1.265 albertel 4895:
4896: $string =~ s/^__END_HASH_REF__//;
4897:
4898: return (\%hash, $string);
1.204 albertel 4899: }
4900:
4901: sub str2array {
1.265 albertel 4902: my ($string)=@_;
4903: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4904: return @$array;
4905: }
4906:
4907: sub str2arrayref {
1.204 albertel 4908: my ($string) = @_;
1.265 albertel 4909: my @array;
4910:
4911: if($string !~ /^__ARRAY_REF__/) {
4912: if (! ($string eq '' || !defined($string))) {
4913: $array[0]='Array reference error';
4914: }
4915: return (\@array, $string);
4916: }
4917:
4918: $string =~ s/^__ARRAY_REF__//;
4919:
4920: while($string !~ /^__END_ARRAY_REF__/) {
4921: my $value='';
4922: if($string =~ /^__HASH_REF__/) {
4923: ($value, $string)=&str2hashref($string);
4924: if(defined($value->{'error'})) {
4925: $array[0] ='Array reference error';
4926: return (\@array, $string);
4927: }
4928: } elsif($string =~ /^__ARRAY_REF__/) {
4929: ($value, $string)=&str2arrayref($string);
4930: if($value->[0] eq 'Array reference error') {
4931: $array[0] ='Array reference error';
4932: return (\@array, $string);
4933: }
4934: } else {
4935: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4936: }
4937: $string =~ s/^&//;
4938:
4939: push(@array, $value);
1.191 harris41 4940: }
1.265 albertel 4941:
4942: $string =~ s/^__END_ARRAY_REF__//;
4943:
4944: return (\@array, $string);
1.168 albertel 4945: }
4946:
1.167 albertel 4947: # -------------------------------------------------------------------Temp Store
4948:
1.168 albertel 4949: sub tmpreset {
4950: my ($symb,$namespace,$domain,$stuname) = @_;
4951: if (!$symb) {
4952: $symb=&symbread();
1.620 albertel 4953: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4954: }
4955: $symb=escape($symb);
4956:
1.620 albertel 4957: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4958: $namespace=~s/\//\_/g;
4959: $namespace=~s/\W//g;
4960:
1.620 albertel 4961: if (!$domain) { $domain=$env{'user.domain'}; }
4962: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4963: if ($domain eq 'public' && $stuname eq 'public') {
4964: $stuname=$ENV{'REMOTE_ADDR'};
4965: }
1.1117 foxr 4966: my $path=LONCAPA::tempdir();
1.168 albertel 4967: my %hash;
4968: if (tie(%hash,'GDBM_File',
4969: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4970: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4971: foreach my $key (keys(%hash)) {
1.180 albertel 4972: if ($key=~ /:$symb/) {
1.168 albertel 4973: delete($hash{$key});
4974: }
4975: }
4976: }
4977: }
4978:
1.167 albertel 4979: sub tmpstore {
1.168 albertel 4980: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4981:
4982: if (!$symb) {
4983: $symb=&symbread();
1.620 albertel 4984: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4985: }
4986: $symb=escape($symb);
4987:
4988: if (!$namespace) {
4989: # I don't think we would ever want to store this for a course.
4990: # it seems this will only be used if we don't have a course.
1.620 albertel 4991: #$namespace=$env{'request.course.id'};
1.168 albertel 4992: #if (!$namespace) {
1.620 albertel 4993: $namespace=$env{'request.state'};
1.168 albertel 4994: #}
4995: }
4996: $namespace=~s/\//\_/g;
4997: $namespace=~s/\W//g;
1.620 albertel 4998: if (!$domain) { $domain=$env{'user.domain'}; }
4999: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5000: if ($domain eq 'public' && $stuname eq 'public') {
5001: $stuname=$ENV{'REMOTE_ADDR'};
5002: }
1.168 albertel 5003: my $now=time;
5004: my %hash;
1.1117 foxr 5005: my $path=LONCAPA::tempdir();
1.168 albertel 5006: if (tie(%hash,'GDBM_File',
5007: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5008: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5009: $hash{"version:$symb"}++;
5010: my $version=$hash{"version:$symb"};
5011: my $allkeys='';
5012: foreach my $key (keys(%$storehash)) {
5013: $allkeys.=$key.':';
1.591 albertel 5014: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5015: }
5016: $hash{"$version:$symb:timestamp"}=$now;
5017: $allkeys.='timestamp';
5018: $hash{"$version:keys:$symb"}=$allkeys;
5019: if (untie(%hash)) {
5020: return 'ok';
5021: } else {
5022: return "error:$!";
5023: }
5024: } else {
5025: return "error:$!";
5026: }
5027: }
1.167 albertel 5028:
1.168 albertel 5029: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5030:
1.168 albertel 5031: sub tmprestore {
5032: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5033:
1.168 albertel 5034: if (!$symb) {
5035: $symb=&symbread();
1.620 albertel 5036: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5037: }
5038: $symb=escape($symb);
5039:
1.620 albertel 5040: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5041:
1.620 albertel 5042: if (!$domain) { $domain=$env{'user.domain'}; }
5043: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5044: if ($domain eq 'public' && $stuname eq 'public') {
5045: $stuname=$ENV{'REMOTE_ADDR'};
5046: }
1.168 albertel 5047: my %returnhash;
5048: $namespace=~s/\//\_/g;
5049: $namespace=~s/\W//g;
5050: my %hash;
1.1117 foxr 5051: my $path=LONCAPA::tempdir();
1.168 albertel 5052: if (tie(%hash,'GDBM_File',
5053: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5054: &GDBM_READER(),0640)) {
1.168 albertel 5055: my $version=$hash{"version:$symb"};
5056: $returnhash{'version'}=$version;
5057: my $scope;
5058: for ($scope=1;$scope<=$version;$scope++) {
5059: my $vkeys=$hash{"$scope:keys:$symb"};
5060: my @keys=split(/:/,$vkeys);
5061: my $key;
5062: $returnhash{"$scope:keys"}=$vkeys;
5063: foreach $key (@keys) {
1.591 albertel 5064: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5065: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5066: }
5067: }
1.168 albertel 5068: if (!(untie(%hash))) {
5069: return "error:$!";
5070: }
5071: } else {
5072: return "error:$!";
5073: }
5074: return %returnhash;
1.167 albertel 5075: }
5076:
1.9 www 5077: # ----------------------------------------------------------------------- Store
5078:
5079: sub store {
1.1269 raeburn 5080: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5081: my $home='';
5082:
1.168 albertel 5083: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5084:
1.213 www 5085: $symb=&symbclean($symb);
1.122 albertel 5086: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5087:
1.620 albertel 5088: if (!$domain) { $domain=$env{'user.domain'}; }
5089: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5090:
5091: &devalidate($symb,$stuname,$domain);
1.109 www 5092:
5093: $symb=escape($symb);
1.187 www 5094: if (!$namespace) {
1.620 albertel 5095: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5096: return '';
5097: }
5098: }
1.620 albertel 5099: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5100:
5101: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5102: $$storehash{'host'}=$perlvar{'lonHostID'};
5103:
1.12 www 5104: my $namevalue='';
1.800 albertel 5105: foreach my $key (keys(%$storehash)) {
5106: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5107: }
1.12 www 5108: $namevalue=~s/\&$//;
1.187 www 5109: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 5110: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5111: }
5112:
1.47 www 5113: # -------------------------------------------------------------- Critical Store
5114:
5115: sub cstore {
1.1269 raeburn 5116: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5117: my $home='';
5118:
1.168 albertel 5119: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5120:
1.213 www 5121: $symb=&symbclean($symb);
1.122 albertel 5122: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5123:
1.620 albertel 5124: if (!$domain) { $domain=$env{'user.domain'}; }
5125: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5126:
5127: &devalidate($symb,$stuname,$domain);
1.109 www 5128:
5129: $symb=escape($symb);
1.187 www 5130: if (!$namespace) {
1.620 albertel 5131: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5132: return '';
5133: }
5134: }
1.620 albertel 5135: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5136:
5137: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5138: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5139:
1.47 www 5140: my $namevalue='';
1.800 albertel 5141: foreach my $key (keys(%$storehash)) {
5142: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5143: }
1.47 www 5144: $namevalue=~s/\&$//;
1.187 www 5145: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5146: return critical
1.1269 raeburn 5147: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5148: }
5149:
1.9 www 5150: # --------------------------------------------------------------------- Restore
5151:
5152: sub restore {
1.124 www 5153: my ($symb,$namespace,$domain,$stuname) = @_;
5154: my $home='';
5155:
1.168 albertel 5156: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5157:
1.122 albertel 5158: if (!$symb) {
1.1224 raeburn 5159: return if ($namespace eq 'courserequests');
5160: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5161: } else {
1.1224 raeburn 5162: unless ($namespace eq 'courserequests') {
5163: $symb=&escape(&symbclean($symb));
5164: }
1.122 albertel 5165: }
1.188 www 5166: if (!$namespace) {
1.620 albertel 5167: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5168: return '';
5169: }
5170: }
1.620 albertel 5171: if (!$domain) { $domain=$env{'user.domain'}; }
5172: if (!$stuname) { $stuname=$env{'user.name'}; }
5173: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5174: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5175:
1.12 www 5176: my %returnhash=();
1.800 albertel 5177: foreach my $line (split(/\&/,$answer)) {
5178: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5179: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5180: }
1.75 www 5181: my $version;
5182: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5183: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5184: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5185: }
1.75 www 5186: }
1.13 www 5187: return %returnhash;
1.34 www 5188: }
5189:
5190: # ---------------------------------------------------------- Course Description
1.1118 foxr 5191: #
5192: #
1.34 www 5193:
5194: sub coursedescription {
1.731 albertel 5195: my ($courseid,$args)=@_;
1.34 www 5196: $courseid=~s/^\///;
1.49 www 5197: $courseid=~s/\_/\//g;
1.34 www 5198: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5199: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5200: my $normalid=$cdomain.'_'.$cnum;
5201: # need to always cache even if we get errors otherwise we keep
5202: # trying and trying and trying to get the course description.
5203: my %envhash=();
5204: my %returnhash=();
1.731 albertel 5205:
5206: my $expiretime=600;
5207: if ($env{'request.course.id'} eq $normalid) {
5208: $expiretime=120;
5209: }
5210:
5211: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5212: if (!$args->{'freshen_cache'}
5213: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5214: foreach my $key (keys(%env)) {
5215: next if ($key !~ /^\Q$prefix\E(.*)/);
5216: my ($setting) = $1;
5217: $returnhash{$setting} = $env{$key};
5218: }
5219: return %returnhash;
5220: }
5221:
1.1118 foxr 5222: # get the data again
5223:
1.731 albertel 5224: if (!$args->{'one_time'}) {
5225: $envhash{'course.'.$normalid.'.last_cache'}=time;
5226: }
1.811 albertel 5227:
1.34 www 5228: if ($chome ne 'no_host') {
1.302 albertel 5229: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5230: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5231: my $username = $env{'user.name'}; # Defult username
5232: if(defined $args->{'user'}) {
5233: $username = $args->{'user'};
5234: }
1.129 albertel 5235: $returnhash{'home'}= $chome;
5236: $returnhash{'domain'} = $cdomain;
5237: $returnhash{'num'} = $cnum;
1.741 raeburn 5238: if (!defined($returnhash{'type'})) {
5239: $returnhash{'type'} = 'Course';
5240: }
1.130 albertel 5241: while (my ($name,$value) = each %returnhash) {
1.53 www 5242: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5243: }
1.270 www 5244: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5245: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5246: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5247: $envhash{'course.'.$normalid.'.home'}=$chome;
5248: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5249: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5250: }
5251: }
1.731 albertel 5252: if (!$args->{'one_time'}) {
1.949 raeburn 5253: &appenv(\%envhash);
1.731 albertel 5254: }
1.302 albertel 5255: return %returnhash;
1.461 www 5256: }
5257:
1.1080 raeburn 5258: sub update_released_required {
5259: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5260: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5261: $cid = $env{'request.course.id'};
5262: $cdom = $env{'course.'.$cid.'.domain'};
5263: $cnum = $env{'course.'.$cid.'.num'};
5264: $chome = $env{'course.'.$cid.'.home'};
5265: }
5266: if ($needsrelease) {
5267: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5268: my $needsupdate;
5269: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5270: $needsupdate = 1;
5271: } else {
5272: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5273: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5274: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5275: $needsupdate = 1;
5276: }
5277: }
5278: if ($needsupdate) {
5279: my %needshash = (
5280: 'internal.releaserequired' => $needsrelease,
5281: );
5282: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5283: if ($putresult eq 'ok') {
5284: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5285: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5286: if (ref($crsinfo{$cid}) eq 'HASH') {
5287: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5288: &courseidput($cdom,\%crsinfo,$chome,'notime');
5289: }
5290: }
5291: }
5292: }
5293: return;
5294: }
5295:
1.461 www 5296: # -------------------------------------------------See if a user is privileged
5297:
5298: sub privileged {
1.1219 raeburn 5299: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5300: my $now = time;
1.1219 raeburn 5301: my $roles;
5302: if (ref($possroles) eq 'ARRAY') {
5303: $roles = $possroles;
5304: } else {
5305: $roles = ['dc','su'];
5306: }
5307: if (ref($possdomains) eq 'ARRAY') {
5308: my %privileged = &privileged_by_domain($possdomains,$roles);
5309: foreach my $dom (@{$possdomains}) {
5310: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5311: (ref($privileged{$dom}) eq 'HASH')) {
5312: foreach my $role (@{$roles}) {
5313: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5314: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5315: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5316: return 1 unless (($end && $end < $now) ||
5317: ($start && $start > $now));
5318: }
5319: }
5320: }
5321: }
5322: }
5323: } else {
5324: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5325: my $now = time;
1.1170 droeschl 5326:
1.1275 musolffc 5327: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5328: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5329: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5330: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5331: or ($tstart && $tstart > $now);
1.1170 droeschl 5332: }
1.1219 raeburn 5333: }
5334: }
5335: return 0;
5336: }
1.1170 droeschl 5337:
1.1219 raeburn 5338: sub privileged_by_domain {
5339: my ($domains,$roles) = @_;
5340: my %privileged = ();
5341: my $cachetime = 60*60*24;
5342: my $now = time;
5343: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5344: return %privileged;
5345: }
5346: foreach my $dom (@{$domains}) {
5347: next if (ref($privileged{$dom}) eq 'HASH');
5348: my $needroles;
5349: foreach my $role (@{$roles}) {
5350: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5351: if (defined($cached)) {
5352: if (ref($result) eq 'HASH') {
5353: $privileged{$dom}{$role} = $result;
5354: }
5355: } else {
5356: $needroles = 1;
5357: }
5358: }
5359: if ($needroles) {
5360: my %dompersonnel = &get_domain_roles($dom,$roles);
5361: $privileged{$dom} = {};
5362: foreach my $server (keys(%dompersonnel)) {
5363: if (ref($dompersonnel{$server}) eq 'HASH') {
5364: foreach my $item (keys(%{$dompersonnel{$server}})) {
5365: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5366: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5367: next if ($end && $end < $now);
5368: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5369: $dompersonnel{$server}{$item};
5370: }
5371: }
5372: }
5373: if (ref($privileged{$dom}) eq 'HASH') {
5374: foreach my $role (@{$roles}) {
5375: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5376: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5377: } else {
5378: my %hash = ();
5379: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5380: }
5381: }
5382: }
5383: }
5384: }
5385: return %privileged;
1.9 www 5386: }
1.1 albertel 5387:
1.103 harris41 5388: # -------------------------------------------------------- Get user privileges
1.11 www 5389:
5390: sub rolesinit {
1.1169 droeschl 5391: my ($domain, $username) = @_;
5392: my %userroles = ('user.login.time' => time);
5393: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5394:
5395: # firstaccess and timerinterval are related to timed maps/resources.
5396: # also, blocking can be triggered by an activating timer
5397: # it's saved in the user's %env.
5398: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5399: my %timerinterval = &dump('timerinterval', $domain, $username);
5400: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5401: %timerintchk, %timerintenv);
5402:
1.1162 raeburn 5403: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5404: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5405: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5406: }
1.1169 droeschl 5407:
1.1162 raeburn 5408: foreach my $key (keys(%timerinterval)) {
5409: my ($cid,$rest) = split(/\0/,$key);
5410: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5411: }
1.1169 droeschl 5412:
1.11 www 5413: my %allroles=();
1.1162 raeburn 5414: my %allgroups=();
1.11 www 5415:
1.1274 raeburn 5416: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5417: my $role = $rolesdump{$area};
5418: $area =~ s/\_\w\w$//;
5419:
5420: my ($trole, $tend, $tstart, $group_privs);
5421:
5422: if ($role =~ /^cr/) {
5423: # Custom role, defined by a user
5424: # e.g., user.role.cr/msu/smith/mynewrole
5425: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5426: $trole = $1;
5427: ($tend, $tstart) = split('_', $2);
5428: } else {
5429: $trole = $role;
5430: }
5431: } elsif ($role =~ m|^gr/|) {
5432: # Role of member in a group, defined within a course/community
5433: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5434: ($trole, $tend, $tstart) = split(/_/, $role);
5435: next if $tstart eq '-1';
5436: ($trole, $group_privs) = split(/\//, $trole);
5437: $group_privs = &unescape($group_privs);
5438: } else {
5439: # Just a normal role, defined in roles.tab
5440: ($trole, $tend, $tstart) = split(/_/,$role);
5441: }
5442:
5443: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5444: $username);
5445: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5446:
5447: # role expired or not available yet?
5448: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5449: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5450:
5451: next if $area eq '' or $trole eq '';
5452:
5453: my $spec = "$trole.$area";
5454: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5455:
5456: if ($trole =~ /^cr\//) {
5457: # Custom role, defined by a user
5458: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5459: } elsif ($trole eq 'gr') {
5460: # Role of a member in a group, defined within a course/community
5461: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5462: next;
5463: } else {
5464: # Normal role, defined in roles.tab
5465: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5466: }
5467:
5468: my $cid = $tdomain.'_'.$trest;
5469: unless ($firstaccchk{$cid}) {
5470: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5471: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5472: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5473: $coursetimerstarts{$cid}{$item};
5474: }
5475: }
5476: $firstaccchk{$cid} = 1;
5477: }
5478: unless ($timerintchk{$cid}) {
5479: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5480: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5481: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5482: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5483: }
1.12 www 5484: }
1.1169 droeschl 5485: $timerintchk{$cid} = 1;
1.191 harris41 5486: }
1.11 www 5487: }
1.1169 droeschl 5488:
5489: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5490: \%allroles, \%allgroups);
5491: $env{'user.adv'} = $userroles{'user.adv'};
5492:
1.1162 raeburn 5493: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5494: }
5495:
1.567 raeburn 5496: sub set_arearole {
1.1215 raeburn 5497: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5498: unless ($nolog) {
1.567 raeburn 5499: # log the associated role with the area
1.1215 raeburn 5500: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5501: }
1.743 albertel 5502: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5503: }
5504:
5505: sub custom_roleprivs {
5506: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5507: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5508: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5509: if (&hostname($homsvr) ne '') {
1.567 raeburn 5510: my ($rdummy,$roledef)=
5511: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5512: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5513: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5514: if (defined($syspriv)) {
1.1043 raeburn 5515: if ($trest =~ /^$match_community$/) {
5516: $syspriv =~ s/bre\&S//;
5517: }
1.567 raeburn 5518: $$allroles{'cm./'}.=':'.$syspriv;
5519: $$allroles{$spec.'./'}.=':'.$syspriv;
5520: }
5521: if ($tdomain ne '') {
5522: if (defined($dompriv)) {
5523: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5524: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5525: }
5526: if (($trest ne '') && (defined($coursepriv))) {
5527: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5528: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5529: }
5530: }
5531: }
5532: }
5533: }
5534:
1.678 raeburn 5535: sub group_roleprivs {
5536: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5537: my $access = 1;
5538: my $now = time;
5539: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5540: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5541: if ($access) {
1.811 albertel 5542: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5543: $$allgroups{$course}{$group} .=':'.$group_privs;
5544: }
5545: }
1.567 raeburn 5546:
5547: sub standard_roleprivs {
5548: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5549: if (defined($pr{$trole.':s'})) {
5550: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5551: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5552: }
5553: if ($tdomain ne '') {
5554: if (defined($pr{$trole.':d'})) {
5555: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5556: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5557: }
5558: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5559: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5560: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5561: }
5562: }
5563: }
5564:
5565: sub set_userprivs {
1.1064 raeburn 5566: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5567: my $author=0;
5568: my $adv=0;
1.678 raeburn 5569: my %grouproles = ();
5570: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5571: my @groupkeys;
1.1000 raeburn 5572: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5573: push(@groupkeys,$role);
5574: }
5575: if (ref($groups_roles) eq 'HASH') {
5576: foreach my $key (keys(%{$groups_roles})) {
5577: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5578: push(@groupkeys,$key);
5579: }
5580: }
5581: }
5582: if (@groupkeys > 0) {
5583: foreach my $role (@groupkeys) {
5584: my ($trole,$area,$sec,$extendedarea);
5585: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5586: $trole = $1;
5587: $area = $2;
5588: $sec = $3;
5589: $extendedarea = $area.$sec;
5590: if (exists($$allgroups{$area})) {
5591: foreach my $group (keys(%{$$allgroups{$area}})) {
5592: my $spec = $trole.'.'.$extendedarea;
5593: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5594: $$allgroups{$area}{$group};
1.1064 raeburn 5595: }
1.678 raeburn 5596: }
5597: }
5598: }
5599: }
5600: }
1.800 albertel 5601: foreach my $group (keys(%grouproles)) {
5602: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5603: }
1.800 albertel 5604: foreach my $role (keys(%{$allroles})) {
5605: my %thesepriv;
1.941 raeburn 5606: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5607: foreach my $item (split(/:/,$$allroles{$role})) {
5608: if ($item ne '') {
5609: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5610: if ($restrictions eq '') {
5611: $thesepriv{$privilege}='F';
5612: } elsif ($thesepriv{$privilege} ne 'F') {
5613: $thesepriv{$privilege}.=$restrictions;
5614: }
5615: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5616: }
5617: }
5618: my $thesestr='';
1.1104 raeburn 5619: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5620: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5621: }
5622: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5623: }
5624: return ($author,$adv);
5625: }
5626:
1.994 raeburn 5627: sub role_status {
1.1104 raeburn 5628: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5629: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5630: my ($one,$two) = split(m{\./},$rolekey,2);
5631: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5632: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5633: $$where = '/'.$two;
1.994 raeburn 5634: $$trolecode=$$role.'.'.$$where;
5635: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5636: $$tstatus='is';
1.1104 raeburn 5637: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5638: $$tstatus='future';
1.1034 raeburn 5639: if ($$tstart<$now) {
5640: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5641: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5642: my (%allroles,%allgroups,$group_privs,
5643: %groups_roles,@rolecodes);
1.1002 raeburn 5644: my %userroles = (
5645: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5646: );
1.1064 raeburn 5647: @rolecodes = ('cm');
1.1002 raeburn 5648: my $spec=$$role.'.'.$$where;
5649: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5650: if ($$role =~ /^cr\//) {
5651: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5652: push(@rolecodes,'cr');
1.1002 raeburn 5653: } elsif ($$role eq 'gr') {
1.1064 raeburn 5654: push(@rolecodes,$$role);
1.1002 raeburn 5655: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5656: $env{'user.name'});
1.1064 raeburn 5657: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5658: (undef,my $group_privs) = split(/\//,$trole);
5659: $group_privs = &unescape($group_privs);
5660: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5661: 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 5662: &get_groups_roles($tdomain,$trest,
5663: \%course_roles,\@rolecodes,
5664: \%groups_roles);
1.1002 raeburn 5665: } else {
1.1064 raeburn 5666: push(@rolecodes,$$role);
1.1002 raeburn 5667: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5668: }
1.1064 raeburn 5669: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5670: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5671: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5672: }
5673: }
1.1034 raeburn 5674: $$tstatus = 'is';
1.1002 raeburn 5675: }
1.994 raeburn 5676: }
5677: if ($$tend) {
1.1104 raeburn 5678: if ($$tend<$update) {
1.994 raeburn 5679: $$tstatus='expired';
5680: } elsif ($$tend<$now) {
5681: $$tstatus='will_not';
5682: }
5683: }
5684: }
5685: }
5686: }
5687:
1.1104 raeburn 5688: sub get_groups_roles {
5689: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5690: return unless((ref($cdom_courseroles) eq 'HASH') &&
5691: (ref($rolecodes) eq 'ARRAY') &&
5692: (ref($groups_roles) eq 'HASH'));
5693: if (keys(%{$cdom_courseroles}) > 0) {
5694: my ($cnum) = ($rest =~ /^($match_courseid)/);
5695: if ($cdom ne '' && $cnum ne '') {
5696: foreach my $key (keys(%{$cdom_courseroles})) {
5697: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5698: my $crsrole = $1;
5699: my $crssec = $2;
5700: if ($crsrole =~ /^cr/) {
5701: unless (grep(/^cr$/,@{$rolecodes})) {
5702: push(@{$rolecodes},'cr');
5703: }
5704: } else {
5705: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5706: push(@{$rolecodes},$crsrole);
5707: }
5708: }
5709: my $rolekey = "$crsrole./$cdom/$cnum";
5710: if ($crssec ne '') {
5711: $rolekey .= "/$crssec";
5712: }
5713: $rolekey .= './';
5714: $groups_roles->{$rolekey} = $rolecodes;
5715: }
5716: }
5717: }
5718: }
5719: return;
5720: }
5721:
5722: sub delete_env_groupprivs {
5723: my ($where,$courseroles,$possroles) = @_;
5724: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5725: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5726: unless (ref($courseroles->{$udom}) eq 'HASH') {
5727: %{$courseroles->{$udom}} =
5728: &get_my_roles('','','userroles',['active'],
5729: $possroles,[$udom],1);
5730: }
5731: if (ref($courseroles->{$udom}) eq 'HASH') {
5732: foreach my $item (keys(%{$courseroles->{$udom}})) {
5733: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5734: my $area = '/'.$cdom.'/'.$cnum;
5735: my $privkey = "user.priv.$crsrole.$area";
5736: if ($crssec ne '') {
5737: $privkey .= '/'.$crssec;
5738: }
5739: $privkey .= ".$area/$group";
5740: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5741: }
5742: }
5743: return;
5744: }
5745:
1.994 raeburn 5746: sub check_adhoc_privs {
1.1104 raeburn 5747: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5748: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5749: my $setprivs;
1.994 raeburn 5750: if ($env{$cckey}) {
5751: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5752: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5753: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5754: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5755: $setprivs = 1;
1.994 raeburn 5756: }
5757: } else {
1.1088 raeburn 5758: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5759: $setprivs = 1;
1.994 raeburn 5760: }
1.1185 raeburn 5761: return $setprivs;
1.994 raeburn 5762: }
5763:
5764: sub set_adhoc_privileges {
5765: # role can be cc or ca
1.1088 raeburn 5766: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5767: my $area = '/'.$dcdom.'/'.$pickedcourse;
5768: my $spec = $role.'.'.$area;
5769: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5770: $env{'user.name'},1);
1.994 raeburn 5771: my %ccrole = ();
5772: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5773: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5774: &appenv(\%userroles,[$role,'cm']);
5775: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5776: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5777: &appenv( {'request.role' => $spec,
5778: 'request.role.domain' => $dcdom,
5779: 'request.course.sec' => ''
5780: }
5781: );
5782: my $tadv=0;
5783: if (&allowed('adv') eq 'F') { $tadv=1; }
5784: &appenv({'request.role.adv' => $tadv});
5785: }
1.994 raeburn 5786: }
5787:
1.12 www 5788: # --------------------------------------------------------------- get interface
5789:
5790: sub get {
1.131 albertel 5791: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5792: my $items='';
1.800 albertel 5793: foreach my $item (@$storearr) {
5794: $items.=&escape($item).'&';
1.191 harris41 5795: }
1.12 www 5796: $items=~s/\&$//;
1.620 albertel 5797: if (!$udomain) { $udomain=$env{'user.domain'}; }
5798: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5799: my $uhome=&homeserver($uname,$udomain);
5800:
1.133 albertel 5801: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5802: my @pairs=split(/\&/,$rep);
1.273 albertel 5803: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5804: return @pairs;
5805: }
1.15 www 5806: my %returnhash=();
1.42 www 5807: my $i=0;
1.800 albertel 5808: foreach my $item (@$storearr) {
5809: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5810: $i++;
1.191 harris41 5811: }
1.15 www 5812: return %returnhash;
1.27 www 5813: }
5814:
5815: # --------------------------------------------------------------- del interface
5816:
5817: sub del {
1.133 albertel 5818: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5819: my $items='';
1.800 albertel 5820: foreach my $item (@$storearr) {
5821: $items.=&escape($item).'&';
1.191 harris41 5822: }
1.984 neumanie 5823:
1.27 www 5824: $items=~s/\&$//;
1.620 albertel 5825: if (!$udomain) { $udomain=$env{'user.domain'}; }
5826: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5827: my $uhome=&homeserver($uname,$udomain);
5828: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5829: }
5830:
5831: # -------------------------------------------------------------- dump interface
5832:
1.1180 droeschl 5833: sub unserialize {
5834: my ($rep, $escapedkeys) = @_;
5835:
5836: return {} if $rep =~ /^error/;
5837:
5838: my %returnhash=();
1.1252 raeburn 5839: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5840: my ($key, $value) = split(/=/, $item, 2);
5841: $key = unescape($key) unless $escapedkeys;
5842: next if $key =~ /^error: 2 /;
1.1252 raeburn 5843: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5844: }
5845: #return %returnhash;
5846: return \%returnhash;
5847: }
5848:
5849: # see Lond::dump_with_regexp
5850: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5851: sub dump {
1.1180 droeschl 5852: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5853: if (!$udomain) { $udomain=$env{'user.domain'}; }
5854: if (!$uname) { $uname=$env{'user.name'}; }
5855: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5856:
1.1266 raeburn 5857: if ($regexp) {
5858: $regexp=&escape($regexp);
5859: } else {
5860: $regexp='.';
5861: }
1.1180 droeschl 5862: if (grep { $_ eq $uhome } current_machine_ids()) {
5863: # user is hosted on this machine
1.1266 raeburn 5864: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5865: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5866: return %{unserialize($reply, $escapedkeys)};
5867: }
1.1166 raeburn 5868: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5869: my @pairs=split(/\&/,$rep);
5870: my %returnhash=();
1.1098 foxr 5871: if (!($rep =~ /^error/ )) {
5872: foreach my $item (@pairs) {
5873: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5874: $key = unescape($key) unless $escapedkeys;
5875: #$key = &unescape($key);
1.1098 foxr 5876: next if ($key =~ /^error: 2 /);
5877: $returnhash{$key}=&thaw_unescape($value);
5878: }
1.755 albertel 5879: }
5880: return %returnhash;
1.407 www 5881: }
5882:
1.1098 foxr 5883:
1.717 albertel 5884: # --------------------------------------------------------- dumpstore interface
5885:
5886: sub dumpstore {
5887: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5888: # same as dump but keys must be escaped. They may contain colon separated
5889: # lists of values that may themself contain colons (e.g. symbs).
5890: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5891: }
5892:
1.407 www 5893: # -------------------------------------------------------------- keys interface
5894:
5895: sub getkeys {
5896: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5897: if (!$udomain) { $udomain=$env{'user.domain'}; }
5898: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5899: my $uhome=&homeserver($uname,$udomain);
5900: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5901: my @keyarray=();
1.800 albertel 5902: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5903: next if ($key =~ /^error: 2 /);
1.800 albertel 5904: push(@keyarray,&unescape($key));
1.407 www 5905: }
5906: return @keyarray;
1.318 matthew 5907: }
5908:
1.319 matthew 5909: # --------------------------------------------------------------- currentdump
5910: sub currentdump {
1.328 matthew 5911: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5912: $courseid = $env{'request.course.id'} if (! defined($courseid));
5913: $sdom = $env{'user.domain'} if (! defined($sdom));
5914: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5915: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5916: my $rep;
5917:
5918: if (grep { $_ eq $uhome } current_machine_ids()) {
5919: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5920: $courseid)));
5921: } else {
5922: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5923: }
5924:
1.318 matthew 5925: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5926: #
1.318 matthew 5927: my %returnhash=();
1.319 matthew 5928: #
5929: if ($rep eq "unknown_cmd") {
5930: # an old lond will not know currentdump
5931: # Do a dump and make it look like a currentdump
1.822 albertel 5932: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5933: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5934: my %hash = @tmp;
5935: @tmp=();
1.424 matthew 5936: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5937: } else {
5938: my @pairs=split(/\&/,$rep);
1.800 albertel 5939: foreach my $pair (@pairs) {
5940: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5941: my ($symb,$param) = split(/:/,$key);
5942: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5943: &thaw_unescape($value);
1.319 matthew 5944: }
1.191 harris41 5945: }
1.12 www 5946: return %returnhash;
1.424 matthew 5947: }
5948:
5949: sub convert_dump_to_currentdump{
5950: my %hash = %{shift()};
5951: my %returnhash;
5952: # Code ripped from lond, essentially. The only difference
5953: # here is the unescaping done by lonnet::dump(). Conceivably
5954: # we might run in to problems with parameter names =~ /^v\./
5955: while (my ($key,$value) = each(%hash)) {
5956: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5957: $symb = &unescape($symb);
5958: $param = &unescape($param);
1.424 matthew 5959: next if ($v eq 'version' || $symb eq 'keys');
5960: next if (exists($returnhash{$symb}) &&
5961: exists($returnhash{$symb}->{$param}) &&
5962: $returnhash{$symb}->{'v.'.$param} > $v);
5963: $returnhash{$symb}->{$param}=$value;
5964: $returnhash{$symb}->{'v.'.$param}=$v;
5965: }
5966: #
5967: # Remove all of the keys in the hashes which keep track of
5968: # the version of the parameter.
5969: while (my ($symb,$param_hash) = each(%returnhash)) {
5970: # use a foreach because we are going to delete from the hash.
5971: foreach my $key (keys(%$param_hash)) {
5972: delete($param_hash->{$key}) if ($key =~ /^v\./);
5973: }
5974: }
5975: return \%returnhash;
1.12 www 5976: }
5977:
1.627 albertel 5978: # ------------------------------------------------------ critical inc interface
5979:
5980: sub cinc {
5981: return &inc(@_,'critical');
5982: }
5983:
1.449 matthew 5984: # --------------------------------------------------------------- inc interface
5985:
5986: sub inc {
1.627 albertel 5987: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5988: if (!$udomain) { $udomain=$env{'user.domain'}; }
5989: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5990: my $uhome=&homeserver($uname,$udomain);
5991: my $items='';
5992: if (! ref($store)) {
5993: # got a single value, so use that instead
5994: $items = &escape($store).'=&';
5995: } elsif (ref($store) eq 'SCALAR') {
5996: $items = &escape($$store).'=&';
5997: } elsif (ref($store) eq 'ARRAY') {
5998: $items = join('=&',map {&escape($_);} @{$store});
5999: } elsif (ref($store) eq 'HASH') {
6000: while (my($key,$value) = each(%{$store})) {
6001: $items.= &escape($key).'='.&escape($value).'&';
6002: }
6003: }
6004: $items=~s/\&$//;
1.627 albertel 6005: if ($critical) {
6006: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6007: } else {
6008: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6009: }
1.449 matthew 6010: }
6011:
1.12 www 6012: # --------------------------------------------------------------- put interface
6013:
6014: sub put {
1.134 albertel 6015: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6016: if (!$udomain) { $udomain=$env{'user.domain'}; }
6017: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6018: my $uhome=&homeserver($uname,$udomain);
1.12 www 6019: my $items='';
1.800 albertel 6020: foreach my $item (keys(%$storehash)) {
6021: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6022: }
1.12 www 6023: $items=~s/\&$//;
1.134 albertel 6024: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6025: }
6026:
1.631 albertel 6027: # ------------------------------------------------------------ newput interface
6028:
6029: sub newput {
6030: my ($namespace,$storehash,$udomain,$uname)=@_;
6031: if (!$udomain) { $udomain=$env{'user.domain'}; }
6032: if (!$uname) { $uname=$env{'user.name'}; }
6033: my $uhome=&homeserver($uname,$udomain);
6034: my $items='';
6035: foreach my $key (keys(%$storehash)) {
6036: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6037: }
6038: $items=~s/\&$//;
6039: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6040: }
6041:
6042: # --------------------------------------------------------- putstore interface
6043:
1.524 raeburn 6044: sub putstore {
1.1269 raeburn 6045: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6046: if (!$udomain) { $udomain=$env{'user.domain'}; }
6047: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6048: my $uhome=&homeserver($uname,$udomain);
6049: my $items='';
1.715 albertel 6050: foreach my $key (keys(%$storehash)) {
6051: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6052: }
1.715 albertel 6053: $items=~s/\&$//;
1.716 albertel 6054: my $esc_symb=&escape($symb);
6055: my $esc_v=&escape($version);
1.715 albertel 6056: my $reply =
1.716 albertel 6057: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6058: $uhome);
1.1269 raeburn 6059: if (($tolog) && ($reply eq 'ok')) {
6060: my $namevalue='';
6061: foreach my $key (keys(%{$storehash})) {
6062: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6063: }
6064: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6065: '&host='.&escape($perlvar{'lonHostID'}).
6066: '&version='.$esc_v.
6067: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6068: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6069: }
1.715 albertel 6070: if ($reply eq 'unknown_cmd') {
1.716 albertel 6071: # gfall back to way things use to be done
1.715 albertel 6072: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6073: $uname);
1.524 raeburn 6074: }
1.715 albertel 6075: return $reply;
6076: }
6077:
6078: sub old_putstore {
1.716 albertel 6079: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6080: if (!$udomain) { $udomain=$env{'user.domain'}; }
6081: if (!$uname) { $uname=$env{'user.name'}; }
6082: my $uhome=&homeserver($uname,$udomain);
6083: my %newstorehash;
1.800 albertel 6084: foreach my $item (keys(%$storehash)) {
6085: my $key = $version.':'.&escape($symb).':'.$item;
6086: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6087: }
6088: my $items='';
6089: my %allitems = ();
1.800 albertel 6090: foreach my $item (keys(%newstorehash)) {
6091: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6092: my $key = $1.':keys:'.$2;
6093: $allitems{$key} .= $3.':';
6094: }
1.800 albertel 6095: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6096: }
1.800 albertel 6097: foreach my $item (keys(%allitems)) {
6098: $allitems{$item} =~ s/\:$//;
6099: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6100: }
6101: $items=~s/\&$//;
6102: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6103: }
6104:
1.47 www 6105: # ------------------------------------------------------ critical put interface
6106:
6107: sub cput {
1.134 albertel 6108: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6109: if (!$udomain) { $udomain=$env{'user.domain'}; }
6110: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6111: my $uhome=&homeserver($uname,$udomain);
1.47 www 6112: my $items='';
1.800 albertel 6113: foreach my $item (keys(%$storehash)) {
6114: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6115: }
1.47 www 6116: $items=~s/\&$//;
1.134 albertel 6117: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6118: }
6119:
6120: # -------------------------------------------------------------- eget interface
6121:
6122: sub eget {
1.133 albertel 6123: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6124: my $items='';
1.800 albertel 6125: foreach my $item (@$storearr) {
6126: $items.=&escape($item).'&';
1.191 harris41 6127: }
1.12 www 6128: $items=~s/\&$//;
1.620 albertel 6129: if (!$udomain) { $udomain=$env{'user.domain'}; }
6130: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6131: my $uhome=&homeserver($uname,$udomain);
6132: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6133: my @pairs=split(/\&/,$rep);
6134: my %returnhash=();
1.42 www 6135: my $i=0;
1.800 albertel 6136: foreach my $item (@$storearr) {
6137: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6138: $i++;
1.191 harris41 6139: }
1.12 www 6140: return %returnhash;
6141: }
6142:
1.667 albertel 6143: # ------------------------------------------------------------ tmpput interface
6144: sub tmpput {
1.802 raeburn 6145: my ($storehash,$server,$context)=@_;
1.667 albertel 6146: my $items='';
1.800 albertel 6147: foreach my $item (keys(%$storehash)) {
6148: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6149: }
6150: $items=~s/\&$//;
1.802 raeburn 6151: if (defined($context)) {
6152: $items .= ':'.&escape($context);
6153: }
1.667 albertel 6154: return &reply("tmpput:$items",$server);
6155: }
6156:
6157: # ------------------------------------------------------------ tmpget interface
6158: sub tmpget {
1.688 albertel 6159: my ($token,$server)=@_;
6160: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6161: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6162: my %returnhash;
6163: foreach my $item (split(/\&/,$rep)) {
6164: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6165: next if ($key =~ /^error: 2 /);
1.667 albertel 6166: $returnhash{&unescape($key)}=&thaw_unescape($value);
6167: }
6168: return %returnhash;
6169: }
6170:
1.1113 raeburn 6171: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6172: sub tmpdel {
6173: my ($token,$server)=@_;
6174: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6175: return &reply("tmpdel:$token",$server);
6176: }
6177:
1.1198 raeburn 6178: # ------------------------------------------------------------ get_timebased_id
6179:
6180: sub get_timebased_id {
6181: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6182: $maxtries) = @_;
6183: my ($newid,$error,$dellock);
6184: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6185: return ('','ok','invalid call to get suffix');
6186: }
6187:
6188: # set defaults for any optional args for which values were not supplied
6189: if ($who eq '') {
6190: $who = $env{'user.name'}.':'.$env{'user.domain'};
6191: }
6192: if (!$locktries) {
6193: $locktries = 3;
6194: }
6195: if (!$maxtries) {
6196: $maxtries = 10;
6197: }
6198:
6199: if (($cdom eq '') || ($cnum eq '')) {
6200: if ($env{'request.course.id'}) {
6201: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6202: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6203: }
6204: if (($cdom eq '') || ($cnum eq '')) {
6205: return ('','ok','call to get suffix not in course context');
6206: }
6207: }
6208:
6209: # construct locking item
6210: my $lockhash = {
6211: $prefix."\0".'locked_'.$keyid => $who,
6212: };
6213: my $tries = 0;
6214:
6215: # attempt to get lock on nohist_$namespace file
6216: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6217: while (($gotlock ne 'ok') && $tries <$locktries) {
6218: $tries ++;
6219: sleep 1;
6220: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6221: }
6222:
6223: # attempt to get unique identifier, based on current timestamp
6224: if ($gotlock eq 'ok') {
6225: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6226: my $id = time;
6227: $newid = $id;
1.1268 raeburn 6228: if ($idtype eq 'addcode') {
6229: $newid .= &sixnum_code();
6230: }
1.1198 raeburn 6231: my $idtries = 0;
6232: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6233: if ($idtype eq 'concat') {
6234: $newid = $id.$idtries;
1.1268 raeburn 6235: } elsif ($idtype eq 'addcode') {
6236: $newid = $newid.&sixnum_code();
1.1198 raeburn 6237: } else {
6238: $newid ++;
6239: }
6240: $idtries ++;
6241: }
6242: if (!exists($inuse{$prefix."\0".$newid})) {
6243: my %new_item = (
6244: $prefix."\0".$newid => $who,
6245: );
6246: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6247: $cdom,$cnum);
6248: if ($putresult ne 'ok') {
6249: undef($newid);
6250: $error = 'error saving new item: '.$putresult;
6251: }
6252: } else {
1.1268 raeburn 6253: undef($newid);
1.1198 raeburn 6254: $error = ('error: no unique suffix available for the new item ');
6255: }
6256: # remove lock
6257: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6258: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6259: } else {
6260: $error = "error: could not obtain lockfile\n";
6261: $dellock = 'ok';
1.1276 raeburn 6262: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6263: $dellock = 'nolock';
6264: }
1.1198 raeburn 6265: }
6266: return ($newid,$dellock,$error);
6267: }
6268:
1.1268 raeburn 6269: sub sixnum_code {
6270: my $code;
6271: for (0..6) {
6272: $code .= int( rand(9) );
6273: }
6274: return $code;
6275: }
6276:
1.765 albertel 6277: # -------------------------------------------------- portfolio access checking
6278:
6279: sub portfolio_access {
1.1270 raeburn 6280: my ($requrl,$clientip) = @_;
1.765 albertel 6281: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6282: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6283: if ($result) {
6284: my %setters;
6285: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6286: my ($startblock,$endblock) =
6287: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6288: if ($startblock && $endblock) {
6289: return 'B';
6290: }
6291: } else {
6292: my ($startblock,$endblock) =
6293: &Apache::loncommon::blockcheck(\%setters,'port');
6294: if ($startblock && $endblock) {
6295: return 'B';
6296: }
6297: }
6298: }
1.765 albertel 6299: if ($result eq 'ok') {
1.766 albertel 6300: return 'F';
1.765 albertel 6301: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6302: return 'A';
1.765 albertel 6303: }
1.766 albertel 6304: return '';
1.765 albertel 6305: }
6306:
6307: sub get_portfolio_access {
1.1270 raeburn 6308: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6309:
6310: if (!ref($access_hash)) {
6311: my $current_perms = &get_portfile_permissions($udom,$unum);
6312: my %access_controls = &get_access_controls($current_perms,$group,
6313: $file_name);
6314: $access_hash = $access_controls{$file_name};
6315: }
6316:
1.1270 raeburn 6317: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6318: my $now = time;
6319: if (ref($access_hash) eq 'HASH') {
6320: foreach my $key (keys(%{$access_hash})) {
6321: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6322: if ($start > $now) {
6323: next;
6324: }
6325: if ($end && $end<$now) {
6326: next;
6327: }
6328: if ($scope eq 'public') {
6329: $public = $key;
6330: last;
6331: } elsif ($scope eq 'guest') {
6332: $guest = $key;
6333: } elsif ($scope eq 'domains') {
6334: push(@domains,$key);
6335: } elsif ($scope eq 'users') {
6336: push(@users,$key);
6337: } elsif ($scope eq 'course') {
6338: push(@courses,$key);
6339: } elsif ($scope eq 'group') {
6340: push(@groups,$key);
1.1270 raeburn 6341: } elsif ($scope eq 'ip') {
6342: push(@ips,$key);
1.765 albertel 6343: }
6344: }
6345: if ($public) {
6346: return 'ok';
1.1270 raeburn 6347: } elsif (@ips > 0) {
6348: my $allowed;
6349: foreach my $ipkey (@ips) {
6350: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6351: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6352: $allowed = 1;
6353: last;
6354: }
6355: }
6356: }
6357: if ($allowed) {
6358: return 'ok';
6359: }
1.765 albertel 6360: }
6361: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6362: if ($guest) {
6363: return $guest;
6364: }
6365: } else {
6366: if (@domains > 0) {
6367: foreach my $domkey (@domains) {
6368: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6369: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6370: return 'ok';
6371: }
6372: }
6373: }
6374: }
6375: if (@users > 0) {
6376: foreach my $userkey (@users) {
1.865 raeburn 6377: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6378: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6379: if (ref($item) eq 'HASH') {
6380: if (($item->{'uname'} eq $env{'user.name'}) &&
6381: ($item->{'udom'} eq $env{'user.domain'})) {
6382: return 'ok';
6383: }
6384: }
6385: }
6386: }
1.765 albertel 6387: }
6388: }
6389: my %roleshash;
6390: my @courses_and_groups = @courses;
6391: push(@courses_and_groups,@groups);
6392: if (@courses_and_groups > 0) {
6393: my (%allgroups,%allroles);
6394: my ($start,$end,$role,$sec,$group);
6395: foreach my $envkey (%env) {
1.1060 raeburn 6396: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6397: my $cid = $2.'_'.$3;
6398: if ($1 eq 'gr') {
6399: $group = $4;
6400: $allgroups{$cid}{$group} = $env{$envkey};
6401: } else {
6402: if ($4 eq '') {
6403: $sec = 'none';
6404: } else {
6405: $sec = $4;
6406: }
6407: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6408: }
1.811 albertel 6409: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6410: my $cid = $2.'_'.$3;
6411: if ($4 eq '') {
6412: $sec = 'none';
6413: } else {
6414: $sec = $4;
6415: }
6416: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6417: }
6418: }
6419: if (keys(%allroles) == 0) {
6420: return;
6421: }
6422: foreach my $key (@courses_and_groups) {
6423: my %content = %{$$access_hash{$key}};
6424: my $cnum = $content{'number'};
6425: my $cdom = $content{'domain'};
6426: my $cid = $cdom.'_'.$cnum;
6427: if (!exists($allroles{$cid})) {
6428: next;
6429: }
6430: foreach my $role_id (keys(%{$content{'roles'}})) {
6431: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6432: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6433: my @status = @{$content{'roles'}{$role_id}{'access'}};
6434: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6435: foreach my $role (keys(%{$allroles{$cid}})) {
6436: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6437: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6438: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6439: if (grep/^all$/,@sections) {
6440: return 'ok';
6441: } else {
6442: if (grep/^$sec$/,@sections) {
6443: return 'ok';
6444: }
6445: }
6446: }
6447: }
6448: if (keys(%{$allgroups{$cid}}) == 0) {
6449: if (grep/^none$/,@groups) {
6450: return 'ok';
6451: }
6452: } else {
6453: if (grep/^all$/,@groups) {
6454: return 'ok';
6455: }
6456: foreach my $group (keys(%{$allgroups{$cid}})) {
6457: if (grep/^$group$/,@groups) {
6458: return 'ok';
6459: }
6460: }
6461: }
6462: }
6463: }
6464: }
6465: }
6466: }
6467: if ($guest) {
6468: return $guest;
6469: }
6470: }
6471: }
6472: return;
6473: }
6474:
6475: sub course_group_datechecker {
6476: my ($dates,$now,$status) = @_;
6477: my ($start,$end) = split(/\./,$dates);
6478: if (!$start && !$end) {
6479: return 'ok';
6480: }
6481: if (grep/^active$/,@{$status}) {
6482: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6483: return 'ok';
6484: }
6485: }
6486: if (grep/^previous$/,@{$status}) {
6487: if ($end > $now ) {
6488: return 'ok';
6489: }
6490: }
6491: if (grep/^future$/,@{$status}) {
6492: if ($start > $now) {
6493: return 'ok';
6494: }
6495: }
6496: return;
6497: }
6498:
6499: sub parse_portfolio_url {
6500: my ($url) = @_;
6501:
6502: my ($type,$udom,$unum,$group,$file_name);
6503:
1.823 albertel 6504: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6505: $type = 1;
6506: $udom = $1;
6507: $unum = $2;
6508: $file_name = $3;
1.823 albertel 6509: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6510: $type = 2;
6511: $udom = $1;
6512: $unum = $2;
6513: $group = $3;
6514: $file_name = $3.'/'.$4;
6515: }
6516: if (wantarray) {
6517: return ($type,$udom,$unum,$file_name,$group);
6518: }
6519: return $type;
6520: }
6521:
6522: sub is_portfolio_url {
6523: my ($url) = @_;
6524: return scalar(&parse_portfolio_url($url));
6525: }
6526:
1.798 raeburn 6527: sub is_portfolio_file {
6528: my ($file) = @_;
1.820 raeburn 6529: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6530: return 1;
6531: }
6532: return;
6533: }
6534:
1.976 raeburn 6535: sub usertools_access {
1.1084 raeburn 6536: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6537: my ($access,%tools);
6538: if ($context eq '') {
6539: $context = 'tools';
6540: }
6541: if ($context eq 'requestcourses') {
6542: %tools = (
6543: official => 1,
6544: unofficial => 1,
1.1006 raeburn 6545: community => 1,
1.1246 raeburn 6546: textbook => 1,
1.1305 raeburn 6547: placement => 1,
1.985 raeburn 6548: );
1.1183 raeburn 6549: } elsif ($context eq 'requestauthor') {
6550: %tools = (
6551: requestauthor => 1,
6552: );
1.985 raeburn 6553: } else {
6554: %tools = (
6555: aboutme => 1,
6556: blog => 1,
1.1177 raeburn 6557: webdav => 1,
1.985 raeburn 6558: portfolio => 1,
6559: );
6560: }
1.976 raeburn 6561: return if (!defined($tools{$tool}));
6562:
1.1242 raeburn 6563: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6564: $udom = $env{'user.domain'};
6565: $uname = $env{'user.name'};
6566: }
6567:
1.978 raeburn 6568: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6569: if ($action ne 'reload') {
1.985 raeburn 6570: if ($context eq 'requestcourses') {
6571: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6572: } elsif ($context eq 'requestauthor') {
6573: return $env{'environment.canrequest.author'};
1.985 raeburn 6574: } else {
6575: return $env{'environment.availabletools.'.$tool};
6576: }
6577: }
1.976 raeburn 6578: }
6579:
1.1183 raeburn 6580: my ($toolstatus,$inststatus,$envkey);
6581: if ($context eq 'requestauthor') {
6582: $envkey = $context;
6583: } else {
6584: $envkey = $context.'.'.$tool;
6585: }
1.976 raeburn 6586:
1.985 raeburn 6587: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6588: ($action ne 'reload')) {
1.1183 raeburn 6589: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6590: $inststatus = $env{'environment.inststatus'};
6591: } else {
1.1084 raeburn 6592: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6593: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6594: $inststatus = $userenvref->{'inststatus'};
6595: } else {
1.1183 raeburn 6596: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6597: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6598: $inststatus = $userenv{'inststatus'};
6599: }
1.976 raeburn 6600: }
6601:
6602: if ($toolstatus ne '') {
6603: if ($toolstatus) {
6604: $access = 1;
6605: } else {
6606: $access = 0;
6607: }
6608: return $access;
6609: }
6610:
1.1084 raeburn 6611: my ($is_adv,%domdef);
6612: if (ref($is_advref) eq 'HASH') {
6613: $is_adv = $is_advref->{'is_adv'};
6614: } else {
6615: $is_adv = &is_advanced_user($udom,$uname);
6616: }
6617: if (ref($domdefref) eq 'HASH') {
6618: %domdef = %{$domdefref};
6619: } else {
6620: %domdef = &get_domain_defaults($udom);
6621: }
1.976 raeburn 6622: if (ref($domdef{$tool}) eq 'HASH') {
6623: if ($is_adv) {
6624: if ($domdef{$tool}{'_LC_adv'} ne '') {
6625: if ($domdef{$tool}{'_LC_adv'}) {
6626: $access = 1;
6627: } else {
6628: $access = 0;
6629: }
6630: return $access;
6631: }
6632: }
6633: if ($inststatus ne '') {
6634: my ($hasaccess,$hasnoaccess);
6635: foreach my $affiliation (split(/:/,$inststatus)) {
6636: if ($domdef{$tool}{$affiliation} ne '') {
6637: if ($domdef{$tool}{$affiliation}) {
6638: $hasaccess = 1;
6639: } else {
6640: $hasnoaccess = 1;
6641: }
6642: }
6643: }
6644: if ($hasaccess || $hasnoaccess) {
6645: if ($hasaccess) {
6646: $access = 1;
6647: } elsif ($hasnoaccess) {
6648: $access = 0;
6649: }
6650: return $access;
6651: }
6652: } else {
6653: if ($domdef{$tool}{'default'} ne '') {
6654: if ($domdef{$tool}{'default'}) {
6655: $access = 1;
6656: } elsif ($domdef{$tool}{'default'} == 0) {
6657: $access = 0;
6658: }
6659: return $access;
6660: }
6661: }
6662: } else {
1.1177 raeburn 6663: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6664: $access = 1;
6665: } else {
6666: $access = 0;
6667: }
1.976 raeburn 6668: return $access;
6669: }
6670: }
6671:
1.1050 raeburn 6672: sub is_course_owner {
6673: my ($cdom,$cnum,$udom,$uname) = @_;
6674: if (($udom eq '') || ($uname eq '')) {
6675: $udom = $env{'user.domain'};
6676: $uname = $env{'user.name'};
6677: }
6678: unless (($udom eq '') || ($uname eq '')) {
6679: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6680: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6681: return 1;
6682: } else {
6683: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6684: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6685: return 1;
6686: }
6687: }
6688: }
6689: }
6690: return;
6691: }
6692:
1.976 raeburn 6693: sub is_advanced_user {
6694: my ($udom,$uname) = @_;
1.1085 raeburn 6695: if ($udom ne '' && $uname ne '') {
6696: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6697: if (wantarray) {
6698: return ($env{'user.adv'},$env{'user.author'});
6699: } else {
6700: return $env{'user.adv'};
6701: }
1.1085 raeburn 6702: }
6703: }
1.976 raeburn 6704: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6705: my %allroles;
1.1128 raeburn 6706: my ($is_adv,$is_author);
1.976 raeburn 6707: foreach my $role (keys(%roleshash)) {
6708: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6709: my $area = '/'.$tdomain.'/'.$trest;
6710: if ($sec ne '') {
6711: $area .= '/'.$sec;
6712: }
6713: if (($area ne '') && ($trole ne '')) {
6714: my $spec=$trole.'.'.$area;
6715: if ($trole =~ /^cr\//) {
6716: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6717: } elsif ($trole ne 'gr') {
6718: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6719: }
1.1128 raeburn 6720: if ($trole eq 'au') {
6721: $is_author = 1;
6722: }
1.976 raeburn 6723: }
6724: }
6725: foreach my $role (keys(%allroles)) {
6726: last if ($is_adv);
6727: foreach my $item (split(/:/,$allroles{$role})) {
6728: if ($item ne '') {
6729: my ($privilege,$restrictions)=split(/&/,$item);
6730: if ($privilege eq 'adv') {
6731: $is_adv = 1;
6732: last;
6733: }
6734: }
6735: }
6736: }
1.1128 raeburn 6737: if (wantarray) {
6738: return ($is_adv,$is_author);
6739: }
1.976 raeburn 6740: return $is_adv;
6741: }
1.798 raeburn 6742:
1.1035 raeburn 6743: sub check_can_request {
1.1036 raeburn 6744: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6745: my $canreq = 0;
6746: my ($types,$typename) = &Apache::loncommon::course_types();
6747: my @options = ('approval','validate','autolimit');
6748: my $optregex = join('|',@options);
6749: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6750: foreach my $type (@{$types}) {
6751: if (&usertools_access($env{'user.name'},
6752: $env{'user.domain'},
6753: $type,undef,'requestcourses')) {
6754: $canreq ++;
1.1036 raeburn 6755: if (ref($request_domains) eq 'HASH') {
6756: push(@{$request_domains->{$type}},$env{'user.domain'});
6757: }
1.1035 raeburn 6758: if ($dom eq $env{'user.domain'}) {
6759: $can_request->{$type} = 1;
6760: }
6761: }
6762: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6763: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6764: if (@curr > 0) {
1.1036 raeburn 6765: foreach my $item (@curr) {
6766: if (ref($request_domains) eq 'HASH') {
6767: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6768: if ($otherdom ne '') {
6769: if (ref($request_domains->{$type}) eq 'ARRAY') {
6770: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6771: push(@{$request_domains->{$type}},$otherdom);
6772: }
6773: } else {
6774: push(@{$request_domains->{$type}},$otherdom);
6775: }
6776: }
6777: }
6778: }
6779: unless($dom eq $env{'user.domain'}) {
6780: $canreq ++;
1.1035 raeburn 6781: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6782: $can_request->{$type} = 1;
6783: }
6784: }
6785: }
6786: }
6787: }
6788: }
6789: return $canreq;
6790: }
6791:
1.341 www 6792: # ---------------------------------------------- Custom access rule evaluation
6793:
6794: sub customaccess {
6795: my ($priv,$uri)=@_;
1.807 albertel 6796: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6797: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6798: $udom = &LONCAPA::clean_domain($udom);
6799: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6800: my $access=0;
1.800 albertel 6801: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6802: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6803: if ($type eq 'user') {
6804: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6805: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6806: if ($tdom) {
6807: if ($tdom ne $env{'user.domain'}) { next; }
6808: }
1.896 albertel 6809: if ($tuname) {
6810: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6811: }
6812: $access=($effect eq 'allow');
6813: last;
6814: }
6815: } else {
6816: if ($role) {
6817: if ($role ne $urole) { next; }
6818: }
6819: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6820: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6821: if ($tdom) {
6822: if ($tdom ne $udom) { next; }
6823: }
6824: if ($tcrs) {
6825: if ($tcrs ne $ucrs) { next; }
6826: }
6827: if ($tsec) {
6828: if ($tsec ne $usec) { next; }
6829: }
6830: $access=($effect eq 'allow');
6831: last;
6832: }
6833: if ($realm eq '' && $role eq '') {
6834: $access=($effect eq 'allow');
6835: }
1.402 bowersj2 6836: }
1.341 www 6837: }
6838: return $access;
6839: }
6840:
1.103 harris41 6841: # ------------------------------------------------- Check for a user privilege
1.12 www 6842:
6843: sub allowed {
1.1281 raeburn 6844: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6845: my $ver_orguri=$uri;
1.439 www 6846: $uri=&deversion($uri);
1.152 www 6847: my $orguri=$uri;
1.52 www 6848: $uri=&declutter($uri);
1.809 raeburn 6849:
1.810 raeburn 6850: if ($priv eq 'evb') {
6851: # Evade communication block restrictions for specified role in a course
6852: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6853: return $1;
6854: } else {
6855: return;
6856: }
6857: }
6858:
1.620 albertel 6859: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6860: # Free bre access to adm and meta resources
1.775 albertel 6861: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6862: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6863: && ($priv eq 'bre')) {
1.14 www 6864: return 'F';
1.159 www 6865: }
6866:
1.545 banghart 6867: # Free bre access to user's own portfolio contents
1.714 raeburn 6868: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6869: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6870: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6871: my %setters;
6872: my ($startblock,$endblock) =
6873: &Apache::loncommon::blockcheck(\%setters,'port');
6874: if ($startblock && $endblock) {
6875: return 'B';
6876: } else {
6877: return 'F';
6878: }
1.545 banghart 6879: }
6880:
1.762 raeburn 6881: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6882: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6883: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6884: if (exists($env{'request.course.id'})) {
6885: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6886: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6887: if (($domain eq $cdom) && ($name eq $cnum)) {
6888: my $courseprivid=$env{'request.course.id'};
6889: $courseprivid=~s/\_/\//;
6890: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6891: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6892: return $1;
1.762 raeburn 6893: } else {
6894: if ($env{'request.course.sec'}) {
6895: $courseprivid.='/'.$env{'request.course.sec'};
6896: }
6897: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6898: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6899: return $2;
6900: }
1.714 raeburn 6901: }
6902: }
6903: }
6904: }
6905:
1.159 www 6906: # Free bre to public access
6907:
6908: if ($priv eq 'bre') {
1.238 www 6909: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6910: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6911: return 'F';
6912: }
1.238 www 6913: if ($copyright eq 'priv') {
6914: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6915: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6916: return '';
6917: }
6918: }
6919: if ($copyright eq 'domain') {
6920: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6921: unless (($env{'user.domain'} eq $1) ||
6922: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6923: return '';
6924: }
1.262 matthew 6925: }
1.620 albertel 6926: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6927: # Library role, so allow browsing of resources in this domain.
6928: return 'F';
1.238 www 6929: }
1.341 www 6930: if ($copyright eq 'custom') {
6931: unless (&customaccess($priv,$uri)) { return ''; }
6932: }
1.14 www 6933: }
1.264 matthew 6934: # Domain coordinator is trying to create a course
1.620 albertel 6935: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6936: # uri is the requested domain in this case.
6937: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6938: # a role of dc for the domain in question.
1.620 albertel 6939: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6940: }
1.29 www 6941:
1.52 www 6942: my $thisallowed='';
6943: my $statecond=0;
6944: my $courseprivid='';
6945:
1.1039 raeburn 6946: my $ownaccess;
1.1043 raeburn 6947: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6948: if (($priv eq 'bro') && ($env{'user.author'})) {
6949: if ($uri eq '') {
6950: $ownaccess = 1;
6951: } else {
6952: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6953: my $udom = $env{'user.domain'};
6954: my $uname = $env{'user.name'};
6955: if ($uri =~ m{^\Q$udom\E/?$}) {
6956: $ownaccess = 1;
1.1040 raeburn 6957: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6958: unless ($uri =~ m{\.\./}) {
6959: $ownaccess = 1;
6960: }
6961: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6962: my $now = time;
6963: if ($uri =~ m{^([^/]+)/?$}) {
6964: my $adom = $1;
6965: foreach my $key (keys(%env)) {
1.1042 raeburn 6966: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6967: my ($start,$end) = split('.',$env{$key});
6968: if (($now >= $start) && (!$end || $end < $now)) {
6969: $ownaccess = 1;
6970: last;
6971: }
6972: }
6973: }
6974: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6975: my $adom = $1;
6976: my $aname = $2;
1.1042 raeburn 6977: foreach my $role ('ca','aa') {
6978: if ($env{"user.role.$role./$adom/$aname"}) {
6979: my ($start,$end) =
6980: split('.',$env{"user.role.$role./$adom/$aname"});
6981: if (($now >= $start) && (!$end || $end < $now)) {
6982: $ownaccess = 1;
6983: last;
6984: }
1.1039 raeburn 6985: }
6986: }
6987: }
6988: }
6989: }
6990: }
6991: }
6992:
1.52 www 6993: # Course
6994:
1.620 albertel 6995: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6996: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6997: $thisallowed.=$1;
6998: }
1.52 www 6999: }
1.29 www 7000:
1.52 www 7001: # Domain
7002:
1.620 albertel 7003: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7004: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7005: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7006: $thisallowed.=$1;
7007: }
1.12 www 7008: }
1.52 www 7009:
1.1141 raeburn 7010: # User who is not author or co-author might still be able to edit
7011: # resource of an author in the domain (e.g., if Domain Coordinator).
7012: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7013: (&allowed('mdc',$env{'request.course.id'}))) {
7014: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7015: $thisallowed.=$1;
7016: }
7017: }
7018:
1.52 www 7019: # Course: uri itself is a course
1.66 www 7020: my $courseuri=$uri;
7021: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7022: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7023:
1.620 albertel 7024: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7025: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7026: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7027: $thisallowed.=$1;
7028: }
1.12 www 7029: }
1.29 www 7030:
1.665 albertel 7031: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7032: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7033: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7034: $thisallowed='';
1.671 raeburn 7035: my ($match)=&is_on_map($uri);
7036: if ($match) {
7037: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7038: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7039: my $value = $1;
7040: if ($noblockcheck) {
7041: $thisallowed.=$value;
1.1162 raeburn 7042: } else {
1.1281 raeburn 7043: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7044: if (@blockers > 0) {
7045: $thisallowed = 'B';
7046: } else {
7047: $thisallowed.=$value;
7048: }
1.1162 raeburn 7049: }
1.671 raeburn 7050: }
7051: } else {
1.705 albertel 7052: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7053: if ($refuri) {
7054: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7055: $thisallowed='F';
1.671 raeburn 7056: } else {
7057: $refuri=&declutter($refuri);
7058: my ($match) = &is_on_map($refuri);
7059: if ($match) {
1.1281 raeburn 7060: if ($noblockcheck) {
7061: $thisallowed='F';
1.1162 raeburn 7062: } else {
1.1281 raeburn 7063: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7064: if (@blockers > 0) {
7065: $thisallowed = 'B';
7066: } else {
7067: $thisallowed='F';
7068: }
1.1162 raeburn 7069: }
1.671 raeburn 7070: }
1.669 raeburn 7071: }
1.671 raeburn 7072: }
7073: }
1.314 www 7074: }
1.492 albertel 7075:
1.766 albertel 7076: if ($priv eq 'bre'
7077: && $thisallowed ne 'F'
7078: && $thisallowed ne '2'
7079: && &is_portfolio_url($uri)) {
1.1270 raeburn 7080: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7081: }
1.1250 raeburn 7082:
1.52 www 7083: # Full access at system, domain or course-wide level? Exit.
1.29 www 7084: if ($thisallowed=~/F/) {
7085: return 'F';
7086: }
7087:
1.52 www 7088: # If this is generating or modifying users, exit with special codes
1.29 www 7089:
1.643 www 7090: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7091: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7092: my ($audom,$auname)=split('/',$uri);
1.643 www 7093: # no author name given, so this just checks on the general right to make a co-author in this domain
7094: unless ($auname) { return $thisallowed; }
7095: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7096: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7097: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7098: ($audom ne $env{'request.role.domain'}))) { return ''; }
7099: }
1.52 www 7100: return $thisallowed;
7101: }
7102: #
1.103 harris41 7103: # Gathered so far: system, domain and course wide privileges
1.52 www 7104: #
7105: # Course: See if uri or referer is an individual resource that is part of
7106: # the course
7107:
1.620 albertel 7108: if ($env{'request.course.id'}) {
1.232 www 7109:
1.620 albertel 7110: $courseprivid=$env{'request.course.id'};
7111: if ($env{'request.course.sec'}) {
7112: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7113: }
7114: $courseprivid=~s/\_/\//;
7115: my $checkreferer=1;
1.232 www 7116: my ($match,$cond)=&is_on_map($uri);
7117: if ($match) {
7118: $statecond=$cond;
1.620 albertel 7119: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7120: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7121: my $value = $1;
7122: if ($priv eq 'bre') {
1.1281 raeburn 7123: if ($noblockcheck) {
7124: $thisallowed.=$value;
1.1162 raeburn 7125: } else {
1.1281 raeburn 7126: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7127: if (@blockers > 0) {
7128: $thisallowed = 'B';
7129: } else {
7130: $thisallowed.=$value;
7131: }
1.1162 raeburn 7132: }
7133: } else {
7134: $thisallowed.=$value;
7135: }
1.52 www 7136: $checkreferer=0;
7137: }
1.29 www 7138: }
1.83 www 7139:
1.148 www 7140: if ($checkreferer) {
1.620 albertel 7141: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7142: unless ($refuri) {
1.800 albertel 7143: foreach my $key (keys(%env)) {
7144: if ($key=~/^httpref\..*\*/) {
7145: my $pattern=$key;
1.156 www 7146: $pattern=~s/^httpref\.\/res\///;
1.148 www 7147: $pattern=~s/\*/\[\^\/\]\+/g;
7148: $pattern=~s/\//\\\//g;
1.152 www 7149: if ($orguri=~/$pattern/) {
1.800 albertel 7150: $refuri=$env{$key};
1.148 www 7151: }
7152: }
1.191 harris41 7153: }
1.148 www 7154: }
1.232 www 7155:
1.148 www 7156: if ($refuri) {
1.152 www 7157: $refuri=&declutter($refuri);
1.232 www 7158: my ($match,$cond)=&is_on_map($refuri);
7159: if ($match) {
7160: my $refstatecond=$cond;
1.620 albertel 7161: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7162: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7163: my $value = $1;
7164: if ($priv eq 'bre') {
1.1281 raeburn 7165: if ($noblockcheck) {
7166: $thisallowed.=$value;
1.1162 raeburn 7167: } else {
1.1281 raeburn 7168: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7169: if (@blockers > 0) {
7170: $thisallowed = 'B';
7171: } else {
7172: $thisallowed.=$value;
7173: }
1.1162 raeburn 7174: }
7175: } else {
7176: $thisallowed.=$value;
7177: }
1.53 www 7178: $uri=$refuri;
7179: $statecond=$refstatecond;
1.52 www 7180: }
7181: }
1.148 www 7182: }
1.29 www 7183: }
1.52 www 7184: }
1.29 www 7185:
1.52 www 7186: #
1.103 harris41 7187: # Gathered now: all privileges that could apply, and condition number
1.52 www 7188: #
7189: #
7190: # Full or no access?
7191: #
1.29 www 7192:
1.52 www 7193: if ($thisallowed=~/F/) {
7194: return 'F';
7195: }
1.29 www 7196:
1.52 www 7197: unless ($thisallowed) {
7198: return '';
7199: }
1.29 www 7200:
1.52 www 7201: # Restrictions exist, deal with them
7202: #
7203: # C:according to course preferences
7204: # R:according to resource settings
7205: # L:unless locked
7206: # X:according to user session state
7207: #
7208:
7209: # Possibly locked functionality, check all courses
1.54 www 7210: # Locks might take effect only after 10 minutes cache expiration for other
7211: # courses, and 2 minutes for current course
1.52 www 7212:
7213: my $envkey;
7214: if ($thisallowed=~/L/) {
1.1000 raeburn 7215: foreach $envkey (keys(%env)) {
1.54 www 7216: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7217: my $courseid=$2;
7218: my $roleid=$1.'.'.$2;
1.92 www 7219: $courseid=~s/^\///;
1.54 www 7220: my $expiretime=600;
1.620 albertel 7221: if ($env{'request.role'} eq $roleid) {
1.54 www 7222: $expiretime=120;
7223: }
7224: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7225: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7226: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7227: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7228: }
1.620 albertel 7229: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7230: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7231: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7232: &log($env{'user.domain'},$env{'user.name'},
7233: $env{'user.home'},
1.57 www 7234: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7235: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7236: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7237: return '';
7238: }
7239: }
1.620 albertel 7240: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7241: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7242: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7243: &log($env{'user.domain'},$env{'user.name'},
7244: $env{'user.home'},
1.57 www 7245: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7246: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7247: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7248: return '';
7249: }
7250: }
7251: }
1.29 www 7252: }
1.52 www 7253: }
7254:
7255: #
7256: # Rest of the restrictions depend on selected course
7257: #
7258:
1.620 albertel 7259: unless ($env{'request.course.id'}) {
1.766 albertel 7260: if ($thisallowed eq 'A') {
7261: return 'A';
1.814 raeburn 7262: } elsif ($thisallowed eq 'B') {
7263: return 'B';
1.766 albertel 7264: } else {
7265: return '1';
7266: }
1.52 www 7267: }
1.29 www 7268:
1.52 www 7269: #
7270: # Now user is definitely in a course
7271: #
1.53 www 7272:
7273:
7274: # Course preferences
7275:
7276: if ($thisallowed=~/C/) {
1.620 albertel 7277: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7278: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7279: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7280: =~/\Q$rolecode\E/) {
1.1304 raeburn 7281: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7282: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7283: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7284: $env{'request.course.id'});
7285: }
1.237 www 7286: return '';
7287: }
7288:
1.620 albertel 7289: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7290: =~/\Q$unamedom\E/) {
1.1304 raeburn 7291: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7292: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7293: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7294: $env{'request.course.id'});
7295: }
1.54 www 7296: return '';
7297: }
1.53 www 7298: }
7299:
7300: # Resource preferences
7301:
7302: if ($thisallowed=~/R/) {
1.620 albertel 7303: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7304: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7305: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7306: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7307: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7308: }
7309: return '';
1.54 www 7310: }
1.53 www 7311: }
1.30 www 7312:
1.246 www 7313: # Restricted by state or randomout?
1.30 www 7314:
1.52 www 7315: if ($thisallowed=~/X/) {
1.620 albertel 7316: if ($env{'acc.randomout'}) {
1.579 albertel 7317: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7318: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7319: return '';
7320: }
1.247 www 7321: }
7322: if (&condval($statecond)) {
1.52 www 7323: return '2';
7324: } else {
7325: return '';
7326: }
7327: }
1.30 www 7328:
1.766 albertel 7329: if ($thisallowed eq 'A') {
7330: return 'A';
1.814 raeburn 7331: } elsif ($thisallowed eq 'B') {
7332: return 'B';
1.766 albertel 7333: }
1.52 www 7334: return 'F';
1.232 www 7335: }
1.1162 raeburn 7336:
1.1192 raeburn 7337: # ------------------------------------------- Check construction space access
7338:
7339: sub constructaccess {
7340: my ($url,$setpriv)=@_;
7341:
7342: # We do not allow editing of previous versions of files
7343: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7344:
7345: # Get username and domain from URL
7346: my ($ownername,$ownerdomain,$ownerhome);
7347:
7348: ($ownerdomain,$ownername) =
1.1297 damieng 7349: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192 raeburn 7350:
7351: # The URL does not really point to any authorspace, forget it
7352: unless (($ownername) && ($ownerdomain)) { return ''; }
7353:
7354: # Now we need to see if the user has access to the authorspace of
7355: # $ownername at $ownerdomain
7356:
7357: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7358: # Real author for this?
7359: $ownerhome = $env{'user.home'};
7360: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7361: return ($ownername,$ownerdomain,$ownerhome);
7362: }
7363: } else {
7364: # Co-author for this?
7365: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7366: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7367: $ownerhome = &homeserver($ownername,$ownerdomain);
7368: return ($ownername,$ownerdomain,$ownerhome);
7369: }
7370: }
7371:
7372: # We don't have any access right now. If we are not possibly going to do anything about this,
7373: # we might as well leave
7374: unless ($setpriv) { return ''; }
7375:
7376: # Backdoor access?
7377: my $allowed=&allowed('eco',$ownerdomain);
7378: # Nope
7379: unless ($allowed) { return ''; }
7380: # Looks like we may have access, but could be locked by the owner of the construction space
7381: if ($allowed eq 'U') {
7382: my %blocked=&get('environment',['domcoord.author'],
7383: $ownerdomain,$ownername);
7384: # Is blocked by owner
7385: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7386: }
7387: if (($allowed eq 'F') || ($allowed eq 'U')) {
7388: # Grant temporary access
7389: my $then=$env{'user.login.time'};
1.1209 raeburn 7390: my $update=$env{'user.update.time'};
1.1192 raeburn 7391: if (!$update) { $update = $then; }
7392: my $refresh=$env{'user.refresh.time'};
7393: if (!$refresh) { $refresh = $update; }
7394: my $now = time;
7395: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7396: $now,'ca','constructaccess');
7397: $ownerhome = &homeserver($ownername,$ownerdomain);
7398: return($ownername,$ownerdomain,$ownerhome);
7399: }
7400: # No business here
7401: return '';
7402: }
7403:
1.1282 raeburn 7404: # ----------------------------------------------------------- Content Blocking
7405:
7406: {
7407: # Caches for faster Course Contents display where content blocking
7408: # is in operation (i.e., interval param set) for timed quiz.
7409: #
7410: # User for whom data are being temporarily cached.
7411: my $cacheduser='';
7412: # Cached blockers for this user (a hash of blocking items).
7413: my %cachedblockers=();
7414: # When the data were last cached.
7415: my $cachedlast='';
7416:
7417: sub load_all_blockers {
7418: my ($uname,$udom,$blocks)=@_;
7419: if (($uname ne '') && ($udom ne '')) {
7420: if (($cacheduser eq $uname.':'.$udom) &&
7421: (abs($cachedlast-time)<5)) {
7422: return;
7423: }
7424: }
7425: $cachedlast=time;
7426: $cacheduser=$uname.':'.$udom;
7427: %cachedblockers = &get_commblock_resources($blocks);
7428: }
7429:
1.1162 raeburn 7430: sub get_comm_blocks {
7431: my ($cdom,$cnum) = @_;
7432: if ($cdom eq '' || $cnum eq '') {
7433: return unless ($env{'request.course.id'});
7434: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7435: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7436: }
7437: my %commblocks;
7438: my $hashid=$cdom.'_'.$cnum;
7439: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7440: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7441: %commblocks = %{$blocksref};
7442: } else {
7443: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7444: my $cachetime = 600;
7445: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7446: }
7447: return %commblocks;
7448: }
7449:
1.1282 raeburn 7450: sub get_commblock_resources {
7451: my ($blocks) = @_;
7452: my %blockers = ();
7453: return %blockers unless ($env{'request.course.id'});
7454: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7455: my %commblocks;
7456: if (ref($blocks) eq 'HASH') {
7457: %commblocks = %{$blocks};
7458: } else {
7459: %commblocks = &get_comm_blocks();
7460: }
1.1282 raeburn 7461: return %blockers unless (keys(%commblocks) > 0);
7462: my $navmap = Apache::lonnavmaps::navmap->new();
7463: return %blockers unless (ref($navmap));
1.1162 raeburn 7464: my $now = time;
7465: foreach my $block (keys(%commblocks)) {
7466: if ($block =~ /^(\d+)____(\d+)$/) {
7467: my ($start,$end) = ($1,$2);
7468: if ($start <= $now && $end >= $now) {
7469: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7470: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7471: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7472: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7473: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7474: }
7475: }
7476: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7477: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7478: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7479: }
7480: }
7481: }
7482: }
7483: }
7484: } elsif ($block =~ /^firstaccess____(.+)$/) {
7485: my $item = $1;
1.1163 raeburn 7486: my @to_test;
1.1162 raeburn 7487: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7488: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7489: my @interval;
7490: my $type = 'map';
7491: if ($item eq 'course') {
7492: $type = 'course';
7493: @interval=&EXT("resource.0.interval");
7494: } else {
7495: if ($item =~ /___\d+___/) {
7496: $type = 'resource';
7497: @interval=&EXT("resource.0.interval",$item);
7498: if (ref($navmap)) {
7499: my $res = $navmap->getBySymb($item);
7500: push(@to_test,$res);
7501: }
1.1162 raeburn 7502: } else {
1.1282 raeburn 7503: my $mapsymb = &symbread($item,1);
7504: if ($mapsymb) {
7505: if (ref($navmap)) {
7506: my $mapres = $navmap->getBySymb($mapsymb);
7507: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7508: foreach my $res (@to_test) {
7509: my $symb = $res->symb();
7510: next if ($symb eq $mapsymb);
7511: if ($symb ne '') {
7512: @interval=&EXT("resource.0.interval",$symb);
7513: if ($interval[1] eq 'map') {
7514: last;
1.1162 raeburn 7515: }
7516: }
7517: }
7518: }
7519: }
7520: }
1.1282 raeburn 7521: }
1.1310 ! raeburn 7522: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 7523: my $timelimit = $1;
1.1282 raeburn 7524: my $first_access;
7525: if ($type eq 'resource') {
7526: $first_access=&get_first_access($interval[1],$item);
7527: } elsif ($type eq 'map') {
7528: $first_access=&get_first_access($interval[1],undef,$item);
7529: } else {
7530: $first_access=&get_first_access($interval[1]);
7531: }
7532: if ($first_access) {
1.1292 raeburn 7533: my $timesup = $first_access+$timelimit;
1.1282 raeburn 7534: if ($timesup > $now) {
7535: my $activeblock;
7536: foreach my $res (@to_test) {
1.1283 raeburn 7537: if ($res->answerable()) {
1.1282 raeburn 7538: $activeblock = 1;
7539: last;
7540: }
7541: }
7542: if ($activeblock) {
7543: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7544: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7545: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7546: }
7547: }
7548: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7549: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7550: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7551: }
1.1162 raeburn 7552: }
7553: }
7554: }
7555: }
7556: }
7557: }
7558: }
7559: }
7560: }
1.1282 raeburn 7561: return %blockers;
1.1162 raeburn 7562: }
7563:
1.1282 raeburn 7564: sub has_comm_blocking {
7565: my ($priv,$symb,$uri,$blocks) = @_;
7566: my @blockers;
7567: return unless ($env{'request.course.id'});
7568: return unless ($priv eq 'bre');
7569: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7570: return if ($env{'request.state'} eq 'construct');
7571: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7572: return unless (keys(%cachedblockers) > 0);
7573: my (%possibles,@symbs);
7574: if (!$symb) {
7575: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7576: }
1.1282 raeburn 7577: if ($symb) {
7578: @symbs = ($symb);
7579: } elsif (keys(%possibles)) {
7580: @symbs = keys(%possibles);
7581: }
7582: my $noblock;
7583: foreach my $symb (@symbs) {
7584: last if ($noblock);
7585: my ($map,$resid,$resurl)=&decode_symb($symb);
7586: foreach my $block (keys(%cachedblockers)) {
7587: if ($block =~ /^firstaccess____(.+)$/) {
7588: my $item = $1;
7589: if (($item eq $map) || ($item eq $symb)) {
7590: $noblock = 1;
7591: last;
7592: }
7593: }
7594: if (ref($cachedblockers{$block}) eq 'HASH') {
7595: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7596: if ($cachedblockers{$block}{'resources'}{$symb}) {
7597: unless (grep(/^\Q$block\E$/,@blockers)) {
7598: push(@blockers,$block);
7599: }
7600: }
7601: }
1.1162 raeburn 7602: }
1.1282 raeburn 7603: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7604: if ($cachedblockers{$block}{'maps'}{$map}) {
7605: unless (grep(/^\Q$block\E$/,@blockers)) {
7606: push(@blockers,$block);
7607: }
7608: }
1.1162 raeburn 7609: }
7610: }
7611: }
1.1282 raeburn 7612: return if ($noblock);
7613: return @blockers;
7614: }
1.1162 raeburn 7615: }
7616:
1.1282 raeburn 7617: # -------------------------------- Deversion and split uri into path an filename
7618:
1.1133 foxr 7619: #
1.1282 raeburn 7620: # Removes the version from a URI and
1.1133 foxr 7621: # splits it in to its filename and path to the filename.
7622: # Seems like File::Basename could have done this more clearly.
7623: # Parameters:
7624: # $uri - input URI
7625: # Returns:
7626: # Two element list consisting of
7627: # $pathname - the URI up to and excluding the trailing /
7628: # $filename - The part of the URI following the last /
7629: # NOTE:
7630: # Another realization of this is simply:
7631: # use File::Basename;
7632: # ...
7633: # $uri = shift;
7634: # $filename = basename($uri);
7635: # $path = dirname($uri);
7636: # return ($filename, $path);
7637: #
7638: # The implementation below is probably faster however.
7639: #
1.710 albertel 7640: sub split_uri_for_cond {
7641: my $uri=&deversion(&declutter(shift));
7642: my @uriparts=split(/\//,$uri);
7643: my $filename=pop(@uriparts);
7644: my $pathname=join('/',@uriparts);
7645: return ($pathname,$filename);
7646: }
1.232 www 7647: # --------------------------------------------------- Is a resource on the map?
7648:
7649: sub is_on_map {
1.710 albertel 7650: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7651: #Trying to find the conditional for the file
1.620 albertel 7652: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7653: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7654: if ($match) {
1.289 bowersj2 7655: return (1,$1);
7656: } else {
1.434 www 7657: return (0,0);
1.289 bowersj2 7658: }
1.12 www 7659: }
7660:
1.427 www 7661: # --------------------------------------------------------- Get symb from alias
7662:
7663: sub get_symb_from_alias {
7664: my $symb=shift;
7665: my ($map,$resid,$url)=&decode_symb($symb);
7666: # Already is a symb
7667: if ($url) { return $symb; }
7668: # Must be an alias
7669: my $aliassymb='';
7670: my %bighash;
1.620 albertel 7671: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7672: &GDBM_READER(),0640)) {
7673: my $rid=$bighash{'mapalias_'.$symb};
7674: if ($rid) {
7675: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7676: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7677: $resid,$bighash{'src_'.$rid});
1.427 www 7678: }
7679: untie %bighash;
7680: }
7681: return $aliassymb;
7682: }
7683:
1.12 www 7684: # ----------------------------------------------------------------- Define Role
7685:
7686: sub definerole {
7687: if (allowed('mcr','/')) {
7688: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7689: foreach my $role (split(':',$sysrole)) {
7690: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7691: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7692: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7693: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7694: return "refused:s:$crole&$cqual";
7695: }
7696: }
1.191 harris41 7697: }
1.800 albertel 7698: foreach my $role (split(':',$domrole)) {
7699: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7700: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7701: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7702: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7703: return "refused:d:$crole&$cqual";
7704: }
7705: }
1.191 harris41 7706: }
1.800 albertel 7707: foreach my $role (split(':',$courole)) {
7708: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7709: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7710: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7711: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7712: return "refused:c:$crole&$cqual";
7713: }
7714: }
1.191 harris41 7715: }
1.620 albertel 7716: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7717: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7718: "rolesdef_$rolename=".
7719: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7720: return reply($command,$env{'user.home'});
1.12 www 7721: } else {
7722: return 'refused';
7723: }
1.105 harris41 7724: }
7725:
7726: # ---------------- Make a metadata query against the network of library servers
7727:
7728: sub metadata_query {
1.1237 raeburn 7729: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7730: my %rhash;
1.845 albertel 7731: my %libserv = &all_library();
1.244 matthew 7732: my @server_list = (defined($server_array) ? @$server_array
7733: : keys(%libserv) );
7734: for my $server (@server_list) {
1.1237 raeburn 7735: my $domains = '';
7736: if (ref($domains_hash) eq 'HASH') {
7737: $domains = $domains_hash->{$server};
7738: }
1.118 harris41 7739: unless ($custom or $customshow) {
1.1237 raeburn 7740: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7741: $rhash{$server}=$reply;
7742: }
7743: else {
7744: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7745: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7746: $server);
7747: $rhash{$server}=$reply;
7748: }
1.112 harris41 7749: }
1.118 harris41 7750: return \%rhash;
1.240 www 7751: }
7752:
7753: # ----------------------------------------- Send log queries and wait for reply
7754:
7755: sub log_query {
7756: my ($uname,$udom,$query,%filters)=@_;
7757: my $uhome=&homeserver($uname,$udom);
7758: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7759: my $uhost=&hostname($uhome);
1.800 albertel 7760: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7761: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7762: $uhome);
1.479 albertel 7763: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7764: return get_query_reply($queryid);
7765: }
7766:
1.818 raeburn 7767: # -------------------------- Update MySQL table for portfolio file
7768:
7769: sub update_portfolio_table {
1.821 raeburn 7770: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7771: if ($group ne '') {
7772: $file_name =~s /^\Q$group\E//;
7773: }
1.818 raeburn 7774: my $homeserver = &homeserver($uname,$udom);
7775: my $queryid=
1.821 raeburn 7776: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7777: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7778: my $reply = &get_query_reply($queryid);
7779: return $reply;
7780: }
7781:
1.899 raeburn 7782: # -------------------------- Update MySQL allusers table
7783:
7784: sub update_allusers_table {
7785: my ($uname,$udom,$names) = @_;
7786: my $homeserver = &homeserver($uname,$udom);
7787: my $queryid=
7788: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7789: 'lastname='.&escape($names->{'lastname'}).'%%'.
7790: 'firstname='.&escape($names->{'firstname'}).'%%'.
7791: 'middlename='.&escape($names->{'middlename'}).'%%'.
7792: 'generation='.&escape($names->{'generation'}).'%%'.
7793: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7794: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7795: return;
1.899 raeburn 7796: }
7797:
1.508 raeburn 7798: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7799:
7800: sub fetch_enrollment_query {
1.511 raeburn 7801: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7802: my $homeserver;
1.547 raeburn 7803: my $maxtries = 1;
1.508 raeburn 7804: if ($context eq 'automated') {
7805: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7806: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7807: } else {
7808: $homeserver = &homeserver($cnum,$dom);
7809: }
1.838 albertel 7810: my $host=&hostname($homeserver);
1.506 raeburn 7811: my $cmd = '';
1.1000 raeburn 7812: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7813: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7814: }
7815: $cmd =~ s/%%$//;
7816: $cmd = &escape($cmd);
7817: my $query = 'fetchenrollment';
1.620 albertel 7818: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7819: unless ($queryid=~/^\Q$host\E\_/) {
7820: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7821: return 'error: '.$queryid;
7822: }
1.506 raeburn 7823: my $reply = &get_query_reply($queryid);
1.547 raeburn 7824: my $tries = 1;
7825: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7826: $reply = &get_query_reply($queryid);
7827: $tries ++;
7828: }
1.526 raeburn 7829: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7830: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7831: } else {
1.901 albertel 7832: my @responses = split(/:/,$reply);
1.515 raeburn 7833: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7834: foreach my $line (@responses) {
7835: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7836: $$replyref{$key} = $value;
7837: }
7838: } else {
1.1117 foxr 7839: my $pathname = LONCAPA::tempdir();
1.800 albertel 7840: foreach my $line (@responses) {
7841: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7842: $$replyref{$key} = $value;
7843: if ($value > 0) {
1.800 albertel 7844: foreach my $item (@{$$affiliatesref{$key}}) {
7845: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7846: my $destname = $pathname.'/'.$filename;
7847: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7848: if ($xml_classlist =~ /^error/) {
7849: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7850: } else {
1.506 raeburn 7851: if ( open(FILE,">$destname") ) {
7852: print FILE &unescape($xml_classlist);
7853: close(FILE);
1.526 raeburn 7854: } else {
7855: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7856: }
7857: }
7858: }
7859: }
7860: }
7861: }
7862: return 'ok';
7863: }
7864: return 'error';
7865: }
7866:
1.242 www 7867: sub get_query_reply {
7868: my $queryid=shift;
1.1117 foxr 7869: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7870: my $reply='';
7871: for (1..100) {
1.1289 damieng 7872: sleep(0.2);
1.240 www 7873: if (-e $replyfile.'.end') {
1.448 albertel 7874: if (open(my $fh,$replyfile)) {
1.904 albertel 7875: $reply = join('',<$fh>);
7876: close($fh);
1.240 www 7877: } else { return 'error: reply_file_error'; }
1.242 www 7878: return &unescape($reply);
7879: }
1.240 www 7880: }
1.242 www 7881: return 'timeout:'.$queryid;
1.240 www 7882: }
7883:
7884: sub courselog_query {
1.241 www 7885: #
7886: # possible filters:
7887: # url: url or symb
7888: # username
7889: # domain
7890: # action: view, submit, grade
7891: # start: timestamp
7892: # end: timestamp
7893: #
1.240 www 7894: my (%filters)=@_;
1.620 albertel 7895: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7896: if ($filters{'url'}) {
7897: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7898: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7899: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7900: }
1.620 albertel 7901: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7902: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7903: return &log_query($cname,$cdom,'courselog',%filters);
7904: }
7905:
7906: sub userlog_query {
1.858 raeburn 7907: #
7908: # possible filters:
7909: # action: log check role
7910: # start: timestamp
7911: # end: timestamp
7912: #
1.240 www 7913: my ($uname,$udom,%filters)=@_;
7914: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7915: }
7916:
1.506 raeburn 7917: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7918:
7919: sub auto_run {
1.508 raeburn 7920: my ($cnum,$cdom) = @_;
1.876 raeburn 7921: my $response = 0;
7922: my $settings;
7923: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7924: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7925: $settings = $domconfig{'autoenroll'};
7926: if ($settings->{'run'} eq '1') {
7927: $response = 1;
7928: }
7929: } else {
1.934 raeburn 7930: my $homeserver;
7931: if (&is_course($cdom,$cnum)) {
7932: $homeserver = &homeserver($cnum,$cdom);
7933: } else {
7934: $homeserver = &domain($cdom,'primary');
7935: }
7936: if ($homeserver ne 'no_host') {
7937: $response = &reply('autorun:'.$cdom,$homeserver);
7938: }
1.876 raeburn 7939: }
1.506 raeburn 7940: return $response;
7941: }
1.776 albertel 7942:
1.506 raeburn 7943: sub auto_get_sections {
1.508 raeburn 7944: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7945: my $homeserver;
7946: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7947: $homeserver = &homeserver($cnum,$cdom);
7948: }
7949: if (!defined($homeserver)) {
7950: if ($cdom =~ /^$match_domain$/) {
7951: $homeserver = &domain($cdom,'primary');
7952: }
7953: }
7954: my @secs;
7955: if (defined($homeserver)) {
7956: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7957: unless ($response eq 'refused') {
7958: @secs = split(/:/,$response);
7959: }
1.506 raeburn 7960: }
7961: return @secs;
7962: }
1.776 albertel 7963:
1.506 raeburn 7964: sub auto_new_course {
1.1099 raeburn 7965: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7966: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7967: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7968: return $response;
7969: }
1.776 albertel 7970:
1.506 raeburn 7971: sub auto_validate_courseID {
1.508 raeburn 7972: my ($cnum,$cdom,$inst_course_id) = @_;
7973: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7974: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7975: return $response;
7976: }
1.776 albertel 7977:
1.1007 raeburn 7978: sub auto_validate_instcode {
1.1020 raeburn 7979: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7980: my ($homeserver,$response);
7981: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7982: $homeserver = &homeserver($cnum,$cdom);
7983: }
7984: if (!defined($homeserver)) {
7985: if ($cdom =~ /^$match_domain$/) {
7986: $homeserver = &domain($cdom,'primary');
7987: }
7988: }
1.1065 raeburn 7989: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7990: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7991: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7992: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7993: }
7994:
1.506 raeburn 7995: sub auto_create_password {
1.873 raeburn 7996: my ($cnum,$cdom,$authparam,$udom) = @_;
7997: my ($homeserver,$response);
1.506 raeburn 7998: my $create_passwd = 0;
7999: my $authchk = '';
1.873 raeburn 8000: if ($udom =~ /^$match_domain$/) {
8001: $homeserver = &domain($udom,'primary');
8002: }
8003: if ($homeserver eq '') {
8004: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8005: $homeserver = &homeserver($cnum,$cdom);
8006: }
8007: }
8008: if ($homeserver eq '') {
8009: $authchk = 'nodomain';
1.506 raeburn 8010: } else {
1.873 raeburn 8011: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8012: if ($response eq 'refused') {
8013: $authchk = 'refused';
8014: } else {
1.901 albertel 8015: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8016: }
1.506 raeburn 8017: }
8018: return ($authparam,$create_passwd,$authchk);
8019: }
8020:
1.706 raeburn 8021: sub auto_photo_permission {
8022: my ($cnum,$cdom,$students) = @_;
8023: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8024: my ($outcome,$perm_reqd,$conditions) =
8025: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8026: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8027: return (undef,undef);
8028: }
1.706 raeburn 8029: return ($outcome,$perm_reqd,$conditions);
8030: }
8031:
8032: sub auto_checkphotos {
8033: my ($uname,$udom,$pid) = @_;
8034: my $homeserver = &homeserver($uname,$udom);
8035: my ($result,$resulttype);
8036: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8037: &escape($uname).':'.&escape($pid),
8038: $homeserver));
1.709 albertel 8039: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8040: return (undef,undef);
8041: }
1.706 raeburn 8042: if ($outcome) {
8043: ($result,$resulttype) = split(/:/,$outcome);
8044: }
8045: return ($result,$resulttype);
8046: }
8047:
8048: sub auto_photochoice {
8049: my ($cnum,$cdom) = @_;
8050: my $homeserver = &homeserver($cnum,$cdom);
8051: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8052: &escape($cdom),
8053: $homeserver)));
1.709 albertel 8054: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8055: return (undef,undef);
8056: }
1.706 raeburn 8057: return ($update,$comment);
8058: }
8059:
8060: sub auto_photoupdate {
8061: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8062: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8063: my $host=&hostname($homeserver);
1.706 raeburn 8064: my $cmd = '';
8065: my $maxtries = 1;
1.800 albertel 8066: foreach my $affiliate (keys(%{$affiliatesref})) {
8067: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8068: }
8069: $cmd =~ s/%%$//;
8070: $cmd = &escape($cmd);
8071: my $query = 'institutionalphotos';
8072: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8073: unless ($queryid=~/^\Q$host\E\_/) {
8074: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8075: return 'error: '.$queryid;
8076: }
8077: my $reply = &get_query_reply($queryid);
8078: my $tries = 1;
8079: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8080: $reply = &get_query_reply($queryid);
8081: $tries ++;
8082: }
8083: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8084: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8085: } else {
8086: my @responses = split(/:/,$reply);
8087: my $outcome = shift(@responses);
8088: foreach my $item (@responses) {
8089: my ($key,$value) = split(/=/,$item);
8090: $$photo{$key} = $value;
8091: }
8092: return $outcome;
8093: }
8094: return 'error';
8095: }
8096:
1.521 raeburn 8097: sub auto_instcode_format {
1.793 albertel 8098: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8099: $cat_order) = @_;
1.521 raeburn 8100: my $courses = '';
1.772 raeburn 8101: my @homeservers;
1.521 raeburn 8102: if ($caller eq 'global') {
1.841 albertel 8103: my %servers = &get_servers($codedom,'library');
8104: foreach my $tryserver (keys(%servers)) {
8105: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8106: push(@homeservers,$tryserver);
8107: }
1.584 raeburn 8108: }
1.1022 raeburn 8109: } elsif ($caller eq 'requests') {
8110: if ($codedom =~ /^$match_domain$/) {
8111: my $chome = &domain($codedom,'primary');
8112: unless ($chome eq 'no_host') {
8113: push(@homeservers,$chome);
8114: }
8115: }
1.521 raeburn 8116: } else {
1.772 raeburn 8117: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8118: }
1.793 albertel 8119: foreach my $code (keys(%{$instcodes})) {
8120: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8121: }
8122: chop($courses);
1.772 raeburn 8123: my $ok_response = 0;
8124: my $response;
8125: while (@homeservers > 0 && $ok_response == 0) {
8126: my $server = shift(@homeservers);
8127: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8128: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8129: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8130: split(/:/,$response);
1.772 raeburn 8131: %{$codes} = (%{$codes},&str2hash($codes_str));
8132: push(@{$codetitles},&str2array($codetitles_str));
8133: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8134: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8135: $ok_response = 1;
8136: }
8137: }
8138: if ($ok_response) {
1.521 raeburn 8139: return 'ok';
1.772 raeburn 8140: } else {
8141: return $response;
1.521 raeburn 8142: }
8143: }
8144:
1.792 raeburn 8145: sub auto_instcode_defaults {
8146: my ($domain,$returnhash,$code_order) = @_;
8147: my @homeservers;
1.841 albertel 8148:
8149: my %servers = &get_servers($domain,'library');
8150: foreach my $tryserver (keys(%servers)) {
8151: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8152: push(@homeservers,$tryserver);
8153: }
1.792 raeburn 8154: }
1.841 albertel 8155:
1.792 raeburn 8156: my $response;
1.841 albertel 8157: foreach my $server (@homeservers) {
1.792 raeburn 8158: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8159: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8160:
8161: foreach my $pair (split(/\&/,$response)) {
8162: my ($name,$value)=split(/\=/,$pair);
8163: if ($name eq 'code_order') {
8164: @{$code_order} = split(/\&/,&unescape($value));
8165: } else {
8166: $returnhash->{&unescape($name)}=&unescape($value);
8167: }
8168: }
8169: return 'ok';
1.792 raeburn 8170: }
1.841 albertel 8171:
8172: return $response;
1.1003 raeburn 8173: }
8174:
8175: sub auto_possible_instcodes {
1.1007 raeburn 8176: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8177: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8178: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8179: return;
8180: }
1.1003 raeburn 8181: my (@homeservers,$uhome);
8182: if (defined(&domain($domain,'primary'))) {
8183: $uhome=&domain($domain,'primary');
8184: push(@homeservers,&domain($domain,'primary'));
8185: } else {
8186: my %servers = &get_servers($domain,'library');
8187: foreach my $tryserver (keys(%servers)) {
8188: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8189: push(@homeservers,$tryserver);
8190: }
8191: }
8192: }
8193: my $response;
8194: foreach my $server (@homeservers) {
8195: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8196: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8197: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8198: split(':',$response);
8199: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8200: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8201: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8202: my ($name,$value)=split('=',$item);
8203: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8204: }
8205: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8206: my ($name,$value)=split('=',$item);
8207: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8208: }
8209: return 'ok';
8210: }
8211: return $response;
8212: }
1.792 raeburn 8213:
1.1010 raeburn 8214: sub auto_courserequest_checks {
8215: my ($dom) = @_;
1.1020 raeburn 8216: my ($homeserver,%validations);
8217: if ($dom =~ /^$match_domain$/) {
8218: $homeserver = &domain($dom,'primary');
8219: }
8220: unless ($homeserver eq 'no_host') {
8221: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8222: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8223: my @items = split(/&/,$response);
8224: foreach my $item (@items) {
8225: my ($key,$value) = split('=',$item);
8226: $validations{&unescape($key)} = &thaw_unescape($value);
8227: }
8228: }
8229: }
1.1010 raeburn 8230: return %validations;
8231: }
8232:
1.1020 raeburn 8233: sub auto_courserequest_validation {
1.1255 raeburn 8234: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8235: my ($homeserver,$response);
8236: if ($dom =~ /^$match_domain$/) {
8237: $homeserver = &domain($dom,'primary');
8238: }
1.1255 raeburn 8239: unless ($homeserver eq 'no_host') {
8240: my $customdata;
8241: if (ref($custominfo) eq 'HASH') {
8242: $customdata = &freeze_escape($custominfo);
8243: }
1.1020 raeburn 8244: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8245: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8246: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8247: $customdata,$homeserver));
1.1020 raeburn 8248: }
8249: return $response;
8250: }
8251:
1.777 albertel 8252: sub auto_validate_class_sec {
1.918 raeburn 8253: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8254: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8255: my $ownerlist;
8256: if (ref($owners) eq 'ARRAY') {
8257: $ownerlist = join(',',@{$owners});
8258: } else {
8259: $ownerlist = $owners;
8260: }
1.773 raeburn 8261: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8262: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8263: return $response;
8264: }
8265:
1.1248 raeburn 8266: sub auto_crsreq_update {
8267: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8268: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8269: my ($homeserver,%crsreqresponse);
8270: if ($cdom =~ /^$match_domain$/) {
8271: $homeserver = &domain($cdom,'primary');
8272: }
8273: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8274: my $info;
8275: if (ref($inbound) eq 'HASH') {
8276: $info = &freeze_escape($inbound);
8277: }
8278: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8279: ':'.&escape($action).':'.&escape($ownername).':'.
8280: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8281: &escape($title).':'.&escape($code).':'.
8282: &escape($accessstart).':'.&escape($accessend).':'.$info,
8283: $homeserver);
1.1248 raeburn 8284: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8285: my @items = split(/&/,$response);
8286: foreach my $item (@items) {
8287: my ($key,$value) = split('=',$item);
8288: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8289: }
8290: }
8291: }
8292: return \%crsreqresponse;
8293: }
8294:
1.1305 raeburn 8295: sub auto_export_grades {
1.1309 raeburn 8296: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8297: my ($homeserver,%exportresponse);
8298: if ($cdom =~ /^$match_domain$/) {
8299: $homeserver = &domain($cdom,'primary');
8300: }
8301: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8302: my $info;
8303: if (ref($inforef) eq 'HASH') {
8304: $info = &freeze_escape($inforef);
8305: }
8306: if (ref($gradesref) eq 'HASH') {
8307: my $grades = &freeze_escape($gradesref);
8308: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8309: $info.':'.$grades,$homeserver);
8310: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8311: my @items = split(/&/,$response);
8312: foreach my $item (@items) {
8313: my ($key,$value) = split('=',$item);
8314: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8315: }
8316: }
8317: }
8318: }
8319: return \%exportresponse;
1.1305 raeburn 8320: }
8321:
1.1287 raeburn 8322: sub check_instcode_cloning {
8323: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8324: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8325: return;
8326: }
8327: my $canclone;
8328: if (@{$code_order} > 0) {
8329: my $instcoderegexp ='^';
8330: my @clonecodes = split(/\&/,$cloner);
8331: foreach my $item (@{$code_order}) {
8332: if (grep(/^\Q$item\E=/,@clonecodes)) {
8333: foreach my $pair (@clonecodes) {
8334: my ($key,$val) = split(/\=/,$pair,2);
8335: $val = &unescape($val);
8336: if ($key eq $item) {
8337: $instcoderegexp .= '('.$val.')';
8338: last;
8339: }
8340: }
8341: } else {
8342: $instcoderegexp .= $codedefaults->{$item};
8343: }
8344: }
8345: $instcoderegexp .= '$';
8346: my (@from,@to);
8347: eval {
8348: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8349: (@to) = ($clonetocode =~ /$instcoderegexp/);
8350: };
8351: if ((@from > 0) && (@to > 0)) {
8352: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8353: if (!@diffs) {
8354: $canclone = 1;
8355: }
8356: }
8357: }
8358: return $canclone;
8359: }
8360:
8361: sub default_instcode_cloning {
8362: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8363: my (%codedefaults,@code_order,$canclone);
8364: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8365: %codedefaults = %{$codedefaultsref};
8366: @code_order = @{$codeorderref};
8367: } elsif ($clonedom) {
8368: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8369: }
8370: if (($domdefclone) && (@code_order)) {
8371: my @clonecodes = split(/\+/,$domdefclone);
8372: my $instcoderegexp ='^';
8373: foreach my $item (@code_order) {
8374: if (grep(/^\Q$item\E$/,@clonecodes)) {
8375: $instcoderegexp .= '('.$codedefaults{$item}.')';
8376: } else {
8377: $instcoderegexp .= $codedefaults{$item};
8378: }
8379: }
8380: $instcoderegexp .= '$';
8381: my (@from,@to);
8382: eval {
8383: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8384: (@to) = ($clonetocode =~ /$instcoderegexp/);
8385: };
8386: if ((@from > 0) && (@to > 0)) {
8387: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8388: if (!@diffs) {
8389: $canclone = 1;
8390: }
8391: }
8392: }
8393: return $canclone;
8394: }
8395:
1.679 raeburn 8396: # ------------------------------------------------------- Course Group routines
8397:
8398: sub get_coursegroups {
1.809 raeburn 8399: my ($cdom,$cnum,$group,$namespace) = @_;
8400: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8401: }
8402:
1.679 raeburn 8403: sub modify_coursegroup {
8404: my ($cdom,$cnum,$groupsettings) = @_;
8405: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8406: }
8407:
1.809 raeburn 8408: sub toggle_coursegroup_status {
8409: my ($cdom,$cnum,$group,$action) = @_;
8410: my ($from_namespace,$to_namespace);
8411: if ($action eq 'delete') {
8412: $from_namespace = 'coursegroups';
8413: $to_namespace = 'deleted_groups';
8414: } else {
8415: $from_namespace = 'deleted_groups';
8416: $to_namespace = 'coursegroups';
8417: }
8418: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8419: if (my $tmp = &error(%curr_group)) {
8420: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8421: return ('read error',$tmp);
8422: } else {
8423: my %savedsettings = %curr_group;
1.809 raeburn 8424: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8425: my $deloutcome;
8426: if ($result eq 'ok') {
1.809 raeburn 8427: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8428: } else {
8429: return ('write error',$result);
8430: }
8431: if ($deloutcome eq 'ok') {
8432: return 'ok';
8433: } else {
8434: return ('delete error',$deloutcome);
8435: }
8436: }
8437: }
8438:
1.679 raeburn 8439: sub modify_group_roles {
1.957 raeburn 8440: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8441: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8442: my $role = 'gr/'.&escape($userprivs);
8443: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8444: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8445: if ($result eq 'ok') {
8446: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8447: }
1.679 raeburn 8448: return $result;
8449: }
8450:
8451: sub modify_coursegroup_membership {
8452: my ($cdom,$cnum,$membership) = @_;
8453: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8454: return $result;
8455: }
8456:
1.682 raeburn 8457: sub get_active_groups {
8458: my ($udom,$uname,$cdom,$cnum) = @_;
8459: my $now = time;
8460: my %groups = ();
8461: foreach my $key (keys(%env)) {
1.811 albertel 8462: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8463: my ($start,$end) = split(/\./,$env{$key});
8464: if (($end!=0) && ($end<$now)) { next; }
8465: if (($start!=0) && ($start>$now)) { next; }
8466: if ($1 eq $cdom && $2 eq $cnum) {
8467: $groups{$3} = $env{$key} ;
8468: }
8469: }
8470: }
8471: return %groups;
8472: }
8473:
1.683 raeburn 8474: sub get_group_membership {
8475: my ($cdom,$cnum,$group) = @_;
8476: return(&dump('groupmembership',$cdom,$cnum,$group));
8477: }
8478:
8479: sub get_users_groups {
8480: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8481: my @usersgroups;
1.683 raeburn 8482: my $cachetime=1800;
8483:
8484: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8485: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8486: if (defined($cached)) {
1.734 albertel 8487: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8488: } else {
8489: $grouplist = '';
1.816 raeburn 8490: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8491: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8492: my $access_end = $env{'course.'.$courseid.
8493: '.default_enrollment_end_date'};
8494: my $now = time;
8495: foreach my $key (keys(%roleshash)) {
8496: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8497: my $group = $1;
8498: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8499: my $start = $2;
8500: my $end = $1;
8501: if ($start == -1) { next; } # deleted from group
8502: if (($start!=0) && ($start>$now)) { next; }
8503: if (($end!=0) && ($end<$now)) {
8504: if ($access_end && $access_end < $now) {
8505: if ($access_end - $end < 86400) {
8506: push(@usersgroups,$group);
1.733 raeburn 8507: }
8508: }
1.817 raeburn 8509: next;
1.733 raeburn 8510: }
1.817 raeburn 8511: push(@usersgroups,$group);
1.683 raeburn 8512: }
8513: }
8514: }
1.817 raeburn 8515: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8516: $grouplist = join(':',@usersgroups);
8517: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8518: }
1.733 raeburn 8519: return @usersgroups;
1.683 raeburn 8520: }
8521:
8522: sub devalidate_getgroups_cache {
8523: my ($udom,$uname,$cdom,$cnum)=@_;
8524: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8525:
1.683 raeburn 8526: my $hashid="$udom:$uname:$courseid";
8527: &devalidate_cache_new('getgroups',$hashid);
8528: }
8529:
1.12 www 8530: # ------------------------------------------------------------------ Plain Text
8531:
8532: sub plaintext {
1.988 raeburn 8533: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8534: if ($short =~ m{^cr/}) {
1.758 albertel 8535: return (split('/',$short))[-1];
8536: }
1.742 raeburn 8537: if (!defined($cid)) {
8538: $cid = $env{'request.course.id'};
8539: }
8540: my %rolenames = (
1.1008 raeburn 8541: Course => 'std',
8542: Community => 'alt1',
1.1305 raeburn 8543: Placement => 'std',
1.742 raeburn 8544: );
1.1037 raeburn 8545: if ($cid ne '') {
8546: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8547: unless ($forcedefault) {
8548: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8549: &Apache::lonlocal::mt_escape(\$roletext);
8550: return &Apache::lonlocal::mt($roletext);
8551: }
8552: }
8553: }
8554: if ((defined($type)) && (defined($rolenames{$type})) &&
8555: (defined($rolenames{$type})) &&
8556: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8557: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8558: } elsif ($cid ne '') {
8559: my $crstype = $env{'course.'.$cid.'.type'};
8560: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8561: (defined($prp{$short}{$rolenames{$crstype}}))) {
8562: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8563: }
1.742 raeburn 8564: }
1.1037 raeburn 8565: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8566: }
8567:
8568: # ----------------------------------------------------------------- Assign Role
8569:
8570: sub assignrole {
1.957 raeburn 8571: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8572: $context)=@_;
1.21 www 8573: my $mrole;
8574: if ($role =~ /^cr\//) {
1.393 www 8575: my $cwosec=$url;
1.811 albertel 8576: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8577: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8578: my $refused = 1;
8579: if ($context eq 'requestcourses') {
8580: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8581: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8582: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8583: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8584: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8585: if ($crsenv{'internal.courseowner'} eq
8586: $env{'user.name'}.':'.$env{'user.domain'}) {
8587: $refused = '';
8588: }
8589: }
8590: }
8591: }
8592: }
8593: if ($refused) {
8594: &logthis('Refused custom assignrole: '.
8595: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8596: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8597: return 'refused';
8598: }
1.104 www 8599: }
1.21 www 8600: $mrole='cr';
1.678 raeburn 8601: } elsif ($role =~ /^gr\//) {
8602: my $cwogrp=$url;
1.811 albertel 8603: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8604: unless (&allowed('mdg',$cwogrp)) {
8605: &logthis('Refused group assignrole: '.
8606: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8607: $env{'user.name'}.' at '.$env{'user.domain'});
8608: return 'refused';
8609: }
8610: $mrole='gr';
1.21 www 8611: } else {
1.82 www 8612: my $cwosec=$url;
1.811 albertel 8613: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8614: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8615: my $refused;
8616: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8617: if (!(&allowed('c'.$role,$url))) {
8618: $refused = 1;
8619: }
8620: } else {
8621: $refused = 1;
8622: }
1.947 raeburn 8623: if ($refused) {
1.1045 raeburn 8624: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8625: if (!$selfenroll && $context eq 'course') {
8626: my %crsenv;
8627: if ($role eq 'cc' || $role eq 'co') {
8628: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8629: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8630: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8631: if ($crsenv{'internal.courseowner'} eq
8632: $env{'user.name'}.':'.$env{'user.domain'}) {
8633: $refused = '';
8634: }
8635: }
8636: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8637: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8638: if ($crsenv{'internal.courseowner'} eq
8639: $env{'user.name'}.':'.$env{'user.domain'}) {
8640: $refused = '';
8641: }
8642: }
8643: }
8644: }
8645: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8646: $refused = '';
1.1017 raeburn 8647: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8648: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8649: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8650: my $wrongcc;
8651: if ($cnum =~ /^$match_community$/) {
8652: $wrongcc = 1 if ($role eq 'cc');
8653: } else {
8654: $wrongcc = 1 if ($role eq 'co');
8655: }
8656: unless ($wrongcc) {
8657: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8658: if ($crsenv{'internal.courseowner'} eq
8659: $env{'user.name'}.':'.$env{'user.domain'}) {
8660: $refused = '';
8661: }
1.1017 raeburn 8662: }
8663: }
1.1183 raeburn 8664: } elsif ($context eq 'requestauthor') {
8665: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8666: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8667: if ($env{'environment.requestauthor'} eq 'automatic') {
8668: $refused = '';
8669: } else {
8670: my %domdefaults = &get_domain_defaults($udom);
8671: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8672: my $checkbystatus;
8673: if ($env{'user.adv'}) {
8674: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8675: if ($disposition eq 'automatic') {
8676: $refused = '';
8677: } elsif ($disposition eq '') {
8678: $checkbystatus = 1;
8679: }
8680: } else {
8681: $checkbystatus = 1;
8682: }
8683: if ($checkbystatus) {
8684: if ($env{'environment.inststatus'}) {
8685: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8686: foreach my $type (@inststatuses) {
8687: if (($type ne '') &&
8688: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8689: $refused = '';
8690: }
8691: }
8692: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8693: $refused = '';
8694: }
8695: }
8696: }
8697: }
8698: }
1.1017 raeburn 8699: }
8700: if ($refused) {
1.947 raeburn 8701: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8702: ' '.$role.' '.$end.' '.$start.' by '.
8703: $env{'user.name'}.' at '.$env{'user.domain'});
8704: return 'refused';
8705: }
1.932 raeburn 8706: }
1.1131 raeburn 8707: } elsif ($role eq 'au') {
8708: if ($url ne '/'.$udom.'/') {
8709: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8710: ' to assign author role for '.$uname.':'.$udom.
8711: ' in domain: '.$url.' refused (wrong domain).');
8712: return 'refused';
8713: }
1.104 www 8714: }
1.21 www 8715: $mrole=$role;
8716: }
1.620 albertel 8717: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8718: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8719: if ($end) { $command.='_'.$end; }
1.21 www 8720: if ($start) {
8721: if ($end) {
1.81 www 8722: $command.='_'.$start;
1.21 www 8723: } else {
1.81 www 8724: $command.='_0_'.$start;
1.21 www 8725: }
8726: }
1.739 raeburn 8727: my $origstart = $start;
8728: my $origend = $end;
1.957 raeburn 8729: my $delflag;
1.357 www 8730: # actually delete
8731: if ($deleteflag) {
1.373 www 8732: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8733: # modify command to delete the role
1.620 albertel 8734: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8735: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8736: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8737: # set start and finish to negative values for userrolelog
8738: $start=-1;
8739: $end=-1;
1.957 raeburn 8740: $delflag = 1;
1.357 www 8741: }
8742: }
8743: # send command
1.349 www 8744: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8745: # log new user role if status is ok
1.349 www 8746: if ($answer eq 'ok') {
1.663 raeburn 8747: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8748: if (($role eq 'cc') || ($role eq 'in') ||
8749: ($role eq 'ep') || ($role eq 'ad') ||
8750: ($role eq 'ta') || ($role eq 'st') ||
8751: ($role=~/^cr/) || ($role eq 'gr') ||
8752: ($role eq 'co')) {
1.1200 raeburn 8753: # for course roles, perform group memberships changes triggered by role change.
8754: unless ($role =~ /^gr/) {
8755: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8756: $origstart,$selfenroll,$context);
8757: }
1.1184 raeburn 8758: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8759: $selfenroll,$context);
8760: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8761: ($role eq 'au') || ($role eq 'dc')) {
8762: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8763: $context);
8764: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8765: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8766: $context);
8767: }
1.1053 raeburn 8768: if ($role eq 'cc') {
8769: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8770: }
1.349 www 8771: }
8772: return $answer;
1.169 harris41 8773: }
8774:
1.1053 raeburn 8775: sub autoupdate_coowners {
8776: my ($url,$end,$start,$uname,$udom) = @_;
8777: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8778: if (($cdom ne '') && ($cnum ne '')) {
8779: my $now = time;
8780: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8781: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8782: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8783: my $instcode = $coursehash{'internal.coursecode'};
8784: if ($instcode ne '') {
1.1056 raeburn 8785: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8786: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8787: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8788: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8789: if ($result eq 'valid') {
8790: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8791: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8792: push(@newcoowners,$coowner);
8793: }
8794: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8795: push(@newcoowners,$uname.':'.$udom);
8796: }
8797: @newcoowners = sort(@newcoowners);
8798: } else {
8799: push(@newcoowners,$uname.':'.$udom);
8800: }
8801: } else {
8802: if ($coursehash{'internal.co-owners'}) {
8803: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8804: unless ($coowner eq $uname.':'.$udom) {
8805: push(@newcoowners,$coowner);
8806: }
8807: }
8808: unless (@newcoowners > 0) {
8809: $delcoowners = 1;
8810: $coowners = '';
8811: }
8812: }
8813: }
8814: if (@newcoowners || $delcoowners) {
8815: &store_coowners($cdom,$cnum,$coursehash{'home'},
8816: $delcoowners,@newcoowners);
8817: }
8818: }
8819: }
8820: }
8821: }
8822: }
8823: }
8824:
8825: sub store_coowners {
8826: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8827: my $cid = $cdom.'_'.$cnum;
8828: my ($coowners,$delresult,$putresult);
8829: if (@newcoowners) {
8830: $coowners = join(',',@newcoowners);
8831: my %coownershash = (
8832: 'internal.co-owners' => $coowners,
8833: );
8834: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8835: if ($putresult eq 'ok') {
8836: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8837: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8838: }
8839: }
8840: }
8841: if ($delcoowners) {
8842: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8843: if ($delresult eq 'ok') {
8844: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8845: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8846: }
8847: }
8848: }
8849: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8850: my %crsinfo =
8851: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8852: if (ref($crsinfo{$cid}) eq 'HASH') {
8853: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8854: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8855: }
8856: }
8857: }
8858:
1.169 harris41 8859: # -------------------------------------------------- Modify user authentication
1.197 www 8860: # Overrides without validation
8861:
1.169 harris41 8862: sub modifyuserauth {
8863: my ($udom,$uname,$umode,$upass)=@_;
8864: my $uhome=&homeserver($uname,$udom);
1.197 www 8865: unless (&allowed('mau',$udom)) { return 'refused'; }
8866: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8867: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8868: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8869: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8870: &escape($upass),$uhome);
1.620 albertel 8871: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8872: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8873: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8874: &log($udom,,$uname,$uhome,
1.620 albertel 8875: 'Authentication changed by '.$env{'user.domain'}.', '.
8876: $env{'user.name'}.', '.$umode.
1.197 www 8877: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8878: unless ($reply eq 'ok') {
1.197 www 8879: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8880: return 'error: '.$reply;
8881: }
1.170 harris41 8882: return 'ok';
1.80 www 8883: }
8884:
1.81 www 8885: # --------------------------------------------------------------- Modify a user
1.80 www 8886:
1.81 www 8887: sub modifyuser {
1.206 matthew 8888: my ($udom, $uname, $uid,
8889: $umode, $upass, $first,
8890: $middle, $last, $gene,
1.1058 raeburn 8891: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8892: $udom= &LONCAPA::clean_domain($udom);
8893: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8894: my $showcandelete = 'none';
8895: if (ref($candelete) eq 'ARRAY') {
8896: if (@{$candelete} > 0) {
8897: $showcandelete = join(', ',@{$candelete});
8898: }
8899: }
1.81 www 8900: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8901: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8902: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8903: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8904: ' desiredhome not specified').
1.620 albertel 8905: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8906: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8907: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8908: my $newuser;
8909: if ($uhome eq 'no_host') {
8910: $newuser = 1;
8911: }
1.80 www 8912: # ----------------------------------------------------------------- Create User
1.406 albertel 8913: if (($uhome eq 'no_host') &&
8914: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8915: my $unhome='';
1.844 albertel 8916: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8917: $unhome = $desiredhome;
1.620 albertel 8918: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8919: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8920: } else { # load balancing routine for determining $unhome
1.81 www 8921: my $loadm=10000000;
1.841 albertel 8922: my %servers = &get_servers($udom,'library');
8923: foreach my $tryserver (keys(%servers)) {
8924: my $answer=reply('load',$tryserver);
8925: if (($answer=~/\d+/) && ($answer<$loadm)) {
8926: $loadm=$answer;
8927: $unhome=$tryserver;
8928: }
1.80 www 8929: }
8930: }
8931: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8932: return 'error: unable to find a home server for '.$uname.
8933: ' in domain '.$udom;
1.80 www 8934: }
8935: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8936: &escape($upass),$unhome);
8937: unless ($reply eq 'ok') {
8938: return 'error: '.$reply;
8939: }
1.230 stredwic 8940: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8941: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8942: return 'error: unable verify users home machine.';
1.80 www 8943: }
1.209 matthew 8944: } # End of creation of new user
1.80 www 8945: # ---------------------------------------------------------------------- Add ID
8946: if ($uid) {
8947: $uid=~tr/A-Z/a-z/;
8948: my %uidhash=&idrget($udom,$uname);
1.196 www 8949: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8950: && (!$forceid)) {
1.80 www 8951: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8952: return 'error: user id "'.$uid.'" does not match '.
8953: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8954: }
8955: } else {
1.1300 raeburn 8956: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 8957: }
8958: }
8959: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8960: my @tmp=&get('environment',
1.899 raeburn 8961: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8962: 'permanentemail','inststatus'],
1.134 albertel 8963: $udom,$uname);
1.1075 raeburn 8964: my (%names,%oldnames);
1.313 matthew 8965: if ($tmp[0] =~ m/^error:.*/) {
8966: %names=();
8967: } else {
8968: %names = @tmp;
1.1075 raeburn 8969: %oldnames = %names;
1.313 matthew 8970: }
1.388 www 8971: #
1.1058 raeburn 8972: # If name, email and/or uid are blank (e.g., because an uploaded file
8973: # of users did not contain them), do not overwrite existing values
8974: # unless field is in $candelete array ref.
8975: #
8976:
8977: my @fields = ('firstname','middlename','lastname','generation',
8978: 'permanentemail','id');
8979: my %newvalues;
8980: if (ref($candelete) eq 'ARRAY') {
8981: foreach my $field (@fields) {
8982: if (grep(/^\Q$field\E$/,@{$candelete})) {
8983: if ($field eq 'firstname') {
8984: $names{$field} = $first;
8985: } elsif ($field eq 'middlename') {
8986: $names{$field} = $middle;
8987: } elsif ($field eq 'lastname') {
8988: $names{$field} = $last;
8989: } elsif ($field eq 'generation') {
8990: $names{$field} = $gene;
8991: } elsif ($field eq 'permanentemail') {
8992: $names{$field} = $email;
8993: } elsif ($field eq 'id') {
8994: $names{$field} = $uid;
8995: }
8996: }
8997: }
8998: }
1.388 www 8999: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9000: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9001: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9002: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9003: if ($email) {
9004: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9005: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9006: }
1.899 raeburn 9007: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9008: if (defined($inststatus)) {
9009: $names{'inststatus'} = '';
9010: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9011: if (ref($usertypes) eq 'HASH') {
9012: my @okstatuses;
9013: foreach my $item (split(/:/,$inststatus)) {
9014: if (defined($usertypes->{$item})) {
9015: push(@okstatuses,$item);
9016: }
9017: }
9018: if (@okstatuses) {
9019: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9020: }
9021: }
9022: }
1.1075 raeburn 9023: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9024: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9025: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9026: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9027: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9028: } else {
9029: $logmsg .= ' during self creation';
9030: }
1.1075 raeburn 9031: my $changed;
9032: if ($newuser) {
9033: $changed = 1;
9034: } else {
9035: foreach my $field (@fields) {
9036: if ($names{$field} ne $oldnames{$field}) {
9037: $changed = 1;
9038: last;
9039: }
9040: }
9041: }
9042: unless ($changed) {
9043: $logmsg = 'No changes in user information needed for: '.$logmsg;
9044: &logthis($logmsg);
9045: return 'ok';
9046: }
9047: my $reply = &put('environment', \%names, $udom,$uname);
9048: if ($reply ne 'ok') {
9049: return 'error: '.$reply;
9050: }
1.1087 raeburn 9051: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9052: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9053: }
1.1075 raeburn 9054: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9055: &devalidate_cache_new('namescache',$uname.':'.$udom);
9056: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9057: &logthis($logmsg);
1.134 albertel 9058: return 'ok';
1.80 www 9059: }
9060:
1.81 www 9061: # -------------------------------------------------------------- Modify student
1.80 www 9062:
1.81 www 9063: sub modifystudent {
9064: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9065: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 9066: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 9067: if (!$cid) {
1.620 albertel 9068: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9069: return 'not_in_class';
9070: }
1.80 www 9071: }
9072: # --------------------------------------------------------------- Make the user
1.81 www 9073: my $reply=&modifyuser
1.209 matthew 9074: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9075: $desiredhome,$email,$inststatus);
1.80 www 9076: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9077: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9078: # student's environment
1.297 matthew 9079: $uid = undef if (!$forceid);
1.455 albertel 9080: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9081: $gene,$usec,$end,$start,$type,$locktype,
9082: $cid,$selfenroll,$context,$credits);
1.297 matthew 9083: return $reply;
9084: }
9085:
9086: sub modify_student_enrollment {
1.1216 raeburn 9087: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
9088: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 9089: my ($cdom,$cnum,$chome);
9090: if (!$cid) {
1.620 albertel 9091: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9092: return 'not_in_class';
9093: }
1.620 albertel 9094: $cdom=$env{'course.'.$cid.'.domain'};
9095: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9096: } else {
9097: ($cdom,$cnum)=split(/_/,$cid);
9098: }
1.620 albertel 9099: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9100: if (!$chome) {
1.457 raeburn 9101: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9102: }
1.455 albertel 9103: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9104: # Make sure the user exists
1.81 www 9105: my $uhome=&homeserver($uname,$udom);
9106: if (($uhome eq '') || ($uhome eq 'no_host')) {
9107: return 'error: no such user';
9108: }
1.297 matthew 9109: # Get student data if we were not given enough information
9110: if (!defined($first) || $first eq '' ||
9111: !defined($last) || $last eq '' ||
9112: !defined($uid) || $uid eq '' ||
9113: !defined($middle) || $middle eq '' ||
9114: !defined($gene) || $gene eq '') {
1.294 matthew 9115: # They did not supply us with enough data to enroll the student, so
9116: # we need to pick up more information.
1.297 matthew 9117: my %tmp = &get('environment',
1.294 matthew 9118: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9119: ,$udom,$uname);
9120:
1.800 albertel 9121: #foreach my $key (keys(%tmp)) {
9122: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9123: #}
1.294 matthew 9124: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9125: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9126: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9127: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9128: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9129: }
1.556 albertel 9130: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9131: my $user = "$uname:$udom";
9132: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9133: my $reply=cput('classlist',
1.1148 raeburn 9134: {$user =>
1.1216 raeburn 9135: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 9136: $cdom,$cnum);
1.1148 raeburn 9137: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9138: &devalidate_getsection_cache($udom,$uname,$cid);
9139: } else {
1.81 www 9140: return 'error: '.$reply;
9141: }
1.297 matthew 9142: # Add student role to user
1.83 www 9143: my $uurl='/'.$cid;
1.81 www 9144: $uurl=~s/\_/\//g;
9145: if ($usec) {
9146: $uurl.='/'.$usec;
9147: }
1.1148 raeburn 9148: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9149: $selfenroll,$context);
9150: if ($result ne 'ok') {
9151: if ($old_entry{$user} ne '') {
9152: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9153: } else {
9154: $reply = &del('classlist',[$user],$cdom,$cnum);
9155: }
9156: }
9157: return $result;
1.21 www 9158: }
9159:
1.556 albertel 9160: sub format_name {
9161: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9162: my $name;
9163: if ($first ne 'lastname') {
9164: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9165: } else {
9166: if ($lastname=~/\S/) {
9167: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9168: $name=~s/\s+,/,/;
9169: } else {
9170: $name.= $firstname.' '.$middlename.' '.$generation;
9171: }
9172: }
9173: $name=~s/^\s+//;
9174: $name=~s/\s+$//;
9175: $name=~s/\s+/ /g;
9176: return $name;
9177: }
9178:
1.84 www 9179: # ------------------------------------------------- Write to course preferences
9180:
9181: sub writecoursepref {
9182: my ($courseid,%prefs)=@_;
9183: $courseid=~s/^\///;
9184: $courseid=~s/\_/\//g;
9185: my ($cdomain,$cnum)=split(/\//,$courseid);
9186: my $chome=homeserver($cnum,$cdomain);
9187: if (($chome eq '') || ($chome eq 'no_host')) {
9188: return 'error: no such course';
9189: }
9190: my $cstring='';
1.800 albertel 9191: foreach my $pref (keys(%prefs)) {
9192: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9193: }
1.84 www 9194: $cstring=~s/\&$//;
9195: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9196: }
9197:
9198: # ---------------------------------------------------------- Make/modify course
9199:
9200: sub createcourse {
1.741 raeburn 9201: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9202: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9203: $url=&declutter($url);
9204: my $cid='';
1.1028 raeburn 9205: if ($context eq 'requestcourses') {
9206: my $can_create = 0;
9207: my ($ownername,$ownerdom) = split(':',$course_owner);
9208: if ($udom eq $ownerdom) {
9209: if (&usertools_access($ownername,$ownerdom,$category,undef,
9210: $context)) {
9211: $can_create = 1;
9212: }
9213: } else {
9214: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9215: $category);
9216: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9217: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9218: if (@curr > 0) {
9219: my @options = qw(approval validate autolimit);
9220: my $optregex = join('|',@options);
9221: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9222: $can_create = 1;
9223: }
9224: }
9225: }
9226: }
9227: if ($can_create) {
9228: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9229: unless (&allowed('ccc',$udom)) {
9230: return 'refused';
9231: }
1.1017 raeburn 9232: }
9233: } else {
9234: return 'refused';
9235: }
1.1028 raeburn 9236: } elsif (!&allowed('ccc',$udom)) {
9237: return 'refused';
1.84 www 9238: }
1.1011 raeburn 9239: # --------------------------------------------------------------- Get Unique ID
9240: my $uname;
9241: if ($cnum =~ /^$match_courseid$/) {
9242: my $chome=&homeserver($cnum,$udom,'true');
9243: if (($chome eq '') || ($chome eq 'no_host')) {
9244: $uname = $cnum;
9245: } else {
1.1038 raeburn 9246: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9247: }
9248: } else {
1.1038 raeburn 9249: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9250: }
9251: return $uname if ($uname =~ /^error/);
9252: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9253: if (!defined($course_server)) {
9254: if (defined(&domain($udom,'primary'))) {
9255: $course_server = &domain($udom,'primary');
9256: } else {
9257: $course_server = $env{'user.home'};
9258: }
9259: }
9260: my %host_servers =
9261: &Apache::lonnet::get_servers($udom,'library');
9262: unless ($host_servers{$course_server}) {
9263: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9264: }
1.84 www 9265: # ------------------------------------------------------------- Make the course
9266: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9267: $course_server);
1.84 www 9268: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9269: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9270: if (($uhome eq '') || ($uhome eq 'no_host')) {
9271: return 'error: no such course';
9272: }
1.271 www 9273: # ----------------------------------------------------------------- Course made
1.516 raeburn 9274: # log existence
1.1029 raeburn 9275: my $now = time;
1.918 raeburn 9276: my $newcourse = {
9277: $udom.'_'.$uname => {
1.921 raeburn 9278: description => $description,
9279: inst_code => $inst_code,
9280: owner => $course_owner,
9281: type => $crstype,
1.1029 raeburn 9282: creator => $env{'user.name'}.':'.
9283: $env{'user.domain'},
9284: created => $now,
9285: context => $context,
1.918 raeburn 9286: },
9287: };
1.921 raeburn 9288: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9289: # set toplevel url
1.271 www 9290: my $topurl=$url;
9291: unless ($nonstandard) {
9292: # ------------------------------------------ For standard courses, make top url
9293: my $mapurl=&clutter($url);
1.278 www 9294: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9295: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9296: <map>
9297: <resource id="1" type="start"></resource>
9298: <resource id="2" src="$mapurl"></resource>
9299: <resource id="3" type="finish"></resource>
9300: <link index="1" from="1" to="2"></link>
9301: <link index="2" from="2" to="3"></link>
9302: </map>
9303: ENDINITMAP
9304: $topurl=&declutter(
1.638 albertel 9305: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9306: );
9307: }
9308: # ----------------------------------------------------------- Write preferences
1.84 www 9309: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9310: ('description' => $description,
9311: 'url' => $topurl,
9312: 'internal.creator' => $env{'user.name'}.':'.
9313: $env{'user.domain'},
9314: 'internal.created' => $now,
9315: 'internal.creationcontext' => $context)
9316: );
1.84 www 9317: return '/'.$udom.'/'.$uname;
9318: }
9319:
1.1011 raeburn 9320: # ------------------------------------------------------------------- Create ID
9321: sub generate_coursenum {
1.1038 raeburn 9322: my ($udom,$crstype) = @_;
1.1011 raeburn 9323: my $domdesc = &domain($udom);
9324: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9325: my $first;
9326: if ($crstype eq 'Community') {
9327: $first = '0';
9328: } else {
9329: $first = int(1+rand(9));
9330: }
9331: my $uname=$first.
1.1011 raeburn 9332: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9333: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9334: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9335: # ----------------------------------------------- Make sure that does not exist
9336: my $uhome=&homeserver($uname,$udom,'true');
9337: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9338: if ($crstype eq 'Community') {
9339: $first = '0';
9340: } else {
9341: $first = int(1+rand(9));
9342: }
9343: $uname=$first.
1.1011 raeburn 9344: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9345: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9346: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9347: $uhome=&homeserver($uname,$udom,'true');
9348: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9349: return 'error: unable to generate unique course-ID';
9350: }
9351: }
9352: return $uname;
9353: }
9354:
1.813 albertel 9355: sub is_course {
1.1167 droeschl 9356: my ($cdom, $cnum) = scalar(@_) == 1 ?
9357: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9358:
9359: return unless $cdom and $cnum;
9360:
9361: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9362: '.');
9363:
1.1219 raeburn 9364: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9365: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9366: }
9367:
1.1015 raeburn 9368: sub store_userdata {
9369: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9370: my $result;
1.1016 raeburn 9371: if ($datakey ne '') {
1.1013 raeburn 9372: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9373: if ($udom eq '' || $uname eq '') {
9374: $udom = $env{'user.domain'};
9375: $uname = $env{'user.name'};
9376: }
9377: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9378: if (($uhome eq '') || ($uhome eq 'no_host')) {
9379: $result = 'error: no_host';
9380: } else {
9381: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9382: $storehash->{'host'} = $perlvar{'lonHostID'};
9383:
9384: my $namevalue='';
9385: foreach my $key (keys(%{$storehash})) {
9386: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9387: }
9388: $namevalue=~s/\&$//;
1.1224 raeburn 9389: unless ($namespace eq 'courserequests') {
9390: $datakey = &escape($datakey);
9391: }
1.1105 raeburn 9392: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9393: $namevalue,$uhome);
1.1013 raeburn 9394: }
9395: } else {
9396: $result = 'error: data to store was not a hash reference';
9397: }
9398: } else {
9399: $result= 'error: invalid requestkey';
9400: }
9401: return $result;
9402: }
9403:
1.21 www 9404: # ---------------------------------------------------------- Assign Custom Role
9405:
9406: sub assigncustomrole {
1.957 raeburn 9407: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9408: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9409: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9410: }
9411:
9412: # ----------------------------------------------------------------- Revoke Role
9413:
9414: sub revokerole {
1.957 raeburn 9415: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9416: my $now=time;
1.965 raeburn 9417: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9418: }
9419:
9420: # ---------------------------------------------------------- Revoke Custom Role
9421:
9422: sub revokecustomrole {
1.957 raeburn 9423: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9424: my $now=time;
1.357 www 9425: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9426: $deleteflag,$selfenroll,$context);
1.17 www 9427: }
9428:
1.533 banghart 9429: # ------------------------------------------------------------ Disk usage
1.535 albertel 9430: sub diskusage {
1.955 raeburn 9431: my ($udom,$uname,$directorypath,$getpropath)=@_;
9432: $directorypath =~ s/\/$//;
9433: my $listing=&reply('du2:'.&escape($directorypath).':'
9434: .&escape($getpropath).':'.&escape($uname).':'
9435: .&escape($udom),homeserver($uname,$udom));
9436: if ($listing eq 'unknown_cmd') {
9437: if ($getpropath) {
9438: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9439: }
9440: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9441: }
1.514 albertel 9442: return $listing;
1.512 banghart 9443: }
9444:
1.566 banghart 9445: sub is_locked {
1.1096 raeburn 9446: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9447: my @check;
9448: my $is_locked;
1.1093 raeburn 9449: push (@check,$file_name);
1.613 albertel 9450: my %locked = &get('file_permissions',\@check,
1.620 albertel 9451: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9452: my ($tmp)=keys(%locked);
9453: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9454:
1.566 banghart 9455: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9456: $is_locked = 'false';
9457: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9458: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9459: $is_locked = 'true';
1.1096 raeburn 9460: if (ref($which) eq 'ARRAY') {
9461: push(@{$which},$entry);
9462: } else {
9463: last;
9464: }
1.745 raeburn 9465: }
9466: }
1.566 banghart 9467: } else {
9468: $is_locked = 'false';
9469: }
1.1093 raeburn 9470: return $is_locked;
1.566 banghart 9471: }
9472:
1.759 albertel 9473: sub declutter_portfile {
9474: my ($file) = @_;
1.833 albertel 9475: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9476: return $file;
9477: }
9478:
1.559 banghart 9479: # ------------------------------------------------------------- Mark as Read Only
9480:
9481: sub mark_as_readonly {
9482: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9483: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9484: my ($tmp)=keys(%current_permissions);
9485: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9486: foreach my $file (@{$files}) {
1.759 albertel 9487: $file = &declutter_portfile($file);
1.561 banghart 9488: push(@{$current_permissions{$file}},$what);
1.559 banghart 9489: }
1.613 albertel 9490: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9491: return;
9492: }
9493:
1.572 banghart 9494: # ------------------------------------------------------------Save Selected Files
9495:
9496: sub save_selected_files {
9497: my ($user, $path, @files) = @_;
9498: my $filename = $user."savedfiles";
1.573 banghart 9499: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9500: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9501: foreach my $file (@files) {
1.620 albertel 9502: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9503: }
9504: foreach my $file (@other_files) {
1.574 banghart 9505: print (OUT $file."\n");
1.572 banghart 9506: }
1.574 banghart 9507: close (OUT);
1.572 banghart 9508: return 'ok';
9509: }
9510:
1.574 banghart 9511: sub clear_selected_files {
9512: my ($user) = @_;
9513: my $filename = $user."savedfiles";
1.1117 foxr 9514: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9515: print (OUT undef);
9516: close (OUT);
9517: return ("ok");
9518: }
9519:
1.572 banghart 9520: sub files_in_path {
9521: my ($user, $path) = @_;
9522: my $filename = $user."savedfiles";
9523: my %return_files;
1.1117 foxr 9524: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9525: while (my $line_in = <IN>) {
1.574 banghart 9526: chomp ($line_in);
9527: my @paths_and_file = split (m!/!, $line_in);
9528: my $file_part = pop (@paths_and_file);
9529: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9530: $path_part.='/';
9531: my $path_and_file = $path_part.$file_part;
9532: if ($path_part eq $path) {
9533: $return_files{$file_part}= 'selected';
9534: }
9535: }
1.574 banghart 9536: close (IN);
9537: return (\%return_files);
1.572 banghart 9538: }
9539:
9540: # called in portfolio select mode, to show files selected NOT in current directory
9541: sub files_not_in_path {
9542: my ($user, $path) = @_;
9543: my $filename = $user."savedfiles";
9544: my @return_files;
9545: my $path_part;
1.1117 foxr 9546: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9547: while (my $line = <IN>) {
1.572 banghart 9548: #ok, I know it's clunky, but I want it to work
1.800 albertel 9549: my @paths_and_file = split(m|/|, $line);
9550: my $file_part = pop(@paths_and_file);
9551: chomp($file_part);
9552: my $path_part = join('/', @paths_and_file);
1.572 banghart 9553: $path_part .= '/';
9554: my $path_and_file = $path_part.$file_part;
9555: if ($path_part ne $path) {
1.800 albertel 9556: push(@return_files, ($path_and_file));
1.572 banghart 9557: }
9558: }
1.800 albertel 9559: close(OUT);
1.574 banghart 9560: return (@return_files);
1.572 banghart 9561: }
9562:
1.1273 raeburn 9563: #------------------------------Submitted/Handedback Portfolio Files Versioning
9564:
9565: sub portfiles_versioning {
9566: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9567: my $portfolio_root = '/userfiles/portfolio';
9568: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9569: foreach my $file (@{$portfiles}) {
9570: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9571: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9572: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9573: my $getpropath = 1;
9574: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9575: $stu_name,$getpropath);
9576: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9577: my $new_answer =
9578: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9579: if ($new_answer ne 'problem getting file') {
9580: push(@{$versioned_portfiles}, $directory.$new_answer);
9581: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9582: [$symb,$env{'request.course.id'},'graded']);
9583: }
9584: }
9585: }
9586:
9587: sub get_next_version {
9588: my ($answer_name, $answer_ext, $dir_list) = @_;
9589: my $version;
9590: if (ref($dir_list) eq 'ARRAY') {
9591: foreach my $row (@{$dir_list}) {
9592: my ($file) = split(/\&/,$row,2);
9593: my ($file_name,$file_version,$file_ext) =
9594: &file_name_version_ext($file);
9595: if (($file_name eq $answer_name) &&
9596: ($file_ext eq $answer_ext)) {
9597: # gets here if filename and extension match,
9598: # regardless of version
9599: if ($file_version ne '') {
9600: # a versioned file is found so save it for later
9601: if ($file_version > $version) {
9602: $version = $file_version;
9603: }
9604: }
9605: }
9606: }
9607: }
9608: $version ++;
9609: return($version);
9610: }
9611:
9612: sub version_selected_portfile {
9613: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9614: my ($answer_name,$answer_ver,$answer_ext) =
9615: &file_name_version_ext($file_name);
9616: my $new_answer;
9617: $env{'form.copy'} =
9618: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9619: if($env{'form.copy'} eq '-1') {
9620: $new_answer = 'problem getting file';
9621: } else {
9622: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9623: my $copy_result =
9624: &finishuserfileupload($stu_name,$domain,'copy',
9625: '/portfolio'.$directory.$new_answer);
9626: }
9627: undef($env{'form.copy'});
9628: return ($new_answer);
9629: }
9630:
9631: sub file_name_version_ext {
9632: my ($file)=@_;
9633: my @file_parts = split(/\./, $file);
9634: my ($name,$version,$ext);
9635: if (@file_parts > 1) {
9636: $ext=pop(@file_parts);
9637: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9638: $version=pop(@file_parts);
9639: }
9640: $name=join('.',@file_parts);
9641: } else {
9642: $name=join('.',@file_parts);
9643: }
9644: return($name,$version,$ext);
9645: }
9646:
1.745 raeburn 9647: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9648:
1.745 raeburn 9649: sub get_portfile_permissions {
9650: my ($domain,$user) = @_;
1.613 albertel 9651: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9652: my ($tmp)=keys(%current_permissions);
9653: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9654: return \%current_permissions;
9655: }
9656:
9657: #---------------------------------------------Get portfolio file access controls
9658:
1.749 raeburn 9659: sub get_access_controls {
1.745 raeburn 9660: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9661: my %access;
9662: my $real_file = $file;
9663: $file =~ s/\.meta$//;
1.745 raeburn 9664: if (defined($file)) {
1.749 raeburn 9665: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9666: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9667: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9668: }
9669: }
1.745 raeburn 9670: } else {
1.749 raeburn 9671: foreach my $key (keys(%{$current_permissions})) {
9672: if ($key =~ /\0accesscontrol$/) {
9673: if (defined($group)) {
9674: if ($key !~ m-^\Q$group\E/-) {
9675: next;
9676: }
9677: }
9678: my ($fullpath) = split(/\0/,$key);
9679: if (ref($$current_permissions{$key}) eq 'HASH') {
9680: foreach my $control (keys(%{$$current_permissions{$key}})) {
9681: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9682: }
9683: }
9684: }
9685: }
9686: }
9687: return %access;
9688: }
9689:
9690: sub modify_access_controls {
9691: my ($file_name,$changes,$domain,$user)=@_;
9692: my ($outcome,$deloutcome);
9693: my %store_permissions;
9694: my %new_values;
9695: my %new_control;
9696: my %translation;
9697: my @deletions = ();
9698: my $now = time;
9699: if (exists($$changes{'activate'})) {
9700: if (ref($$changes{'activate'}) eq 'HASH') {
9701: my @newitems = sort(keys(%{$$changes{'activate'}}));
9702: my $numnew = scalar(@newitems);
9703: for (my $i=0; $i<$numnew; $i++) {
9704: my $newkey = $newitems[$i];
9705: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9706: if ($newkey =~ /^\d+:/) {
9707: $newkey =~ s/^(\d+)/$newid/;
9708: $translation{$1} = $newid;
9709: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9710: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9711: $translation{$1} = $newid;
9712: }
1.749 raeburn 9713: $new_values{$file_name."\0".$newkey} =
9714: $$changes{'activate'}{$newitems[$i]};
9715: $new_control{$newkey} = $now;
9716: }
9717: }
9718: }
9719: my %todelete;
9720: my %changed_items;
9721: foreach my $action ('delete','update') {
9722: if (exists($$changes{$action})) {
9723: if (ref($$changes{$action}) eq 'HASH') {
9724: foreach my $key (keys(%{$$changes{$action}})) {
9725: my ($itemnum) = ($key =~ /^([^:]+):/);
9726: if ($action eq 'delete') {
9727: $todelete{$itemnum} = 1;
9728: } else {
9729: $changed_items{$itemnum} = $key;
9730: }
9731: }
1.745 raeburn 9732: }
9733: }
1.749 raeburn 9734: }
9735: # get lock on access controls for file.
9736: my $lockhash = {
9737: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9738: ':'.$env{'user.domain'},
9739: };
9740: my $tries = 0;
9741: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9742:
1.1288 damieng 9743: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9744: $tries ++;
1.1289 damieng 9745: sleep(0.1);
1.749 raeburn 9746: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9747: }
9748: if ($gotlock eq 'ok') {
9749: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9750: my ($tmp)=keys(%curr_permissions);
9751: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9752: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9753: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9754: if (ref($curr_controls) eq 'HASH') {
9755: foreach my $control_item (keys(%{$curr_controls})) {
9756: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9757: if (defined($todelete{$itemnum})) {
9758: push(@deletions,$file_name."\0".$control_item);
9759: } else {
9760: if (defined($changed_items{$itemnum})) {
9761: $new_control{$changed_items{$itemnum}} = $now;
9762: push(@deletions,$file_name."\0".$control_item);
9763: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9764: } else {
9765: $new_control{$control_item} = $$curr_controls{$control_item};
9766: }
9767: }
1.745 raeburn 9768: }
9769: }
9770: }
1.970 raeburn 9771: my ($group);
9772: if (&is_course($domain,$user)) {
9773: ($group,my $file) = split(/\//,$file_name,2);
9774: }
1.749 raeburn 9775: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9776: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9777: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9778: # remove lock
9779: my @del_lock = ($file_name."\0".'locked_access_records');
9780: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9781: my $sqlresult =
1.970 raeburn 9782: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9783: $group);
1.749 raeburn 9784: } else {
9785: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9786: }
1.749 raeburn 9787: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9788: }
9789:
1.827 raeburn 9790: sub make_public_indefinitely {
1.1271 raeburn 9791: my (@requrl) = @_;
9792: return &automated_portfile_access('public',\@requrl);
9793: }
9794:
9795: sub automated_portfile_access {
9796: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9797: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9798: return 'invalid';
9799: }
1.1271 raeburn 9800: my %urls;
9801: if (ref($addsref) eq 'ARRAY') {
9802: foreach my $requrl (@{$addsref}) {
9803: if (&is_portfolio_url($requrl)) {
9804: unless (exists($urls{$requrl})) {
9805: $urls{$requrl} = 'add';
9806: }
9807: }
9808: }
9809: }
9810: if (ref($delsref) eq 'ARRAY') {
9811: foreach my $requrl (@{$delsref}) {
9812: if (&is_portfolio_url($requrl)) {
9813: unless (exists($urls{$requrl})) {
9814: $urls{$requrl} = 'delete';
9815: }
9816: }
9817: }
9818: }
9819: unless (keys(%urls)) {
9820: return 'invalid';
9821: }
9822: my $ip;
9823: if ($accesstype eq 'ip') {
9824: if (ref($info) eq 'HASH') {
9825: if ($info->{'ip'} ne '') {
9826: $ip = $info->{'ip'};
9827: }
9828: }
9829: if ($ip eq '') {
9830: return 'invalid';
9831: }
9832: }
9833: my $errors;
1.827 raeburn 9834: my $now = time;
1.1271 raeburn 9835: my %current_perms;
9836: foreach my $requrl (sort(keys(%urls))) {
9837: my $action;
9838: if ($urls{$requrl} eq 'add') {
9839: $action = 'activate';
9840: } else {
9841: $action = 'none';
9842: }
9843: my $aclnum = 0;
1.827 raeburn 9844: my (undef,$udom,$unum,$file_name,$group) =
9845: &parse_portfolio_url($requrl);
1.1271 raeburn 9846: unless (exists($current_perms{$unum.':'.$udom})) {
9847: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9848: }
9849: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9850: $group,$file_name);
9851: foreach my $key (keys(%{$access_controls{$file_name}})) {
9852: my ($num,$scope,$end,$start) =
9853: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9854: if ($scope eq $accesstype) {
9855: if (($start <= $now) && ($end == 0)) {
9856: if ($accesstype eq 'ip') {
9857: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9858: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9859: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9860: if ($urls{$requrl} eq 'add') {
9861: $action = 'none';
9862: last;
9863: } else {
9864: $action = 'delete';
9865: $aclnum = $num;
9866: last;
9867: }
9868: }
9869: }
9870: }
9871: } elsif ($accesstype eq 'public') {
9872: if ($urls{$requrl} eq 'add') {
9873: $action = 'none';
9874: last;
9875: } else {
9876: $action = 'delete';
9877: $aclnum = $num;
9878: last;
9879: }
9880: }
9881: } elsif ($accesstype eq 'public') {
1.827 raeburn 9882: $action = 'update';
9883: $aclnum = $num;
1.1271 raeburn 9884: last;
1.827 raeburn 9885: }
9886: }
9887: }
9888: if ($action eq 'none') {
1.1271 raeburn 9889: next;
1.827 raeburn 9890: } else {
9891: my %changes;
9892: my $newend = 0;
9893: my $newstart = $now;
1.1271 raeburn 9894: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 9895: $changes{$action}{$newkey} = {
1.1271 raeburn 9896: type => $accesstype,
1.827 raeburn 9897: time => {
9898: start => $newstart,
9899: end => $newend,
9900: },
9901: };
1.1271 raeburn 9902: if ($accesstype eq 'ip') {
9903: $changes{$action}{$newkey}{'ip'} = [$ip];
9904: }
1.827 raeburn 9905: my ($outcome,$deloutcome,$new_values,$translation) =
9906: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 9907: unless ($outcome eq 'ok') {
9908: $errors .= $outcome.' ';
9909: }
1.827 raeburn 9910: }
1.1271 raeburn 9911: }
9912: if ($errors) {
9913: $errors =~ s/\s$//;
9914: return $errors;
1.827 raeburn 9915: } else {
1.1271 raeburn 9916: return 'ok';
1.827 raeburn 9917: }
9918: }
9919:
1.745 raeburn 9920: #------------------------------------------------------Get Marked as Read Only
9921:
9922: sub get_marked_as_readonly {
9923: my ($domain,$user,$what,$group) = @_;
9924: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9925: my @readonly_files;
1.629 banghart 9926: my $cmp1=$what;
9927: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9928: while (my ($file_name,$value) = each(%{$current_permissions})) {
9929: if (defined($group)) {
9930: if ($file_name !~ m-^\Q$group\E/-) {
9931: next;
9932: }
9933: }
1.561 banghart 9934: if (ref($value) eq "ARRAY"){
9935: foreach my $stored_what (@{$value}) {
1.629 banghart 9936: my $cmp2=$stored_what;
1.759 albertel 9937: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9938: $cmp2=join('',@{$stored_what});
1.745 raeburn 9939: }
1.629 banghart 9940: if ($cmp1 eq $cmp2) {
1.561 banghart 9941: push(@readonly_files, $file_name);
1.745 raeburn 9942: last;
1.563 banghart 9943: } elsif (!defined($what)) {
9944: push(@readonly_files, $file_name);
1.745 raeburn 9945: last;
1.561 banghart 9946: }
9947: }
1.745 raeburn 9948: }
1.561 banghart 9949: }
9950: return @readonly_files;
9951: }
1.577 banghart 9952: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9953:
1.577 banghart 9954: sub get_marked_as_readonly_hash {
1.745 raeburn 9955: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9956: my %readonly_files;
1.745 raeburn 9957: while (my ($file_name,$value) = each(%{$current_permissions})) {
9958: if (defined($group)) {
9959: if ($file_name !~ m-^\Q$group\E/-) {
9960: next;
9961: }
9962: }
1.577 banghart 9963: if (ref($value) eq "ARRAY"){
9964: foreach my $stored_what (@{$value}) {
1.745 raeburn 9965: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9966: foreach my $lock_descriptor(@{$stored_what}) {
9967: if ($lock_descriptor eq 'graded') {
9968: $readonly_files{$file_name} = 'graded';
9969: } elsif ($lock_descriptor eq 'handback') {
9970: $readonly_files{$file_name} = 'handback';
9971: } else {
9972: if (!exists($readonly_files{$file_name})) {
9973: $readonly_files{$file_name} = 'locked';
9974: }
9975: }
1.745 raeburn 9976: }
1.750 banghart 9977: }
1.577 banghart 9978: }
9979: }
9980: }
9981: return %readonly_files;
9982: }
1.559 banghart 9983: # ------------------------------------------------------------ Unmark as Read Only
9984:
9985: sub unmark_as_readonly {
1.629 banghart 9986: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9987: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9988: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9989: $file_name = &declutter_portfile($file_name);
1.634 albertel 9990: my $symb_crs = $what;
9991: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9992: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9993: my ($tmp)=keys(%current_permissions);
9994: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9995: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9996: foreach my $file (@readonly_files) {
1.759 albertel 9997: my $clean_file = &declutter_portfile($file);
9998: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9999: my $current_locks = $current_permissions{$file};
1.563 banghart 10000: my @new_locks;
10001: my @del_keys;
10002: if (ref($current_locks) eq "ARRAY"){
10003: foreach my $locker (@{$current_locks}) {
1.632 albertel 10004: my $compare=$locker;
1.749 raeburn 10005: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10006: $compare=join('',@{$locker});
1.746 raeburn 10007: if ($compare ne $symb_crs) {
10008: push(@new_locks, $locker);
10009: }
1.563 banghart 10010: }
10011: }
1.650 albertel 10012: if (scalar(@new_locks) > 0) {
1.563 banghart 10013: $current_permissions{$file} = \@new_locks;
10014: } else {
10015: push(@del_keys, $file);
1.613 albertel 10016: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10017: delete($current_permissions{$file});
1.563 banghart 10018: }
10019: }
1.561 banghart 10020: }
1.613 albertel 10021: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10022: return;
10023: }
1.512 banghart 10024:
1.17 www 10025: # ------------------------------------------------------------ Directory lister
10026:
10027: sub dirlist {
1.955 raeburn 10028: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10029: $uri=~s/^\///;
10030: $uri=~s/\/$//;
1.253 stredwic 10031: my ($udom, $uname);
1.955 raeburn 10032: if ($getuserdir) {
1.253 stredwic 10033: $udom = $userdomain;
10034: $uname = $username;
1.955 raeburn 10035: } else {
10036: (undef,$udom,$uname)=split(/\//,$uri);
10037: if(defined($userdomain)) {
10038: $udom = $userdomain;
10039: }
10040: if(defined($username)) {
10041: $uname = $username;
10042: }
1.253 stredwic 10043: }
1.955 raeburn 10044: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10045:
1.955 raeburn 10046: $dirRoot = $perlvar{'lonDocRoot'};
10047: if (defined($getpropath)) {
10048: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10049: $dirRoot =~ s/\/$//;
1.955 raeburn 10050: } elsif (defined($getuserdir)) {
10051: my $subdir=$uname.'__';
10052: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10053: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10054: ."/$udom/$subdir/$uname";
10055: } elsif (defined($alternateRoot)) {
10056: $dirRoot = $alternateRoot;
1.751 banghart 10057: }
1.253 stredwic 10058:
10059: if($udom) {
10060: if($uname) {
1.1135 raeburn 10061: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10062: if ($uhome eq 'no_host') {
10063: return ([],'no_host');
10064: }
1.955 raeburn 10065: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10066: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10067: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10068: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10069: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10070: } else {
10071: @listing_results = map { &unescape($_); } split(/:/,$listing);
10072: }
1.605 matthew 10073: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10074: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10075: @listing_results = split(/:/,$listing);
10076: } else {
10077: @listing_results = map { &unescape($_); } split(/:/,$listing);
10078: }
1.1135 raeburn 10079: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10080: ($listing eq 'rejected') || ($listing eq 'refused') ||
10081: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10082: return ([],$listing);
10083: } else {
10084: return (\@listing_results);
1.1135 raeburn 10085: }
1.955 raeburn 10086: } elsif(!$alternateRoot) {
1.1136 raeburn 10087: my (%allusers,%listerror);
1.841 albertel 10088: my %servers = &get_servers($udom,'library');
1.955 raeburn 10089: foreach my $tryserver (keys(%servers)) {
10090: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10091: &escape($udom),$tryserver);
10092: if ($listing eq 'unknown_cmd') {
10093: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10094: $udom, $tryserver);
10095: } else {
10096: @listing_results = map { &unescape($_); } split(/:/,$listing);
10097: }
1.841 albertel 10098: if ($listing eq 'unknown_cmd') {
10099: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10100: $udom, $tryserver);
10101: @listing_results = split(/:/,$listing);
10102: } else {
10103: @listing_results =
10104: map { &unescape($_); } split(/:/,$listing);
10105: }
1.1136 raeburn 10106: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10107: ($listing eq 'rejected') || ($listing eq 'refused') ||
10108: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10109: $listerror{$tryserver} = $listing;
10110: } else {
1.841 albertel 10111: foreach my $line (@listing_results) {
10112: my ($entry) = split(/&/,$line,2);
10113: $allusers{$entry} = 1;
10114: }
10115: }
1.253 stredwic 10116: }
1.1136 raeburn 10117: my @alluserslist=();
1.800 albertel 10118: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10119: push(@alluserslist,$user.'&user');
1.253 stredwic 10120: }
1.1136 raeburn 10121: return (\@alluserslist);
1.253 stredwic 10122: } else {
1.1136 raeburn 10123: return ([],'missing username');
1.253 stredwic 10124: }
1.955 raeburn 10125: } elsif(!defined($getpropath)) {
1.1136 raeburn 10126: my $path = $perlvar{'lonDocRoot'}.'/res/';
10127: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10128: return (\@all_domains);
1.955 raeburn 10129: } else {
1.1136 raeburn 10130: return ([],'missing domain');
1.275 stredwic 10131: }
10132: }
10133:
10134: # --------------------------------------------- GetFileTimestamp
10135: # This function utilizes dirlist and returns the date stamp for
10136: # when it was last modified. It will also return an error of -1
10137: # if an error occurs
10138:
10139: sub GetFileTimestamp {
1.955 raeburn 10140: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10141: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10142: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10143: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10144: undef,$getuserdir);
10145: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10146: return -1;
10147: }
10148: if (ref($fileref) eq 'ARRAY') {
10149: my @stats = split('&',$fileref->[0]);
1.375 matthew 10150: # @stats contains first the filename, then the stat output
10151: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10152: } else {
10153: return -1;
1.253 stredwic 10154: }
1.26 www 10155: }
10156:
1.712 albertel 10157: sub stat_file {
10158: my ($uri) = @_;
1.787 albertel 10159: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10160:
1.955 raeburn 10161: my ($udom,$uname,$file);
1.712 albertel 10162: if ($uri =~ m-^/(uploaded|editupload)/-) {
10163: ($udom,$uname,$file) =
1.811 albertel 10164: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10165: $file = 'userfiles/'.$file;
10166: }
10167: if ($uri =~ m-^/res/-) {
10168: ($udom,$uname) =
1.807 albertel 10169: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10170: $file = $uri;
10171: }
10172:
10173: if (!$udom || !$uname || !$file) {
10174: # unable to handle the uri
10175: return ();
10176: }
1.956 raeburn 10177: my $getpropath;
10178: if ($file =~ /^userfiles\//) {
10179: $getpropath = 1;
10180: }
1.1136 raeburn 10181: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10182: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10183: return ();
10184: } else {
10185: if (ref($listref) eq 'ARRAY') {
10186: my @stats = split('&',$listref->[0]);
10187: shift(@stats); #filename is first
10188: return @stats;
10189: }
1.712 albertel 10190: }
10191: return ();
10192: }
10193:
1.26 www 10194: # -------------------------------------------------------- Value of a Condition
10195:
1.713 albertel 10196: # gets the value of a specific preevaluated condition
10197: # stored in the string $env{user.state.<cid>}
10198: # or looks up a condition reference in the bighash and if if hasn't
10199: # already been evaluated recurses into docondval to get the value of
10200: # the condition, then memoizing it to
10201: # $env{user.state.<cid>.<condition>}
1.40 www 10202: sub directcondval {
10203: my $number=shift;
1.620 albertel 10204: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10205: &Apache::lonuserstate::evalstate();
10206: }
1.713 albertel 10207: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10208: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10209: } elsif ($number =~ /^_/) {
10210: my $sub_condition;
10211: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10212: &GDBM_READER(),0640)) {
10213: $sub_condition=$bighash{'conditions'.$number};
10214: untie(%bighash);
10215: }
10216: my $value = &docondval($sub_condition);
1.949 raeburn 10217: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10218: return $value;
10219: }
1.620 albertel 10220: if ($env{'user.state.'.$env{'request.course.id'}}) {
10221: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10222: } else {
10223: return 2;
10224: }
10225: }
10226:
1.713 albertel 10227: # get the collection of conditions for this resource
1.26 www 10228: sub condval {
10229: my $condidx=shift;
1.54 www 10230: my $allpathcond='';
1.713 albertel 10231: foreach my $cond (split(/\|/,$condidx)) {
10232: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10233: $allpathcond.=
10234: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10235: }
1.191 harris41 10236: }
1.54 www 10237: $allpathcond=~s/\|$//;
1.713 albertel 10238: return &docondval($allpathcond);
10239: }
10240:
10241: #evaluates an expression of conditions
10242: sub docondval {
10243: my ($allpathcond) = @_;
10244: my $result=0;
10245: if ($env{'request.course.id'}
10246: && defined($allpathcond)) {
10247: my $operand='|';
10248: my @stack;
10249: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10250: if ($chunk eq '(') {
10251: push @stack,($operand,$result);
10252: } elsif ($chunk eq ')') {
10253: my $before=pop @stack;
10254: if (pop @stack eq '&') {
10255: $result=$result>$before?$before:$result;
10256: } else {
10257: $result=$result>$before?$result:$before;
10258: }
10259: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10260: $operand=$chunk;
10261: } else {
10262: my $new=directcondval($chunk);
10263: if ($operand eq '&') {
10264: $result=$result>$new?$new:$result;
10265: } else {
10266: $result=$result>$new?$result:$new;
10267: }
10268: }
10269: }
1.26 www 10270: }
10271: return $result;
1.421 albertel 10272: }
10273:
10274: # ---------------------------------------------------- Devalidate courseresdata
10275:
10276: sub devalidatecourseresdata {
10277: my ($coursenum,$coursedomain)=@_;
10278: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10279: &devalidate_cache_new('courseres',$hashid);
1.28 www 10280: }
10281:
1.763 www 10282:
1.200 www 10283: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10284: #
10285: # Parameters:
10286: # $coursenum - Number of the course.
10287: # $coursedomain - Domain at which the course was created.
10288: # Returns:
10289: # A hash of the course parameters along (I think) with timestamps
10290: # and version info.
1.877 foxr 10291:
1.624 albertel 10292: sub get_courseresdata {
10293: my ($coursenum,$coursedomain)=@_;
1.200 www 10294: my $coursehom=&homeserver($coursenum,$coursedomain);
10295: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10296: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10297: my %dumpreply;
1.417 albertel 10298: unless (defined($cached)) {
1.624 albertel 10299: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10300: $result=\%dumpreply;
1.251 albertel 10301: my ($tmp) = keys(%dumpreply);
10302: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10303: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10304: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10305: return $tmp;
1.416 albertel 10306: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10307: $result=undef;
1.599 albertel 10308: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10309: }
10310: }
1.624 albertel 10311: return $result;
10312: }
10313:
1.633 albertel 10314: sub devalidateuserresdata {
10315: my ($uname,$udom)=@_;
10316: my $hashid="$udom:$uname";
10317: &devalidate_cache_new('userres',$hashid);
10318: }
10319:
1.624 albertel 10320: sub get_userresdata {
10321: my ($uname,$udom)=@_;
10322: #most student don\'t have any data set, check if there is some data
10323: if (&EXT_cache_status($udom,$uname)) { return undef; }
10324:
10325: my $hashid="$udom:$uname";
10326: my ($result,$cached)=&is_cached_new('userres',$hashid);
10327: if (!defined($cached)) {
10328: my %resourcedata=&dump('resourcedata',$udom,$uname);
10329: $result=\%resourcedata;
10330: &do_cache_new('userres',$hashid,$result,600);
10331: }
10332: my ($tmp)=keys(%$result);
10333: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10334: return $result;
10335: }
10336: #error 2 occurs when the .db doesn't exist
10337: if ($tmp!~/error: 2 /) {
1.1294 raeburn 10338: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10339: &logthis("<font color=\"blue\">WARNING:".
10340: " Trying to get resource data for ".
10341: $uname." at ".$udom.": ".
10342: $tmp."</font>");
10343: }
1.624 albertel 10344: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10345: #&EXT_cache_set($udom,$uname);
10346: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10347: undef($tmp); # not really an error so don't send it back
1.624 albertel 10348: }
10349: return $tmp;
10350: }
1.879 foxr 10351: #----------------------------------------------- resdata - return resource data
10352: # Purpose:
10353: # Return resource data for either users or for a course.
10354: # Parameters:
10355: # $name - Course/user name.
10356: # $domain - Name of the domain the user/course is registered on.
10357: # $type - Type of thing $name is (must be 'course' or 'user'
1.1301 raeburn 10358: # $mapp - decluttered URL of enclosing map
10359: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
10360: # $recurseup - Ref to array of map URLs, starting with map containing
10361: # $mapp up through hierarchy of nested maps to top level map.
10362: # $courseid - CourseID (first part of param identifier).
10363: # $modifier - Middle part of param identifier.
10364: # $what - Last part of param identifier.
1.879 foxr 10365: # @which - Array of names of resources desired.
10366: # Returns:
10367: # The value of the first reasource in @which that is found in the
10368: # resource hash.
10369: # Exceptional Conditions:
10370: # If the $type passed in is not valid (not the string 'course' or
10371: # 'user', an undefined reference is returned.
10372: # If none of the resources are found, an undef is returned
1.624 albertel 10373: sub resdata {
1.1301 raeburn 10374: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
10375: $modifier,$what,@which)=@_;
1.624 albertel 10376: my $result;
10377: if ($type eq 'course') {
10378: $result=&get_courseresdata($name,$domain);
10379: } elsif ($type eq 'user') {
10380: $result=&get_userresdata($name,$domain);
10381: }
10382: if (!ref($result)) { return $result; }
1.251 albertel 10383: foreach my $item (@which) {
1.1301 raeburn 10384: if ($item->[1] eq 'course') {
10385: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
10386: unless ($$recursed) {
1.1302 raeburn 10387: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 10388: $$recursed = 1;
10389: }
10390: foreach my $item (@${recurseup}) {
10391: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
10392: last if (defined($result->{$norecursechk}));
10393: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
10394: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
10395: }
10396: }
10397: }
10398: if (defined($result->{$item->[0]})) {
1.927 albertel 10399: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10400: }
1.250 albertel 10401: }
1.291 albertel 10402: return undef;
1.200 www 10403: }
10404:
1.1298 raeburn 10405: sub get_domain_ltitools {
10406: my ($cdom) = @_;
10407: my %ltitools;
10408: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10409: if (defined($cached)) {
10410: if (ref($result) eq 'HASH') {
10411: %ltitools = %{$result};
10412: }
10413: } else {
10414: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10415: if (ref($domconfig{'ltitools'}) eq 'HASH') {
10416: %ltitools = %{$domconfig{'ltitools'}};
10417: }
10418: my $cachetime = 24*60*60;
10419: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10420: }
10421: return %ltitools;
10422: }
10423:
1.1236 raeburn 10424: sub get_numsuppfiles {
10425: my ($cnum,$cdom,$ignorecache)=@_;
10426: my $hashid=$cnum.':'.$cdom;
10427: my ($suppcount,$cached);
10428: unless ($ignorecache) {
10429: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10430: }
10431: unless (defined($cached)) {
10432: my $chome=&homeserver($cnum,$cdom);
10433: unless ($chome eq 'no_host') {
10434: ($suppcount,my $errors) = (0,0);
10435: my $suppmap = 'supplemental.sequence';
10436: ($suppcount,$errors) =
10437: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10438: }
10439: &do_cache_new('suppcount',$hashid,$suppcount,600);
10440: }
10441: return $suppcount;
10442: }
10443:
1.379 matthew 10444: #
10445: # EXT resource caching routines
10446: #
10447:
1.1302 raeburn 10448: {
10449: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
10450: #
10451: # The course for which we cache
10452: my $cachedmapkey='';
10453: # The cached recursive maps for this course
10454: my %cachedmaps=();
10455: # When this was last done
10456: my $cachedmaptime='';
10457:
1.379 matthew 10458: sub clear_EXT_cache_status {
1.383 albertel 10459: &delenv('cache.EXT.');
1.379 matthew 10460: }
10461:
10462: sub EXT_cache_status {
10463: my ($target_domain,$target_user) = @_;
1.383 albertel 10464: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10465: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10466: # We know already the user has no data
10467: return 1;
10468: } else {
10469: return 0;
10470: }
10471: }
10472:
10473: sub EXT_cache_set {
10474: my ($target_domain,$target_user) = @_;
1.383 albertel 10475: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10476: #&appenv({$cachename => time});
1.379 matthew 10477: }
10478:
1.28 www 10479: # --------------------------------------------------------- Value of a Variable
1.58 www 10480: sub EXT {
1.715 albertel 10481:
1.1228 raeburn 10482: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10483: unless ($varname) { return ''; }
1.218 albertel 10484: #get real user name/domain, courseid and symb
10485: my $courseid;
1.359 albertel 10486: my $publicuser;
1.427 www 10487: if ($symbparm) {
10488: $symbparm=&get_symb_from_alias($symbparm);
10489: }
1.218 albertel 10490: if (!($uname && $udom)) {
1.790 albertel 10491: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10492: if (!$symbparm) { $symbparm=$cursymb; }
10493: } else {
1.620 albertel 10494: $courseid=$env{'request.course.id'};
1.218 albertel 10495: }
1.48 www 10496: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10497: my $rest;
1.320 albertel 10498: if (defined($therest[0])) {
1.48 www 10499: $rest=join('.',@therest);
10500: } else {
10501: $rest='';
10502: }
1.320 albertel 10503:
1.57 www 10504: my $qualifierrest=$qualifier;
10505: if ($rest) { $qualifierrest.='.'.$rest; }
10506: my $spacequalifierrest=$space;
10507: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10508: if ($realm eq 'user') {
1.48 www 10509: # --------------------------------------------------------------- user.resource
10510: if ($space eq 'resource') {
1.651 albertel 10511: if ( (defined($Apache::lonhomework::parsing_a_problem)
10512: || defined($Apache::lonhomework::parsing_a_task))
10513: &&
1.744 albertel 10514: ($symbparm eq &symbread()) ) {
10515: # if we are in the middle of processing the resource the
10516: # get the value we are planning on committing
10517: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10518: return $Apache::lonhomework::results{$qualifierrest};
10519: } else {
10520: return $Apache::lonhomework::history{$qualifierrest};
10521: }
1.335 albertel 10522: } else {
1.359 albertel 10523: my %restored;
1.620 albertel 10524: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10525: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10526: } else {
10527: %restored=&restore($symbparm,$courseid,$udom,$uname);
10528: }
1.335 albertel 10529: return $restored{$qualifierrest};
10530: }
1.48 www 10531: # ----------------------------------------------------------------- user.access
10532: } elsif ($space eq 'access') {
1.218 albertel 10533: # FIXME - not supporting calls for a specific user
1.48 www 10534: return &allowed($qualifier,$rest);
10535: # ------------------------------------------ user.preferences, user.environment
10536: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10537: if (($uname eq $env{'user.name'}) &&
10538: ($udom eq $env{'user.domain'})) {
10539: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10540: } else {
1.359 albertel 10541: my %returnhash;
10542: if (!$publicuser) {
10543: %returnhash=&userenvironment($udom,$uname,
10544: $qualifierrest);
10545: }
1.218 albertel 10546: return $returnhash{$qualifierrest};
10547: }
1.48 www 10548: # ----------------------------------------------------------------- user.course
10549: } elsif ($space eq 'course') {
1.218 albertel 10550: # FIXME - not supporting calls for a specific user
1.620 albertel 10551: return $env{join('.',('request.course',$qualifier))};
1.48 www 10552: # ------------------------------------------------------------------- user.role
10553: } elsif ($space eq 'role') {
1.218 albertel 10554: # FIXME - not supporting calls for a specific user
1.620 albertel 10555: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10556: if ($qualifier eq 'value') {
10557: return $role;
10558: } elsif ($qualifier eq 'extent') {
10559: return $where;
10560: }
10561: # ----------------------------------------------------------------- user.domain
10562: } elsif ($space eq 'domain') {
1.218 albertel 10563: return $udom;
1.48 www 10564: # ------------------------------------------------------------------- user.name
10565: } elsif ($space eq 'name') {
1.218 albertel 10566: return $uname;
1.48 www 10567: # ---------------------------------------------------- Any other user namespace
1.29 www 10568: } else {
1.359 albertel 10569: my %reply;
10570: if (!$publicuser) {
10571: %reply=&get($space,[$qualifierrest],$udom,$uname);
10572: }
10573: return $reply{$qualifierrest};
1.48 www 10574: }
1.236 www 10575: } elsif ($realm eq 'query') {
10576: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10577: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10578: [$spacequalifierrest]);
1.620 albertel 10579: return $env{'form.'.$spacequalifierrest};
1.236 www 10580: } elsif ($realm eq 'request') {
1.48 www 10581: # ------------------------------------------------------------- request.browser
10582: if ($space eq 'browser') {
1.1145 bisitz 10583: return $env{'browser.'.$qualifier};
1.57 www 10584: # ------------------------------------------------------------ request.filename
10585: } else {
1.620 albertel 10586: return $env{'request.'.$spacequalifierrest};
1.29 www 10587: }
1.28 www 10588: } elsif ($realm eq 'course') {
1.48 www 10589: # ---------------------------------------------------------- course.description
1.620 albertel 10590: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10591: } elsif ($realm eq 'resource') {
1.165 www 10592:
1.620 albertel 10593: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10594: if (!$symbparm) { $symbparm=&symbread(); }
10595: }
1.693 albertel 10596:
1.1232 raeburn 10597: if ($qualifier eq '') {
10598: if ($space eq 'title') {
10599: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10600: return &gettitle($symbparm);
10601: }
1.693 albertel 10602:
1.1232 raeburn 10603: if ($space eq 'map') {
10604: my ($map) = &decode_symb($symbparm);
10605: return &symbread($map);
10606: }
10607: if ($space eq 'maptitle') {
10608: my ($map) = &decode_symb($symbparm);
10609: return &gettitle($map);
10610: }
10611: if ($space eq 'filename') {
10612: if ($symbparm) {
10613: return &clutter((&decode_symb($symbparm))[2]);
10614: }
10615: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10616: }
1.1232 raeburn 10617:
1.1233 raeburn 10618: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10619: if ($space eq 'visibleparts') {
10620: my $navmap = Apache::lonnavmaps::navmap->new();
10621: my $item;
10622: if (ref($navmap)) {
10623: my $res = $navmap->getBySymb($symbparm);
10624: my $parts = $res->parts();
10625: if (ref($parts) eq 'ARRAY') {
10626: $item = join(',',@{$parts});
10627: }
10628: undef($navmap);
1.1232 raeburn 10629: }
1.1233 raeburn 10630: return $item;
1.1232 raeburn 10631: }
10632: }
10633: }
1.693 albertel 10634:
1.1301 raeburn 10635: my ($section, $group, @groups, @recurseup, $recursed);
10636: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 10637: if (($courseid eq '') && ($cid)) {
10638: $courseid = $cid;
10639: }
10640: if (($symbparm && $courseid) &&
10641: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10642:
1.218 albertel 10643: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10644:
1.60 www 10645: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10646: my $symbp=$symbparm;
1.1301 raeburn 10647: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10648: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 10649: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 10650: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 10651: if (($env{'user.name'} eq $uname) &&
10652: ($env{'user.domain'} eq $udom)) {
10653: $section=$env{'request.course.sec'};
1.733 raeburn 10654: @groups = split(/:/,$env{'request.course.groups'});
10655: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10656: } else {
1.539 albertel 10657: if (! defined($usection)) {
1.551 albertel 10658: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10659: } else {
10660: $section = $usection;
10661: }
1.733 raeburn 10662: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10663: }
10664:
10665: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10666: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 10667: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 10668: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10669:
1.593 albertel 10670: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10671: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 10672: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 10673: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10674:
1.60 www 10675: # ----------------------------------------------------------- first, check user
1.624 albertel 10676:
1.1301 raeburn 10677: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
10678: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 10679: ([$courselevelr,'resource'],
10680: [$courselevelm,'map' ],
1.1301 raeburn 10681: [$courseleveli,'map' ],
1.927 albertel 10682: [$courselevel, 'course' ]));
1.931 albertel 10683: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10684:
1.594 albertel 10685: # ------------------------------------------------ second, check some of course
1.684 raeburn 10686: my $coursereply;
1.691 raeburn 10687: if (@groups > 0) {
10688: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 10689: $recurseparm,$mapparm,$spacequalifierrest,
10690: $mapp,\$recursed,\@recurseup);
10691: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10692: }
1.96 www 10693:
1.684 raeburn 10694: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10695: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10696: 'course',$mapp,\$recursed,\@recurseup,
10697: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 10698: ([$seclevelr, 'resource'],
10699: [$seclevelm, 'map' ],
1.1301 raeburn 10700: [$secleveli, 'map' ],
1.927 albertel 10701: [$seclevel, 'course' ],
10702: [$courselevelr,'resource']));
10703: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10704:
1.60 www 10705: # ------------------------------------------------------ third, check map parms
1.218 albertel 10706: my %parmhash=();
10707: my $thisparm='';
10708: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10709: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10710: &GDBM_READER(),0640)) {
1.218 albertel 10711: $thisparm=$parmhash{$symbparm};
10712: untie(%parmhash);
10713: }
1.927 albertel 10714: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10715: }
1.594 albertel 10716: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 10717:
10718: my $what = $spacequalifierrest;
10719: $what=~s/\./\_/;
1.282 albertel 10720: my $filename;
10721: if (!$symbparm) { $symbparm=&symbread(); }
10722: if ($symbparm) {
1.409 www 10723: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10724: } else {
1.620 albertel 10725: $filename=$env{'request.filename'};
1.282 albertel 10726: }
1.1301 raeburn 10727: my $metadata=&metadata($filename,$what);
1.927 albertel 10728: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 10729: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 10730: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10731:
1.1301 raeburn 10732: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 10733: if ($symbparm && defined($courseid) &&
1.620 albertel 10734: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10735: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10736: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10737: 'course',$mapp,\$recursed,\@recurseup,
10738: $courseid,'.',$spacequalifierrest,
1.927 albertel 10739: ([$courselevelm,'map' ],
1.1301 raeburn 10740: [$courseleveli,'map' ],
1.927 albertel 10741: [$courselevel, 'course']));
10742: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10743: }
1.145 www 10744: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10745: unless ($space eq '0') {
1.336 albertel 10746: my @parts=split(/_/,$space);
10747: my $id=pop(@parts);
10748: my $part=join('_',@parts);
10749: if ($part eq '') { $part='0'; }
1.927 albertel 10750: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10751: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10752: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10753: }
1.395 albertel 10754: if ($recurse) { return undef; }
10755: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10756: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10757: # ---------------------------------------------------- Any other user namespace
10758: } elsif ($realm eq 'environment') {
10759: # ----------------------------------------------------------------- environment
1.620 albertel 10760: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10761: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10762: } else {
1.770 albertel 10763: if ($uname eq 'anonymous' && $udom eq '') {
10764: return '';
10765: }
1.219 albertel 10766: my %returnhash=&userenvironment($udom,$uname,
10767: $spacequalifierrest);
10768: return $returnhash{$spacequalifierrest};
10769: }
1.28 www 10770: } elsif ($realm eq 'system') {
1.48 www 10771: # ----------------------------------------------------------------- system.time
10772: if ($space eq 'time') {
10773: return time;
10774: }
1.696 albertel 10775: } elsif ($realm eq 'server') {
10776: # ----------------------------------------------------------------- system.time
10777: if ($space eq 'name') {
10778: return $ENV{'SERVER_NAME'};
10779: }
1.28 www 10780: }
1.48 www 10781: return '';
1.61 www 10782: }
10783:
1.927 albertel 10784: sub get_reply {
10785: my ($reply_value) = @_;
1.940 raeburn 10786: if (ref($reply_value) eq 'ARRAY') {
10787: if (wantarray) {
10788: return @$reply_value;
10789: }
10790: return $reply_value->[0];
10791: } else {
10792: return $reply_value;
1.927 albertel 10793: }
10794: }
10795:
1.691 raeburn 10796: sub check_group_parms {
1.1301 raeburn 10797: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
10798: $recursed,$recurseupref) = @_;
10799: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
10800: [$what,'course']);
10801: my $coursereply;
1.691 raeburn 10802: foreach my $group (@{$groups}) {
1.1301 raeburn 10803: my @groupitems = ();
1.691 raeburn 10804: foreach my $level (@levels) {
1.927 albertel 10805: my $item = $courseid.'.['.$group.'].'.$level->[0];
10806: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10807: }
1.1301 raeburn 10808: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10809: $env{'course.'.$courseid.'.domain'},
10810: 'course',$mapp,$recursed,$recurseupref,
10811: $courseid,'.['.$group.'].',$what,
10812: @groupitems);
10813: last if (defined($coursereply));
1.691 raeburn 10814: }
10815: return $coursereply;
10816: }
10817:
1.1301 raeburn 10818: sub get_map_hierarchy {
1.1302 raeburn 10819: my ($mapname,$courseid) = @_;
10820: my @recurseup = ();
1.1301 raeburn 10821: if ($mapname) {
1.1302 raeburn 10822: if (($cachedmapkey eq $courseid) &&
10823: (abs($cachedmaptime-time)<5)) {
10824: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
10825: return @{$cachedmaps{$mapname}};
10826: }
10827: }
1.1301 raeburn 10828: my $navmap = Apache::lonnavmaps::navmap->new();
10829: if (ref($navmap)) {
10830: @recurseup = $navmap->recurseup_maps($mapname);
10831: undef($navmap);
1.1302 raeburn 10832: $cachedmaps{$mapname} = \@recurseup;
10833: $cachedmaptime=time;
10834: $cachedmapkey=$courseid;
1.1301 raeburn 10835: }
10836: }
10837: return @recurseup;
10838: }
10839:
1.1302 raeburn 10840: }
10841:
1.691 raeburn 10842: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10843: my ($courseid,@groups) = @_;
10844: @groups = sort(@groups);
1.691 raeburn 10845: return @groups;
10846: }
10847:
1.395 albertel 10848: sub packages_tab_default {
10849: my ($uri,$varname)=@_;
10850: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10851:
10852: my (@extension,@specifics,$do_default);
10853: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10854: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10855: if ($pack_type eq 'default') {
10856: $do_default=1;
10857: } elsif ($pack_type eq 'extension') {
10858: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10859: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10860: # only look at packages defaults for packages that this id is
1.738 albertel 10861: push(@specifics,[$package,$pack_type,$pack_part]);
10862: }
10863: }
10864: # first look for a package that matches the requested part id
10865: foreach my $package (@specifics) {
10866: my (undef,$pack_type,$pack_part)=@{$package};
10867: next if ($pack_part ne $part);
10868: if (defined($packagetab{"$pack_type&$name&default"})) {
10869: return $packagetab{"$pack_type&$name&default"};
10870: }
10871: }
10872: # look for any possible matching non extension_ package
10873: foreach my $package (@specifics) {
10874: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10875: if (defined($packagetab{"$pack_type&$name&default"})) {
10876: return $packagetab{"$pack_type&$name&default"};
10877: }
1.585 albertel 10878: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10879: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10880: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10881: }
10882: }
1.738 albertel 10883: # look for any posible extension_ match
10884: foreach my $package (@extension) {
10885: my ($package,$pack_type)=@{$package};
10886: if (defined($packagetab{"$pack_type&$name&default"})) {
10887: return $packagetab{"$pack_type&$name&default"};
10888: }
10889: if (defined($packagetab{$package."&$name&default"})) {
10890: return $packagetab{$package."&$name&default"};
10891: }
10892: }
10893: # look for a global default setting
10894: if ($do_default && defined($packagetab{"default&$name&default"})) {
10895: return $packagetab{"default&$name&default"};
10896: }
1.395 albertel 10897: return undef;
10898: }
10899:
1.334 albertel 10900: sub add_prefix_and_part {
10901: my ($prefix,$part)=@_;
10902: my $keyroot;
10903: if (defined($prefix) && $prefix !~ /^__/) {
10904: # prefix that has a part already
10905: $keyroot=$prefix;
10906: } elsif (defined($prefix)) {
10907: # prefix that is missing a part
10908: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10909: } else {
10910: # no prefix at all
10911: if (defined($part)) { $keyroot='_'.$part; }
10912: }
10913: return $keyroot;
10914: }
10915:
1.71 www 10916: # ---------------------------------------------------------------- Get metadata
10917:
1.599 albertel 10918: my %metaentry;
1.1070 www 10919: my %importedpartids;
1.71 www 10920: sub metadata {
1.176 www 10921: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10922: $uri=&declutter($uri);
1.288 albertel 10923: # if it is a non metadata possible uri return quickly
1.529 albertel 10924: if (($uri eq '') ||
10925: (($uri =~ m|^/*adm/|) &&
1.1298 raeburn 10926: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108 raeburn 10927: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10928: return undef;
10929: }
1.1261 raeburn 10930: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10931: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10932: return undef;
1.288 albertel 10933: }
1.73 www 10934: my $filename=$uri;
10935: $uri=~s/\.meta$//;
1.172 www 10936: #
10937: # Is the metadata already cached?
1.177 www 10938: # Look at timestamp of caching
1.172 www 10939: # Everything is cached by the main uri, libraries are never directly cached
10940: #
1.428 albertel 10941: if (!defined($liburi)) {
1.599 albertel 10942: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10943: if (defined($cached)) { return $result->{':'.$what}; }
10944: }
10945: {
1.1069 www 10946: # Imported parts would go here
1.1070 www 10947: my %importedids=();
10948: my @origfileimportpartids=();
1.1069 www 10949: my $importedparts=0;
1.172 www 10950: #
10951: # Is this a recursive call for a library?
10952: #
1.599 albertel 10953: # if (! exists($metacache{$uri})) {
10954: # $metacache{$uri}={};
10955: # }
1.924 albertel 10956: my $cachetime = 60*60;
1.171 www 10957: if ($liburi) {
10958: $liburi=&declutter($liburi);
10959: $filename=$liburi;
1.401 bowersj2 10960: } else {
1.599 albertel 10961: &devalidate_cache_new('meta',$uri);
10962: undef(%metaentry);
1.401 bowersj2 10963: }
1.140 www 10964: my %metathesekeys=();
1.73 www 10965: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10966: my $metastring;
1.1140 www 10967: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10968: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10969: $metastring =
1.929 albertel 10970: &Apache::lonnet::ssi_body($which,
1.924 albertel 10971: ('grade_target' => 'meta'));
10972: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10973: } elsif (($uri !~ m -^(editupload)/-) &&
10974: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10975: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10976: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10977: $metastring=&getfile($file);
1.489 albertel 10978: }
1.208 albertel 10979: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10980: my $token;
1.140 www 10981: undef %metathesekeys;
1.71 www 10982: while ($token=$parser->get_token) {
1.339 albertel 10983: if ($token->[0] eq 'S') {
10984: if (defined($token->[2]->{'package'})) {
1.172 www 10985: #
10986: # This is a package - get package info
10987: #
1.339 albertel 10988: my $package=$token->[2]->{'package'};
10989: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10990: if (defined($token->[2]->{'id'})) {
10991: $keyroot.='_'.$token->[2]->{'id'};
10992: }
1.599 albertel 10993: if ($metaentry{':packages'}) {
10994: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10995: } else {
1.599 albertel 10996: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10997: }
1.736 albertel 10998: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10999: my $part=$keyroot;
11000: $part=~s/^\_//;
1.736 albertel 11001: if ($pack_entry=~/^\Q$package\E\&/ ||
11002: $pack_entry=~/^\Q$package\E_0\&/) {
11003: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11004: # ignore package.tab specified default values
11005: # here &package_tab_default() will fetch those
11006: if ($subp eq 'default') { next; }
1.736 albertel 11007: my $value=$packagetab{$pack_entry};
1.432 albertel 11008: my $unikey;
11009: if ($pack =~ /_0$/) {
11010: $unikey='parameter_0_'.$name;
11011: $part=0;
11012: } else {
11013: $unikey='parameter'.$keyroot.'_'.$name;
11014: }
1.339 albertel 11015: if ($subp eq 'display') {
11016: $value.=' [Part: '.$part.']';
11017: }
1.599 albertel 11018: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11019: $metathesekeys{$unikey}=1;
1.599 albertel 11020: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11021: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11022: }
1.599 albertel 11023: if (defined($metaentry{':'.$unikey.'.default'})) {
11024: $metaentry{':'.$unikey}=
11025: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11026: }
1.339 albertel 11027: }
11028: }
11029: } else {
1.172 www 11030: #
11031: # This is not a package - some other kind of start tag
1.339 albertel 11032: #
11033: my $entry=$token->[1];
1.1068 www 11034: my $unikey='';
1.175 www 11035:
1.339 albertel 11036: if ($entry eq 'import') {
1.175 www 11037: #
11038: # Importing a library here
1.339 albertel 11039: #
1.1067 www 11040: my $location=$parser->get_text('/import');
11041: my $dir=$filename;
11042: $dir=~s|[^/]*$||;
11043: $location=&filelocation($dir,$location);
1.1069 www 11044:
1.1068 www 11045: my $importmode=$token->[2]->{'importmode'};
11046: if ($importmode eq 'problem') {
1.1069 www 11047: # Import as problem/response
1.1068 www 11048: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11049: } elsif ($importmode eq 'part') {
11050: # Import as part(s)
1.1069 www 11051: $importedparts=1;
11052: # We need to get the original file and the imported file to get the part order correct
11053: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11054: # Load and inspect original file
1.1070 www 11055: if ($#origfileimportpartids<0) {
11056: undef(%importedpartids);
11057: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11058: my $origfile=&getfile($origfilelocation);
11059: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11060: }
11061:
1.1069 www 11062: # Load and inspect imported file
11063: my $impfile=&getfile($location);
11064: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11065: if ($#impfilepartids>=0) {
11066: # This problem had parts
1.1070 www 11067: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11068: } else {
11069: # Importing by turning a single problem into a problem part
11070: # It gets the import-tags ID as part-ID
11071: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11072: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11073: }
1.1068 www 11074: } else {
11075: # Normal import
11076: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11077: if (defined($token->[2]->{'id'})) {
11078: $unikey.='_'.$token->[2]->{'id'};
11079: }
1.1067 www 11080: }
11081:
1.339 albertel 11082: if ($depthcount<20) {
1.736 albertel 11083: my $metadata =
11084: &metadata($uri,'keys', $location,$unikey,
11085: $depthcount+1);
11086: foreach my $meta (split(',',$metadata)) {
11087: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11088: $metathesekeys{$meta}=1;
1.339 albertel 11089: }
1.1068 www 11090:
11091: }
1.1067 www 11092: } else {
11093: #
11094: # Not importing, some other kind of non-package, non-library start tag
11095: #
11096: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11097: if (defined($token->[2]->{'id'})) {
11098: $unikey.='_'.$token->[2]->{'id'};
11099: }
1.339 albertel 11100: if (defined($token->[2]->{'name'})) {
11101: $unikey.='_'.$token->[2]->{'name'};
11102: }
11103: $metathesekeys{$unikey}=1;
1.736 albertel 11104: foreach my $param (@{$token->[3]}) {
11105: $metaentry{':'.$unikey.'.'.$param} =
11106: $token->[2]->{$param};
1.339 albertel 11107: }
11108: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11109: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11110: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11111: # only ws inside the tag, and not in default, so use default
11112: # as value
1.599 albertel 11113: $metaentry{':'.$unikey}=$default;
1.908 albertel 11114: } elsif ( $internaltext =~ /\S/ ) {
11115: # something interesting inside the tag
11116: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11117: } else {
1.908 albertel 11118: # no interesting values, don't set a default
1.339 albertel 11119: }
1.172 www 11120: # end of not-a-package not-a-library import
1.339 albertel 11121: }
1.172 www 11122: # end of not-a-package start tag
1.339 albertel 11123: }
1.172 www 11124: # the next is the end of "start tag"
1.339 albertel 11125: }
11126: }
1.483 albertel 11127: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11128: $extension = lc($extension);
11129: if ($extension eq 'htm') { $extension='html'; }
11130:
1.737 albertel 11131: foreach my $key (keys(%packagetab)) {
1.483 albertel 11132: #no specific packages #how's our extension
11133: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11134: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11135: \%metathesekeys);
11136: }
1.883 albertel 11137:
11138: if (!exists($metaentry{':packages'})
11139: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11140: foreach my $key (keys(%packagetab)) {
1.483 albertel 11141: #no specific packages well let's get default then
11142: if ($key!~/^default&/) { next; }
1.488 albertel 11143: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11144: \%metathesekeys);
11145: }
11146: }
1.338 www 11147: # are there custom rights to evaluate
1.599 albertel 11148: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11149:
1.338 www 11150: #
11151: # Importing a rights file here
1.339 albertel 11152: #
11153: unless ($depthcount) {
1.599 albertel 11154: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11155: my $dir=$filename;
11156: $dir=~s|[^/]*$||;
11157: $location=&filelocation($dir,$location);
1.736 albertel 11158: my $rights_metadata =
11159: &metadata($uri,'keys',$location,'_rights',
11160: $depthcount+1);
11161: foreach my $rights (split(',',$rights_metadata)) {
11162: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11163: $metathesekeys{$rights}=1;
1.339 albertel 11164: }
11165: }
11166: }
1.737 albertel 11167: # uniqifiy package listing
11168: my %seen;
11169: my @uniq_packages =
11170: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11171: $metaentry{':packages'} = join(',',@uniq_packages);
11172:
1.1070 www 11173: if ($importedparts) {
11174: # We had imported parts and need to rebuild partorder
11175: $metaentry{':partorder'}='';
11176: $metathesekeys{'partorder'}=1;
11177: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11178: if ($origfileimportpartids[$index] eq 'part') {
11179: # original part, part of the problem
11180: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11181: } else {
11182: # we have imported parts at this position
11183: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11184: }
11185: }
11186: $metaentry{':partorder'}=~s/^\,//;
11187: }
11188:
1.737 albertel 11189: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11190: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11191: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11192: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11193: # this is the end of "was not already recently cached
1.71 www 11194: }
1.599 albertel 11195: return $metaentry{':'.$what};
1.261 albertel 11196: }
11197:
1.488 albertel 11198: sub metadata_create_package_def {
1.483 albertel 11199: my ($uri,$key,$package,$metathesekeys)=@_;
11200: my ($pack,$name,$subp)=split(/\&/,$key);
11201: if ($subp eq 'default') { next; }
11202:
1.599 albertel 11203: if (defined($metaentry{':packages'})) {
11204: $metaentry{':packages'}.=','.$package;
1.483 albertel 11205: } else {
1.599 albertel 11206: $metaentry{':packages'}=$package;
1.483 albertel 11207: }
11208: my $value=$packagetab{$key};
11209: my $unikey;
11210: $unikey='parameter_0_'.$name;
1.599 albertel 11211: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11212: $$metathesekeys{$unikey}=1;
1.599 albertel 11213: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11214: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11215: }
1.599 albertel 11216: if (defined($metaentry{':'.$unikey.'.default'})) {
11217: $metaentry{':'.$unikey}=
11218: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11219: }
11220: }
11221:
1.261 albertel 11222: sub metadata_generate_part0 {
11223: my ($metadata,$metacache,$uri) = @_;
11224: my %allnames;
1.737 albertel 11225: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11226: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11227: my $part=$$metacache{':'.$metakey.'.part'};
11228: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11229: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11230: $allnames{$name}=$part;
11231: }
11232: }
11233: }
11234: foreach my $name (keys(%allnames)) {
11235: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11236: my $key=":parameter_0_$name";
1.261 albertel 11237: $$metacache{"$key.part"}='0';
11238: $$metacache{"$key.name"}=$name;
1.428 albertel 11239: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11240: $allnames{$name}.'_'.$name.
11241: '.type'};
1.428 albertel 11242: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11243: '.display'};
1.644 www 11244: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11245: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11246: $$metacache{"$key.display"}=$olddis;
11247: }
1.71 www 11248: }
11249:
1.764 albertel 11250: # ------------------------------------------------------ Devalidate title cache
11251:
11252: sub devalidate_title_cache {
11253: my ($url)=@_;
11254: if (!$env{'request.course.id'}) { return; }
11255: my $symb=&symbread($url);
11256: if (!$symb) { return; }
11257: my $key=$env{'request.course.id'}."\0".$symb;
11258: &devalidate_cache_new('title',$key);
11259: }
11260:
1.1014 droeschl 11261: # ------------------------------------------------- Get the title of a course
11262:
11263: sub current_course_title {
11264: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11265: }
1.301 www 11266: # ------------------------------------------------- Get the title of a resource
11267:
11268: sub gettitle {
11269: my $urlsymb=shift;
11270: my $symb=&symbread($urlsymb);
1.534 albertel 11271: if ($symb) {
1.620 albertel 11272: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11273: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11274: if (defined($cached)) {
11275: return $result;
11276: }
1.534 albertel 11277: my ($map,$resid,$url)=&decode_symb($symb);
11278: my $title='';
1.907 albertel 11279: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11280: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11281: } else {
11282: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11283: &GDBM_READER(),0640)) {
11284: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11285: $title=$bighash{'title_'.$mapid.'.'.$resid};
11286: untie(%bighash);
11287: }
1.534 albertel 11288: }
11289: $title=~s/\&colon\;/\:/gs;
11290: if ($title) {
1.1159 www 11291: # Remember both $symb and $title for dynamic metadata
11292: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11293: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11294: # Cache this title and then return it
1.599 albertel 11295: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11296: }
11297: $urlsymb=$url;
11298: }
11299: my $title=&metadata($urlsymb,'title');
11300: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11301: return $title;
1.301 www 11302: }
1.613 albertel 11303:
1.614 albertel 11304: sub get_slot {
11305: my ($which,$cnum,$cdom)=@_;
11306: if (!$cnum || !$cdom) {
1.790 albertel 11307: (undef,my $courseid)=&whichuser();
1.620 albertel 11308: $cdom=$env{'course.'.$courseid.'.domain'};
11309: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11310: }
1.703 albertel 11311: my $key=join("\0",'slots',$cdom,$cnum,$which);
11312: my %slotinfo;
11313: if (exists($remembered{$key})) {
11314: $slotinfo{$which} = $remembered{$key};
11315: } else {
11316: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11317: &Apache::lonhomework::showhash(%slotinfo);
11318: my ($tmp)=keys(%slotinfo);
11319: if ($tmp=~/^error:/) { return (); }
11320: $remembered{$key} = $slotinfo{$which};
11321: }
1.616 albertel 11322: if (ref($slotinfo{$which}) eq 'HASH') {
11323: return %{$slotinfo{$which}};
11324: }
11325: return $slotinfo{$which};
1.614 albertel 11326: }
1.1150 raeburn 11327:
11328: sub get_reservable_slots {
11329: my ($cnum,$cdom,$uname,$udom) = @_;
11330: my $now = time;
11331: my $reservable_info;
11332: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11333: if (exists($remembered{$key})) {
11334: $reservable_info = $remembered{$key};
11335: } else {
11336: my %resv;
11337: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11338: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11339: $reservable_info = \%resv;
11340: $remembered{$key} = $reservable_info;
11341: }
11342: return $reservable_info;
11343: }
11344:
11345: sub get_course_slots {
11346: my ($cnum,$cdom) = @_;
11347: my $hashid=$cnum.':'.$cdom;
11348: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11349: if (defined($cached)) {
11350: if (ref($result) eq 'HASH') {
11351: return %{$result};
11352: }
11353: } else {
11354: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11355: my ($tmp) = keys(%slots);
11356: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11357: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11358: return %slots;
11359: }
11360: }
11361: return;
11362: }
11363:
11364: sub devalidate_slots_cache {
11365: my ($cnum,$cdom)=@_;
11366: my $hashid=$cnum.':'.$cdom;
11367: &devalidate_cache_new('allslots',$hashid);
11368: }
11369:
1.1181 raeburn 11370: sub get_coursechange {
11371: my ($cdom,$cnum) = @_;
11372: if ($cdom eq '' || $cnum eq '') {
11373: return unless ($env{'request.course.id'});
11374: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11375: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11376: }
11377: my $hashid=$cdom.'_'.$cnum;
11378: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11379: if ((defined($cached)) && ($change ne '')) {
11380: return $change;
11381: } else {
11382: my %crshash;
11383: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11384: if ($crshash{'internal.contentchange'} eq '') {
11385: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11386: if ($change eq '') {
11387: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11388: $change = $crshash{'internal.created'};
11389: }
11390: } else {
11391: $change = $crshash{'internal.contentchange'};
11392: }
11393: my $cachetime = 600;
11394: &do_cache_new('crschange',$hashid,$change,$cachetime);
11395: }
11396: return $change;
11397: }
11398:
11399: sub devalidate_coursechange_cache {
11400: my ($cnum,$cdom)=@_;
11401: my $hashid=$cnum.':'.$cdom;
11402: &devalidate_cache_new('crschange',$hashid);
11403: }
11404:
1.31 www 11405: # ------------------------------------------------- Update symbolic store links
11406:
11407: sub symblist {
11408: my ($mapname,%newhash)=@_;
1.438 www 11409: $mapname=&deversion(&declutter($mapname));
1.31 www 11410: my %hash;
1.620 albertel 11411: if (($env{'request.course.fn'}) && (%newhash)) {
11412: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11413: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11414: foreach my $url (keys(%newhash)) {
1.711 albertel 11415: next if ($url eq 'last_known'
11416: && $env{'form.no_update_last_known'});
11417: $hash{declutter($url)}=&encode_symb($mapname,
11418: $newhash{$url}->[1],
11419: $newhash{$url}->[0]);
1.191 harris41 11420: }
1.31 www 11421: if (untie(%hash)) {
11422: return 'ok';
11423: }
11424: }
11425: }
11426: return 'error';
1.212 www 11427: }
11428:
11429: # --------------------------------------------------------------- Verify a symb
11430:
11431: sub symbverify {
1.1190 raeburn 11432: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11433: my $thisfn=$thisurl;
1.439 www 11434: $thisfn=&declutter($thisfn);
1.215 www 11435: # direct jump to resource in page or to a sequence - will construct own symbs
11436: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11437: # check URL part
1.409 www 11438: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11439:
1.431 www 11440: unless ($url eq $thisfn) { return 0; }
1.213 www 11441:
1.216 www 11442: $symb=&symbclean($symb);
1.510 www 11443: $thisurl=&deversion($thisurl);
1.439 www 11444: $thisfn=&deversion($thisfn);
1.213 www 11445:
11446: my %bighash;
11447: my $okay=0;
1.431 www 11448:
1.620 albertel 11449: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11450: &GDBM_READER(),0640)) {
1.1204 raeburn 11451: my $noclutter;
1.1032 raeburn 11452: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11453: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11454: if ($map =~ m{^uploaded/.+\.page$}) {
11455: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11456: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11457: $noclutter = 1;
11458: }
11459: }
11460: my $ids;
11461: if ($noclutter) {
11462: $ids=$bighash{'ids_'.$thisurl};
11463: } else {
11464: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11465: }
1.1102 raeburn 11466: unless ($ids) {
11467: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11468: $ids=$bighash{$idkey};
1.216 www 11469: }
11470: if ($ids) {
11471: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11472: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11473: $symb =~ s/\?.+$//;
1.1202 raeburn 11474: }
1.800 albertel 11475: foreach my $id (split(/\,/,$ids)) {
11476: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11477: if (
11478: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11479: eq $symb) {
11480: if (ref($encstate)) {
11481: $$encstate = $bighash{'encrypted_'.$id};
11482: }
1.620 albertel 11483: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11484: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11485: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11486: $okay=1;
1.1202 raeburn 11487: last;
1.582 albertel 11488: }
11489: }
1.216 www 11490: }
11491: }
1.213 www 11492: untie(%bighash);
11493: }
11494: return $okay;
1.31 www 11495: }
11496:
1.210 www 11497: # --------------------------------------------------------------- Clean-up symb
11498:
11499: sub symbclean {
11500: my $symb=shift;
1.568 albertel 11501: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11502: # remove version from map
11503: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11504:
1.210 www 11505: # remove version from URL
11506: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11507:
1.507 www 11508: # remove wrapper
11509:
1.510 www 11510: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11511: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11512: return $symb;
1.409 www 11513: }
11514:
11515: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11516:
11517: sub encode_symb {
11518: my ($map,$resid,$url)=@_;
11519: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11520: }
1.409 www 11521:
11522: sub decode_symb {
1.568 albertel 11523: my $symb=shift;
11524: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11525: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11526: return (&fixversion($map),$resid,&fixversion($url));
11527: }
11528:
11529: sub fixversion {
11530: my $fn=shift;
1.609 banghart 11531: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11532: my %bighash;
11533: my $uri=&clutter($fn);
1.620 albertel 11534: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11535: # is this cached?
1.599 albertel 11536: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11537: if (defined($cached)) { return $result; }
11538: # unfortunately not cached, or expired
1.620 albertel 11539: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11540: &GDBM_READER(),0640)) {
11541: if ($bighash{'version_'.$uri}) {
11542: my $version=$bighash{'version_'.$uri};
1.444 www 11543: unless (($version eq 'mostrecent') ||
11544: ($version==&getversion($uri))) {
1.440 www 11545: $uri=~s/\.(\w+)$/\.$version\.$1/;
11546: }
11547: }
11548: untie %bighash;
1.413 www 11549: }
1.599 albertel 11550: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11551: }
11552:
11553: sub deversion {
11554: my $url=shift;
11555: $url=~s/\.\d+\.(\w+)$/\.$1/;
11556: return $url;
1.210 www 11557: }
11558:
1.31 www 11559: # ------------------------------------------------------ Return symb list entry
11560:
11561: sub symbread {
1.1282 raeburn 11562: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 11563: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 11564: if (defined($env{$cache_str})) {
11565: if ($ignorecachednull) {
11566: return $env{$cache_str} unless ($env{$cache_str} eq '');
11567: } else {
11568: return $env{$cache_str};
11569: }
11570: }
1.242 www 11571: # no filename provided? try from environment
1.1265 raeburn 11572: unless ($thisfn) {
1.620 albertel 11573: if ($env{'request.symb'}) {
11574: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11575: }
1.620 albertel 11576: $thisfn=$env{'request.filename'};
1.44 www 11577: }
1.569 albertel 11578: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11579: # is that filename actually a symb? Verify, clean, and return
11580: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11581: if (&symbverify($thisfn,$1)) {
1.620 albertel 11582: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11583: }
1.242 www 11584: }
1.44 www 11585: $thisfn=declutter($thisfn);
1.31 www 11586: my %hash;
1.37 www 11587: my %bighash;
11588: my $syval='';
1.620 albertel 11589: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11590: my $targetfn = $thisfn;
1.609 banghart 11591: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11592: $targetfn = 'adm/wrapper/'.$thisfn;
11593: }
1.687 albertel 11594: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11595: $targetfn=$1;
11596: }
1.620 albertel 11597: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11598: &GDBM_READER(),0640)) {
1.481 raeburn 11599: $syval=$hash{$targetfn};
1.37 www 11600: untie(%hash);
11601: }
11602: # ---------------------------------------------------------- There was an entry
11603: if ($syval) {
1.601 albertel 11604: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11605: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11606: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11607: #return $env{$cache_str}='';
1.601 albertel 11608: #}
11609: #$syval.=$1;
11610: #}
1.37 www 11611: } else {
11612: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11613: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11614: &GDBM_READER(),0640)) {
1.37 www 11615: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11616: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11617: unless ($ids) {
11618: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11619: }
11620: unless ($ids) {
11621: # alias?
11622: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11623: }
1.37 www 11624: if ($ids) {
11625: # ------------------------------------------------------------------- Has ID(s)
11626: my @possibilities=split(/\,/,$ids);
1.39 www 11627: if ($#possibilities==0) {
11628: # ----------------------------------------------- There is only one possibility
1.37 www 11629: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11630: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11631: $resid,$thisfn);
1.1282 raeburn 11632: if (ref($possibles) eq 'HASH') {
11633: $possibles->{$syval} = 1;
11634: }
11635: if ($checkforblock) {
11636: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11637: if (@blockers) {
11638: $syval = '';
11639: return;
11640: }
11641: }
11642: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11643: # ------------------------------------------ There is more than one possibility
11644: my $realpossible=0;
1.800 albertel 11645: foreach my $id (@possibilities) {
11646: my $file=$bighash{'src_'.$id};
1.1282 raeburn 11647: my $canaccess;
11648: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11649: $canaccess = 1;
11650: } else {
11651: $canaccess = &allowed('bre',$file);
11652: }
11653: if ($canaccess) {
11654: my ($mapid,$resid)=split(/\./,$id);
11655: if ($bighash{'map_type_'.$mapid} ne 'page') {
11656: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11657: $resid,$thisfn);
11658: if (ref($possibles) eq 'HASH') {
11659: $possibles->{$syval} = 1;
11660: }
11661: if ($checkforblock) {
11662: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11663: unless (@blockers > 0) {
11664: $syval = $poss_syval;
11665: $realpossible++;
11666: }
11667: } else {
11668: $syval = $poss_syval;
11669: $realpossible++;
11670: }
11671: }
1.39 www 11672: }
1.191 harris41 11673: }
1.39 www 11674: if ($realpossible!=1) { $syval=''; }
1.249 www 11675: } else {
11676: $syval='';
1.37 www 11677: }
11678: }
1.1282 raeburn 11679: untie(%bighash);
1.481 raeburn 11680: }
1.31 www 11681: }
1.62 www 11682: if ($syval) {
1.620 albertel 11683: return $env{$cache_str}=$syval;
1.62 www 11684: }
1.31 www 11685: }
1.949 raeburn 11686: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11687: return $env{$cache_str}='';
1.31 www 11688: }
11689:
11690: # ---------------------------------------------------------- Return random seed
11691:
1.32 www 11692: sub numval {
11693: my $txt=shift;
11694: $txt=~tr/A-J/0-9/;
11695: $txt=~tr/a-j/0-9/;
11696: $txt=~tr/K-T/0-9/;
11697: $txt=~tr/k-t/0-9/;
11698: $txt=~tr/U-Z/0-5/;
11699: $txt=~tr/u-z/0-5/;
11700: $txt=~s/\D//g;
1.564 albertel 11701: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11702: return int($txt);
1.368 albertel 11703: }
11704:
1.484 albertel 11705: sub numval2 {
11706: my $txt=shift;
11707: $txt=~tr/A-J/0-9/;
11708: $txt=~tr/a-j/0-9/;
11709: $txt=~tr/K-T/0-9/;
11710: $txt=~tr/k-t/0-9/;
11711: $txt=~tr/U-Z/0-5/;
11712: $txt=~tr/u-z/0-5/;
11713: $txt=~s/\D//g;
11714: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11715: my $total;
11716: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11717: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11718: return int($total);
11719: }
11720:
1.575 albertel 11721: sub numval3 {
11722: use integer;
11723: my $txt=shift;
11724: $txt=~tr/A-J/0-9/;
11725: $txt=~tr/a-j/0-9/;
11726: $txt=~tr/K-T/0-9/;
11727: $txt=~tr/k-t/0-9/;
11728: $txt=~tr/U-Z/0-5/;
11729: $txt=~tr/u-z/0-5/;
11730: $txt=~s/\D//g;
11731: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11732: my $total;
11733: foreach my $val (@txts) { $total+=$val; }
11734: if ($_64bit) { $total=(($total<<32)>>32); }
11735: return $total;
11736: }
11737:
1.675 albertel 11738: sub digest {
11739: my ($data)=@_;
11740: my $digest=&Digest::MD5::md5($data);
11741: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11742: my ($e,$f);
11743: {
11744: use integer;
11745: $e=($a+$b);
11746: $f=($c+$d);
11747: if ($_64bit) {
11748: $e=(($e<<32)>>32);
11749: $f=(($f<<32)>>32);
11750: }
11751: }
11752: if (wantarray) {
11753: return ($e,$f);
11754: } else {
11755: my $g;
11756: {
11757: use integer;
11758: $g=($e+$f);
11759: if ($_64bit) {
11760: $g=(($g<<32)>>32);
11761: }
11762: }
11763: return $g;
11764: }
11765: }
11766:
1.368 albertel 11767: sub latest_rnd_algorithm_id {
1.675 albertel 11768: return '64bit5';
1.366 albertel 11769: }
1.32 www 11770:
1.503 albertel 11771: sub get_rand_alg {
11772: my ($courseid)=@_;
1.790 albertel 11773: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11774: if ($courseid) {
1.620 albertel 11775: return $env{"course.$courseid.rndseed"};
1.503 albertel 11776: }
11777: return &latest_rnd_algorithm_id();
11778: }
11779:
1.562 albertel 11780: sub validCODE {
11781: my ($CODE)=@_;
11782: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11783: return 0;
11784: }
11785:
1.491 albertel 11786: sub getCODE {
1.620 albertel 11787: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11788: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11789: defined($Apache::lonhomework::parsing_a_task) ) &&
11790: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11791: return $Apache::lonhomework::history{'resource.CODE'};
11792: }
11793: return undef;
11794: }
1.1133 foxr 11795: #
11796: # Determines the random seed for a specific context:
11797: #
11798: # parameters:
11799: # symb - in course context the symb for the seed.
11800: # course_id - The course id of the form domain_coursenum.
11801: # domain - Domain for the user.
11802: # course - Course for the user.
11803: # cenv - environment of the course.
11804: #
11805: # NOTE:
11806: # All parameters are picked out of the environment if missing
11807: # or not defined.
11808: # If a symb cannot be determined the current time is used instead.
11809: #
11810: # For a given well defined symb, courside, domain, username,
11811: # and course environment, the seed is reproducible.
11812: #
1.31 www 11813: sub rndseed {
1.1133 foxr 11814: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11815: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11816: if (!defined($symb)) {
1.366 albertel 11817: unless ($symb=$wsymb) { return time; }
11818: }
1.1146 foxr 11819: if (!defined $courseid) {
11820: $courseid=$wcourseid;
11821: }
11822: if (!defined $domain) { $domain=$wdomain; }
11823: if (!defined $username) { $username=$wusername }
1.1133 foxr 11824:
11825: my $which;
11826: if (defined($cenv->{'rndseed'})) {
11827: $which = $cenv->{'rndseed'};
11828: } else {
11829: $which =&get_rand_alg($courseid);
11830: }
1.491 albertel 11831: if (defined(&getCODE())) {
1.1133 foxr 11832:
1.675 albertel 11833: if ($which eq '64bit5') {
11834: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11835: } elsif ($which eq '64bit4') {
1.575 albertel 11836: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11837: } else {
11838: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11839: }
1.675 albertel 11840: } elsif ($which eq '64bit5') {
11841: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11842: } elsif ($which eq '64bit4') {
11843: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11844: } elsif ($which eq '64bit3') {
11845: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11846: } elsif ($which eq '64bit2') {
11847: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11848: } elsif ($which eq '64bit') {
11849: return &rndseed_64bit($symb,$courseid,$domain,$username);
11850: }
11851: return &rndseed_32bit($symb,$courseid,$domain,$username);
11852: }
11853:
11854: sub rndseed_32bit {
11855: my ($symb,$courseid,$domain,$username)=@_;
11856: {
11857: use integer;
11858: my $symbchck=unpack("%32C*",$symb) << 27;
11859: my $symbseed=numval($symb) << 22;
11860: my $namechck=unpack("%32C*",$username) << 17;
11861: my $nameseed=numval($username) << 12;
11862: my $domainseed=unpack("%32C*",$domain) << 7;
11863: my $courseseed=unpack("%32C*",$courseid);
11864: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11865: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11866: #&logthis("rndseed :$num:$symb");
1.564 albertel 11867: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11868: return $num;
11869: }
11870: }
11871:
11872: sub rndseed_64bit {
11873: my ($symb,$courseid,$domain,$username)=@_;
11874: {
11875: use integer;
11876: my $symbchck=unpack("%32S*",$symb) << 21;
11877: my $symbseed=numval($symb) << 10;
11878: my $namechck=unpack("%32S*",$username);
11879:
11880: my $nameseed=numval($username) << 21;
11881: my $domainseed=unpack("%32S*",$domain) << 10;
11882: my $courseseed=unpack("%32S*",$courseid);
11883:
11884: my $num1=$symbchck+$symbseed+$namechck;
11885: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11886: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11887: #&logthis("rndseed :$num:$symb");
1.564 albertel 11888: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11889: return "$num1,$num2";
1.155 albertel 11890: }
1.366 albertel 11891: }
11892:
1.443 albertel 11893: sub rndseed_64bit2 {
11894: my ($symb,$courseid,$domain,$username)=@_;
11895: {
11896: use integer;
11897: # strings need to be an even # of cahracters long, it it is odd the
11898: # last characters gets thrown away
11899: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11900: my $symbseed=numval($symb) << 10;
11901: my $namechck=unpack("%32S*",$username.' ');
11902:
11903: my $nameseed=numval($username) << 21;
1.501 albertel 11904: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11905: my $courseseed=unpack("%32S*",$courseid.' ');
11906:
11907: my $num1=$symbchck+$symbseed+$namechck;
11908: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11909: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11910: #&logthis("rndseed :$num:$symb");
1.803 albertel 11911: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11912: return "$num1,$num2";
11913: }
11914: }
11915:
11916: sub rndseed_64bit3 {
11917: my ($symb,$courseid,$domain,$username)=@_;
11918: {
11919: use integer;
11920: # strings need to be an even # of cahracters long, it it is odd the
11921: # last characters gets thrown away
11922: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11923: my $symbseed=numval2($symb) << 10;
11924: my $namechck=unpack("%32S*",$username.' ');
11925:
11926: my $nameseed=numval2($username) << 21;
1.443 albertel 11927: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11928: my $courseseed=unpack("%32S*",$courseid.' ');
11929:
11930: my $num1=$symbchck+$symbseed+$namechck;
11931: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11932: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11933: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11934: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11935:
1.503 albertel 11936: return "$num1:$num2";
1.443 albertel 11937: }
11938: }
11939:
1.575 albertel 11940: sub rndseed_64bit4 {
11941: my ($symb,$courseid,$domain,$username)=@_;
11942: {
11943: use integer;
11944: # strings need to be an even # of cahracters long, it it is odd the
11945: # last characters gets thrown away
11946: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11947: my $symbseed=numval3($symb) << 10;
11948: my $namechck=unpack("%32S*",$username.' ');
11949:
11950: my $nameseed=numval3($username) << 21;
11951: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11952: my $courseseed=unpack("%32S*",$courseid.' ');
11953:
11954: my $num1=$symbchck+$symbseed+$namechck;
11955: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11956: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11957: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11958: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11959:
1.575 albertel 11960: return "$num1:$num2";
11961: }
11962: }
11963:
1.675 albertel 11964: sub rndseed_64bit5 {
11965: my ($symb,$courseid,$domain,$username)=@_;
11966: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11967: return "$num1:$num2";
11968: }
11969:
1.366 albertel 11970: sub rndseed_CODE_64bit {
11971: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11972: {
1.366 albertel 11973: use integer;
1.443 albertel 11974: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11975: my $symbseed=numval2($symb);
1.491 albertel 11976: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11977: my $CODEseed=numval(&getCODE());
1.443 albertel 11978: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11979: my $num1=$symbseed+$CODEchck;
11980: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11981: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11982: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11983: if ($_64bit) { $num1=(($num1<<32)>>32); }
11984: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11985: return "$num1:$num2";
1.366 albertel 11986: }
11987: }
11988:
1.575 albertel 11989: sub rndseed_CODE_64bit4 {
11990: my ($symb,$courseid,$domain,$username)=@_;
11991: {
11992: use integer;
11993: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11994: my $symbseed=numval3($symb);
11995: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11996: my $CODEseed=numval3(&getCODE());
11997: my $courseseed=unpack("%32S*",$courseid.' ');
11998: my $num1=$symbseed+$CODEchck;
11999: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12000: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12001: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12002: if ($_64bit) { $num1=(($num1<<32)>>32); }
12003: if ($_64bit) { $num2=(($num2<<32)>>32); }
12004: return "$num1:$num2";
12005: }
12006: }
12007:
1.675 albertel 12008: sub rndseed_CODE_64bit5 {
12009: my ($symb,$courseid,$domain,$username)=@_;
12010: my $code = &getCODE();
12011: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12012: return "$num1:$num2";
12013: }
12014:
1.366 albertel 12015: sub setup_random_from_rndseed {
12016: my ($rndseed)=@_;
1.503 albertel 12017: if ($rndseed =~/([,:])/) {
1.1262 raeburn 12018: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12019: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12020: &Math::Random::random_set_seed_from_phrase($rndseed);
12021: } else {
12022: &Math::Random::random_set_seed($num1,$num2);
12023: }
1.366 albertel 12024: } else {
12025: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12026: }
1.36 albertel 12027: }
12028:
1.474 albertel 12029: sub latest_receipt_algorithm_id {
1.835 albertel 12030: return 'receipt3';
1.474 albertel 12031: }
12032:
1.480 www 12033: sub recunique {
12034: my $fucourseid=shift;
12035: my $unique;
1.835 albertel 12036: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12037: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12038: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12039: } else {
12040: $unique=$perlvar{'lonReceipt'};
12041: }
12042: return unpack("%32C*",$unique);
12043: }
12044:
12045: sub recprefix {
12046: my $fucourseid=shift;
12047: my $prefix;
1.835 albertel 12048: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12049: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12050: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12051: } else {
12052: $prefix=$perlvar{'lonHostID'};
12053: }
12054: return unpack("%32C*",$prefix);
12055: }
12056:
1.76 www 12057: sub ireceipt {
1.474 albertel 12058: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12059:
12060: my $return =&recprefix($fucourseid).'-';
12061:
12062: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12063: $env{'request.state'} eq 'construct') {
12064: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12065: return $return;
12066: }
12067:
1.76 www 12068: my $cuname=unpack("%32C*",$funame);
12069: my $cudom=unpack("%32C*",$fudom);
12070: my $cucourseid=unpack("%32C*",$fucourseid);
12071: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12072: my $cunique=&recunique($fucourseid);
1.474 albertel 12073: my $cpart=unpack("%32S*",$part);
1.835 albertel 12074: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12075:
1.790 albertel 12076: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12077:
12078: $return.= ($cunique%$cuname+
12079: $cunique%$cudom+
12080: $cusymb%$cuname+
12081: $cusymb%$cudom+
12082: $cucourseid%$cuname+
12083: $cucourseid%$cudom+
12084: $cpart%$cuname+
12085: $cpart%$cudom);
12086: } else {
12087: $return.= ($cunique%$cuname+
12088: $cunique%$cudom+
12089: $cusymb%$cuname+
12090: $cusymb%$cudom+
12091: $cucourseid%$cuname+
12092: $cucourseid%$cudom);
12093: }
12094: return $return;
1.76 www 12095: }
12096:
12097: sub receipt {
1.474 albertel 12098: my ($part)=@_;
1.790 albertel 12099: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12100: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12101: }
1.260 ng 12102:
1.790 albertel 12103: sub whichuser {
12104: my ($passedsymb)=@_;
12105: my ($symb,$courseid,$domain,$name,$publicuser);
12106: if (defined($env{'form.grade_symb'})) {
12107: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12108: my $allowed=&allowed('vgr',$tmp_courseid);
12109: if (!$allowed &&
12110: exists($env{'request.course.sec'}) &&
12111: $env{'request.course.sec'} !~ /^\s*$/) {
12112: $allowed=&allowed('vgr',$tmp_courseid.
12113: '/'.$env{'request.course.sec'});
12114: }
12115: if ($allowed) {
12116: ($symb)=&get_env_multiple('form.grade_symb');
12117: $courseid=$tmp_courseid;
12118: ($domain)=&get_env_multiple('form.grade_domain');
12119: ($name)=&get_env_multiple('form.grade_username');
12120: return ($symb,$courseid,$domain,$name,$publicuser);
12121: }
12122: }
12123: if (!$passedsymb) {
12124: $symb=&symbread();
12125: } else {
12126: $symb=$passedsymb;
12127: }
12128: $courseid=$env{'request.course.id'};
12129: $domain=$env{'user.domain'};
12130: $name=$env{'user.name'};
12131: if ($name eq 'public' && $domain eq 'public') {
12132: if (!defined($env{'form.username'})) {
12133: $env{'form.username'}.=time.rand(10000000);
12134: }
12135: $name.=$env{'form.username'};
12136: }
12137: return ($symb,$courseid,$domain,$name,$publicuser);
12138:
12139: }
12140:
1.36 albertel 12141: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12142: # returns either the contents of the file or
12143: # -1 if the file doesn't exist
1.481 raeburn 12144: #
12145: # if the target is a file that was uploaded via DOCS,
12146: # a check will be made to see if a current copy exists on the local server,
12147: # if it does this will be served, otherwise a copy will be retrieved from
12148: # the home server for the course and stored in /home/httpd/html/userfiles on
12149: # the local server.
1.472 albertel 12150:
1.36 albertel 12151: sub getfile {
1.538 albertel 12152: my ($file) = @_;
1.609 banghart 12153: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12154: &repcopy($file);
12155: return &readfile($file);
12156: }
12157:
12158: sub repcopy_userfile {
12159: my ($file)=@_;
1.1142 raeburn 12160: my $londocroot = $perlvar{'lonDocRoot'};
12161: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12162: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12163: my ($cdom,$cnum,$filename) =
1.811 albertel 12164: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12165: my $uri="/uploaded/$cdom/$cnum/$filename";
12166: if (-e "$file") {
1.828 www 12167: # we already have a local copy, check it out
1.538 albertel 12168: my @fileinfo = stat($file);
1.828 www 12169: my $rtncode;
12170: my $info;
1.538 albertel 12171: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12172: if ($lwpresp ne 'ok') {
1.828 www 12173: # there is no such file anymore, even though we had a local copy
1.482 albertel 12174: if ($rtncode eq '404') {
1.538 albertel 12175: unlink($file);
1.482 albertel 12176: }
12177: return -1;
12178: }
12179: if ($info < $fileinfo[9]) {
1.828 www 12180: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12181: return 'ok';
1.828 www 12182: } else {
12183: # the file is outdated, get rid of it
12184: unlink($file);
1.482 albertel 12185: }
1.828 www 12186: }
12187: # one way or the other, at this point, we don't have the file
12188: # construct the correct path for the file
12189: my @parts = ($cdom,$cnum);
12190: if ($filename =~ m|^(.+)/[^/]+$|) {
12191: push @parts, split(/\//,$1);
12192: }
12193: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12194: foreach my $part (@parts) {
12195: $path .= '/'.$part;
12196: if (!-e $path) {
12197: mkdir($path,0770);
1.482 albertel 12198: }
12199: }
1.828 www 12200: # now the path exists for sure
12201: # get a user agent
12202: my $ua=new LWP::UserAgent;
12203: my $transferfile=$file.'.in.transfer';
12204: # FIXME: this should flock
12205: if (-e $transferfile) { return 'ok'; }
12206: my $request;
12207: $uri=~s/^\///;
1.980 raeburn 12208: my $homeserver = &homeserver($cnum,$cdom);
12209: my $protocol = $protocol{$homeserver};
12210: $protocol = 'http' if ($protocol ne 'https');
12211: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12212: my $response=$ua->request($request,$transferfile);
12213: # did it work?
12214: if ($response->is_error()) {
12215: unlink($transferfile);
12216: &logthis("Userfile repcopy failed for $uri");
12217: return -1;
12218: }
12219: # worked, rename the transfer file
12220: rename($transferfile,$file);
1.607 raeburn 12221: return 'ok';
1.481 raeburn 12222: }
12223:
1.517 albertel 12224: sub tokenwrapper {
12225: my $uri=shift;
1.980 raeburn 12226: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12227: $uri=~s|^/||;
1.620 albertel 12228: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12229: my $token=$1;
1.552 albertel 12230: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12231: if ($udom && $uname && $file) {
12232: $file=~s|(\?\.*)*$||;
1.949 raeburn 12233: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12234: my $homeserver = &homeserver($uname,$udom);
12235: my $protocol = $protocol{$homeserver};
12236: $protocol = 'http' if ($protocol ne 'https');
12237: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12238: (($uri=~/\?/)?'&':'?').'token='.$token.
12239: '&tokenissued='.$perlvar{'lonHostID'};
12240: } else {
12241: return '/adm/notfound.html';
12242: }
12243: }
12244:
1.828 www 12245: # call with reqtype HEAD: get last modification time
12246: # call with reqtype GET: get the file contents
12247: # Do not call this with reqtype GET for large files! It loads everything into memory
12248: #
1.481 raeburn 12249: sub getuploaded {
12250: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12251: $uri=~s/^\///;
1.980 raeburn 12252: my $homeserver = &homeserver($cnum,$cdom);
12253: my $protocol = $protocol{$homeserver};
12254: $protocol = 'http' if ($protocol ne 'https');
12255: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12256: my $ua=new LWP::UserAgent;
12257: my $request=new HTTP::Request($reqtype,$uri);
12258: my $response=$ua->request($request);
12259: $$rtncode = $response->code;
1.482 albertel 12260: if (! $response->is_success()) {
12261: return 'failed';
12262: }
12263: if ($reqtype eq 'HEAD') {
1.486 www 12264: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12265: } elsif ($reqtype eq 'GET') {
12266: $$info = $response->content;
1.472 albertel 12267: }
1.482 albertel 12268: return 'ok';
1.36 albertel 12269: }
12270:
1.481 raeburn 12271: sub readfile {
12272: my $file = shift;
12273: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12274: my $fh;
12275: open($fh,"<$file");
12276: my $a='';
1.800 albertel 12277: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12278: return $a;
12279: }
12280:
1.36 albertel 12281: sub filelocation {
1.590 banghart 12282: my ($dir,$file) = @_;
12283: my $location;
12284: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12285:
12286: if ($file =~ m-^/adm/-) {
12287: $file=~s-^/adm/wrapper/-/-;
12288: $file=~s-^/adm/coursedocs/showdoc/-/-;
12289: }
1.882 albertel 12290:
1.1139 www 12291: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12292: $location = $file;
1.609 banghart 12293: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12294: my ($udom,$uname,$filename)=
1.811 albertel 12295: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12296: my $home=&homeserver($uname,$udom);
12297: my $is_me=0;
12298: my @ids=¤t_machine_ids();
12299: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12300: if ($is_me) {
1.1117 foxr 12301: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12302: } else {
12303: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12304: $udom.'/'.$uname.'/'.$filename;
12305: }
1.882 albertel 12306: } elsif ($file =~ m-^/adm/-) {
12307: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12308: } else {
12309: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12310: $file=~s:^/(res|priv)/:/:;
12311: my $space=$1;
1.590 banghart 12312: if ( !( $file =~ m:^/:) ) {
12313: $location = $dir. '/'.$file;
12314: } else {
1.1142 raeburn 12315: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12316: }
1.59 albertel 12317: }
1.590 banghart 12318: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12319: while ($location=~m{/\.\./}) {
12320: if ($location =~ m{/[^/]+/\.\./}) {
12321: $location=~ s{/[^/]+/\.\./}{/}g;
12322: } else {
12323: $location=~ s{/\.\./}{/}g;
12324: }
12325: } #remove dir/..
1.590 banghart 12326: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12327: return $location;
1.46 www 12328: }
1.36 albertel 12329:
1.46 www 12330: sub hreflocation {
12331: my ($dir,$file)=@_;
1.980 raeburn 12332: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12333: $file=filelocation($dir,$file);
1.700 albertel 12334: } elsif ($file=~m-^/adm/-) {
12335: $file=~s-^/adm/wrapper/-/-;
12336: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12337: }
12338: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12339: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12340: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12341: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12342: {/uploaded/$1/$2/}x;
1.46 www 12343: }
1.913 albertel 12344: if ($file=~ m{^/userfiles/}) {
12345: $file =~ s{^/userfiles/}{/uploaded/};
12346: }
1.462 albertel 12347: return $file;
1.465 albertel 12348: }
12349:
1.1139 www 12350:
12351:
12352:
12353:
1.465 albertel 12354: sub current_machine_domains {
1.853 albertel 12355: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12356: }
12357:
12358: sub machine_domains {
12359: my ($hostname) = @_;
1.465 albertel 12360: my @domains;
1.838 albertel 12361: my %hostname = &all_hostnames();
1.465 albertel 12362: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12363: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12364: if ($hostname eq $name) {
1.844 albertel 12365: push(@domains,&host_domain($id));
1.465 albertel 12366: }
12367: }
12368: return @domains;
12369: }
12370:
12371: sub current_machine_ids {
1.853 albertel 12372: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12373: }
12374:
12375: sub machine_ids {
12376: my ($hostname) = @_;
12377: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12378: my @ids;
1.888 albertel 12379: my %name_to_host = &all_names();
1.889 albertel 12380: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12381: return @{ $name_to_host{$hostname} };
12382: }
12383: return;
1.31 www 12384: }
12385:
1.824 raeburn 12386: sub additional_machine_domains {
12387: my @domains;
12388: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12389: while( my $line = <$fh>) {
12390: $line =~ s/\s//g;
12391: push(@domains,$line);
12392: }
12393: return @domains;
12394: }
12395:
12396: sub default_login_domain {
12397: my $domain = $perlvar{'lonDefDomain'};
12398: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12399: foreach my $posdom (¤t_machine_domains(),
12400: &additional_machine_domains()) {
12401: if (lc($posdom) eq lc($testdomain)) {
12402: $domain=$posdom;
12403: last;
12404: }
12405: }
12406: return $domain;
12407: }
12408:
1.31 www 12409: # ------------------------------------------------------------- Declutters URLs
12410:
12411: sub declutter {
12412: my $thisfn=shift;
1.569 albertel 12413: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12414: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12415: $thisfn=~s{^/home/httpd/html}{};
12416: }
1.31 www 12417: $thisfn=~s/^\///;
1.697 albertel 12418: $thisfn=~s|^adm/wrapper/||;
12419: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12420: $thisfn=~s/^res\///;
1.1172 bisitz 12421: $thisfn=~s/^priv\///;
1.1032 raeburn 12422: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12423: $thisfn=~s/\?.+$//;
12424: }
1.268 www 12425: return $thisfn;
12426: }
12427:
12428: # ------------------------------------------------------------- Clutter up URLs
12429:
12430: sub clutter {
12431: my $thisfn='/'.&declutter(shift);
1.887 albertel 12432: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12433: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12434: $thisfn='/res'.$thisfn;
12435: }
1.1031 raeburn 12436: if ($thisfn !~m|^/adm|) {
12437: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12438: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12439: } else {
12440: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12441: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12442: if ($embstyle eq 'ssi'
12443: || ($embstyle eq 'hdn')
12444: || ($embstyle eq 'rat')
12445: || ($embstyle eq 'prv')
12446: || ($embstyle eq 'ign')) {
12447: #do nothing with these
12448: } elsif (($embstyle eq 'img')
1.695 albertel 12449: || ($embstyle eq 'emb')
12450: || ($embstyle eq 'wrp')) {
12451: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12452: } elsif ($embstyle eq 'unk'
12453: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12454: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12455: } else {
1.718 www 12456: # &logthis("Got a blank emb style");
1.695 albertel 12457: }
1.694 albertel 12458: }
1.1298 raeburn 12459: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
12460: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12461: }
1.31 www 12462: return $thisfn;
1.12 www 12463: }
12464:
1.787 albertel 12465: sub clutter_with_no_wrapper {
12466: my $uri = &clutter(shift);
12467: if ($uri =~ m-^/adm/-) {
12468: $uri =~ s-^/adm/wrapper/-/-;
12469: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12470: }
12471: return $uri;
12472: }
12473:
1.557 albertel 12474: sub freeze_escape {
12475: my ($value)=@_;
12476: if (ref($value)) {
12477: $value=&nfreeze($value);
12478: return '__FROZEN__'.&escape($value);
12479: }
12480: return &escape($value);
12481: }
12482:
1.11 www 12483:
1.557 albertel 12484: sub thaw_unescape {
12485: my ($value)=@_;
12486: if ($value =~ /^__FROZEN__/) {
12487: substr($value,0,10,undef);
12488: $value=&unescape($value);
12489: return &thaw($value);
12490: }
12491: return &unescape($value);
12492: }
12493:
1.436 albertel 12494: sub correct_line_ends {
12495: my ($result)=@_;
12496: $$result =~s/\r\n/\n/mg;
12497: $$result =~s/\r/\n/mg;
1.415 albertel 12498: }
1.1 albertel 12499: # ================================================================ Main Program
12500:
1.184 www 12501: sub goodbye {
1.204 albertel 12502: &logthis("Starting Shut down");
1.443 albertel 12503: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12504: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12505: #converted
1.599 albertel 12506: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12507: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12508: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12509: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12510: #1.1 only
1.870 albertel 12511: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12512: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12513: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12514: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12515: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12516: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12517: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12518: &flushcourselogs();
12519: &logthis("Shutting down");
12520: }
12521:
1.852 albertel 12522: sub get_dns {
1.1210 raeburn 12523: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12524: if (!$ignore_cache) {
12525: my ($content,$cached)=
12526: &Apache::lonnet::is_cached_new('dns',$url);
12527: if ($cached) {
1.1210 raeburn 12528: &$func($content,$hashref);
1.869 albertel 12529: return;
12530: }
12531: }
12532:
12533: my %alldns;
1.852 albertel 12534: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12535: foreach my $dns (<$config>) {
12536: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12537: my $line = $1;
12538: my ($host,$protocol) = split(/:/,$line);
12539: if ($protocol ne 'https') {
12540: $protocol = 'http';
12541: }
12542: $alldns{$host} = $protocol;
1.869 albertel 12543: }
12544: while (%alldns) {
1.1263 raeburn 12545: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12546: my $ua=new LWP::UserAgent;
1.1134 raeburn 12547: $ua->timeout(30);
1.979 raeburn 12548: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12549: my $response=$ua->request($request);
1.979 raeburn 12550: delete($alldns{$dns});
1.852 albertel 12551: next if ($response->is_error());
12552: my @content = split("\n",$response->content);
1.1210 raeburn 12553: unless ($nocache) {
1.1219 raeburn 12554: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12555: }
12556: &$func(\@content,$hashref);
1.869 albertel 12557: return;
1.852 albertel 12558: }
12559: close($config);
1.871 albertel 12560: my $which = (split('/',$url))[3];
12561: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12562: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12563: my @content = <$config>;
1.1210 raeburn 12564: &$func(\@content,$hashref);
12565: return;
12566: }
12567:
12568: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12569: sub parse_dns_checksums_tab {
1.1210 raeburn 12570: my ($lines,$hashref) = @_;
1.1264 raeburn 12571: my $lonhost = $perlvar{'lonHostID'};
12572: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12573: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12574: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12575: my $webconfdir = '/etc/httpd/conf';
12576: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12577: $webconfdir = '/etc/apache2';
12578: } elsif ($distro =~ /^sles(\d+)$/) {
12579: if ($1 >= 10) {
12580: $webconfdir = '/etc/apache2';
12581: }
12582: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12583: if ($1 >= 10.0) {
12584: $webconfdir = '/etc/apache2';
12585: }
12586: }
1.1210 raeburn 12587: my ($release,$timestamp) = split(/\-/,$loncaparev);
12588: my (%chksum,%revnum);
12589: if (ref($lines) eq 'ARRAY') {
12590: chomp(@{$lines});
1.1238 raeburn 12591: my $version = shift(@{$lines});
12592: if ($version eq $release) {
1.1210 raeburn 12593: foreach my $line (@{$lines}) {
1.1238 raeburn 12594: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12595: if ($file =~ m{^/etc/httpd/conf}) {
12596: if ($webconfdir eq '/etc/apache2') {
12597: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12598: }
12599: }
1.1238 raeburn 12600: $chksum{$file} = $shasum;
12601: $revnum{$file} = $version;
1.1210 raeburn 12602: }
12603: if (ref($hashref) eq 'HASH') {
12604: %{$hashref} = (
12605: sums => \%chksum,
12606: versions => \%revnum,
12607: );
12608: }
12609: }
12610: }
1.869 albertel 12611: return;
1.852 albertel 12612: }
1.1210 raeburn 12613:
12614: sub fetch_dns_checksums {
1.1238 raeburn 12615: my %checksums;
12616: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12617: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12618: my ($release,$timestamp) = split(/\-/,$loncaparev);
12619: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12620: \%checksums);
1.1210 raeburn 12621: return \%checksums;
12622: }
12623:
1.327 albertel 12624: # ------------------------------------------------------------ Read domain file
12625: {
1.852 albertel 12626: my $loaded;
1.846 albertel 12627: my %domain;
12628:
1.852 albertel 12629: sub parse_domain_tab {
12630: my ($lines) = @_;
12631: foreach my $line (@$lines) {
12632: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12633:
1.846 albertel 12634: chomp($line);
1.852 albertel 12635: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12636: my %this_domain;
12637: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12638: 'lang_def', 'city', 'longi', 'lati',
12639: 'primary') {
12640: $this_domain{$field} = shift(@elements);
12641: }
12642: $domain{$name} = \%this_domain;
1.852 albertel 12643: }
12644: }
1.864 albertel 12645:
12646: sub reset_domain_info {
12647: undef($loaded);
12648: undef(%domain);
12649: }
12650:
1.852 albertel 12651: sub load_domain_tab {
1.1293 raeburn 12652: my ($ignore_cache,$nocache) = @_;
12653: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12654: my $fh;
12655: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12656: my @lines = <$fh>;
12657: &parse_domain_tab(\@lines);
1.448 albertel 12658: }
1.852 albertel 12659: close($fh);
12660: $loaded = 1;
1.327 albertel 12661: }
1.846 albertel 12662:
12663: sub domain {
1.852 albertel 12664: &load_domain_tab() if (!$loaded);
12665:
1.846 albertel 12666: my ($name,$what) = @_;
12667: return if ( !exists($domain{$name}) );
12668:
12669: if (!$what) {
12670: return $domain{$name}{'description'};
12671: }
12672: return $domain{$name}{$what};
12673: }
1.974 raeburn 12674:
12675: sub domain_info {
12676: &load_domain_tab() if (!$loaded);
12677: return %domain;
12678: }
12679:
1.327 albertel 12680: }
12681:
12682:
1.1 albertel 12683: # ------------------------------------------------------------- Read hosts file
12684: {
1.838 albertel 12685: my %hostname;
1.844 albertel 12686: my %hostdom;
1.845 albertel 12687: my %libserv;
1.852 albertel 12688: my $loaded;
1.888 albertel 12689: my %name_to_host;
1.1074 raeburn 12690: my %internetdom;
1.1107 raeburn 12691: my %LC_dns_serv;
1.852 albertel 12692:
12693: sub parse_hosts_tab {
12694: my ($file) = @_;
12695: foreach my $configline (@$file) {
12696: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12697: chomp($configline);
12698: if ($configline =~ /^\^/) {
12699: if ($configline =~ /^\^([\w.\-]+)/) {
12700: $LC_dns_serv{$1} = 1;
12701: }
12702: next;
12703: }
1.1074 raeburn 12704: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12705: $name=~s/\s//g;
12706: if ($id && $domain && $role && $name) {
12707: $hostname{$id}=$name;
1.888 albertel 12708: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12709: $hostdom{$id}=$domain;
12710: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12711: if (defined($protocol)) {
12712: if ($protocol eq 'https') {
12713: $protocol{$id} = $protocol;
12714: } else {
12715: $protocol{$id} = 'http';
12716: }
1.968 raeburn 12717: } else {
1.969 raeburn 12718: $protocol{$id} = 'http';
1.968 raeburn 12719: }
1.1074 raeburn 12720: if (defined($intdom)) {
12721: $internetdom{$id} = $intdom;
12722: }
1.852 albertel 12723: }
12724: }
12725: }
1.864 albertel 12726:
12727: sub reset_hosts_info {
1.897 albertel 12728: &purge_remembered();
1.864 albertel 12729: &reset_domain_info();
12730: &reset_hosts_ip_info();
1.892 albertel 12731: undef(%name_to_host);
1.864 albertel 12732: undef(%hostname);
12733: undef(%hostdom);
12734: undef(%libserv);
12735: undef($loaded);
12736: }
1.1 albertel 12737:
1.852 albertel 12738: sub load_hosts_tab {
1.1293 raeburn 12739: my ($ignore_cache,$nocache) = @_;
12740: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12741: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12742: my @config = <$config>;
12743: &parse_hosts_tab(\@config);
12744: close($config);
12745: $loaded=1;
1.1 albertel 12746: }
1.852 albertel 12747:
1.838 albertel 12748: sub hostname {
1.852 albertel 12749: &load_hosts_tab() if (!$loaded);
12750:
1.838 albertel 12751: my ($lonid) = @_;
12752: return $hostname{$lonid};
12753: }
1.845 albertel 12754:
1.838 albertel 12755: sub all_hostnames {
1.852 albertel 12756: &load_hosts_tab() if (!$loaded);
12757:
1.838 albertel 12758: return %hostname;
12759: }
1.845 albertel 12760:
1.888 albertel 12761: sub all_names {
1.1293 raeburn 12762: my ($ignore_cache,$nocache) = @_;
12763: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12764:
12765: return %name_to_host;
12766: }
12767:
1.974 raeburn 12768: sub all_host_domain {
12769: &load_hosts_tab() if (!$loaded);
12770: return %hostdom;
12771: }
12772:
1.845 albertel 12773: sub is_library {
1.852 albertel 12774: &load_hosts_tab() if (!$loaded);
12775:
1.845 albertel 12776: return exists($libserv{$_[0]});
12777: }
12778:
12779: sub all_library {
1.852 albertel 12780: &load_hosts_tab() if (!$loaded);
12781:
1.845 albertel 12782: return %libserv;
12783: }
12784:
1.1062 droeschl 12785: sub unique_library {
12786: #2x reverse removes all hostnames that appear more than once
12787: my %unique = reverse &all_library();
12788: return reverse %unique;
12789: }
12790:
1.841 albertel 12791: sub get_servers {
1.852 albertel 12792: &load_hosts_tab() if (!$loaded);
12793:
1.841 albertel 12794: my ($domain,$type) = @_;
12795: my %possible_hosts = ($type eq 'library') ? %libserv
12796: : %hostname;
12797: my %result;
1.842 albertel 12798: if (ref($domain) eq 'ARRAY') {
12799: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12800: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12801: $result{$host} = $hostname;
12802: }
12803: }
12804: } else {
12805: while ( my ($host,$hostname) = each(%possible_hosts)) {
12806: if ($hostdom{$host} eq $domain) {
12807: $result{$host} = $hostname;
12808: }
1.841 albertel 12809: }
12810: }
12811: return %result;
12812: }
1.845 albertel 12813:
1.1062 droeschl 12814: sub get_unique_servers {
12815: my %unique = reverse &get_servers(@_);
12816: return reverse %unique;
12817: }
12818:
1.844 albertel 12819: sub host_domain {
1.852 albertel 12820: &load_hosts_tab() if (!$loaded);
12821:
1.844 albertel 12822: my ($lonid) = @_;
12823: return $hostdom{$lonid};
12824: }
12825:
1.841 albertel 12826: sub all_domains {
1.852 albertel 12827: &load_hosts_tab() if (!$loaded);
12828:
1.841 albertel 12829: my %seen;
12830: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12831: return @uniq;
12832: }
1.1074 raeburn 12833:
12834: sub internet_dom {
12835: &load_hosts_tab() if (!$loaded);
12836:
12837: my ($lonid) = @_;
12838: return $internetdom{$lonid};
12839: }
1.1107 raeburn 12840:
12841: sub is_LC_dns {
12842: &load_hosts_tab() if (!$loaded);
12843:
12844: my ($hostname) = @_;
12845: return exists($LC_dns_serv{$hostname});
12846: }
12847:
1.1 albertel 12848: }
12849:
1.847 albertel 12850: {
12851: my %iphost;
1.856 albertel 12852: my %name_to_ip;
12853: my %lonid_to_ip;
1.869 albertel 12854:
1.847 albertel 12855: sub get_hosts_from_ip {
12856: my ($ip) = @_;
12857: my %iphosts = &get_iphost();
12858: if (ref($iphosts{$ip})) {
12859: return @{$iphosts{$ip}};
12860: }
12861: return;
1.839 albertel 12862: }
1.864 albertel 12863:
12864: sub reset_hosts_ip_info {
12865: undef(%iphost);
12866: undef(%name_to_ip);
12867: undef(%lonid_to_ip);
12868: }
1.856 albertel 12869:
12870: sub get_host_ip {
12871: my ($lonid) = @_;
12872: if (exists($lonid_to_ip{$lonid})) {
12873: return $lonid_to_ip{$lonid};
12874: }
12875: my $name=&hostname($lonid);
12876: my $ip = gethostbyname($name);
12877: return if (!$ip || length($ip) ne 4);
12878: $ip=inet_ntoa($ip);
12879: $name_to_ip{$name} = $ip;
12880: $lonid_to_ip{$lonid} = $ip;
12881: return $ip;
12882: }
1.847 albertel 12883:
12884: sub get_iphost {
1.1293 raeburn 12885: my ($ignore_cache,$nocache) = @_;
1.894 albertel 12886:
1.869 albertel 12887: if (!$ignore_cache) {
12888: if (%iphost) {
12889: return %iphost;
12890: }
12891: my ($ip_info,$cached)=
12892: &Apache::lonnet::is_cached_new('iphost','iphost');
12893: if ($cached) {
12894: %iphost = %{$ip_info->[0]};
12895: %name_to_ip = %{$ip_info->[1]};
12896: %lonid_to_ip = %{$ip_info->[2]};
12897: return %iphost;
12898: }
12899: }
1.894 albertel 12900:
12901: # get yesterday's info for fallback
12902: my %old_name_to_ip;
12903: my ($ip_info,$cached)=
12904: &Apache::lonnet::is_cached_new('iphost','iphost');
12905: if ($cached) {
12906: %old_name_to_ip = %{$ip_info->[1]};
12907: }
12908:
1.1293 raeburn 12909: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 12910: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12911: my $ip;
12912: if (!exists($name_to_ip{$name})) {
12913: $ip = gethostbyname($name);
12914: if (!$ip || length($ip) ne 4) {
1.894 albertel 12915: if (defined($old_name_to_ip{$name})) {
12916: $ip = $old_name_to_ip{$name};
12917: &logthis("Can't find $name defaulting to old $ip");
12918: } else {
12919: &logthis("Name $name no IP found");
12920: next;
12921: }
12922: } else {
12923: $ip=inet_ntoa($ip);
1.847 albertel 12924: }
12925: $name_to_ip{$name} = $ip;
12926: } else {
12927: $ip = $name_to_ip{$name};
1.653 albertel 12928: }
1.888 albertel 12929: foreach my $id (@{ $name_to_host{$name} }) {
12930: $lonid_to_ip{$id} = $ip;
12931: }
12932: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12933: }
1.1293 raeburn 12934: unless ($nocache) {
12935: &do_cache_new('iphost','iphost',
12936: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12937: 48*60*60);
12938: }
1.869 albertel 12939:
1.847 albertel 12940: return %iphost;
1.598 albertel 12941: }
12942:
1.992 raeburn 12943: #
12944: # Given a DNS returns the loncapa host name for that DNS
12945: #
12946: sub host_from_dns {
12947: my ($dns) = @_;
12948: my @hosts;
12949: my $ip;
12950:
1.993 raeburn 12951: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12952: $ip = $name_to_ip{$dns};
12953: }
12954: if (!$ip) {
12955: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12956: if (length($ip) == 4) {
12957: $ip = &IO::Socket::inet_ntoa($ip);
12958: }
12959: }
12960: if ($ip) {
12961: @hosts = get_hosts_from_ip($ip);
12962: return $hosts[0];
12963: }
12964: return undef;
1.986 foxr 12965: }
1.992 raeburn 12966:
1.1074 raeburn 12967: sub get_internet_names {
12968: my ($lonid) = @_;
12969: return if ($lonid eq '');
12970: my ($idnref,$cached)=
12971: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12972: if ($cached) {
12973: return $idnref;
12974: }
12975: my $ip = &get_host_ip($lonid);
12976: my @hosts = &get_hosts_from_ip($ip);
12977: my %iphost = &get_iphost();
12978: my (@idns,%seen);
12979: foreach my $id (@hosts) {
12980: my $dom = &host_domain($id);
12981: my $prim_id = &domain($dom,'primary');
12982: my $prim_ip = &get_host_ip($prim_id);
12983: next if ($seen{$prim_ip});
12984: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12985: foreach my $id (@{$iphost{$prim_ip}}) {
12986: my $intdom = &internet_dom($id);
12987: unless (grep(/^\Q$intdom\E$/,@idns)) {
12988: push(@idns,$intdom);
12989: }
12990: }
12991: }
12992: $seen{$prim_ip} = 1;
12993: }
1.1219 raeburn 12994: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12995: }
12996:
1.986 foxr 12997: }
12998:
1.1079 raeburn 12999: sub all_loncaparevs {
1.1249 raeburn 13000: 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 13001: }
13002:
1.1227 raeburn 13003: # ---------------------------------------------------------- Read loncaparev table
13004: {
13005: sub load_loncaparevs {
13006: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13007: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13008: while (my $configline=<$config>) {
13009: chomp($configline);
13010: my ($hostid,$loncaparev)=split(/:/,$configline);
13011: $loncaparevs{$hostid}=$loncaparev;
13012: }
13013: close($config);
13014: }
13015: }
13016: }
13017: }
13018:
13019: # ---------------------------------------------------------- Read serverhostID table
13020: {
13021: sub load_serverhomeIDs {
13022: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13023: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13024: while (my $configline=<$config>) {
13025: chomp($configline);
13026: my ($name,$id)=split(/:/,$configline);
13027: $serverhomeIDs{$name}=$id;
13028: }
13029: close($config);
13030: }
13031: }
13032: }
13033: }
13034:
13035:
1.862 albertel 13036: BEGIN {
13037:
13038: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13039: unless ($readit) {
13040: {
13041: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13042: %perlvar = (%perlvar,%{$configvars});
13043: }
13044:
13045:
1.1 albertel 13046: # ------------------------------------------------------ Read spare server file
13047: {
1.448 albertel 13048: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13049:
13050: while (my $configline=<$config>) {
13051: chomp($configline);
1.284 matthew 13052: if ($configline) {
1.784 albertel 13053: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13054: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13055: push(@{ $spareid{$type} }, $host);
1.1 albertel 13056: }
13057: }
1.448 albertel 13058: close($config);
1.1 albertel 13059: }
1.11 www 13060: # ------------------------------------------------------------ Read permissions
13061: {
1.448 albertel 13062: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13063:
13064: while (my $configline=<$config>) {
1.448 albertel 13065: chomp($configline);
13066: if ($configline) {
13067: my ($role,$perm)=split(/ /,$configline);
13068: if ($perm ne '') { $pr{$role}=$perm; }
13069: }
1.11 www 13070: }
1.448 albertel 13071: close($config);
1.11 www 13072: }
13073:
13074: # -------------------------------------------- Read plain texts for permissions
13075: {
1.448 albertel 13076: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13077:
13078: while (my $configline=<$config>) {
1.448 albertel 13079: chomp($configline);
13080: if ($configline) {
1.742 raeburn 13081: my ($short,@plain)=split(/:/,$configline);
13082: %{$prp{$short}} = ();
13083: if (@plain > 0) {
13084: $prp{$short}{'std'} = $plain[0];
13085: for (my $i=1; $i<@plain; $i++) {
13086: $prp{$short}{'alt'.$i} = $plain[$i];
13087: }
13088: }
1.448 albertel 13089: }
1.135 www 13090: }
1.448 albertel 13091: close($config);
1.135 www 13092: }
13093:
13094: # ---------------------------------------------------------- Read package table
13095: {
1.448 albertel 13096: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13097:
13098: while (my $configline=<$config>) {
1.483 albertel 13099: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13100: chomp($configline);
13101: my ($short,$plain)=split(/:/,$configline);
13102: my ($pack,$name)=split(/\&/,$short);
13103: if ($plain ne '') {
13104: $packagetab{$pack.'&'.$name.'&name'}=$name;
13105: $packagetab{$short}=$plain;
13106: }
1.11 www 13107: }
1.448 albertel 13108: close($config);
1.329 matthew 13109: }
13110:
1.1073 raeburn 13111: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13112:
13113: &load_loncaparevs();
1.1073 raeburn 13114:
1.1074 raeburn 13115: # ---------------------------------------------------------- Read serverhostID table
13116:
1.1227 raeburn 13117: &load_serverhomeIDs();
13118:
13119: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13120: {
13121: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13122: if (-e $file) {
13123: my $parser = HTML::LCParser->new($file);
13124: while (my $token = $parser->get_token()) {
13125: if ($token->[0] eq 'S') {
13126: my $item = $token->[1];
13127: my $name = $token->[2]{'name'};
13128: my $value = $token->[2]{'value'};
1.1285 raeburn 13129: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13130: my $namematch = $token->[2]{'namematch'};
13131: if ($item eq 'parameter') {
13132: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13133: my $release = $parser->get_text();
13134: $release =~ s/(^\s*|\s*$ )//gx;
13135: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13136: }
13137: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13138: my $release = $parser->get_text();
13139: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13140: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13141: }
13142: }
13143: }
13144: }
1.1073 raeburn 13145: }
13146:
1.1138 raeburn 13147: # ---------------------------------------------------------- Read managers table
13148: {
13149: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13150: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13151: while (my $configline=<$config>) {
13152: chomp($configline);
13153: next if ($configline =~ /^\#/);
13154: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13155: $managerstab{$configline} = 1;
13156: }
13157: }
13158: close($config);
13159: }
13160: }
13161: }
13162:
1.329 matthew 13163: # ------------- set up temporary directory
13164: {
1.1117 foxr 13165: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13166:
1.11 www 13167: }
13168:
1.794 albertel 13169: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13170: 'compress_threshold'=> 20_000,
13171: });
1.185 www 13172:
1.281 www 13173: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13174: $dumpcount=0;
1.958 www 13175: $locknum=0;
1.22 www 13176:
1.163 harris41 13177: &logtouch();
1.672 albertel 13178: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13179: $readit=1;
1.564 albertel 13180: {
13181: use integer;
13182: my $test=(2**32)+1;
1.568 albertel 13183: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13184: &logthis(" Detected 64bit platform ($_64bit)");
13185: }
1.195 www 13186: }
1.1 albertel 13187: }
1.179 www 13188:
1.1 albertel 13189: 1;
1.191 harris41 13190: __END__
13191:
1.243 albertel 13192: =pod
13193:
1.191 harris41 13194: =head1 NAME
13195:
1.243 albertel 13196: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13197:
13198: =head1 SYNOPSIS
13199:
1.243 albertel 13200: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13201:
13202: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13203:
1.243 albertel 13204: Common parameters:
13205:
13206: =over 4
13207:
13208: =item *
13209:
13210: $uname : an internal username (if $cname expecting a course Id specifically)
13211:
13212: =item *
13213:
13214: $udom : a domain (if $cdom expecting a course's domain specifically)
13215:
13216: =item *
13217:
13218: $symb : a resource instance identifier
13219:
13220: =item *
13221:
13222: $namespace : the name of a .db file that contains the data needed or
13223: being set.
13224:
13225: =back
13226:
1.394 bowersj2 13227: =head1 OVERVIEW
1.191 harris41 13228:
1.394 bowersj2 13229: lonnet provides subroutines which interact with the
13230: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13231: about classes, users, and resources.
1.243 albertel 13232:
13233: For many of these objects you can also use this to store data about
13234: them or modify them in various ways.
1.191 harris41 13235:
1.394 bowersj2 13236: =head2 Symbs
1.191 harris41 13237:
1.394 bowersj2 13238: To identify a specific instance of a resource, LON-CAPA uses symbols
13239: or "symbs"X<symb>. These identifiers are built from the URL of the
13240: map, the resource number of the resource in the map, and the URL of
13241: the resource itself. The latter is somewhat redundant, but might help
13242: if maps change.
13243:
13244: An example is
13245:
13246: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13247:
13248: The respective map entry is
13249:
13250: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13251: title="Problem 2">
13252: </resource>
13253:
13254: Symbs are used by the random number generator, as well as to store and
13255: restore data specific to a certain instance of for example a problem.
13256:
13257: =head2 Storing And Retrieving Data
13258:
13259: X<store()>X<cstore()>X<restore()>Three of the most important functions
13260: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13261: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13262: is is the non-critical message twin of cstore. These functions are for
13263: handlers to store a perl hash to a user's permanent data space in an
13264: easy manner, and to retrieve it again on another call. It is expected
13265: that a handler would use this once at the beginning to retrieve data,
13266: and then again once at the end to send only the new data back.
13267:
13268: The data is stored in the user's data directory on the user's
13269: homeserver under the ID of the course.
13270:
13271: The hash that is returned by restore will have all of the previous
13272: value for all of the elements of the hash.
13273:
13274: Example:
13275:
13276: #creating a hash
13277: my %hash;
13278: $hash{'foo'}='bar';
13279:
13280: #storing it
13281: &Apache::lonnet::cstore(\%hash);
13282:
13283: #changing a value
13284: $hash{'foo'}='notbar';
13285:
13286: #adding a new value
13287: $hash{'bar'}='foo';
13288: &Apache::lonnet::cstore(\%hash);
13289:
13290: #retrieving the hash
13291: my %history=&Apache::lonnet::restore();
13292:
13293: #print the hash
13294: foreach my $key (sort(keys(%history))) {
13295: print("\%history{$key} = $history{$key}");
13296: }
13297:
13298: Will print out:
1.191 harris41 13299:
1.394 bowersj2 13300: %history{1:foo} = bar
13301: %history{1:keys} = foo:timestamp
13302: %history{1:timestamp} = 990455579
13303: %history{2:bar} = foo
13304: %history{2:foo} = notbar
13305: %history{2:keys} = foo:bar:timestamp
13306: %history{2:timestamp} = 990455580
13307: %history{bar} = foo
13308: %history{foo} = notbar
13309: %history{timestamp} = 990455580
13310: %history{version} = 2
13311:
13312: Note that the special hash entries C<keys>, C<version> and
13313: C<timestamp> were added to the hash. C<version> will be equal to the
13314: total number of versions of the data that have been stored. The
13315: C<timestamp> attribute will be the UNIX time the hash was
13316: stored. C<keys> is available in every historical section to list which
13317: keys were added or changed at a specific historical revision of a
13318: hash.
13319:
13320: B<Warning>: do not store the hash that restore returns directly. This
13321: will cause a mess since it will restore the historical keys as if the
13322: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13323:
1.394 bowersj2 13324: Calling convention:
1.191 harris41 13325:
1.1225 raeburn 13326: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13327: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13328:
1.394 bowersj2 13329: For more detailed information, see lonnet specific documentation.
1.191 harris41 13330:
1.394 bowersj2 13331: =head1 RETURN MESSAGES
1.191 harris41 13332:
1.394 bowersj2 13333: =over 4
1.191 harris41 13334:
1.394 bowersj2 13335: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13336:
1.394 bowersj2 13337: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13338: when the connection is brought back up
1.191 harris41 13339:
1.394 bowersj2 13340: =item * B<con_failed>: unable to contact remote host and unable to save message
13341: for later delivery
1.191 harris41 13342:
1.967 bisitz 13343: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13344:
1.394 bowersj2 13345: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13346: that was requested
1.191 harris41 13347:
1.243 albertel 13348: =back
1.191 harris41 13349:
1.243 albertel 13350: =head1 PUBLIC SUBROUTINES
1.191 harris41 13351:
1.243 albertel 13352: =head2 Session Environment Functions
1.191 harris41 13353:
1.243 albertel 13354: =over 4
1.191 harris41 13355:
1.394 bowersj2 13356: =item *
13357: X<appenv()>
1.949 raeburn 13358: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13359: the user envirnoment file, and will be restored for each access this
1.620 albertel 13360: user makes during this session, also modifies the %env for the current
1.949 raeburn 13361: process. Optional rolesarrayref - if defined contains a reference to an array
13362: of roles which are exempt from the restriction on modifying user.role entries
13363: in the user's environment.db and in %env.
1.191 harris41 13364:
13365: =item *
1.394 bowersj2 13366: X<delenv()>
1.987 raeburn 13367: B<delenv($delthis,$regexp)>: removes all items from the session
13368: environment file that begin with $delthis. If the
13369: optional second arg - $regexp - is true, $delthis is treated as a
13370: regular expression, otherwise \Q$delthis\E is used.
13371: The values are also deleted from the current processes %env.
1.191 harris41 13372:
1.795 albertel 13373: =item * get_env_multiple($name)
13374:
13375: gets $name from the %env hash, it seemlessly handles the cases where multiple
13376: values may be defined and end up as an array ref.
13377:
13378: returns an array of values
13379:
1.243 albertel 13380: =back
13381:
13382: =head2 User Information
1.191 harris41 13383:
1.243 albertel 13384: =over 4
1.191 harris41 13385:
13386: =item *
1.394 bowersj2 13387: X<queryauthenticate()>
13388: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13389: authentication scheme
13390:
13391: =item *
1.394 bowersj2 13392: X<authenticate()>
1.1073 raeburn 13393: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13394: authenticate user from domain's lib servers (first use the current
13395: one). C<$upass> should be the users password.
1.1073 raeburn 13396: $checkdefauth is optional (value is 1 if a check should be made to
13397: authenticate user using default authentication method, and allow
13398: account creation if username does not have account in the domain).
13399: $clientcancheckhost is optional (value is 1 if checking whether the
13400: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13401:
13402: =item *
1.394 bowersj2 13403: X<homeserver()>
13404: B<homeserver($uname,$udom)>: find the server which has
13405: the user's directory and files (there must be only one), this caches
13406: the answer, and also caches if there is a borken connection.
1.191 harris41 13407:
13408: =item *
1.394 bowersj2 13409: X<idget()>
1.1300 raeburn 13410: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
13411: a list of student/employee IDs or clicker IDs
13412: (student/employee IDs are a unique resource in a domain, there must be
13413: only 1 ID per username, and only 1 username per ID in a specific domain).
13414: clickerIDs are not necessarily unique, as students might share clickers.
13415: (returns hash: id=>name,id=>name)
1.191 harris41 13416:
13417: =item *
1.394 bowersj2 13418: X<idrget()>
13419: B<idrget($udom,@unames)>: find the IDs behind a list of
13420: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13421:
13422: =item *
1.394 bowersj2 13423: X<idput()>
1.1300 raeburn 13424: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
13425: names and associated student/employee IDs or clicker IDs.
13426:
13427: =item *
13428: X<iddel()>
13429: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
13430: student/employee ID or clicker ID username look-ups from domain.
13431: The homeserver ($uhome) and namespace ($namespace) are optional.
13432: If no $uhome is provided, it will be determined usig &homeserver()
13433: for each user. If no $namespace is provided, the default is ids.
13434:
13435: =item *
13436: X<updateclickers()>
13437: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
13438: clicker ID-to-username look-ups in clickers.db on library server.
13439: Permitted actions are add or del (i.e., add or delete). The
13440: clickers.db contains clickerID as keys (escaped), and each corresponding
13441: value is an escaped comma-separated list of usernames (for whom the
13442: library server is the homeserver), who registered that particular ID.
13443: If $critical is true, the update will be sent via &critical, otherwise
13444: &reply() will be used.
1.191 harris41 13445:
13446: =item *
1.394 bowersj2 13447: X<rolesinit()>
1.1169 droeschl 13448: B<rolesinit($udom,$username)>: get user privileges.
13449: returns user role, first access and timer interval hashes
1.243 albertel 13450:
13451: =item *
1.1171 droeschl 13452: X<privileged()>
13453: B<privileged($username,$domain)>: returns a true if user has a
13454: privileged and active role (i.e. su or dc), false otherwise.
13455:
13456: =item *
1.551 albertel 13457: X<getsection()>
13458: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13459: course $cname, return section name/number or '' for "not in course"
13460: and '-1' for "no section"
13461:
13462: =item *
1.394 bowersj2 13463: X<userenvironment()>
13464: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13465: passed in @what from the requested user's environment, returns a hash
13466:
1.858 raeburn 13467: =item *
13468: X<userlog_query()>
1.859 albertel 13469: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13470: activity.log file. %filters defines filters applied when parsing the
13471: log file. These can be start or end timestamps, or the type of action
13472: - log to look for Login or Logout events, check for Checkin or
13473: Checkout, role for role selection. The response is in the form
13474: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13475: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13476:
1.243 albertel 13477: =back
13478:
13479: =head2 User Roles
13480:
13481: =over 4
13482:
13483: =item *
13484:
1.1284 raeburn 13485: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13486: returns codes for allowed actions.
13487:
13488: The first argument is required, all others are optional.
13489:
13490: $priv is the privilege being checked.
13491: $uri contains additional information about what is being checked for access (e.g.,
13492: URL, course ID etc.).
13493: $symb is the unique resource instance identifier in a course; if needed,
13494: but not provided, it will be retrieved via a call to &symbread().
13495: $role is the role for which a priv is being checked (only used if priv is evb).
13496: $clientip is the user's IP address (only used when checking for access to portfolio
13497: files).
13498: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13499: prevents recursive calls to &allowed.
13500:
1.243 albertel 13501: F: full access
13502: U,I,K: authentication modes (cxx only)
13503: '': forbidden
13504: 1: user needs to choose course
13505: 2: browse allowed
1.766 albertel 13506: A: passphrase authentication needed
1.1284 raeburn 13507: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13508:
13509: =item *
13510:
1.1192 raeburn 13511: constructaccess($url,$setpriv) : check for access to construction space URL
13512:
13513: See if the owner domain and name in the URL match those in the
13514: expected environment. If so, return three element list
13515: ($ownername,$ownerdomain,$ownerhome).
13516:
13517: Otherwise return the null string.
13518:
13519: If second argument 'setpriv' is true, it assigns the privileges,
13520: and returns the same three element list, unless the owner has
13521: blocked "ad hoc" Domain Coordinator access to the Author Space,
13522: in which case the null string is returned.
13523:
13524: =item *
13525:
1.243 albertel 13526: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13527: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13528: and course level
13529:
13530: =item *
13531:
1.988 raeburn 13532: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13533: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13534: $type is Course (default) or Community.
1.988 raeburn 13535: If $forcedefault evaluates to true, text returned will be default
13536: text for $type. Otherwise, if this is a course, the text returned
13537: will be a custom name for the role (if defined in the course's
13538: environment). If no custom name is defined the default is returned.
13539:
1.832 raeburn 13540: =item *
13541:
1.1219 raeburn 13542: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13543: All arguments are optional. Returns a hash of a roles, either for
13544: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13545: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13546: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13547: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13548: For each key, value is set to colon-separated start and end times for
13549: the role. If no username and domain are specified, will default to
1.934 raeburn 13550: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13551: of role statuses (active, future or previous), roles
13552: (e.g., cc,in, st etc.) and domains of the roles which can be used
13553: to restrict the list of roles reported. If no array ref is
13554: provided for types, will default to return only active roles.
1.834 albertel 13555:
1.1195 raeburn 13556: =item *
13557:
13558: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 13559: user: $uname:$udom has a role in the course: $cdom_$cnum.
13560:
13561: Additional optional arguments are: $type (if role checking is to be restricted
13562: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13563: available roles) or future (roles available in the future), and
13564: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13565: have active Domain Coordinator role in course's domain or in additional
13566: domains (specified in 'Domains to check for privileged users' in course
13567: environment -- set via: Course Settings -> Classlists and staff listing).
13568:
13569: =item *
13570:
13571: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13572: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13573: $possdomains and $possroles are optional array refs -- to domains to check and
13574: roles to check. If $possdomains is not specified, a dump will be done of the
13575: users' roles.db to check for a dc or su role in any domain. This can be
13576: time consuming if &privileged is called repeatedly (e.g., when displaying a
13577: classlist), so in such cases, supplying a $possdomains array is preferred, as
13578: this then allows &privileged_by_domain() to be used, which caches the identity
13579: of privileged users, eliminating the need for repeated calls to &dump().
13580:
13581: =item *
13582:
13583: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13584: where the outer hash keys are domains specified in the $possdomains array ref,
13585: next inner hash keys are privileged roles specified in the $roles array ref,
13586: and the innermost hash contains key = value pairs for username:domain = end:start
13587: for active or future "privileged" users with that role in that domain. To avoid
13588: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13589: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13590:
1.243 albertel 13591: =back
13592:
13593: =head2 User Modification
13594:
13595: =over 4
13596:
13597: =item *
13598:
1.957 raeburn 13599: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13600: user for the level given by URL. Optional start and end dates (leave empty
13601: string or zero for "no date")
1.191 harris41 13602:
13603: =item *
13604:
1.243 albertel 13605: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13606: change a users, password, possible return values are: ok,
13607: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13608: refused
1.191 harris41 13609:
13610: =item *
13611:
1.243 albertel 13612: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13613:
13614: =item *
13615:
1.1058 raeburn 13616: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13617: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13618:
13619: will update user information (firstname,middlename,lastname,generation,
13620: permanentemail), and if forceid is true, student/employee ID also.
13621: A user's institutional affiliation(s) can also be updated.
13622: User information fields will not be overwritten with empty entries
13623: unless the field is included in the $candelete array reference.
13624: This array is included when a single user is modified via "Manage Users",
13625: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13626:
13627: =item *
13628:
1.286 matthew 13629: modifystudent
13630:
1.957 raeburn 13631: modify a student's enrollment and identification information.
1.1235 raeburn 13632: The course id is resolved based on the current user's environment.
13633: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13634: associated with a course.
13635:
1.297 matthew 13636: This call is essentially a wrapper for lonnet::modifyuser and
13637: lonnet::modify_student_enrollment
1.286 matthew 13638:
13639: Inputs:
13640:
13641: =over 4
13642:
1.957 raeburn 13643: =item B<$udom> Student's loncapa domain
1.286 matthew 13644:
1.957 raeburn 13645: =item B<$uname> Student's loncapa login name
1.286 matthew 13646:
1.964 bisitz 13647: =item B<$uid> Student/Employee ID
1.286 matthew 13648:
1.957 raeburn 13649: =item B<$umode> Student's authentication mode
1.286 matthew 13650:
1.957 raeburn 13651: =item B<$upass> Student's password
1.286 matthew 13652:
1.957 raeburn 13653: =item B<$first> Student's first name
1.286 matthew 13654:
1.957 raeburn 13655: =item B<$middle> Student's middle name
1.286 matthew 13656:
1.957 raeburn 13657: =item B<$last> Student's last name
1.286 matthew 13658:
1.957 raeburn 13659: =item B<$gene> Student's generation
1.286 matthew 13660:
1.957 raeburn 13661: =item B<$usec> Student's section in course
1.286 matthew 13662:
13663: =item B<$end> Unix time of the roles expiration
13664:
13665: =item B<$start> Unix time of the roles start date
13666:
13667: =item B<$forceid> If defined, allow $uid to be changed
13668:
13669: =item B<$desiredhome> server to use as home server for student
13670:
1.957 raeburn 13671: =item B<$email> Student's permanent e-mail address
13672:
13673: =item B<$type> Type of enrollment (auto or manual)
13674:
1.963 raeburn 13675: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13676:
13677: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13678:
1.963 raeburn 13679: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13680:
1.963 raeburn 13681: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13682:
1.1216 raeburn 13683: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13684:
13685: =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 13686:
1.286 matthew 13687: =back
1.297 matthew 13688:
13689: =item *
13690:
13691: modify_student_enrollment
13692:
1.1235 raeburn 13693: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13694: 'role.request.course' must be defined for this function to proceed.
13695:
13696: Inputs:
13697:
13698: =over 4
13699:
1.1235 raeburn 13700: =item $udom, student's domain
1.297 matthew 13701:
1.1235 raeburn 13702: =item $uname, student's name
1.297 matthew 13703:
1.1235 raeburn 13704: =item $uid, student's user id
1.297 matthew 13705:
1.1235 raeburn 13706: =item $first, student's first name
1.297 matthew 13707:
13708: =item $middle
13709:
13710: =item $last
13711:
13712: =item $gene
13713:
13714: =item $usec
13715:
13716: =item $end
13717:
13718: =item $start
13719:
1.957 raeburn 13720: =item $type
13721:
13722: =item $locktype
13723:
13724: =item $cid
13725:
13726: =item $selfenroll
13727:
13728: =item $context
13729:
1.1216 raeburn 13730: =item $credits, number of credits student will earn from this class
13731:
1.297 matthew 13732: =back
13733:
1.191 harris41 13734:
13735: =item *
13736:
1.243 albertel 13737: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13738: custom role; give a custom role to a user for the level given by URL. Specify
13739: name and domain of role author, and role name
1.191 harris41 13740:
13741: =item *
13742:
1.243 albertel 13743: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13744:
13745: =item *
13746:
1.243 albertel 13747: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13748:
13749: =back
13750:
13751: =head2 Course Infomation
13752:
13753: =over 4
1.191 harris41 13754:
13755: =item *
13756:
1.1118 foxr 13757: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13758: specified course id, including all environment settings for the
13759: course, the description of the course will be in the hash under the
13760: key 'description'
1.191 harris41 13761:
1.1118 foxr 13762: $options is an optional parameter that if supplied is a hash reference that controls
13763: what how this function works. It has the following key/values:
13764:
13765: =over 4
13766:
13767: =item freshen_cache
13768:
13769: If defined, and the environment cache for the course is valid, it is
13770: returned in the returned hash.
13771:
13772: =item one_time
13773:
13774: If defined, the last cache time is set to _now_
13775:
13776: =item user
13777:
13778: If defined, the supplied username is used instead of the current user.
13779:
13780:
13781: =back
13782:
1.191 harris41 13783: =item *
13784:
1.624 albertel 13785: resdata($name,$domain,$type,@which) : request for current parameter
13786: setting for a specific $type, where $type is either 'course' or 'user',
13787: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 13788: answers for 10 minutes.
1.243 albertel 13789:
1.877 foxr 13790: =item *
13791:
13792: get_courseresdata($courseid, $domain) : dump the entire course resource
13793: data base, returning a hash that is keyed by the resource name and has
13794: values that are the resource value. I believe that the timestamps and
13795: versions are also returned.
13796:
1.1236 raeburn 13797: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13798: supplemental content area. This routine caches the number of files for
13799: 10 minutes.
13800:
1.243 albertel 13801: =back
13802:
13803: =head2 Course Modification
13804:
13805: =over 4
1.191 harris41 13806:
13807: =item *
13808:
1.243 albertel 13809: writecoursepref($courseid,%prefs) : write preferences (environment
13810: database) for a course
1.191 harris41 13811:
13812: =item *
13813:
1.1011 raeburn 13814: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13815:
13816: =item *
13817:
1.1038 raeburn 13818: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13819:
1.1167 droeschl 13820: =item *
13821:
13822: is_course($courseid), is_course($cdom, $cnum)
13823:
13824: Accepts either a combined $courseid (in the form of domain_courseid) or the
13825: two component version $cdom, $cnum. It checks if the specified course exists.
13826:
13827: Returns:
13828: undef if the course doesn't exist, otherwise
13829: in scalar context the combined courseid.
13830: in list context the two components of the course identifier, domain and
13831: courseid.
13832:
1.243 albertel 13833: =back
13834:
13835: =head2 Resource Subroutines
13836:
13837: =over 4
1.191 harris41 13838:
13839: =item *
13840:
1.243 albertel 13841: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13842:
13843: =item *
13844:
1.243 albertel 13845: repcopy($filename) : subscribes to the requested file, and attempts to
13846: replicate from the owning library server, Might return
1.607 raeburn 13847: 'unavailable', 'not_found', 'forbidden', 'ok', or
13848: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13849: resource. Expects the local filesystem pathname
13850: (/home/httpd/html/res/....)
13851:
13852: =back
13853:
13854: =head2 Resource Information
13855:
13856: =over 4
1.191 harris41 13857:
13858: =item *
13859:
1.1228 raeburn 13860: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13861: and returns the value of a variety of different possible values,
13862: $varname should be a request string, and the other parameters can be
13863: used to specify who and what one is asking about. Ordinarily, $cid
13864: does not need to be specified, as it is retrived from
13865: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13866: within lonuserstate::loadmap() when initializing a course, before
13867: $env{'request.course.id'} has been set, so it needs to be provided
13868: in that one case.
1.243 albertel 13869:
13870: Possible values for $varname are environment.lastname (or other item
13871: from the envirnment hash), user.name (or someother aspect about the
13872: user), resource.0.maxtries (or some other part and parameter of a
13873: resource)
1.204 albertel 13874:
13875: =item *
13876:
1.243 albertel 13877: directcondval($number) : get current value of a condition; reads from a state
13878: string
1.204 albertel 13879:
13880: =item *
13881:
1.243 albertel 13882: condval($condidx) : value of condition index based on state
1.204 albertel 13883:
13884: =item *
13885:
1.243 albertel 13886: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13887: resource's metadata, $what should be either a specific key, or either
13888: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13889: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13890:
13891: this function automatically caches all requests
1.191 harris41 13892:
13893: =item *
13894:
1.243 albertel 13895: metadata_query($query,$custom,$customshow) : make a metadata query against the
13896: network of library servers; returns file handle of where SQL and regex results
13897: will be stored for query
1.191 harris41 13898:
13899: =item *
13900:
1.1282 raeburn 13901: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13902: return symbolic list entry (all arguments optional).
13903:
13904: Args: filename is the filename (including path) for the file for which a symb
13905: is required; donotrecurse, if true will prevent calls to allowed() being made
13906: to check access status if more than one resource was found in the bighash
13907: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13908: a randompick); ignorecachednull, if true will prevent a symb of '' being
13909: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13910: cause possible symbs to be checked to determine if they are subject to content
13911: blocking, if so they will not be included as possible symbs; possibles is a
13912: ref to a hash, which, as a side effect, will be populated with all possible
13913: symbs (content blocking not tested).
13914:
1.243 albertel 13915: returns the data handle
1.191 harris41 13916:
13917: =item *
13918:
1.1190 raeburn 13919: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13920: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13921: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13922: on failure, user must be in a course, as it assumes the existence of
13923: the course initial hash, and uses $env('request.course.id'}. The third
13924: arg is an optional reference to a scalar. If this arg is passed in the
13925: call to symbverify, it will be set to 1 if the symb has been set to be
13926: encrypted; otherwise it will be null.
1.191 harris41 13927:
13928: =item *
13929:
1.243 albertel 13930: symbclean($symb) : removes versions numbers from a symb, returns the
13931: cleaned symb
1.191 harris41 13932:
13933: =item *
13934:
1.243 albertel 13935: is_on_map($uri) : checks if the $uri is somewhere on the current
13936: course map, user must be in a course for it to work.
1.191 harris41 13937:
13938: =item *
13939:
1.243 albertel 13940: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13941:
13942: =item *
13943:
1.243 albertel 13944: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13945: a random seed, all arguments are optional, if they aren't sent it uses the
13946: environment to derive them. Note: if symb isn't sent and it can't get one
13947: from &symbread it will use the current time as its return value
1.191 harris41 13948:
13949: =item *
13950:
1.243 albertel 13951: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13952: unfakeable, receipt
1.191 harris41 13953:
13954: =item *
13955:
1.620 albertel 13956: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13957:
13958: =item *
13959:
1.243 albertel 13960: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13961:
13962: =item *
13963:
1.243 albertel 13964: 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 13965:
13966: =item *
13967:
1.243 albertel 13968: 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 13969:
13970: =item *
13971:
1.243 albertel 13972: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13973:
13974: =item *
13975:
1.243 albertel 13976: devalidate($symb) : devalidate temporary spreadsheet calculations,
13977: forcing spreadsheet to reevaluate the resource scores next time.
13978:
1.1195 raeburn 13979: =item *
13980:
1.1196 raeburn 13981: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13982: when viewing in course context.
1.1195 raeburn 13983:
1.1196 raeburn 13984: input: six args -- filename (decluttered), course number, course domain,
13985: url, symb (if registered) and group (if this is a
13986: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13987:
1.1196 raeburn 13988: output: array of five scalars --
1.1195 raeburn 13989: $cfile -- url for file editing if editable on current server
13990: $home -- homeserver of resource (i.e., for author if published,
13991: or course if uploaded.).
13992: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13993: $forceedit -- 1 if icon/link should be to go to edit mode
13994: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13995:
13996: =item *
13997:
13998: is_course_upload($file,$cnum,$cdom)
13999:
14000: Used in course context to determine if current file was uploaded to
14001: the course (i.e., would be found in /userfiles/docs on the course's
14002: homeserver.
14003:
14004: input: 3 args -- filename (decluttered), course number and course domain.
14005: output: boolean -- 1 if file was uploaded.
14006:
1.243 albertel 14007: =back
14008:
14009: =head2 Storing/Retreiving Data
14010:
14011: =over 4
1.191 harris41 14012:
14013: =item *
14014:
1.1269 raeburn 14015: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14016: permanently for this url; hashref needs to be given and should be a \%hashname;
14017: the remaining args aren't required and if they aren't passed or are '' they will
14018: be derived from the env (with the exception of $laststore, which is an
14019: optional arg used when a user's submission is stored in grading).
14020: $laststore is $version=$timestamp, where $version is the most recent version
14021: number retrieved for the corresponding $symb in the $namespace db file, and
14022: $timestamp is the timestamp for that transaction (UNIX time).
14023: $laststore is currently only passed when cstore() is called by
14024: structuretags::finalize_storage().
1.191 harris41 14025:
14026: =item *
14027:
1.1269 raeburn 14028: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14029: but uses critical subroutine
1.191 harris41 14030:
14031: =item *
14032:
1.243 albertel 14033: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14034: all args are optional
1.191 harris41 14035:
14036: =item *
14037:
1.717 albertel 14038: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14039: dumps the complete (or key matching regexp) namespace into a hash
14040: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14041: normally &store()ed into
14042:
14043: $range should be either an integer '100' (give me the first 100
14044: matching records)
14045: or be two integers sperated by a - with no spaces
14046: '30-50' (give me the 30th through the 50th matching
14047: records)
14048:
14049:
14050: =item *
14051:
1.1269 raeburn 14052: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14053: replaces a &store() version of data with a replacement set of data
14054: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14055: reference. If $tolog is true, the transaction is logged in the courselog
14056: with an action=PUTSTORE.
1.717 albertel 14057:
14058: =item *
14059:
1.243 albertel 14060: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14061: works very similar to store/cstore, but all data is stored in a
14062: temporary location and can be reset using tmpreset, $storehash should
14063: be a hash reference, returns nothing on success
1.191 harris41 14064:
14065: =item *
14066:
1.243 albertel 14067: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14068: similar to restore, but all data is stored in a temporary location and
14069: can be reset using tmpreset. Returns a hash of values on success,
14070: error string otherwise.
1.191 harris41 14071:
14072: =item *
14073:
1.243 albertel 14074: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14075: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14076:
14077: =item *
14078:
1.243 albertel 14079: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14080: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14081:
14082: =item *
14083:
1.243 albertel 14084: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14085: namesp ($udom and $uname are optional)
1.191 harris41 14086:
14087: =item *
14088:
1.702 albertel 14089: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14090: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14091: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14092:
1.702 albertel 14093: $range should be either an integer '100' (give me the first 100
14094: matching records)
14095: or be two integers sperated by a - with no spaces
14096: '30-50' (give me the 30th through the 50th matching
14097: records)
1.449 matthew 14098: =item *
14099:
14100: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14101: $store can be a scalar, an array reference, or if the amount to be
14102: incremented is > 1, a hash reference.
14103:
14104: ($udom and $uname are optional)
1.191 harris41 14105:
14106: =item *
14107:
1.243 albertel 14108: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14109: ($udom and $uname are optional)
1.191 harris41 14110:
14111: =item *
14112:
1.243 albertel 14113: cput($namespace,$storehash,$udom,$uname) : critical put
14114: ($udom and $uname are optional)
1.191 harris41 14115:
14116: =item *
14117:
1.748 albertel 14118: newput($namespace,$storehash,$udom,$uname) :
14119:
14120: Attempts to store the items in the $storehash, but only if they don't
14121: currently exist, if this succeeds you can be certain that you have
14122: successfully created a new key value pair in the $namespace db.
14123:
14124:
14125: Args:
14126: $namespace: name of database to store values to
14127: $storehash: hashref to store to the db
14128: $udom: (optional) domain of user containing the db
14129: $uname: (optional) name of user caontaining the db
14130:
14131: Returns:
14132: 'ok' -> succeeded in storing all keys of $storehash
14133: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14134: least <key> already existed in the db (other
14135: requested keys may also already exist)
1.967 bisitz 14136: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14137: 'con_lost' -> unable to contact request server
14138: 'refused' -> action was not allowed by remote machine
14139:
14140:
14141: =item *
14142:
1.243 albertel 14143: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14144: reference filled in from namesp (encrypts the return communication)
14145: ($udom and $uname are optional)
1.191 harris41 14146:
14147: =item *
14148:
1.243 albertel 14149: log($udom,$name,$home,$message) : write to permanent log for user; use
14150: critical subroutine
14151:
1.806 raeburn 14152: =item *
14153:
1.860 raeburn 14154: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14155: array reference filled in from namespace found in domain level on either
14156: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14157:
14158: =item *
14159:
1.860 raeburn 14160: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14161: domain level either on specified domain server ($uhome) or primary domain
14162: server ($udom and $uhome are optional)
1.806 raeburn 14163:
1.943 raeburn 14164: =item *
14165:
1.1240 raeburn 14166: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14167: for: authentication, language, quotas, timezone, date locale, and portal URL in
14168: the target domain.
14169:
14170: May also include additional key => value pairs for the following groups:
14171:
14172: =over
14173:
14174: =item
14175: disk quotas (MB allocated by default to portfolios and authoring spaces).
14176:
14177: =over
14178:
14179: =item defaultquota, authorquota
14180:
14181: =back
14182:
14183: =item
14184: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14185: portfolio for users).
14186:
14187: =over
14188:
14189: =item
14190: aboutme, blog, webdav, portfolio
14191:
14192: =back
14193:
14194: =item
14195: requestcourses: ability to request courses, and how requests are processed.
14196:
14197: =over
14198:
14199: =item
1.1305 raeburn 14200: official, unofficial, community, textbook, placement
1.1240 raeburn 14201:
14202: =back
14203:
14204: =item
14205: inststatus: types of institutional affiliation, and order in which they are displayed.
14206:
14207: =over
14208:
14209: =item
1.1256 raeburn 14210: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14211:
14212: =back
14213:
14214: =item
14215: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14216: for course's uploaded content.
14217:
14218: =over
14219:
14220: =item
1.1246 raeburn 14221: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 14222: communityquota, textbookquota, placementquota
1.1240 raeburn 14223:
14224: =back
14225:
14226: =item
14227: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14228: on your servers.
14229:
14230: =over
14231:
14232: =item
14233: remotesessions, hostedsessions
14234:
14235: =back
14236:
14237: =back
14238:
14239: In cases where a domain coordinator has never used the "Set Domain Configuration"
14240: utility to create a configuration.db file on a domain's primary library server
14241: only the following domain defaults: auth_def, auth_arg_def, lang_def
14242: -- corresponding values are authentication type (internal, krb4, krb5,
14243: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14244: will be available. Values are retrieved from cache (if current), unless the
14245: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14246: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14247:
14248: Typical usage:
1.943 raeburn 14249:
1.1240 raeburn 14250: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14251:
1.243 albertel 14252: =back
14253:
14254: =head2 Network Status Functions
14255:
14256: =over 4
1.191 harris41 14257:
14258: =item *
14259:
1.1137 raeburn 14260: dirlist() : return directory list based on URI (first arg).
14261:
14262: Inputs: 1 required, 5 optional.
14263:
14264: =over
14265:
14266: =item
14267: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14268:
14269: =item
14270: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14271:
14272: =item
14273: $username - username of user/course to be listed. Extracted from $uri if absent.
14274:
14275: =item
14276: $getpropath - boolean: 1 if prepend path using &propath().
14277:
14278: =item
14279: $getuserdir - boolean: 1 if prepend path for "userfiles".
14280:
14281: =item
14282: $alternateRoot - path to prepend in place of path from $uri.
14283:
14284: =back
14285:
14286: Returns: Array of up to two items.
14287:
14288: =over
14289:
14290: a reference to an array of files/subdirectories
14291:
14292: =over
14293:
14294: Each element in the array of files/subdirectories is a & separated list of
14295: item name and the result of running stat on the item. If dirlist was requested
14296: for a file instead of a directory, the item name will be ''. For a directory
14297: listing, if the item is a metadata file, the element will end &N&M
14298: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14299: default copyright set (1).
14300:
14301: =back
14302:
14303: a scalar containing error condition (if encountered).
14304:
14305: =over
14306:
14307: =item
14308: no_host (no homeserver identified for $username:$domain).
14309:
14310: =item
14311: no_such_host (server contacted for listing not identified as valid host).
14312:
14313: =item
14314: con_lost (connection to remote server failed).
14315:
14316: =item
14317: refused (invalid $username:$domain received on lond side).
14318:
14319: =item
14320: no_such_dir (directory at specified path on lond side does not exist).
14321:
14322: =item
14323: empty (directory at specified path on lond side is empty).
14324:
14325: =over
14326:
14327: This is currently not encountered because the &ls3, &ls2,
14328: &ls (_handler) routines on the lond side do not filter out
14329: . and .. from a directory listing.
14330:
14331: =back
14332:
14333: =back
14334:
14335: =back
1.191 harris41 14336:
14337: =item *
14338:
1.243 albertel 14339: spareserver() : find server with least workload from spare.tab
14340:
1.986 foxr 14341:
14342: =item *
14343:
14344: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14345: if there is no corresponding loncapa host.
14346:
1.243 albertel 14347: =back
14348:
1.986 foxr 14349:
1.243 albertel 14350: =head2 Apache Request
14351:
14352: =over 4
1.191 harris41 14353:
14354: =item *
14355:
1.243 albertel 14356: ssi($url,%hash) : server side include, does a complete request cycle on url to
14357: localhost, posts hash
14358:
14359: =back
14360:
14361: =head2 Data to String to Data
14362:
14363: =over 4
1.191 harris41 14364:
14365: =item *
14366:
1.243 albertel 14367: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14368: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14369:
14370: =item *
14371:
1.243 albertel 14372: hashref2str($hashref) : convert a hashref into a string complete with
14373: escaping and '=' and '&' separators, supports elements that are
14374: arrayrefs and hashrefs
1.191 harris41 14375:
14376: =item *
14377:
1.243 albertel 14378: arrayref2str($arrayref) : convert an arrayref into a string complete
14379: with escaping and '&' separators, supports elements that are arrayrefs
14380: and hashrefs
1.191 harris41 14381:
14382: =item *
14383:
1.243 albertel 14384: str2hash($string) : convert string to hash using unescaping and
14385: splitting on '=' and '&', supports elements that are arrayrefs and
14386: hashrefs
1.191 harris41 14387:
14388: =item *
14389:
1.243 albertel 14390: str2array($string) : convert string to hash using unescaping and
14391: splitting on '&', supports elements that are arrayrefs and hashrefs
14392:
14393: =back
14394:
14395: =head2 Logging Routines
14396:
14397:
14398: These routines allow one to make log messages in the lonnet.log and
14399: lonnet.perm logfiles.
1.191 harris41 14400:
1.1119 foxr 14401: =over 4
14402:
1.191 harris41 14403: =item *
14404:
1.243 albertel 14405: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14406:
14407: =item *
14408:
1.243 albertel 14409: logthis() : append message to the normal lonnet.log file, it gets
14410: preiodically rolled over and deleted.
1.191 harris41 14411:
14412: =item *
14413:
1.243 albertel 14414: logperm() : append a permanent message to lonnet.perm.log, this log
14415: file never gets deleted by any automated portion of the system, only
14416: messages of critical importance should go in here.
14417:
1.1119 foxr 14418:
1.243 albertel 14419: =back
14420:
14421: =head2 General File Helper Routines
14422:
14423: =over 4
1.191 harris41 14424:
14425: =item *
14426:
1.481 raeburn 14427: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14428: (a) files in /uploaded
14429: (i) If a local copy of the file exists -
14430: compares modification date of local copy with last-modified date for
14431: definitive version stored on home server for course. If local copy is
14432: stale, requests a new version from the home server and stores it.
14433: If the original has been removed from the home server, then local copy
14434: is unlinked.
14435: (ii) If local copy does not exist -
14436: requests the file from the home server and stores it.
14437:
14438: If $caller is 'uploadrep':
14439: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14440: for request for files originally uploaded via DOCS.
14441: - returns 'ok' if fresh local copy now available, -1 otherwise.
14442:
14443: Otherwise:
14444: This indicates a call from the content generation phase of the request.
14445: - returns the entire contents of the file or -1.
14446:
14447: (b) files in /res
14448: - returns the entire contents of a file or -1;
14449: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14450:
1.712 albertel 14451:
14452: =item *
14453:
14454: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14455: reference
14456:
14457: returns either a stat() list of data about the file or an empty list
14458: if the file doesn't exist or couldn't find out about it (connection
14459: problems or user unknown)
14460:
1.191 harris41 14461: =item *
14462:
1.243 albertel 14463: filelocation($dir,$file) : returns file system location of a file
14464: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14465: directory that relative $file lookups are to looked in ($dir of /a/dir
14466: and a file of ../bob will become /a/bob)
1.191 harris41 14467:
14468: =item *
14469:
14470: hreflocation($dir,$file) : returns file system location or a URL; same as
14471: filelocation except for hrefs
14472:
14473: =item *
14474:
1.1261 raeburn 14475: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14476: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14477:
1.243 albertel 14478: =back
14479:
1.608 albertel 14480: =head2 Usererfile file routines (/uploaded*)
14481:
14482: =over 4
14483:
14484: =item *
14485:
14486: userfileupload(): main rotine for putting a file in a user or course's
14487: filespace, arguments are,
14488:
1.620 albertel 14489: formname - required - this is the name of the element in $env where the
1.608 albertel 14490: filename, and the contents of the file to create/modifed exist
1.620 albertel 14491: the filename is in $env{'form.'.$formname.'.filename'} and the
14492: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14493: context - if coursedoc, store the file in the course of the active role
14494: of the current user;
14495: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14496: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14497: subdir - required - subdirectory to put the file in under ../userfiles/
14498: if undefined, it will be placed in "unknown"
14499:
14500: (This routine calls clean_filename() to remove any dangerous
14501: characters from the filename, and then calls finuserfileupload() to
14502: complete the transaction)
14503:
14504: returns either the url of the uploaded file (/uploaded/....) if successful
14505: and /adm/notfound.html if unsuccessful
14506:
14507: =item *
14508:
14509: clean_filename(): routine for cleaing a filename up for storage in
14510: userfile space, argument is:
14511:
14512: filename - proposed filename
14513:
14514: returns: the new clean filename
14515:
14516: =item *
14517:
1.1090 raeburn 14518: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14519: userspace, probably shouldn't be called directly
14520:
14521: docuname: username or courseid of destination for the file
14522: docudom: domain of user/course of destination for the file
14523: formname: same as for userfileupload()
1.1090 raeburn 14524: fname: filename (including subdirectories) for the file
14525: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14526: allfiles: reference to hash used to store objects found by parser
14527: codebase: reference to hash used for codebases of java objects found by parser
14528: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14529: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14530: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14531: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14532: context: if 'overwrite', will move the uploaded file from its temporary location to
14533: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14534: mimetype: reference to scalar to accommodate mime type determined
14535: from File::MMagic if $parser = parse.
1.608 albertel 14536:
14537: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14538: and /adm/notfound.html if unsuccessful (or an error message if context
14539: was 'overwrite').
14540:
1.608 albertel 14541:
14542: =item *
14543:
14544: renameuserfile(): renames an existing userfile to a new name
14545:
14546: Args:
14547: docuname: username or courseid of destination for the file
14548: docudom: domain of user/course of destination for the file
14549: old: current file name (including any subdirs under userfiles)
14550: new: desired file name (including any subdirs under userfiles)
14551:
14552: =item *
14553:
14554: mkdiruserfile(): creates a directory is a userfiles dir
14555:
14556: Args:
14557: docuname: username or courseid of destination for the file
14558: docudom: domain of user/course of destination for the file
14559: dir: dir to create (including any subdirs under userfiles)
14560:
14561: =item *
14562:
14563: removeuserfile(): removes a file that exists in userfiles
14564:
14565: Args:
14566: docuname: username or courseid of destination for the file
14567: docudom: domain of user/course of destination for the file
14568: fname: filname to delete (including any subdirs under userfiles)
14569:
14570: =item *
14571:
14572: removeuploadedurl(): convience function for removeuserfile()
14573:
14574: Args:
14575: url: a full /uploaded/... url to delete
14576:
1.747 albertel 14577: =item *
14578:
14579: get_portfile_permissions():
14580: Args:
14581: domain: domain of user or course contain the portfolio files
14582: user: name of user or num of course contain the portfolio files
14583: Returns:
14584: hashref of a dump of the proper file_permissions.db
14585:
14586:
14587: =item *
14588:
14589: get_access_controls():
14590:
14591: Args:
14592: current_permissions: the hash ref returned from get_portfile_permissions()
14593: group: (optional) the group you want the files associated with
14594: file: (optional) the file you want access info on
14595:
14596: Returns:
1.749 raeburn 14597: a hash (keys are file names) of hashes containing
14598: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14599: values are XML containing access control settings (see below)
1.747 albertel 14600:
14601: Internal notes:
14602:
1.749 raeburn 14603: access controls are stored in file_permissions.db as key=value pairs.
14604: key -> path to file/file_name\0uniqueID:scope_end_start
14605: where scope -> public,guest,course,group,domains or users.
14606: end -> UNIX time for end of access (0 -> no end date)
14607: start -> UNIX time for start of access
14608:
14609: value -> XML description of access control
14610: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14611: <start></start>
14612: <end></end>
14613:
14614: <password></password> for scope type = guest
14615:
14616: <domain></domain> for scope type = course or group
14617: <number></number>
14618: <roles id="">
14619: <role></role>
14620: <access></access>
14621: <section></section>
14622: <group></group>
14623: </roles>
14624:
14625: <dom></dom> for scope type = domains
14626:
14627: <users> for scope type = users
14628: <user>
14629: <uname></uname>
14630: <udom></udom>
14631: </user>
14632: </users>
14633: </scope>
14634:
14635: Access data is also aggregated for each file in an additional key=value pair:
14636: key -> path to file/file_name\0accesscontrol
14637: value -> reference to hash
14638: hash contains key = value pairs
14639: where key = uniqueID:scope_end_start
14640: value = UNIX time record was last updated
14641:
14642: Used to improve speed of look-ups of access controls for each file.
14643:
14644: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14645:
1.1198 raeburn 14646: =item *
14647:
1.749 raeburn 14648: modify_access_controls():
14649:
14650: Modifies access controls for a portfolio file
14651: Args
14652: 1. file name
14653: 2. reference to hash of required changes,
14654: 3. domain
14655: 4. username
14656: where domain,username are the domain of the portfolio owner
14657: (either a user or a course)
14658:
14659: Returns:
14660: 1. result of additions or updates ('ok' or 'error', with error message).
14661: 2. result of deletions ('ok' or 'error', with error message).
14662: 3. reference to hash of any new or updated access controls.
14663: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14664: key = integer (inbound ID)
1.1198 raeburn 14665: value = uniqueID
14666:
14667: =item *
14668:
14669: get_timebased_id():
14670:
14671: Attempts to get a unique timestamp-based suffix for use with items added to a
14672: course via the Course Editor (e.g., folders, composite pages,
14673: group bulletin boards).
14674:
14675: Args: (first three required; six others optional)
14676:
14677: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14678: docssequence, or name of group
14679:
14680: 2. keyid (alphanumeric): name of temporary locking key in hash,
14681: e.g., num, boardids
14682:
14683: 3. namespace: name of gdbm file used to store suffixes already assigned;
14684: file will be named nohist_namespace.db
14685:
14686: 4. cdom: domain of course; default is current course domain from %env
14687:
14688: 5. cnum: course number; default is current course number from %env
14689:
14690: 6. idtype: set to concat if an additional digit is to be appended to the
14691: unix timestamp to form the suffix, if the plain timestamp is already
14692: in use. Default is to not do this, but simply increment the unix
14693: timestamp by 1 until a unique key is obtained.
14694:
14695: 7. who: holder of locking key; defaults to user:domain for user.
14696:
14697: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14698: retrying); default is 3.
14699:
14700: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14701:
14702: Returns:
14703:
14704: 1. suffix obtained (numeric)
14705:
14706: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14707:
14708: 3. error: contains (localized) error message if an error occurred.
14709:
1.747 albertel 14710:
1.608 albertel 14711: =back
14712:
1.243 albertel 14713: =head2 HTTP Helper Routines
14714:
14715: =over 4
14716:
1.191 harris41 14717: =item *
14718:
14719: escape() : unpack non-word characters into CGI-compatible hex codes
14720:
14721: =item *
14722:
14723: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14724:
1.243 albertel 14725: =back
14726:
14727: =head1 PRIVATE SUBROUTINES
14728:
14729: =head2 Underlying communication routines (Shouldn't call)
14730:
14731: =over 4
14732:
14733: =item *
14734:
14735: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14736:
14737: =item *
14738:
14739: reply() : uses subreply to send a message to remote machine, logs all failures
14740:
14741: =item *
14742:
14743: critical() : passes a critical message to another server; if cannot
14744: get through then place message in connection buffer directory and
14745: returns con_delayed, if incapable of saving message, returns
14746: con_failed
14747:
14748: =item *
14749:
14750: reconlonc() : tries to reconnect lonc client processes.
14751:
14752: =back
14753:
14754: =head2 Resource Access Logging
14755:
14756: =over 4
14757:
14758: =item *
14759:
14760: flushcourselogs() : flush (save) buffer logs and access logs
14761:
14762: =item *
14763:
14764: courselog($what) : save message for course in hash
14765:
14766: =item *
14767:
14768: courseacclog($what) : save message for course using &courselog(). Perform
14769: special processing for specific resource types (problems, exams, quizzes, etc).
14770:
1.191 harris41 14771: =item *
14772:
14773: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14774: as a PerlChildExitHandler
1.243 albertel 14775:
14776: =back
14777:
14778: =head2 Other
14779:
14780: =over 4
14781:
14782: =item *
14783:
14784: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14785:
14786: =back
14787:
14788: =cut
1.877 foxr 14789:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>