Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1288
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1288 ! damieng 4: # $Id: lonnet.pm,v 1.1287 2015/05/21 23:40:25 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1245 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.539 albertel 95: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1288 ! damieng 104: use Time::HiRes qw(sleep);
1.1117 foxr 105:
1.1090 raeburn 106: use File::Copy;
1.676 albertel 107:
1.195 www 108: my $readit;
1.1288 ! damieng 109: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 110:
1.619 albertel 111: require Exporter;
112:
113: our @ISA = qw (Exporter);
114: our @EXPORT = qw(%env);
115:
1.449 matthew 116:
1.1187 raeburn 117: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 118: {
119: my $logid;
1.1187 raeburn 120: sub write_log {
1.1188 raeburn 121: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 122: if ($context eq 'course') {
123: if (($cnum eq '') || ($cdom eq '')) {
124: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
125: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
126: }
1.957 raeburn 127: }
1.1184 raeburn 128: $logid ++;
1.957 raeburn 129: my $now = time();
130: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 131: my $logentry = {
132: $id => {
133: 'exe_uname' => $env{'user.name'},
134: 'exe_udom' => $env{'user.domain'},
135: 'exe_time' => $now,
136: 'exe_ip' => $ENV{'REMOTE_ADDR'},
137: 'delflag' => $delflag,
138: 'logentry' => $storehash,
139: 'uname' => $uname,
140: 'udom' => $udom,
141: }
142: };
143: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 144: }
145: }
1.1 albertel 146:
1.163 harris41 147: sub logtouch {
148: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 149: unless (-e "$execdir/logs/lonnet.log") {
150: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 151: close $fh;
152: }
153: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
154: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
155: }
156:
1.1 albertel 157: sub logthis {
158: my $message=shift;
159: my $execdir=$perlvar{'lonDaemons'};
160: my $now=time;
161: my $local=localtime($now);
1.448 albertel 162: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 163: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
164: print $fh $logstring;
1.448 albertel 165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
170: sub logperm {
171: my $message=shift;
172: my $execdir=$perlvar{'lonDaemons'};
173: my $now=time;
174: my $local=localtime($now);
1.448 albertel 175: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
176: print $fh "$now:$message:$local\n";
177: close($fh);
178: }
1.1 albertel 179: return 1;
180: }
181:
1.850 albertel 182: sub create_connection {
1.853 albertel 183: my ($hostname,$lonid) = @_;
1.851 albertel 184: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 185: Type => SOCK_STREAM,
186: Timeout => 10);
187: return 0 if (!$client);
1.890 albertel 188: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 189: my $result = <$client>;
190: chomp($result);
191: return 1 if ($result eq 'done');
192: return 0;
193: }
194:
1.983 raeburn 195: sub get_server_timezone {
196: my ($cnum,$cdom) = @_;
197: my $home=&homeserver($cnum,$cdom);
198: if ($home ne 'no_host') {
199: my $cachetime = 24*3600;
200: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
201: if (defined($cached)) {
202: return $timezone;
203: } else {
204: my $timezone = &reply('servertimezone',$home);
205: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
206: }
207: }
208: }
1.850 albertel 209:
1.1106 raeburn 210: sub get_server_distarch {
211: my ($lonhost,$ignore_cache) = @_;
212: if (defined($lonhost)) {
213: if (!defined(&hostname($lonhost))) {
214: return;
215: }
216: my $cachetime = 12*3600;
217: if (!$ignore_cache) {
218: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
219: if (defined($cached)) {
220: return $distarch;
221: }
222: }
223: my $rep = &reply('serverdistarch',$lonhost);
224: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
225: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
226: $rep eq '') {
227: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
228: }
229: }
230: return;
231: }
232:
1.993 raeburn 233: sub get_server_loncaparev {
1.1073 raeburn 234: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 235: if (defined($lonhost)) {
236: if (!defined(&hostname($lonhost))) {
237: undef($lonhost);
238: }
239: }
240: if (!defined($lonhost)) {
241: if (defined(&domain($dom,'primary'))) {
242: $lonhost=&domain($dom,'primary');
243: if ($lonhost eq 'no_host') {
244: undef($lonhost);
245: }
246: }
247: }
248: if (defined($lonhost)) {
1.1073 raeburn 249: my $cachetime = 12*3600;
250: if (!$ignore_cache) {
251: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
252: if (defined($cached)) {
253: return $loncaparev;
254: }
255: }
256: my ($answer,$loncaparev);
257: my @ids=¤t_machine_ids();
258: if (grep(/^\Q$lonhost\E$/,@ids)) {
259: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 260: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 261: $loncaparev = $1;
262: }
263: } else {
264: $answer = &reply('serverloncaparev',$lonhost);
265: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
266: if ($caller eq 'loncron') {
267: my $ua=new LWP::UserAgent;
1.1082 raeburn 268: $ua->timeout(4);
1.1073 raeburn 269: my $protocol = $protocol{$lonhost};
270: $protocol = 'http' if ($protocol ne 'https');
271: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
272: my $request=new HTTP::Request('GET',$url);
273: my $response=$ua->request($request);
274: unless ($response->is_error()) {
275: my $content = $response->content;
1.1081 raeburn 276: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 277: $loncaparev = $1;
278: }
279: }
280: } else {
281: $loncaparev = $loncaparevs{$lonhost};
282: }
1.1081 raeburn 283: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 284: $loncaparev = $1;
285: }
1.993 raeburn 286: }
1.1073 raeburn 287: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 288: }
289: }
290:
1.1074 raeburn 291: sub get_server_homeID {
292: my ($hostname,$ignore_cache,$caller) = @_;
293: unless ($ignore_cache) {
294: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
295: if (defined($cached)) {
296: return $serverhomeID;
297: }
298: }
299: my $cachetime = 12*3600;
300: my $serverhomeID;
301: if ($caller eq 'loncron') {
302: my @machine_ids = &machine_ids($hostname);
303: foreach my $id (@machine_ids) {
304: my $response = &reply('serverhomeID',$id);
305: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
306: $serverhomeID = $response;
307: last;
308: }
309: }
310: if ($serverhomeID eq '') {
311: $serverhomeID = $machine_ids[-1];
312: }
313: } else {
314: $serverhomeID = $serverhomeIDs{$hostname};
315: }
316: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
317: }
318:
1.1121 raeburn 319: sub get_remote_globals {
320: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 321: my ($result,%returnhash,%whatneeded);
322: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 323: foreach my $what (sort(keys(%{$whathash}))) {
324: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 325: my ($response,$cached);
1.1121 raeburn 326: unless ($ignore_cache) {
1.1125 raeburn 327: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 328: }
329: if (defined($cached)) {
1.1125 raeburn 330: $returnhash{$what} = $response;
1.1121 raeburn 331: } else {
1.1125 raeburn 332: $whatneeded{$what} = 1;
1.1121 raeburn 333: }
334: }
1.1125 raeburn 335: if (keys(%whatneeded) == 0) {
336: $result = 'ok';
337: } else {
1.1121 raeburn 338: my $requested = &freeze_escape(\%whatneeded);
339: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 340: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
341: ($rep eq 'unknown_cmd')) {
342: $result = $rep;
343: } else {
344: $result = 'ok';
1.1121 raeburn 345: my @pairs=split(/\&/,$rep);
1.1125 raeburn 346: foreach my $item (@pairs) {
347: my ($key,$value)=split(/=/,$item,2);
348: my $what = &unescape($key);
349: my $hashid = $lonhost.'-'.$what;
350: $returnhash{$what}=&thaw_unescape($value);
351: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 352: }
353: }
354: }
355: }
1.1125 raeburn 356: return ($result,\%returnhash);
1.1121 raeburn 357: }
358:
1.1124 raeburn 359: sub remote_devalidate_cache {
1.1241 raeburn 360: my ($lonhost,$cachekeys) = @_;
361: my $items;
362: return unless (ref($cachekeys) eq 'ARRAY');
363: my $cachestr = join('&',@{$cachekeys});
364: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 365: return $response;
366: }
367:
1.1 albertel 368: # -------------------------------------------------- Non-critical communication
369: sub subreply {
370: my ($cmd,$server)=@_;
1.838 albertel 371: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 372: #
373: # With loncnew process trimming, there's a timing hole between lonc server
374: # process exit and the master server picking up the listen on the AF_UNIX
375: # socket. In that time interval, a lock file will exist:
376:
377: my $lockfile=$peerfile.".lock";
378: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1288 ! damieng 379: Time::HiRes::sleep(0.1);
1.549 foxr 380: }
381: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 382: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 383: #
1.550 foxr 384: # We'll give the connection a few tries before abandoning it. If
385: # connection is not possible, we'll con_lost back to the client.
386: #
387: my $client;
388: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
389: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
390: Type => SOCK_STREAM,
391: Timeout => 10);
1.869 albertel 392: if ($client) {
1.550 foxr 393: last; # Connected!
1.850 albertel 394: } else {
1.853 albertel 395: &create_connection(&hostname($server),$server);
1.550 foxr 396: }
1.1288 ! damieng 397: Time::HiRes::sleep(0.1); # Try again later if failed connection.
1.550 foxr 398: }
399: my $answer;
400: if ($client) {
1.704 albertel 401: print $client "sethost:$server:$cmd\n";
1.550 foxr 402: $answer=<$client>;
403: if (!$answer) { $answer="con_lost"; }
404: chomp($answer);
405: } else {
406: $answer = 'con_lost'; # Failed connection.
407: }
1.1 albertel 408: return $answer;
409: }
410:
411: sub reply {
412: my ($cmd,$server)=@_;
1.838 albertel 413: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 414: my $answer=subreply($cmd,$server);
1.65 www 415: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 416: &logthis("<font color=\"blue\">WARNING:".
1.12 www 417: " $cmd to $server returned $answer</font>");
418: }
1.1 albertel 419: return $answer;
420: }
421:
422: # ----------------------------------------------------------- Send USR1 to lonc
423:
424: sub reconlonc {
1.891 albertel 425: my ($lonid) = @_;
426: my $hostname = &hostname($lonid);
427: if ($lonid) {
428: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
429: if ($hostname && -e $peerfile) {
430: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
431: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
432: Type => SOCK_STREAM,
433: Timeout => 10);
434: if ($client) {
435: print $client ("reset_retries\n");
436: my $answer=<$client>;
437: #reset just this one.
438: }
439: }
440: return;
441: }
442:
1.836 www 443: &logthis("Trying to reconnect lonc");
1.1 albertel 444: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 445: if (open(my $fh,"<$loncfile")) {
1.1 albertel 446: my $loncpid=<$fh>;
447: chomp($loncpid);
448: if (kill 0 => $loncpid) {
449: &logthis("lonc at pid $loncpid responding, sending USR1");
450: kill USR1 => $loncpid;
451: sleep 1;
1.836 www 452: } else {
1.12 www 453: &logthis(
1.672 albertel 454: "<font color=\"blue\">WARNING:".
1.12 www 455: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 456: }
457: } else {
1.836 www 458: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 459: }
460: }
461:
462: # ------------------------------------------------------ Critical communication
1.12 www 463:
1.1 albertel 464: sub critical {
465: my ($cmd,$server)=@_;
1.838 albertel 466: unless (&hostname($server)) {
1.672 albertel 467: &logthis("<font color=\"blue\">WARNING:".
1.89 www 468: " Critical message to unknown server ($server)</font>");
469: return 'no_such_host';
470: }
1.1 albertel 471: my $answer=reply($cmd,$server);
472: if ($answer eq 'con_lost') {
473: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 474: my $answer=reply($cmd,$server);
1.1 albertel 475: if ($answer eq 'con_lost') {
476: my $now=time;
477: my $middlename=$cmd;
1.5 www 478: $middlename=substr($middlename,0,16);
1.1 albertel 479: $middlename=~s/\W//g;
480: my $dfilename=
1.305 www 481: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
482: $dumpcount++;
1.1 albertel 483: {
1.448 albertel 484: my $dfh;
485: if (open($dfh,">$dfilename")) {
486: print $dfh "$cmd\n";
487: close($dfh);
488: }
1.1 albertel 489: }
1.1288 ! damieng 490: sleep 1;
1.1 albertel 491: my $wcmd='';
492: {
1.448 albertel 493: my $dfh;
494: if (open($dfh,"<$dfilename")) {
495: $wcmd=<$dfh>;
496: close($dfh);
497: }
1.1 albertel 498: }
499: chomp($wcmd);
1.7 www 500: if ($wcmd eq $cmd) {
1.672 albertel 501: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 502: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 503: &logperm("D:$server:$cmd");
504: return 'con_delayed';
505: } else {
1.672 albertel 506: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 507: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 508: &logperm("F:$server:$cmd");
509: return 'con_failed';
510: }
511: }
512: }
513: return $answer;
1.405 albertel 514: }
515:
1.755 albertel 516: # ------------------------------------------- check if return value is an error
517:
518: sub error {
519: my ($result) = @_;
1.756 albertel 520: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 521: if ($2 == 2) { return undef; }
522: return $1;
523: }
524: return undef;
525: }
526:
1.783 albertel 527: sub convert_and_load_session_env {
528: my ($lonidsdir,$handle)=@_;
529: my @profile;
530: {
1.917 albertel 531: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
532: if (!$opened) {
1.915 albertel 533: return 0;
534: }
1.783 albertel 535: flock($idf,LOCK_SH);
536: @profile=<$idf>;
537: close($idf);
538: }
539: my %temp_env;
540: foreach my $line (@profile) {
1.786 albertel 541: if ($line !~ m/=/) {
542: return 0;
543: }
1.783 albertel 544: chomp($line);
545: my ($envname,$envvalue)=split(/=/,$line,2);
546: $temp_env{&unescape($envname)} = &unescape($envvalue);
547: }
548: unlink("$lonidsdir/$handle.id");
549: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
550: 0640)) {
551: %disk_env = %temp_env;
552: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
553: untie(%disk_env);
554: }
1.786 albertel 555: return 1;
1.783 albertel 556: }
557:
1.374 www 558: # ------------------------------------------- Transfer profile into environment
1.780 albertel 559: my $env_loaded;
560: sub transfer_profile_to_env {
1.788 albertel 561: my ($lonidsdir,$handle,$force_transfer) = @_;
562: if (!$force_transfer && $env_loaded) { return; }
1.374 www 563:
1.720 albertel 564: if (!defined($lonidsdir)) {
565: $lonidsdir = $perlvar{'lonIDsDir'};
566: }
567: if (!defined($handle)) {
568: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
569: }
570:
1.786 albertel 571: my $convert;
572: {
1.917 albertel 573: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
574: if (!$opened) {
1.915 albertel 575: return;
576: }
1.786 albertel 577: flock($idf,LOCK_SH);
578: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
579: &GDBM_READER(),0640)) {
580: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
581: untie(%disk_env);
582: } else {
583: $convert = 1;
584: }
585: }
586: if ($convert) {
587: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
588: &logthis("Failed to load session, or convert session.");
589: }
1.374 www 590: }
1.783 albertel 591:
1.786 albertel 592: my %remove;
1.783 albertel 593: while ( my $envname = each(%env) ) {
1.433 matthew 594: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
595: if ($time < time-300) {
1.783 albertel 596: $remove{$key}++;
1.433 matthew 597: }
598: }
599: }
1.783 albertel 600:
1.619 albertel 601: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 602: $env_loaded=1;
1.783 albertel 603: foreach my $expired_key (keys(%remove)) {
1.433 matthew 604: &delenv($expired_key);
1.374 www 605: }
1.1 albertel 606: }
607:
1.916 albertel 608: # ---------------------------------------------------- Check for valid session
609: sub check_for_valid_session {
1.1245 raeburn 610: my ($r,$name,$userhashref) = @_;
1.916 albertel 611: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 612: if ($name eq '') {
613: $name = 'lonID';
614: }
615: my $lonid=$cookies{$name};
1.916 albertel 616: return undef if (!$lonid);
617:
618: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 619: my $lonidsdir;
620: if ($name eq 'lonDAV') {
621: $lonidsdir=$r->dir_config('lonDAVsessDir');
622: } else {
623: $lonidsdir=$r->dir_config('lonIDsDir');
624: }
1.916 albertel 625: return undef if (!-e "$lonidsdir/$handle.id");
626:
1.917 albertel 627: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
628: return undef if (!$opened);
1.916 albertel 629:
630: flock($idf,LOCK_SH);
631: my %disk_env;
632: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
633: &GDBM_READER(),0640)) {
634: return undef;
635: }
636:
637: if (!defined($disk_env{'user.name'})
638: || !defined($disk_env{'user.domain'})) {
639: return undef;
640: }
1.1245 raeburn 641:
642: if (ref($userhashref) eq 'HASH') {
643: $userhashref->{'name'} = $disk_env{'user.name'};
644: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 645: }
1.1245 raeburn 646:
1.916 albertel 647: return $handle;
648: }
649:
1.830 albertel 650: sub timed_flock {
651: my ($file,$lock_type) = @_;
652: my $failed=0;
653: eval {
654: local $SIG{__DIE__}='DEFAULT';
655: local $SIG{ALRM}=sub {
656: $failed=1;
657: die("failed lock");
658: };
659: alarm(13);
660: flock($file,$lock_type);
661: alarm(0);
662: };
663: if ($failed) {
664: return undef;
665: } else {
666: return 1;
667: }
668: }
669:
1.5 www 670: # ---------------------------------------------------------- Append Environment
671:
672: sub appenv {
1.949 raeburn 673: my ($newenv,$roles) = @_;
674: if (ref($newenv) eq 'HASH') {
675: foreach my $key (keys(%{$newenv})) {
676: my $refused = 0;
677: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
678: $refused = 1;
679: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 680: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 681: if (grep(/^\Q$role\E$/,@{$roles})) {
682: $refused = 0;
683: }
684: }
685: }
686: if ($refused) {
687: &logthis("<font color=\"blue\">WARNING: ".
688: "Attempt to modify environment ".$key." to ".$newenv->{$key}
689: .'</font>');
690: delete($newenv->{$key});
691: } else {
692: $env{$key}=$newenv->{$key};
693: }
694: }
695: my $opened = open(my $env_file,'+<',$env{'user.environment'});
696: if ($opened
697: && &timed_flock($env_file,LOCK_EX)
698: &&
699: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
700: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
701: while (my ($key,$value) = each(%{$newenv})) {
702: $disk_env{$key} = $value;
703: }
704: untie(%disk_env);
1.35 www 705: }
1.191 harris41 706: }
1.56 www 707: return 'ok';
708: }
709: # ----------------------------------------------------- Delete from Environment
710:
711: sub delenv {
1.1104 raeburn 712: my ($delthis,$regexp,$roles) = @_;
713: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
714: my $refused = 1;
715: if (ref($roles) eq 'ARRAY') {
716: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
717: if (grep(/^\Q$role\E$/,@{$roles})) {
718: $refused = 0;
719: }
720: }
721: if ($refused) {
722: &logthis("<font color=\"blue\">WARNING: ".
723: "Attempt to delete from environment ".$delthis);
724: return 'error';
725: }
1.56 www 726: }
1.917 albertel 727: my $opened = open(my $env_file,'+<',$env{'user.environment'});
728: if ($opened
1.915 albertel 729: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 730: &&
731: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
732: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 733: foreach my $key (keys(%disk_env)) {
1.987 raeburn 734: if ($regexp) {
735: if ($key=~/^$delthis/) {
736: delete($env{$key});
737: delete($disk_env{$key});
738: }
739: } else {
740: if ($key=~/^\Q$delthis\E/) {
741: delete($env{$key});
742: delete($disk_env{$key});
743: }
744: }
1.448 albertel 745: }
1.783 albertel 746: untie(%disk_env);
1.5 www 747: }
748: return 'ok';
1.369 albertel 749: }
750:
1.790 albertel 751: sub get_env_multiple {
752: my ($name) = @_;
753: my @values;
754: if (defined($env{$name})) {
755: # exists is it an array
756: if (ref($env{$name})) {
757: @values=@{ $env{$name} };
758: } else {
759: $values[0]=$env{$name};
760: }
761: }
762: return(@values);
763: }
764:
1.958 www 765: # ------------------------------------------------------------------- Locking
766:
767: sub set_lock {
768: my ($text)=@_;
769: $locknum++;
770: my $id=$$.'-'.$locknum;
771: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
772: 'session.lock.'.$id => $text});
773: return $id;
774: }
775:
776: sub get_locks {
777: my $num=0;
778: my %texts=();
779: foreach my $lock (split(/\,/,$env{'session.locks'})) {
780: if ($lock=~/\w/) {
781: $num++;
782: $texts{$lock}=$env{'session.lock.'.$lock};
783: }
784: }
785: return ($num,%texts);
786: }
787:
788: sub remove_lock {
789: my ($id)=@_;
790: my $newlocks='';
791: foreach my $lock (split(/\,/,$env{'session.locks'})) {
792: if (($lock=~/\w/) && ($lock ne $id)) {
793: $newlocks.=','.$lock;
794: }
795: }
796: &appenv({'session.locks' => $newlocks});
797: &delenv('session.lock.'.$id);
798: }
799:
800: sub remove_all_locks {
801: my $activelocks=$env{'session.locks'};
802: foreach my $lock (split(/\,/,$env{'session.locks'})) {
803: if ($lock=~/\w/) {
804: &remove_lock($lock);
805: }
806: }
807: }
808:
809:
1.369 albertel 810: # ------------------------------------------ Find out current server userload
811: sub userload {
812: my $numusers=0;
813: {
814: opendir(LONIDS,$perlvar{'lonIDsDir'});
815: my $filename;
816: my $curtime=time;
817: while ($filename=readdir(LONIDS)) {
1.925 albertel 818: next if ($filename eq '.' || $filename eq '..');
819: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 820: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 821: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 822: }
823: closedir(LONIDS);
824: }
825: my $userloadpercent=0;
826: my $maxuserload=$perlvar{'lonUserLoadLim'};
827: if ($maxuserload) {
1.371 albertel 828: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 829: }
1.372 albertel 830: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 831: return $userloadpercent;
1.283 www 832: }
833:
1.1 albertel 834: # ------------------------------ Find server with least workload from spare.tab
1.11 www 835:
1.1 albertel 836: sub spareserver {
1.1083 raeburn 837: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 838: my $spare_server;
1.370 albertel 839: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 840: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
841: : $userloadpercent;
1.1083 raeburn 842: my ($uint_dom,$remotesessions);
843: if (($udom ne '') && (&domain($udom) ne '')) {
844: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
845: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
846: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
847: $remotesessions = $udomdefaults{'remotesessions'};
848: }
1.1123 raeburn 849: my $spareshash = &this_host_spares($udom);
850: if (ref($spareshash) eq 'HASH') {
851: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
852: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 853: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
854: $try_server));
1.1123 raeburn 855: ($spare_server, $lowest_load) =
856: &compare_server_load($try_server, $spare_server, $lowest_load);
857: }
1.1083 raeburn 858: }
1.784 albertel 859:
1.1123 raeburn 860: my $found_server = ($spare_server ne '' && $lowest_load < 100);
861:
862: if (!$found_server) {
863: if (ref($spareshash->{'default'}) eq 'ARRAY') {
864: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 865: next unless (&spare_can_host($udom,$uint_dom,
866: $remotesessions,$try_server));
1.1123 raeburn 867: ($spare_server, $lowest_load) =
868: &compare_server_load($try_server, $spare_server, $lowest_load);
869: }
870: }
871: }
1.784 albertel 872: }
873:
874: if (!$want_server_name) {
1.968 raeburn 875: my $protocol = 'http';
876: if ($protocol{$spare_server} eq 'https') {
877: $protocol = $protocol{$spare_server};
878: }
1.1001 raeburn 879: if (defined($spare_server)) {
880: my $hostname = &hostname($spare_server);
1.1083 raeburn 881: if (defined($hostname)) {
1.1001 raeburn 882: $spare_server = $protocol.'://'.$hostname;
883: }
884: }
1.784 albertel 885: }
886: return $spare_server;
887: }
888:
889: sub compare_server_load {
1.1253 raeburn 890: my ($try_server, $spare_server, $lowest_load, $required) = @_;
891:
892: if ($required) {
893: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
894: my $remoterev = &get_server_loncaparev(undef,$try_server);
895: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
896: if (($major eq '' && $minor eq '') ||
897: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
898: return ($spare_server,$lowest_load);
899: }
900: }
1.784 albertel 901:
902: my $loadans = &reply('load', $try_server);
903: my $userloadans = &reply('userload',$try_server);
904:
905: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 906: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 907: }
908:
909: my $load;
910: if ($loadans =~ /\d/) {
911: if ($userloadans =~ /\d/) {
912: #both are numbers, pick the bigger one
913: $load = ($loadans > $userloadans) ? $loadans
914: : $userloadans;
1.411 albertel 915: } else {
1.784 albertel 916: $load = $loadans;
1.411 albertel 917: }
1.784 albertel 918: } else {
919: $load = $userloadans;
920: }
921:
922: if (($load =~ /\d/) && ($load < $lowest_load)) {
923: $spare_server = $try_server;
924: $lowest_load = $load;
1.370 albertel 925: }
1.784 albertel 926: return ($spare_server,$lowest_load);
1.202 matthew 927: }
1.914 albertel 928:
929: # --------------------------- ask offload servers if user already has a session
930: sub find_existing_session {
931: my ($udom,$uname) = @_;
1.1123 raeburn 932: my $spareshash = &this_host_spares($udom);
933: if (ref($spareshash) eq 'HASH') {
934: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
935: foreach my $try_server (@{ $spareshash->{'primary'} }) {
936: return $try_server if (&has_user_session($try_server, $udom, $uname));
937: }
938: }
939: if (ref($spareshash->{'default'}) eq 'ARRAY') {
940: foreach my $try_server (@{ $spareshash->{'default'} }) {
941: return $try_server if (&has_user_session($try_server, $udom, $uname));
942: }
943: }
1.914 albertel 944: }
945: return;
946: }
947:
948: # -------------------------------- ask if server already has a session for user
949: sub has_user_session {
950: my ($lonid,$udom,$uname) = @_;
951: my $result = &reply(join(':','userhassession',
952: map {&escape($_)} ($udom,$uname)),$lonid);
953: return 1 if ($result eq 'ok');
954:
955: return 0;
956: }
957:
1.1076 raeburn 958: # --------- determine least loaded server in a user's domain which allows login
959:
960: sub choose_server {
1.1259 raeburn 961: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 962: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 963: my %servers = &get_servers($udom);
1.1076 raeburn 964: my $lowest_load = 30000;
1.1259 raeburn 965: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
966: if ($skiploadbal) {
967: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
968: unless (defined($cached)) {
969: my $cachetime = 60*60*24;
970: my %domconfig =
971: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
972: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
973: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
974: $cachetime);
975: }
976: }
977: }
1.1076 raeburn 978: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 979: if ($skiploadbal) {
980: if (ref($balancers) eq 'HASH') {
981: next if (exists($balancers->{$lonhost}));
982: }
983: }
1.1115 raeburn 984: my $loginvia;
985: if ($checkloginvia) {
986: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 987: if ($loginvia) {
988: my ($server,$path) = split(/:/,$loginvia);
989: ($login_host, $lowest_load) =
1.1253 raeburn 990: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 991: if ($login_host eq $server) {
992: $portal_path = $path;
1.1151 raeburn 993: $isredirect = 1;
1.1116 raeburn 994: }
995: } else {
996: ($login_host, $lowest_load) =
1.1253 raeburn 997: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 998: if ($login_host eq $lonhost) {
999: $portal_path = '';
1.1151 raeburn 1000: $isredirect = '';
1.1116 raeburn 1001: }
1002: }
1003: } else {
1.1076 raeburn 1004: ($login_host, $lowest_load) =
1.1253 raeburn 1005: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1006: }
1007: }
1008: if ($login_host ne '') {
1.1116 raeburn 1009: $hostname = &hostname($login_host);
1.1076 raeburn 1010: }
1.1151 raeburn 1011: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1012: }
1013:
1.202 matthew 1014: # --------------------------------------------- Try to change a user's password
1015:
1016: sub changepass {
1.799 raeburn 1017: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1018: $currentpass = &escape($currentpass);
1019: $newpass = &escape($newpass);
1.1030 raeburn 1020: my $lonhost = $perlvar{'lonHostID'};
1021: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1022: $server);
1023: if (! $answer) {
1024: &logthis("No reply on password change request to $server ".
1025: "by $uname in domain $udom.");
1026: } elsif ($answer =~ "^ok") {
1027: &logthis("$uname in $udom successfully changed their password ".
1028: "on $server.");
1029: } elsif ($answer =~ "^pwchange_failure") {
1030: &logthis("$uname in $udom was unable to change their password ".
1031: "on $server. The action was blocked by either lcpasswd ".
1032: "or pwchange");
1033: } elsif ($answer =~ "^non_authorized") {
1034: &logthis("$uname in $udom did not get their password correct when ".
1035: "attempting to change it on $server.");
1036: } elsif ($answer =~ "^auth_mode_error") {
1037: &logthis("$uname in $udom attempted to change their password despite ".
1038: "not being locally or internally authenticated on $server.");
1039: } elsif ($answer =~ "^unknown_user") {
1040: &logthis("$uname in $udom attempted to change their password ".
1041: "on $server but were unable to because $server is not ".
1042: "their home server.");
1043: } elsif ($answer =~ "^refused") {
1044: &logthis("$server refused to change $uname in $udom password because ".
1045: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1046: } elsif ($answer =~ "invalid_client") {
1047: &logthis("$server refused to change $uname in $udom password because ".
1048: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1049: }
1050: return $answer;
1.1 albertel 1051: }
1052:
1.169 harris41 1053: # ----------------------- Try to determine user's current authentication scheme
1054:
1055: sub queryauthenticate {
1056: my ($uname,$udom)=@_;
1.456 albertel 1057: my $uhome=&homeserver($uname,$udom);
1058: if (!$uhome) {
1059: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1060: return 'no_host';
1061: }
1062: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1063: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1064: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1065: }
1.456 albertel 1066: return $answer;
1.169 harris41 1067: }
1068:
1.1 albertel 1069: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1070:
1.1 albertel 1071: sub authenticate {
1.1073 raeburn 1072: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1073: $upass=&escape($upass);
1074: $uname= &LONCAPA::clean_username($uname);
1.836 www 1075: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1076: my $newhome;
1.836 www 1077: if ((!$uhome) || ($uhome eq 'no_host')) {
1078: # Maybe the machine was offline and only re-appeared again recently?
1079: &reconlonc();
1080: # One more
1.952 raeburn 1081: $uhome=&homeserver($uname,$udom,1);
1082: if (($uhome eq 'no_host') && $checkdefauth) {
1083: if (defined(&domain($udom,'primary'))) {
1084: $newhome=&domain($udom,'primary');
1085: }
1086: if ($newhome ne '') {
1087: $uhome = $newhome;
1088: }
1089: }
1.836 www 1090: if ((!$uhome) || ($uhome eq 'no_host')) {
1091: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1092: return 'no_host';
1093: }
1.1 albertel 1094: }
1.1073 raeburn 1095: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1096: if ($answer eq 'authorized') {
1.952 raeburn 1097: if ($newhome) {
1098: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1099: return 'no_account_on_host';
1100: } else {
1101: &logthis("User $uname at $udom authorized by $uhome");
1102: return $uhome;
1103: }
1.471 albertel 1104: }
1105: if ($answer eq 'non_authorized') {
1106: &logthis("User $uname at $udom rejected by $uhome");
1107: return 'no_host';
1.9 www 1108: }
1.471 albertel 1109: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1110: return 'no_host';
1111: }
1112:
1.1073 raeburn 1113: sub can_host_session {
1.1074 raeburn 1114: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1115: my $canhost = 1;
1.1074 raeburn 1116: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1117: if (ref($remotesessions) eq 'HASH') {
1118: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1119: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1120: $canhost = 0;
1121: } else {
1122: $canhost = 1;
1123: }
1124: }
1125: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1126: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1127: $canhost = 1;
1128: } else {
1129: $canhost = 0;
1130: }
1131: }
1132: if ($canhost) {
1133: if ($remotesessions->{'version'} ne '') {
1134: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1135: if ($reqmajor ne '' && $reqminor ne '') {
1136: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1137: my $major = $1;
1138: my $minor = $2;
1139: if (($major < $reqmajor ) ||
1140: (($major == $reqmajor) && ($minor < $reqminor))) {
1141: $canhost = 0;
1142: }
1143: } else {
1144: $canhost = 0;
1145: }
1146: }
1147: }
1148: }
1149: }
1150: if ($canhost) {
1151: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1152: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1153: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1154: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1155: if (($uint_dom ne '') &&
1156: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1157: $canhost = 0;
1158: } else {
1159: $canhost = 1;
1160: }
1161: }
1162: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1163: if (($uint_dom ne '') &&
1164: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1165: $canhost = 1;
1166: } else {
1167: $canhost = 0;
1168: }
1169: }
1170: }
1171: }
1172: return $canhost;
1173: }
1174:
1.1083 raeburn 1175: sub spare_can_host {
1176: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1177: my $canhost=1;
1.1279 raeburn 1178: my $try_server_hostname = &hostname($try_server);
1179: my $serverhomeID = &get_server_homeID($try_server_hostname);
1180: my $serverhomedom = &host_domain($serverhomeID);
1181: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1182: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1183: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1184: $canhost = 0;
1185: }
1186: }
1187: if (($canhost) && ($uint_dom)) {
1188: my @intdoms;
1189: my $internet_names = &get_internet_names($try_server);
1190: if (ref($internet_names) eq 'ARRAY') {
1191: @intdoms = @{$internet_names};
1192: }
1193: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1194: my $remoterev = &get_server_loncaparev(undef,$try_server);
1195: $canhost = &can_host_session($udom,$try_server,$remoterev,
1196: $remotesessions,
1197: $defdomdefaults{'hostedsessions'});
1198: }
1.1083 raeburn 1199: }
1200: return $canhost;
1201: }
1202:
1.1123 raeburn 1203: sub this_host_spares {
1204: my ($dom) = @_;
1.1126 raeburn 1205: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1206: my @hosts = ¤t_machine_ids();
1207: foreach my $lonhost (@hosts) {
1208: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1209: $dom_in_use = $dom;
1210: $lonhost_in_use = $lonhost;
1.1123 raeburn 1211: last;
1212: }
1213: }
1.1126 raeburn 1214: if ($dom_in_use ne '') {
1215: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1216: }
1217: if (ref($result) ne 'HASH') {
1218: $lonhost_in_use = $perlvar{'lonHostID'};
1219: $dom_in_use = &host_domain($lonhost_in_use);
1220: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1221: if (ref($result) ne 'HASH') {
1222: $result = \%spareid;
1223: }
1224: }
1225: return $result;
1226: }
1227:
1228: sub spares_for_offload {
1229: my ($dom_in_use,$lonhost_in_use) = @_;
1230: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1231: if (defined($cached)) {
1232: return $result;
1233: } else {
1.1126 raeburn 1234: my $cachetime = 60*60*24;
1235: my %domconfig =
1236: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1237: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1238: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1239: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1240: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1241: }
1242: }
1243: }
1244: }
1.1126 raeburn 1245: return;
1.1123 raeburn 1246: }
1247:
1.1129 raeburn 1248: sub get_lonbalancer_config {
1249: my ($servers) = @_;
1250: my ($currbalancer,$currtargets);
1251: if (ref($servers) eq 'HASH') {
1252: foreach my $server (keys(%{$servers})) {
1253: my %what = (
1254: spareid => 1,
1255: perlvar => 1,
1256: );
1257: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1258: if ($result eq 'ok') {
1259: if (ref($returnhash) eq 'HASH') {
1260: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1261: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1262: $currbalancer = $server;
1263: $currtargets = {};
1264: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1265: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1266: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1267: }
1268: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1269: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1270: }
1271: }
1272: last;
1273: }
1274: }
1275: }
1276: }
1277: }
1278: }
1279: return ($currbalancer,$currtargets);
1280: }
1281:
1282: sub check_loadbalancing {
1283: my ($uname,$udom) = @_;
1.1191 raeburn 1284: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1285: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1286: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1287: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1288: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1289: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1290: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1291: my $serverhomedom = &host_domain($lonhost);
1292:
1293: my $cachetime = 60*60*24;
1294:
1295: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1296: $dom_in_use = $udom;
1297: $homeintdom = 1;
1298: } else {
1299: $dom_in_use = $serverhomedom;
1300: }
1301: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1302: unless (defined($cached)) {
1303: my %domconfig =
1304: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1305: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1306: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1307: }
1308: }
1309: if (ref($result) eq 'HASH') {
1.1191 raeburn 1310: ($is_balancer,$currtargets,$currrules) =
1311: &check_balancer_result($result,@hosts);
1.1129 raeburn 1312: if ($is_balancer) {
1313: if (ref($currrules) eq 'HASH') {
1314: if ($homeintdom) {
1315: if ($uname ne '') {
1316: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1317: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1318: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1319: $rule_in_effect = $currrules->{'_LC_author'};
1320: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1321: $rule_in_effect = $currrules->{'_LC_adv'}
1322: }
1323: }
1324: if ($rule_in_effect eq '') {
1325: my %userenv = &userenvironment($udom,$uname,'inststatus');
1326: if ($userenv{'inststatus'} ne '') {
1327: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1328: my ($othertitle,$usertypes,$types) =
1329: &Apache::loncommon::sorted_inst_types($udom);
1330: if (ref($types) eq 'ARRAY') {
1331: foreach my $type (@{$types}) {
1332: if (grep(/^\Q$type\E$/,@statuses)) {
1333: if (exists($currrules->{$type})) {
1334: $rule_in_effect = $currrules->{$type};
1335: }
1336: }
1337: }
1338: }
1339: } else {
1340: if (exists($currrules->{'default'})) {
1341: $rule_in_effect = $currrules->{'default'};
1342: }
1343: }
1344: }
1345: } else {
1346: if (exists($currrules->{'default'})) {
1347: $rule_in_effect = $currrules->{'default'};
1348: }
1349: }
1350: } else {
1351: if ($currrules->{'_LC_external'} ne '') {
1352: $rule_in_effect = $currrules->{'_LC_external'};
1353: }
1354: }
1355: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1356: $uname,$udom);
1357: }
1358: }
1359: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1360: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1361: unless (defined($cached)) {
1362: my %domconfig =
1363: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1364: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1365: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1366: }
1367: }
1368: if (ref($result) eq 'HASH') {
1.1191 raeburn 1369: ($is_balancer,$currtargets,$currrules) =
1370: &check_balancer_result($result,@hosts);
1371: if ($is_balancer) {
1.1129 raeburn 1372: if (ref($currrules) eq 'HASH') {
1373: if ($currrules->{'_LC_internetdom'} ne '') {
1374: $rule_in_effect = $currrules->{'_LC_internetdom'};
1375: }
1376: }
1377: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1378: $uname,$udom);
1379: }
1380: } else {
1381: if ($perlvar{'lonBalancer'} eq 'yes') {
1382: $is_balancer = 1;
1383: $offloadto = &this_host_spares($dom_in_use);
1384: }
1385: }
1386: } else {
1387: if ($perlvar{'lonBalancer'} eq 'yes') {
1388: $is_balancer = 1;
1389: $offloadto = &this_host_spares($dom_in_use);
1390: }
1391: }
1.1176 raeburn 1392: if ($is_balancer) {
1393: my $lowest_load = 30000;
1394: if (ref($offloadto) eq 'HASH') {
1395: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1396: foreach my $try_server (@{$offloadto->{'primary'}}) {
1397: ($otherserver,$lowest_load) =
1398: &compare_server_load($try_server,$otherserver,$lowest_load);
1399: }
1.1129 raeburn 1400: }
1.1176 raeburn 1401: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1402:
1.1176 raeburn 1403: if (!$found_server) {
1404: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1405: foreach my $try_server (@{$offloadto->{'default'}}) {
1406: ($otherserver,$lowest_load) =
1407: &compare_server_load($try_server,$otherserver,$lowest_load);
1408: }
1409: }
1410: }
1411: } elsif (ref($offloadto) eq 'ARRAY') {
1412: if (@{$offloadto} == 1) {
1413: $otherserver = $offloadto->[0];
1414: } elsif (@{$offloadto} > 1) {
1415: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1416: ($otherserver,$lowest_load) =
1417: &compare_server_load($try_server,$otherserver,$lowest_load);
1418: }
1419: }
1420: }
1.1176 raeburn 1421: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1422: $is_balancer = 0;
1423: if ($uname ne '' && $udom ne '') {
1424: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1425:
1426: &appenv({'user.loadbalexempt' => $lonhost,
1427: 'user.loadbalcheck.time' => time});
1428: }
1.1129 raeburn 1429: }
1430: }
1431: }
1432: return ($is_balancer,$otherserver);
1433: }
1434:
1.1191 raeburn 1435: sub check_balancer_result {
1436: my ($result,@hosts) = @_;
1437: my ($is_balancer,$currtargets,$currrules);
1438: if (ref($result) eq 'HASH') {
1439: if ($result->{'lonhost'} ne '') {
1440: my $currbalancer = $result->{'lonhost'};
1441: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1442: $is_balancer = 1;
1443: $currtargets = $result->{'targets'};
1444: $currrules = $result->{'rules'};
1445: }
1446: } else {
1447: foreach my $key (keys(%{$result})) {
1448: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1449: (ref($result->{$key}) eq 'HASH')) {
1450: $is_balancer = 1;
1451: $currrules = $result->{$key}{'rules'};
1452: $currtargets = $result->{$key}{'targets'};
1453: last;
1454: }
1455: }
1456: }
1457: }
1458: return ($is_balancer,$currtargets,$currrules);
1459: }
1460:
1.1129 raeburn 1461: sub get_loadbalancer_targets {
1462: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1463: my $offloadto;
1.1175 raeburn 1464: if ($rule_in_effect eq 'none') {
1465: return [$perlvar{'lonHostID'}];
1466: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1467: $offloadto = $currtargets;
1468: } else {
1469: if ($rule_in_effect eq 'homeserver') {
1470: my $homeserver = &homeserver($uname,$udom);
1471: if ($homeserver ne 'no_host') {
1472: $offloadto = [$homeserver];
1473: }
1474: } elsif ($rule_in_effect eq 'externalbalancer') {
1475: my %domconfig =
1476: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1477: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1478: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1479: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1480: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1481: }
1482: }
1483: } else {
1.1178 raeburn 1484: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1485: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1486: if (&hostname($remotebalancer) ne '') {
1487: $offloadto = [$remotebalancer];
1488: }
1489: }
1490: } elsif (&hostname($rule_in_effect) ne '') {
1491: $offloadto = [$rule_in_effect];
1492: }
1493: }
1494: return $offloadto;
1495: }
1496:
1.1127 raeburn 1497: sub internet_dom_servers {
1498: my ($dom) = @_;
1499: my (%uniqservers,%servers);
1500: my $primaryserver = &hostname(&domain($dom,'primary'));
1501: my @machinedoms = &machine_domains($primaryserver);
1502: foreach my $mdom (@machinedoms) {
1503: my %currservers = %servers;
1504: my %server = &get_servers($mdom);
1505: %servers = (%currservers,%server);
1506: }
1507: my %by_hostname;
1508: foreach my $id (keys(%servers)) {
1509: push(@{$by_hostname{$servers{$id}}},$id);
1510: }
1511: foreach my $hostname (sort(keys(%by_hostname))) {
1512: if (@{$by_hostname{$hostname}} > 1) {
1513: my $match = 0;
1514: foreach my $id (@{$by_hostname{$hostname}}) {
1515: if (&host_domain($id) eq $dom) {
1516: $uniqservers{$id} = $hostname;
1517: $match = 1;
1518: }
1519: }
1520: unless ($match) {
1521: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1522: }
1523: } else {
1524: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1525: }
1526: }
1527: return %uniqservers;
1528: }
1529:
1.1 albertel 1530: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1531:
1.599 albertel 1532: my %homecache;
1.1 albertel 1533: sub homeserver {
1.230 stredwic 1534: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1535: my $index="$uname:$udom";
1.426 albertel 1536:
1.599 albertel 1537: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1538:
1539: my %servers = &get_servers($udom,'library');
1540: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1541: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1542: exists($badServerCache{$tryserver}));
1.841 albertel 1543:
1544: my $answer=reply("home:$udom:$uname",$tryserver);
1545: if ($answer eq 'found') {
1546: delete($badServerCache{$tryserver});
1547: return $homecache{$index}=$tryserver;
1548: } elsif ($answer eq 'no_host') {
1549: $badServerCache{$tryserver}=1;
1550: }
1.1 albertel 1551: }
1552: return 'no_host';
1.70 www 1553: }
1554:
1555: # ------------------------------------- Find the usernames behind a list of IDs
1556:
1557: sub idget {
1558: my ($udom,@ids)=@_;
1559: my %returnhash=();
1560:
1.841 albertel 1561: my %servers = &get_servers($udom,'library');
1562: foreach my $tryserver (keys(%servers)) {
1563: my $idlist=join('&',@ids);
1564: $idlist=~tr/A-Z/a-z/;
1565: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1566: my @answer=();
1567: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1568: @answer=split(/\&/,$reply);
1569: } ;
1570: my $i;
1571: for ($i=0;$i<=$#ids;$i++) {
1572: if ($answer[$i]) {
1573: $returnhash{$ids[$i]}=$answer[$i];
1574: }
1575: }
1576: }
1.70 www 1577: return %returnhash;
1578: }
1579:
1580: # ------------------------------------- Find the IDs behind a list of usernames
1581:
1582: sub idrget {
1583: my ($udom,@unames)=@_;
1584: my %returnhash=();
1.800 albertel 1585: foreach my $uname (@unames) {
1586: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1587: }
1.70 www 1588: return %returnhash;
1589: }
1590:
1591: # ------------------------------- Store away a list of names and associated IDs
1592:
1593: sub idput {
1594: my ($udom,%ids)=@_;
1595: my %servers=();
1.800 albertel 1596: foreach my $uname (keys(%ids)) {
1597: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1598: my $uhom=&homeserver($uname,$udom);
1.70 www 1599: if ($uhom ne 'no_host') {
1.800 albertel 1600: my $id=&escape($ids{$uname});
1.70 www 1601: $id=~tr/A-Z/a-z/;
1.800 albertel 1602: my $esc_unam=&escape($uname);
1.70 www 1603: if ($servers{$uhom}) {
1.800 albertel 1604: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1605: } else {
1.800 albertel 1606: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1607: }
1608: }
1.191 harris41 1609: }
1.800 albertel 1610: foreach my $server (keys(%servers)) {
1611: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1612: }
1.344 www 1613: }
1614:
1.1231 raeburn 1615: # ---------------------------------------- Delete unwanted IDs from ids.db file
1616:
1617: sub iddel {
1618: my ($udom,$idshashref,$uhome)=@_;
1619: my %result=();
1620: unless (ref($idshashref) eq 'HASH') {
1621: return %result;
1622: }
1623: my %servers=();
1624: while (my ($id,$uname) = each(%{$idshashref})) {
1625: my $uhom;
1626: if ($uhome) {
1627: $uhom = $uhome;
1628: } else {
1629: $uhom=&homeserver($uname,$udom);
1630: }
1631: if ($uhom ne 'no_host') {
1632: if ($servers{$uhom}) {
1633: $servers{$uhom}.='&'.&escape($id);
1634: } else {
1635: $servers{$uhom}=&escape($id);
1636: }
1637: }
1638: }
1639: foreach my $server (keys(%servers)) {
1640: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1641: }
1642: return %result;
1643: }
1644:
1.1023 raeburn 1645: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1646: sub dump_dom {
1.1165 droeschl 1647: my ($namespace, $udom, $regexp) = @_;
1648:
1649: $udom ||= $env{'user.domain'};
1650:
1651: return () unless $udom;
1652:
1653: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1654: }
1655:
1.1023 raeburn 1656: # ------------------------------------------ get items from domain db files
1.806 raeburn 1657:
1658: sub get_dom {
1.860 raeburn 1659: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1660: return if ($udom eq 'public');
1.806 raeburn 1661: my $items='';
1662: foreach my $item (@$storearr) {
1663: $items.=&escape($item).'&';
1664: }
1665: $items=~s/\&$//;
1.860 raeburn 1666: if (!$udom) {
1667: $udom=$env{'user.domain'};
1.1267 raeburn 1668: return if ($udom eq 'public');
1.860 raeburn 1669: if (defined(&domain($udom,'primary'))) {
1670: $uhome=&domain($udom,'primary');
1671: } else {
1.874 albertel 1672: undef($uhome);
1.860 raeburn 1673: }
1674: } else {
1675: if (!$uhome) {
1676: if (defined(&domain($udom,'primary'))) {
1677: $uhome=&domain($udom,'primary');
1678: }
1679: }
1680: }
1681: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1682: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1683: my %returnhash;
1.875 albertel 1684: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1685: return %returnhash;
1686: }
1.806 raeburn 1687: my @pairs=split(/\&/,$rep);
1688: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1689: return @pairs;
1690: }
1691: my $i=0;
1692: foreach my $item (@$storearr) {
1693: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1694: $i++;
1695: }
1696: return %returnhash;
1697: } else {
1.880 banghart 1698: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1699: }
1700: }
1701:
1702: # -------------------------------------------- put items in domain db files
1703:
1704: sub put_dom {
1.860 raeburn 1705: my ($namespace,$storehash,$udom,$uhome)=@_;
1706: if (!$udom) {
1707: $udom=$env{'user.domain'};
1708: if (defined(&domain($udom,'primary'))) {
1709: $uhome=&domain($udom,'primary');
1710: } else {
1.874 albertel 1711: undef($uhome);
1.860 raeburn 1712: }
1713: } else {
1714: if (!$uhome) {
1715: if (defined(&domain($udom,'primary'))) {
1716: $uhome=&domain($udom,'primary');
1717: }
1718: }
1719: }
1720: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1721: my $items='';
1722: foreach my $item (keys(%$storehash)) {
1723: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1724: }
1725: $items=~s/\&$//;
1726: return &reply("putdom:$udom:$namespace:$items",$uhome);
1727: } else {
1.860 raeburn 1728: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1729: }
1730: }
1731:
1.1023 raeburn 1732: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1733: sub newput_dom {
1.1023 raeburn 1734: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1735: my $result;
1736: if (!$udom) {
1737: $udom=$env{'user.domain'};
1738: }
1.1023 raeburn 1739: if ($udom) {
1740: my $uname = &get_domainconfiguser($udom);
1741: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1742: }
1743: return $result;
1744: }
1745:
1.1023 raeburn 1746: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1747: sub del_dom {
1.1023 raeburn 1748: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1749: if (ref($storearr) eq 'ARRAY') {
1750: if (!$udom) {
1751: $udom=$env{'user.domain'};
1752: }
1.1023 raeburn 1753: if ($udom) {
1754: my $uname = &get_domainconfiguser($udom);
1755: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1756: }
1757: }
1758: }
1759:
1.1023 raeburn 1760: # ----------------------------------construct domainconfig user for a domain
1761: sub get_domainconfiguser {
1762: my ($udom) = @_;
1763: return $udom.'-domainconfig';
1764: }
1765:
1.837 raeburn 1766: sub retrieve_inst_usertypes {
1767: my ($udom) = @_;
1768: my (%returnhash,@order);
1.989 raeburn 1769: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1770: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1771: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1772: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1773: } else {
1774: if (defined(&domain($udom,'primary'))) {
1775: my $uhome=&domain($udom,'primary');
1776: my $rep=&reply("inst_usertypes:$udom",$uhome);
1777: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1778: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1779: return (\%returnhash,\@order);
1780: }
1781: my ($hashitems,$orderitems) = split(/:/,$rep);
1782: my @pairs=split(/\&/,$hashitems);
1783: foreach my $item (@pairs) {
1784: my ($key,$value)=split(/=/,$item,2);
1785: $key = &unescape($key);
1786: next if ($key =~ /^error: 2 /);
1787: $returnhash{$key}=&thaw_unescape($value);
1788: }
1789: my @esc_order = split(/\&/,$orderitems);
1790: foreach my $item (@esc_order) {
1791: push(@order,&unescape($item));
1792: }
1793: } else {
1.1256 raeburn 1794: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1795: }
1.1256 raeburn 1796: return (\%returnhash,\@order);
1.837 raeburn 1797: }
1798: }
1799:
1.868 raeburn 1800: sub is_domainimage {
1801: my ($url) = @_;
1802: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1803: if (&domain($1) ne '') {
1804: return '1';
1805: }
1806: }
1807: return;
1808: }
1809:
1.899 raeburn 1810: sub inst_directory_query {
1811: my ($srch) = @_;
1812: my $udom = $srch->{'srchdomain'};
1813: my %results;
1814: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1815: my $outcome;
1.899 raeburn 1816: if ($homeserver ne '') {
1.904 albertel 1817: my $queryid=&reply("querysend:instdirsearch:".
1818: &escape($srch->{'srchby'}).':'.
1819: &escape($srch->{'srchterm'}).':'.
1820: &escape($srch->{'srchtype'}),$homeserver);
1821: my $host=&hostname($homeserver);
1822: if ($queryid !~/^\Q$host\E\_/) {
1823: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1824: return;
1825: }
1826: my $response = &get_query_reply($queryid);
1827: my $maxtries = 5;
1828: my $tries = 1;
1829: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1830: $response = &get_query_reply($queryid);
1831: $tries ++;
1832: }
1833:
1834: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1835: if ($response eq 'unavailable') {
1836: $outcome = $response;
1837: } else {
1838: $outcome = 'ok';
1839: my @matches = split(/\n/,$response);
1840: foreach my $match (@matches) {
1841: my ($key,$value) = split(/=/,$match);
1842: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1843: }
1.899 raeburn 1844: }
1845: }
1846: }
1.909 raeburn 1847: return ($outcome,%results);
1.899 raeburn 1848: }
1849:
1850: sub usersearch {
1851: my ($srch) = @_;
1852: my $dom = $srch->{'srchdomain'};
1853: my %results;
1854: my %libserv = &all_library();
1855: my $query = 'usersearch';
1856: foreach my $tryserver (keys(%libserv)) {
1857: if (&host_domain($tryserver) eq $dom) {
1858: my $host=&hostname($tryserver);
1859: my $queryid=
1.911 raeburn 1860: &reply("querysend:".&escape($query).':'.
1861: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1862: &escape($srch->{'srchtype'}).':'.
1863: &escape($srch->{'srchterm'}),$tryserver);
1864: if ($queryid !~/^\Q$host\E\_/) {
1865: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1866: next;
1.899 raeburn 1867: }
1868: my $reply = &get_query_reply($queryid);
1869: my $maxtries = 1;
1870: my $tries = 1;
1871: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1872: $reply = &get_query_reply($queryid);
1873: $tries ++;
1874: }
1875: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1876: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1877: } else {
1.911 raeburn 1878: my @matches;
1879: if ($reply =~ /\n/) {
1880: @matches = split(/\n/,$reply);
1881: } else {
1882: @matches = split(/\&/,$reply);
1883: }
1.899 raeburn 1884: foreach my $match (@matches) {
1885: my ($uname,$udom,%userhash);
1.911 raeburn 1886: foreach my $entry (split(/:/,$match)) {
1887: my ($key,$value) =
1888: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1889: $userhash{$key} = $value;
1890: if ($key eq 'username') {
1891: $uname = $value;
1892: } elsif ($key eq 'domain') {
1893: $udom = $value;
1.911 raeburn 1894: }
1.899 raeburn 1895: }
1896: $results{$uname.':'.$udom} = \%userhash;
1897: }
1898: }
1899: }
1900: }
1901: return %results;
1902: }
1903:
1.912 raeburn 1904: sub get_instuser {
1905: my ($udom,$uname,$id) = @_;
1906: my $homeserver = &domain($udom,'primary');
1907: my ($outcome,%results);
1908: if ($homeserver ne '') {
1909: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1910: &escape($id).':'.&escape($udom),$homeserver);
1911: my $host=&hostname($homeserver);
1912: if ($queryid !~/^\Q$host\E\_/) {
1913: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1914: return;
1915: }
1916: my $response = &get_query_reply($queryid);
1917: my $maxtries = 5;
1918: my $tries = 1;
1919: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1920: $response = &get_query_reply($queryid);
1921: $tries ++;
1922: }
1923: if (!&error($response) && $response ne 'refused') {
1924: if ($response eq 'unavailable') {
1925: $outcome = $response;
1926: } else {
1927: $outcome = 'ok';
1928: my @matches = split(/\n/,$response);
1929: foreach my $match (@matches) {
1930: my ($key,$value) = split(/=/,$match);
1931: $results{&unescape($key)} = &thaw_unescape($value);
1932: }
1933: }
1934: }
1935: }
1936: my %userinfo;
1937: if (ref($results{$uname}) eq 'HASH') {
1938: %userinfo = %{$results{$uname}};
1939: }
1940: return ($outcome,%userinfo);
1941: }
1942:
1943: sub inst_rulecheck {
1.923 raeburn 1944: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1945: my %returnhash;
1946: if ($udom ne '') {
1947: if (ref($rules) eq 'ARRAY') {
1948: @{$rules} = map {&escape($_);} (@{$rules});
1949: my $rulestr = join(':',@{$rules});
1950: my $homeserver=&domain($udom,'primary');
1951: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1952: my $response;
1953: if ($item eq 'username') {
1954: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1955: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1956: $homeserver));
1.923 raeburn 1957: } elsif ($item eq 'id') {
1958: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1959: ':'.&escape($id).':'.$rulestr,
1960: $homeserver));
1.945 raeburn 1961: } elsif ($item eq 'selfcreate') {
1962: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1963: &escape($udom).':'.&escape($uname).
1964: ':'.$rulestr,$homeserver));
1.923 raeburn 1965: }
1.912 raeburn 1966: if ($response ne 'refused') {
1967: my @pairs=split(/\&/,$response);
1968: foreach my $item (@pairs) {
1969: my ($key,$value)=split(/=/,$item,2);
1970: $key = &unescape($key);
1971: next if ($key =~ /^error: 2 /);
1972: $returnhash{$key}=&thaw_unescape($value);
1973: }
1974: }
1975: }
1976: }
1977: }
1978: return %returnhash;
1979: }
1980:
1981: sub inst_userrules {
1.923 raeburn 1982: my ($udom,$check) = @_;
1.912 raeburn 1983: my (%ruleshash,@ruleorder);
1984: if ($udom ne '') {
1985: my $homeserver=&domain($udom,'primary');
1986: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1987: my $response;
1988: if ($check eq 'id') {
1989: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1990: $homeserver);
1.943 raeburn 1991: } elsif ($check eq 'email') {
1992: $response=&reply('instemailrules:'.&escape($udom),
1993: $homeserver);
1.923 raeburn 1994: } else {
1995: $response=&reply('instuserrules:'.&escape($udom),
1996: $homeserver);
1997: }
1.912 raeburn 1998: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1999: ($response ne 'unknown_cmd') &&
1.912 raeburn 2000: ($response ne 'no_such_host')) {
2001: my ($hashitems,$orderitems) = split(/:/,$response);
2002: my @pairs=split(/\&/,$hashitems);
2003: foreach my $item (@pairs) {
2004: my ($key,$value)=split(/=/,$item,2);
2005: $key = &unescape($key);
2006: next if ($key =~ /^error: 2 /);
2007: $ruleshash{$key}=&thaw_unescape($value);
2008: }
2009: my @esc_order = split(/\&/,$orderitems);
2010: foreach my $item (@esc_order) {
2011: push(@ruleorder,&unescape($item));
2012: }
2013: }
2014: }
2015: }
2016: return (\%ruleshash,\@ruleorder);
2017: }
2018:
1.976 raeburn 2019: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2020:
2021: sub get_domain_defaults {
1.1240 raeburn 2022: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2023: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2024: my $cachetime = 60*60*24;
1.1240 raeburn 2025: unless ($ignore_cache) {
2026: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2027: if (defined($cached)) {
2028: if (ref($result) eq 'HASH') {
2029: return %{$result};
2030: }
1.943 raeburn 2031: }
2032: }
2033: my %domdefaults;
2034: my %domconfig =
1.989 raeburn 2035: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2036: 'requestcourses','inststatus',
1.1183 raeburn 2037: 'coursedefaults','usersessions',
1.1258 raeburn 2038: 'requestauthor','selfenrollment',
2039: 'coursecategories'],$domain);
1.1254 raeburn 2040: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2041: if (ref($domconfig{'defaults'}) eq 'HASH') {
2042: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2043: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2044: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2045: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2046: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2047: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2048: } else {
2049: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2050: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2051: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2052: }
1.976 raeburn 2053: if (ref($domconfig{'quotas'}) eq 'HASH') {
2054: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2055: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2056: } else {
2057: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2058: }
1.1177 raeburn 2059: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2060: foreach my $item (@usertools) {
2061: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2062: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2063: }
2064: }
1.1229 raeburn 2065: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2066: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2067: }
1.976 raeburn 2068: }
1.985 raeburn 2069: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246 raeburn 2070: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2071: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2072: }
2073: }
1.1183 raeburn 2074: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2075: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2076: }
1.989 raeburn 2077: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2078: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2079: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2080: }
2081: }
1.1047 raeburn 2082: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2083: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2084: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2085: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2086: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2087: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2088: }
1.1254 raeburn 2089: foreach my $type (@coursetypes) {
2090: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2091: unless ($type eq 'community') {
2092: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2093: }
2094: }
2095: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2096: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2097: }
1.1277 raeburn 2098: if ($domdefaults{'postsubmit'} eq 'on') {
2099: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2100: $domdefaults{$type.'postsubtimeout'} =
2101: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2102: }
2103: }
1.1230 raeburn 2104: }
1.1286 raeburn 2105: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2106: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2107: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2108: if (@clonecodes) {
2109: $domdefaults{'canclone'} = join('+',@clonecodes);
2110: }
2111: }
2112: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2113: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2114: }
1.1047 raeburn 2115: }
1.1073 raeburn 2116: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2117: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2118: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2119: }
2120: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2121: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2122: }
1.1279 raeburn 2123: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2124: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2125: }
1.1073 raeburn 2126: }
1.1254 raeburn 2127: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2128: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2129: my @settings = ('types','registered','enroll_dates','access_dates','section',
2130: 'approval','limit');
2131: foreach my $type (@coursetypes) {
2132: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2133: my @mgrdc = ();
2134: foreach my $item (@settings) {
2135: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2136: push(@mgrdc,$item);
2137: }
2138: }
2139: if (@mgrdc) {
2140: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2141: }
2142: }
2143: }
2144: }
2145: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2146: foreach my $type (@coursetypes) {
2147: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2148: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2149: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2150: }
2151: }
2152: }
2153: }
2154: }
1.1258 raeburn 2155: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2156: $domdefaults{'catauth'} = 'std';
2157: $domdefaults{'catunauth'} = 'std';
2158: if ($domconfig{'coursecategories'}{'auth'}) {
2159: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2160: }
2161: if ($domconfig{'coursecategories'}{'unauth'}) {
2162: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2163: }
2164: }
1.1219 raeburn 2165: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2166: return %domdefaults;
2167: }
2168:
1.344 www 2169: # --------------------------------------------------- Assign a key to a student
2170:
2171: sub assign_access_key {
1.364 www 2172: #
2173: # a valid key looks like uname:udom#comments
2174: # comments are being appended
2175: #
1.498 www 2176: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2177: $kdom=
1.620 albertel 2178: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2179: $knum=
1.620 albertel 2180: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2181: $cdom=
1.620 albertel 2182: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2183: $cnum=
1.620 albertel 2184: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2185: $udom=$env{'user.name'} unless (defined($udom));
2186: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2187: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2188: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2189: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2190: # assigned to this person
2191: # - this should not happen,
1.345 www 2192: # unless something went wrong
2193: # the first time around
2194: # ready to assign
1.364 www 2195: $logentry=$1.'; '.$logentry;
1.496 www 2196: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2197: $kdom,$knum) eq 'ok') {
1.345 www 2198: # key now belongs to user
1.346 www 2199: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2200: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2201: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2202: return 'ok';
2203: } else {
2204: return
2205: 'error: Count not permanently assign key, will need to be re-entered later.';
2206: }
2207: } else {
2208: return 'error: Could not assign key, try again later.';
2209: }
1.364 www 2210: } elsif (!$existing{$ckey}) {
1.345 www 2211: # the key does not exist
2212: return 'error: The key does not exist';
2213: } else {
2214: # the key is somebody else's
2215: return 'error: The key is already in use';
2216: }
1.344 www 2217: }
2218:
1.364 www 2219: # ------------------------------------------ put an additional comment on a key
2220:
2221: sub comment_access_key {
2222: #
2223: # a valid key looks like uname:udom#comments
2224: # comments are being appended
2225: #
2226: my ($ckey,$cdom,$cnum,$logentry)=@_;
2227: $cdom=
1.620 albertel 2228: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2229: $cnum=
1.620 albertel 2230: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2231: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2232: if ($existing{$ckey}) {
2233: $existing{$ckey}.='; '.$logentry;
2234: # ready to assign
1.367 www 2235: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2236: $cdom,$cnum) eq 'ok') {
2237: return 'ok';
2238: } else {
2239: return 'error: Count not store comment.';
2240: }
2241: } else {
2242: # the key does not exist
2243: return 'error: The key does not exist';
2244: }
2245: }
2246:
1.344 www 2247: # ------------------------------------------------------ Generate a set of keys
2248:
2249: sub generate_access_keys {
1.364 www 2250: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2251: $cdom=
1.620 albertel 2252: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2253: $cnum=
1.620 albertel 2254: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2255: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2256: unless (($cdom) && ($cnum)) { return 0; }
2257: if ($number>10000) { return 0; }
2258: sleep(2); # make sure don't get same seed twice
2259: srand(time()^($$+($$<<15))); # from "Programming Perl"
2260: my $total=0;
2261: for (my $i=1;$i<=$number;$i++) {
2262: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2263: sprintf("%lx",int(100000*rand)).'-'.
2264: sprintf("%lx",int(100000*rand));
2265: $newkey=~s/1/g/g; # folks mix up 1 and l
2266: $newkey=~s/0/h/g; # and also 0 and O
2267: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2268: if ($existing{$newkey}) {
2269: $i--;
2270: } else {
1.364 www 2271: if (&put('accesskeys',
2272: { $newkey => '# generated '.localtime().
1.620 albertel 2273: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2274: '; '.$logentry },
2275: $cdom,$cnum) eq 'ok') {
1.344 www 2276: $total++;
2277: }
2278: }
2279: }
1.620 albertel 2280: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2281: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2282: return $total;
2283: }
2284:
2285: # ------------------------------------------------------- Validate an accesskey
2286:
2287: sub validate_access_key {
2288: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2289: $cdom=
1.620 albertel 2290: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2291: $cnum=
1.620 albertel 2292: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2293: $udom=$env{'user.domain'} unless (defined($udom));
2294: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2295: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2296: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2297: }
2298:
2299: # ------------------------------------- Find the section of student in a course
1.652 albertel 2300: sub devalidate_getsection_cache {
2301: my ($udom,$unam,$courseid)=@_;
2302: my $hashid="$udom:$unam:$courseid";
2303: &devalidate_cache_new('getsection',$hashid);
2304: }
1.298 matthew 2305:
1.815 albertel 2306: sub courseid_to_courseurl {
2307: my ($courseid) = @_;
2308: #already url style courseid
2309: return $courseid if ($courseid =~ m{^/});
2310:
2311: if (exists($env{'course.'.$courseid.'.num'})) {
2312: my $cnum = $env{'course.'.$courseid.'.num'};
2313: my $cdom = $env{'course.'.$courseid.'.domain'};
2314: return "/$cdom/$cnum";
2315: }
2316:
2317: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2318: if (exists($courseinfo{'num'})) {
2319: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2320: }
2321:
2322: return undef;
2323: }
2324:
1.298 matthew 2325: sub getsection {
2326: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2327: my $cachetime=1800;
1.551 albertel 2328:
2329: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2330: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2331: if (defined($cached)) { return $result; }
2332:
1.298 matthew 2333: my %Pending;
2334: my %Expired;
2335: #
2336: # Each role can either have not started yet (pending), be active,
2337: # or have expired.
2338: #
2339: # If there is an active role, we are done.
2340: #
2341: # If there is more than one role which has not started yet,
2342: # choose the one which will start sooner
2343: # If there is one role which has not started yet, return it.
2344: #
2345: # If there is more than one expired role, choose the one which ended last.
2346: # If there is a role which has expired, return it.
2347: #
1.815 albertel 2348: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2349: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2350: foreach my $key (keys(%roleshash)) {
1.479 albertel 2351: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2352: my $section=$1;
2353: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2354: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2355: my $now=time;
1.548 albertel 2356: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2357: $Expired{$end}=$section;
2358: next;
2359: }
1.548 albertel 2360: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2361: $Pending{$start}=$section;
2362: next;
2363: }
1.599 albertel 2364: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2365: }
2366: #
2367: # Presumedly there will be few matching roles from the above
2368: # loop and the sorting time will be negligible.
2369: if (scalar(keys(%Pending))) {
2370: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2371: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2372: }
2373: if (scalar(keys(%Expired))) {
2374: my @sorted = sort {$a <=> $b} keys(%Expired);
2375: my $time = pop(@sorted);
1.599 albertel 2376: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2377: }
1.599 albertel 2378: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2379: }
1.70 www 2380:
1.599 albertel 2381: sub save_cache {
2382: &purge_remembered();
1.722 albertel 2383: #&Apache::loncommon::validate_page();
1.620 albertel 2384: undef(%env);
1.780 albertel 2385: undef($env_loaded);
1.599 albertel 2386: }
1.452 albertel 2387:
1.599 albertel 2388: my $to_remember=-1;
2389: my %remembered;
2390: my %accessed;
2391: my $kicks=0;
2392: my $hits=0;
1.849 albertel 2393: sub make_key {
2394: my ($name,$id) = @_;
1.872 albertel 2395: if (length($id) > 65
2396: && length(&escape($id)) > 200) {
2397: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2398: }
1.849 albertel 2399: return &escape($name.':'.$id);
2400: }
2401:
1.599 albertel 2402: sub devalidate_cache_new {
2403: my ($name,$id,$debug) = @_;
2404: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2405: $id=&make_key($name,$id);
1.599 albertel 2406: $memcache->delete($id);
2407: delete($remembered{$id});
2408: delete($accessed{$id});
2409: }
2410:
2411: sub is_cached_new {
2412: my ($name,$id,$debug) = @_;
1.849 albertel 2413: $id=&make_key($name,$id);
1.599 albertel 2414: if (exists($remembered{$id})) {
1.1133 foxr 2415: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2416: $accessed{$id}=[&gettimeofday()];
2417: $hits++;
2418: return ($remembered{$id},1);
2419: }
2420: my $value = $memcache->get($id);
2421: if (!(defined($value))) {
2422: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2423: return (undef,undef);
1.416 albertel 2424: }
1.599 albertel 2425: if ($value eq '__undef__') {
2426: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2427: $value=undef;
2428: }
2429: &make_room($id,$value,$debug);
2430: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2431: return ($value,1);
2432: }
2433:
2434: sub do_cache_new {
2435: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2436: $id=&make_key($name,$id);
1.599 albertel 2437: my $setvalue=$value;
2438: if (!defined($setvalue)) {
2439: $setvalue='__undef__';
2440: }
1.623 albertel 2441: if (!defined($time) ) {
2442: $time=600;
2443: }
1.599 albertel 2444: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2445: my $result = $memcache->set($id,$setvalue,$time);
2446: if (! $result) {
1.872 albertel 2447: &logthis("caching of id -> $id failed");
1.910 albertel 2448: $memcache->disconnect_all();
1.872 albertel 2449: }
1.600 albertel 2450: # need to make a copy of $value
1.919 albertel 2451: &make_room($id,$value,$debug);
1.599 albertel 2452: return $value;
2453: }
2454:
2455: sub make_room {
2456: my ($id,$value,$debug)=@_;
1.919 albertel 2457:
2458: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2459: : $value;
1.599 albertel 2460: if ($to_remember<0) { return; }
2461: $accessed{$id}=[&gettimeofday()];
2462: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2463: my $to_kick;
2464: my $max_time=0;
2465: foreach my $other (keys(%accessed)) {
2466: if (&tv_interval($accessed{$other}) > $max_time) {
2467: $to_kick=$other;
2468: $max_time=&tv_interval($accessed{$other});
2469: }
2470: }
2471: delete($remembered{$to_kick});
2472: delete($accessed{$to_kick});
2473: $kicks++;
2474: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2475: return;
2476: }
2477:
1.599 albertel 2478: sub purge_remembered {
1.604 albertel 2479: #&logthis("Tossing ".scalar(keys(%remembered)));
2480: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2481: undef(%remembered);
2482: undef(%accessed);
1.428 albertel 2483: }
1.70 www 2484: # ------------------------------------- Read an entry from a user's environment
2485:
2486: sub userenvironment {
2487: my ($udom,$unam,@what)=@_;
1.976 raeburn 2488: my $items;
2489: foreach my $item (@what) {
2490: $items.=&escape($item).'&';
2491: }
2492: $items=~s/\&$//;
1.70 www 2493: my %returnhash=();
1.1009 raeburn 2494: my $uhome = &homeserver($unam,$udom);
2495: unless ($uhome eq 'no_host') {
2496: my @answer=split(/\&/,
2497: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2498: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2499: return %returnhash;
2500: }
1.1009 raeburn 2501: my $i;
2502: for ($i=0;$i<=$#what;$i++) {
2503: $returnhash{$what[$i]}=&unescape($answer[$i]);
2504: }
1.70 www 2505: }
2506: return %returnhash;
1.1 albertel 2507: }
2508:
1.617 albertel 2509: # ---------------------------------------------------------- Get a studentphoto
2510: sub studentphoto {
2511: my ($udom,$unam,$ext) = @_;
2512: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2513: if (defined($env{'request.course.id'})) {
1.708 raeburn 2514: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2515: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2516: return(&retrievestudentphoto($udom,$unam,$ext));
2517: } else {
2518: my ($result,$perm_reqd)=
1.707 albertel 2519: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2520: if ($result eq 'ok') {
2521: if (!($perm_reqd eq 'yes')) {
2522: return(&retrievestudentphoto($udom,$unam,$ext));
2523: }
2524: }
2525: }
2526: }
2527: } else {
2528: my ($result,$perm_reqd) =
1.707 albertel 2529: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2530: if ($result eq 'ok') {
2531: if (!($perm_reqd eq 'yes')) {
2532: return(&retrievestudentphoto($udom,$unam,$ext));
2533: }
2534: }
2535: }
2536: return '/adm/lonKaputt/lonlogo_broken.gif';
2537: }
2538:
2539: sub retrievestudentphoto {
2540: my ($udom,$unam,$ext,$type) = @_;
2541: my $home=&Apache::lonnet::homeserver($unam,$udom);
2542: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2543: if ($ret eq 'ok') {
2544: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2545: if ($type eq 'thumbnail') {
2546: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2547: }
2548: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2549: return $tokenurl;
2550: } else {
2551: if ($type eq 'thumbnail') {
2552: return '/adm/lonKaputt/genericstudent_tn.gif';
2553: } else {
2554: return '/adm/lonKaputt/lonlogo_broken.gif';
2555: }
1.617 albertel 2556: }
2557: }
2558:
1.263 www 2559: # -------------------------------------------------------------------- New chat
2560:
2561: sub chatsend {
1.724 raeburn 2562: my ($newentry,$anon,$group)=@_;
1.620 albertel 2563: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2564: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2565: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2566: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2567: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2568: &escape($newentry)).':'.$group,$chome);
1.292 www 2569: }
2570:
2571: # ------------------------------------------ Find current version of a resource
2572:
2573: sub getversion {
2574: my $fname=&clutter(shift);
1.1189 raeburn 2575: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2576: return ¤tversion(&filelocation('',$fname));
2577: }
2578:
2579: sub currentversion {
2580: my $fname=shift;
2581: my $author=$fname;
2582: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2583: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2584: my $home=&homeserver($uname,$udom);
1.292 www 2585: if ($home eq 'no_host') {
2586: return -1;
2587: }
1.1112 www 2588: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2589: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2590: return -1;
2591: }
1.1112 www 2592: return $answer;
1.263 www 2593: }
2594:
1.1111 www 2595: #
2596: # Return special version number of resource if set by override, empty otherwise
2597: #
2598: sub usedversion {
2599: my $fname=shift;
2600: unless ($fname) { $fname=$env{'request.uri'}; }
2601: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2602: if ($urlversion) { return $urlversion; }
2603: return '';
2604: }
2605:
1.1 albertel 2606: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2607:
1.1 albertel 2608: sub subscribe {
2609: my $fname=shift;
1.761 raeburn 2610: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2611: $fname=~s/[\n\r]//g;
1.1 albertel 2612: my $author=$fname;
2613: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2614: my ($udom,$uname)=split(/\//,$author);
2615: my $home=homeserver($uname,$udom);
1.335 albertel 2616: if ($home eq 'no_host') {
2617: return 'not_found';
1.1 albertel 2618: }
2619: my $answer=reply("sub:$fname",$home);
1.64 www 2620: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2621: $answer.=' by '.$home;
2622: }
1.1 albertel 2623: return $answer;
2624: }
2625:
1.8 www 2626: # -------------------------------------------------------------- Replicate file
2627:
2628: sub repcopy {
2629: my $filename=shift;
1.23 www 2630: $filename=~s/\/+/\//g;
1.1142 raeburn 2631: my $londocroot = $perlvar{'lonDocRoot'};
2632: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2633: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2634: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2635: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2636: return &repcopy_userfile($filename);
2637: }
1.532 albertel 2638: $filename=~s/[\n\r]//g;
1.8 www 2639: my $transname="$filename.in.transfer";
1.828 www 2640: # FIXME: this should flock
1.607 raeburn 2641: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2642: my $remoteurl=subscribe($filename);
1.64 www 2643: if ($remoteurl =~ /^con_lost by/) {
2644: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2645: return 'unavailable';
1.8 www 2646: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2647: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2648: return 'not_found';
1.64 www 2649: } elsif ($remoteurl =~ /^rejected by/) {
2650: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2651: return 'forbidden';
1.20 www 2652: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2653: return 'ok';
1.8 www 2654: } else {
1.290 www 2655: my $author=$filename;
2656: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2657: my ($udom,$uname)=split(/\//,$author);
2658: my $home=homeserver($uname,$udom);
2659: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2660: my @parts=split(/\//,$filename);
2661: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2662: if ($path ne "$londocroot/res") {
1.8 www 2663: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2664: return 'bad_request';
1.8 www 2665: }
2666: my $count;
2667: for ($count=5;$count<$#parts;$count++) {
2668: $path.="/$parts[$count]";
2669: if ((-e $path)!=1) {
2670: mkdir($path,0777);
2671: }
2672: }
2673: my $ua=new LWP::UserAgent;
2674: my $request=new HTTP::Request('GET',"$remoteurl");
2675: my $response=$ua->request($request,$transname);
2676: if ($response->is_error()) {
2677: unlink($transname);
2678: my $message=$response->status_line;
1.672 albertel 2679: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2680: ." LWP get: $message: $filename</font>");
1.607 raeburn 2681: return 'unavailable';
1.8 www 2682: } else {
1.16 www 2683: if ($remoteurl!~/\.meta$/) {
2684: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2685: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2686: if ($mresponse->is_error()) {
2687: unlink($filename.'.meta');
2688: &logthis(
1.672 albertel 2689: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2690: }
2691: }
1.8 www 2692: rename($transname,$filename);
1.607 raeburn 2693: return 'ok';
1.8 www 2694: }
1.290 www 2695: }
1.8 www 2696: }
1.330 www 2697: }
2698:
2699: # ------------------------------------------------ Get server side include body
2700: sub ssi_body {
1.381 albertel 2701: my ($filelink,%form)=@_;
1.606 matthew 2702: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2703: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2704: }
1.953 www 2705: my $output='';
2706: my $response;
1.980 raeburn 2707: if ($filelink=~/^https?\:/) {
1.954 raeburn 2708: ($output,$response)=&externalssi($filelink);
1.953 www 2709: } else {
1.1004 droeschl 2710: $filelink .= $filelink=~/\?/ ? '&' : '?';
2711: $filelink .= 'inhibitmenu=yes';
1.953 www 2712: ($output,$response)=&ssi($filelink,%form);
2713: }
1.778 albertel 2714: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2715: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2716: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2717: if (wantarray) {
2718: return ($output, $response);
2719: } else {
2720: return $output;
2721: }
1.8 www 2722: }
2723:
1.15 www 2724: # --------------------------------------------------------- Server Side Include
2725:
1.782 albertel 2726: sub absolute_url {
2727: my ($host_name) = @_;
2728: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2729: if ($host_name eq '') {
2730: $host_name = $ENV{'SERVER_NAME'};
2731: }
2732: return $protocol.$host_name;
2733: }
2734:
1.942 foxr 2735: #
2736: # Server side include.
2737: # Parameters:
2738: # fn Possibly encrypted resource name/id.
2739: # form Hash that describes how the rendering should be done
2740: # and other things.
1.944 foxr 2741: # Returns:
1.950 raeburn 2742: # Scalar context: The content of the response.
2743: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2744: #
1.15 www 2745: sub ssi {
2746:
1.944 foxr 2747: my ($fn,%form)=@_;
1.15 www 2748: my $ua=new LWP::UserAgent;
1.23 www 2749: my $request;
1.711 albertel 2750:
2751: $form{'no_update_last_known'}=1;
1.895 albertel 2752: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2753: if (%form) {
1.782 albertel 2754: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 2755: $request->content(join('&',map {
2756: my $name = escape($_);
2757: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2758: ? join("&$name=", map {escape($_) } @{$form{$_}})
2759: : &escape($form{$_}) );
2760: } keys(%form)));
1.23 www 2761: } else {
1.782 albertel 2762: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2763: }
2764:
1.15 www 2765: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2766: my $response= $ua->request($request);
1.1182 foxr 2767: my $content = $response->content;
2768:
2769:
1.944 foxr 2770: if (wantarray) {
1.1173 foxr 2771: return ($content, $response);
1.944 foxr 2772: } else {
1.1173 foxr 2773: return $content;
1.942 foxr 2774: }
1.324 www 2775: }
2776:
2777: sub externalssi {
2778: my ($url)=@_;
2779: my $ua=new LWP::UserAgent;
2780: my $request=new HTTP::Request('GET',$url);
2781: my $response=$ua->request($request);
1.954 raeburn 2782: if (wantarray) {
2783: return ($response->content, $response);
2784: } else {
2785: return $response->content;
2786: }
1.15 www 2787: }
1.254 www 2788:
1.492 albertel 2789: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2790:
2791: sub allowuploaded {
2792: my ($srcurl,$url)=@_;
2793: $url=&clutter(&declutter($url));
2794: my $dir=$url;
2795: $dir=~s/\/[^\/]+$//;
2796: my %httpref=();
2797: my $httpurl=&hreflocation('',$url);
2798: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2799: &Apache::lonnet::appenv(\%httpref);
1.254 www 2800: }
1.477 raeburn 2801:
1.1193 raeburn 2802: #
2803: # Determine if the current user should be able to edit a particular resource,
2804: # when viewing in course context.
2805: # (a) When viewing resource used to determine if "Edit" item is included in
2806: # Functions.
2807: # (b) When displaying folder contents in course editor, used to determine if
2808: # "Edit" link will be displayed alongside resource.
2809: #
1.1196 raeburn 2810: # input: six args -- filename (decluttered), course number, course domain,
2811: # url, symb (if registered) and group (if this is a group
2812: # item -- e.g., bulletin board, group page etc.).
2813: # output: array of five scalars --
1.1193 raeburn 2814: # $cfile -- url for file editing if editable on current server
2815: # $home -- homeserver of resource (i.e., for author if published,
2816: # or course if uploaded.).
2817: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2818: # $forceedit -- 1 if icon/link should be to go to edit mode
2819: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2820: #
2821:
2822: sub can_edit_resource {
1.1194 raeburn 2823: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2824: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2825: #
2826: # For aboutme pages user can only edit his/her own.
2827: #
1.1199 raeburn 2828: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2829: my ($sdom,$sname) = ($1,$2);
2830: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2831: $home = $env{'user.home'};
2832: $cfile = $resurl;
2833: if ($env{'form.forceedit'}) {
2834: $forceview = 1;
2835: } else {
2836: $forceedit = 1;
2837: }
2838: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2839: } else {
2840: return;
2841: }
2842: }
2843:
2844: if ($env{'request.course.id'}) {
2845: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2846: if ($group ne '') {
2847: # if this is a group homepage or group bulletin board, check group privs
2848: my $allowed = 0;
1.1197 raeburn 2849: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2850: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2851: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2852: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2853: $allowed = 1;
2854: }
1.1197 raeburn 2855: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2856: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2857: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2858: $allowed = 1;
2859: }
2860: }
2861: if ($allowed) {
2862: $home=&homeserver($cnum,$cdom);
2863: if ($env{'form.forceedit'}) {
2864: $forceview = 1;
2865: } else {
2866: $forceedit = 1;
2867: }
2868: $cfile = $resurl;
2869: } else {
2870: return;
2871: }
2872: } else {
1.1208 raeburn 2873: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2874: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2875: return;
2876: }
2877: } elsif (!$crsedit) {
1.1194 raeburn 2878: #
2879: # No edit allowed where CC has switched to student role.
2880: #
2881: return;
2882: }
2883: }
2884: }
2885:
1.1193 raeburn 2886: if ($file ne '') {
2887: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2888: if (&is_course_upload($file,$cnum,$cdom)) {
2889: $uploaded = 1;
2890: $incourse = 1;
1.1193 raeburn 2891: if ($file =~/\.(htm|html|css|js|txt)$/) {
2892: $cfile = &hreflocation('',$file);
1.1201 raeburn 2893: if ($env{'form.forceedit'}) {
2894: $forceview = 1;
2895: } else {
2896: $forceedit = 1;
2897: }
1.1194 raeburn 2898: }
2899: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2900: $incourse = 1;
2901: if ($env{'form.forceedit'}) {
2902: $forceview = 1;
2903: } else {
2904: $forceedit = 1;
2905: }
2906: $cfile = $resurl;
2907: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2908: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2909: $incourse = 1;
2910: if ($env{'form.forceedit'}) {
2911: $forceview = 1;
2912: } else {
2913: $forceedit = 1;
2914: }
2915: $cfile = $resurl;
1.1199 raeburn 2916: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2917: $incourse = 1;
2918: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2919: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2920: $incourse = 1;
1.1199 raeburn 2921: if ($env{'form.forceedit'}) {
2922: $forceview = 1;
2923: } else {
2924: $forceedit = 1;
2925: }
2926: $cfile = $resurl;
1.1208 raeburn 2927: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2928: $incourse = 1;
2929: if ($env{'form.forceedit'}) {
2930: $forceview = 1;
2931: } else {
2932: $forceedit = 1;
2933: }
2934: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2935: }
2936: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2937: my $template = '/res/lib/templates/simpleproblem.problem';
2938: if (&is_on_map($template)) {
2939: $incourse = 1;
2940: $forceview = 1;
2941: $cfile = $template;
1.1193 raeburn 2942: }
1.1199 raeburn 2943: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2944: $incourse = 1;
2945: if ($env{'form.forceedit'}) {
2946: $forceview = 1;
2947: } else {
2948: $forceedit = 1;
2949: }
2950: $cfile = $resurl;
2951: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2952: $incourse = 1;
2953: $forceview = 1;
2954: if ($symb) {
2955: my ($map,$id,$res)=&decode_symb($symb);
2956: $env{'request.symb'} = $symb;
2957: $cfile = &clutter($res);
2958: } else {
2959: $cfile = $env{'form.suppurl'};
2960: $cfile =~ s{^http://}{};
2961: $cfile = '/adm/wrapper/ext/'.$cfile;
2962: }
1.1234 raeburn 2963: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2964: if ($env{'form.forceedit'}) {
2965: $forceview = 1;
2966: } else {
2967: $forceedit = 1;
2968: }
2969: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2970: }
2971: }
1.1194 raeburn 2972: if ($uploaded || $incourse) {
2973: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2974: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2975: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2976: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2977: # Check that the user has permission to edit this resource
2978: my $setpriv = 1;
2979: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2980: if (defined($cfudom)) {
2981: $home=&homeserver($cfuname,$cfudom);
2982: $cfile=$file;
2983: }
2984: }
1.1194 raeburn 2985: if (($cfile ne '') && (!$incourse || $uploaded) &&
2986: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2987: my @ids=¤t_machine_ids();
2988: unless (grep(/^\Q$home\E$/,@ids)) {
2989: $switchserver=1;
2990: }
2991: }
2992: }
1.1194 raeburn 2993: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2994: }
2995:
2996: sub is_course_upload {
2997: my ($file,$cnum,$cdom) = @_;
2998: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2999: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3000: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3001: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3002: return 1;
3003: }
3004: return;
3005: }
3006:
1.1194 raeburn 3007: sub in_course {
1.1195 raeburn 3008: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3009: if ($hideprivileged) {
3010: my $skipuser;
1.1219 raeburn 3011: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3012: my @possdoms = ($cdom);
3013: if ($coursehash{'checkforpriv'}) {
3014: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3015: }
3016: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3017: $skipuser = 1;
3018: if ($coursehash{'nothideprivileged'}) {
3019: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3020: my $user;
3021: if ($item =~ /:/) {
3022: $user = $item;
3023: } else {
3024: $user = join(':',split(/[\@]/,$item));
3025: }
3026: if ($user eq $uname.':'.$udom) {
3027: undef($skipuser);
3028: last;
3029: }
3030: }
3031: }
3032: if ($skipuser) {
3033: return 0;
3034: }
3035: }
3036: }
1.1194 raeburn 3037: $type ||= 'any';
3038: if (!defined($cdom) || !defined($cnum)) {
3039: my $cid = $env{'request.course.id'};
3040: $cdom = $env{'course.'.$cid.'.domain'};
3041: $cnum = $env{'course.'.$cid.'.num'};
3042: }
3043: my $typesref;
1.1195 raeburn 3044: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3045: $typesref = ['active','previous','future'];
3046: } elsif ($type eq 'previous' || $type eq 'future') {
3047: $typesref = [$type];
3048: }
3049: my %roles = &get_my_roles($uname,$udom,'userroles',
3050: $typesref,undef,[$cdom]);
3051: my ($tmp) = keys(%roles);
3052: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3053: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3054: if (@course_roles > 0) {
3055: return 1;
3056: }
3057: return 0;
3058: }
3059:
1.478 albertel 3060: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3061: # input: action, courseID, current domain, intended
1.637 raeburn 3062: # path to file, source of file, instruction to parse file for objects,
3063: # ref to hash for embedded objects,
3064: # ref to hash for codebase of java objects.
1.1095 raeburn 3065: # reference to scalar to accommodate mime type determined
3066: # from File::MMagic if $parser = parse.
1.637 raeburn 3067: #
1.485 raeburn 3068: # output: url to file (if action was uploaddoc),
3069: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3070: #
1.478 albertel 3071: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3072: # course.
1.477 raeburn 3073: #
1.478 albertel 3074: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3075: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3076: # course's home server.
1.477 raeburn 3077: #
1.478 albertel 3078: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3079: # be copied from $source (current location) to
3080: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3081: # and will then be copied to
3082: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3083: # course's home server.
1.485 raeburn 3084: #
1.481 raeburn 3085: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3086: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3087: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3088: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3089: # in course's home server.
1.637 raeburn 3090: #
1.477 raeburn 3091:
3092: sub process_coursefile {
1.1095 raeburn 3093: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3094: $mimetype)=@_;
1.477 raeburn 3095: my $fetchresult;
1.638 albertel 3096: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3097: if ($action eq 'propagate') {
1.638 albertel 3098: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3099: $home);
1.481 raeburn 3100: } else {
1.477 raeburn 3101: my $fpath = '';
3102: my $fname = $file;
1.478 albertel 3103: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3104: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3105: my $filepath = &build_filepath($fpath);
1.481 raeburn 3106: if ($action eq 'copy') {
3107: if ($source eq '') {
3108: $fetchresult = 'no source file';
3109: return $fetchresult;
3110: } else {
3111: my $destination = $filepath.'/'.$fname;
3112: rename($source,$destination);
3113: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3114: $home);
1.481 raeburn 3115: }
3116: } elsif ($action eq 'uploaddoc') {
3117: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3118: print $fh $env{'form.'.$source};
1.481 raeburn 3119: close($fh);
1.637 raeburn 3120: if ($parser eq 'parse') {
1.1024 raeburn 3121: my $mm = new File::MMagic;
1.1095 raeburn 3122: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3123: if ($type eq 'text/html') {
1.1024 raeburn 3124: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3125: unless ($parse_result eq 'ok') {
3126: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3127: }
1.637 raeburn 3128: }
1.1095 raeburn 3129: if (ref($mimetype)) {
3130: $$mimetype = $type;
3131: }
1.637 raeburn 3132: }
1.477 raeburn 3133: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3134: $home);
1.481 raeburn 3135: if ($fetchresult eq 'ok') {
3136: return '/uploaded/'.$fpath.'/'.$fname;
3137: } else {
3138: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3139: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3140: return '/adm/notfound.html';
3141: }
1.477 raeburn 3142: }
3143: }
1.485 raeburn 3144: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3145: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3146: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3147: }
3148: return $fetchresult;
3149: }
3150:
1.637 raeburn 3151: sub build_filepath {
3152: my ($fpath) = @_;
3153: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3154: unless ($fpath eq '') {
3155: my @parts=split('/',$fpath);
3156: foreach my $part (@parts) {
3157: $filepath.= '/'.$part;
3158: if ((-e $filepath)!=1) {
3159: mkdir($filepath,0777);
3160: }
3161: }
3162: }
3163: return $filepath;
3164: }
3165:
3166: sub store_edited_file {
1.638 albertel 3167: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3168: my $file = $primary_url;
3169: $file =~ s#^/uploaded/$docudom/$docuname/##;
3170: my $fpath = '';
3171: my $fname = $file;
3172: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3173: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3174: my $filepath = &build_filepath($fpath);
3175: open(my $fh,'>'.$filepath.'/'.$fname);
3176: print $fh $content;
3177: close($fh);
1.638 albertel 3178: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3179: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3180: $home);
1.637 raeburn 3181: if ($$fetchresult eq 'ok') {
3182: return '/uploaded/'.$fpath.'/'.$fname;
3183: } else {
1.638 albertel 3184: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3185: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3186: return '/adm/notfound.html';
3187: }
3188: }
3189:
1.531 albertel 3190: sub clean_filename {
1.831 albertel 3191: my ($fname,$args)=@_;
1.315 www 3192: # Replace Windows backslashes by forward slashes
1.257 www 3193: $fname=~s/\\/\//g;
1.831 albertel 3194: if (!$args->{'keep_path'}) {
3195: # Get rid of everything but the actual filename
3196: $fname=~s/^.*\/([^\/]+)$/$1/;
3197: }
1.315 www 3198: # Replace spaces by underscores
3199: $fname=~s/\s+/\_/g;
3200: # Replace all other weird characters by nothing
1.831 albertel 3201: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3202: # Replace all .\d. sequences with _\d. so they no longer look like version
3203: # numbers
3204: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3205: return $fname;
3206: }
1.1051 raeburn 3207: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3208: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3209: # image with the same aspect ratio as the original, but with dimensions which do
3210: # not exceed $resizewidth and $resizeheight.
3211:
1.984 neumanie 3212: sub resizeImage {
1.1051 raeburn 3213: my ($img_path,$resizewidth,$resizeheight) = @_;
3214: my $ima = Image::Magick->new;
3215: my $resized;
3216: if (-e $img_path) {
3217: $ima->Read($img_path);
3218: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3219: my $width = $ima->Get('width');
3220: my $height = $ima->Get('height');
3221: if ($width > $resizewidth) {
3222: my $factor = $width/$resizewidth;
3223: my $newheight = $height/$factor;
3224: $ima->Scale(width=>$resizewidth,height=>$newheight);
3225: $resized = 1;
3226: }
3227: }
3228: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3229: my $width = $ima->Get('width');
3230: my $height = $ima->Get('height');
3231: if ($height > $resizeheight) {
3232: my $factor = $height/$resizeheight;
3233: my $newwidth = $width/$factor;
3234: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3235: $resized = 1;
3236: }
3237: }
3238: if ($resized) {
3239: $ima->Write($img_path);
3240: }
3241: }
3242: return;
1.977 amueller 3243: }
3244:
1.608 albertel 3245: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3246: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3247: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3248: # $context - possible values: coursedoc, existingfile, overwrite,
3249: # canceloverwrite, or ''.
3250: # if 'coursedoc': upload to the current course
3251: # if 'existingfile': write file to tmp/overwrites directory
3252: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3253: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3254: # $subdir - directory in userfile to store the file into
1.858 raeburn 3255: # $parser - instruction to parse file for objects ($parser = parse)
3256: # $allfiles - reference to hash for embedded objects
3257: # $codebase - reference to hash for codebase of java objects
3258: # $desuname - username for permanent storage of uploaded file
3259: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3260: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3261: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3262: # $resizewidth - width (pixels) to which to resize uploaded image
3263: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3264: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3265: # from File::MMagic.
1.858 raeburn 3266: #
1.686 albertel 3267: # output: url of file in userspace, or error: <message>
3268: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3269:
1.531 albertel 3270: sub userfileupload {
1.1090 raeburn 3271: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3272: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3273: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3274: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3275: $fname=&clean_filename($fname);
1.1090 raeburn 3276: # See if there is anything left
1.257 www 3277: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3278: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3279: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3280: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3281: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3282: my $now = time;
1.1090 raeburn 3283: my $filepath;
1.1095 raeburn 3284: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3285: $filepath = 'tmp/helprequests/'.$now;
3286: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3287: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3288: '_'.$env{'user.domain'}.'/pending';
3289: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3290: my ($docuname,$docudom);
3291: if ($destudom) {
3292: $docudom = $destudom;
3293: } else {
3294: $docudom = $env{'user.domain'};
3295: }
3296: if ($destuname) {
3297: $docuname = $destuname;
3298: } else {
3299: $docuname = $env{'user.name'};
3300: }
3301: if (exists($env{'form.group'})) {
3302: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3303: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3304: }
3305: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3306: if ($context eq 'canceloverwrite') {
3307: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3308: if (-e $tempfile) {
3309: my @info = stat($tempfile);
3310: if ($info[9] eq $env{'form.timestamp'}) {
3311: unlink($tempfile);
3312: }
3313: }
3314: return;
1.523 raeburn 3315: }
3316: }
1.1090 raeburn 3317: # Create the directory if not present
1.741 raeburn 3318: my @parts=split(/\//,$filepath);
3319: my $fullpath = $perlvar{'lonDaemons'};
3320: for (my $i=0;$i<@parts;$i++) {
3321: $fullpath .= '/'.$parts[$i];
3322: if ((-e $fullpath)!=1) {
3323: mkdir($fullpath,0777);
3324: }
3325: }
3326: open(my $fh,'>'.$fullpath.'/'.$fname);
3327: print $fh $env{'form.'.$formname};
3328: close($fh);
1.1090 raeburn 3329: if ($context eq 'existingfile') {
3330: my @info = stat($fullpath.'/'.$fname);
3331: return ($fullpath.'/'.$fname,$info[9]);
3332: } else {
3333: return $fullpath.'/'.$fname;
3334: }
1.523 raeburn 3335: }
1.995 raeburn 3336: if ($subdir eq 'scantron') {
3337: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3338: } else {
1.995 raeburn 3339: $fname="$subdir/$fname";
3340: }
1.1090 raeburn 3341: if ($context eq 'coursedoc') {
1.638 albertel 3342: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3343: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3344: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3345: return &finishuserfileupload($docuname,$docudom,
3346: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3347: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3348: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3349: } else {
1.1218 raeburn 3350: if ($env{'form.folder'}) {
3351: $fname=$env{'form.folder'}.'/'.$fname;
3352: }
1.638 albertel 3353: return &process_coursefile('uploaddoc',$docuname,$docudom,
3354: $fname,$formname,$parser,
1.1095 raeburn 3355: $allfiles,$codebase,$mimetype);
1.481 raeburn 3356: }
1.719 banghart 3357: } elsif (defined($destuname)) {
3358: my $docuname=$destuname;
3359: my $docudom=$destudom;
1.860 raeburn 3360: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3361: $parser,$allfiles,$codebase,
1.1051 raeburn 3362: $thumbwidth,$thumbheight,
1.1095 raeburn 3363: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3364: } else {
1.638 albertel 3365: my $docuname=$env{'user.name'};
3366: my $docudom=$env{'user.domain'};
1.1220 raeburn 3367: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3368: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3369: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3370: }
1.860 raeburn 3371: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3372: $parser,$allfiles,$codebase,
1.1051 raeburn 3373: $thumbwidth,$thumbheight,
1.1095 raeburn 3374: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3375: }
1.271 www 3376: }
3377:
3378: sub finishuserfileupload {
1.860 raeburn 3379: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3380: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3381: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3382: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3383:
1.860 raeburn 3384: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3385: $file=$fname;
3386: if ($fname=~m|/|) {
3387: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3388: $path.=$fnamepath.'/';
3389: }
1.259 www 3390: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3391: my $count;
3392: for ($count=4;$count<=$#parts;$count++) {
3393: $filepath.="/$parts[$count]";
3394: if ((-e $filepath)!=1) {
3395: mkdir($filepath,0777);
3396: }
3397: }
1.984 neumanie 3398:
1.258 www 3399: # Save the file
3400: {
1.701 albertel 3401: if (!open(FH,'>'.$filepath.'/'.$file)) {
3402: &logthis('Failed to create '.$filepath.'/'.$file);
3403: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3404: return '/adm/notfound.html';
3405: }
1.1090 raeburn 3406: if ($context eq 'overwrite') {
1.1117 foxr 3407: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3408: my $target = $filepath.'/'.$file;
3409: if (-e $source) {
3410: my @info = stat($source);
3411: if ($info[9] eq $env{'form.timestamp'}) {
3412: unless (&File::Copy::move($source,$target)) {
3413: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3414: return "Moving from $source failed";
3415: }
3416: } else {
3417: return "Temporary file: $source had unexpected date/time for last modification";
3418: }
3419: } else {
3420: return "Temporary file: $source missing";
3421: }
3422: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3423: &logthis('Failed to write to '.$filepath.'/'.$file);
3424: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3425: return '/adm/notfound.html';
3426: }
1.570 albertel 3427: close(FH);
1.1051 raeburn 3428: if ($resizewidth && $resizeheight) {
3429: my $mm = new File::MMagic;
3430: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3431: if ($mime_type =~ m{^image/}) {
3432: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3433: }
1.977 amueller 3434: }
1.258 www 3435: }
1.1152 raeburn 3436: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3437: if (ref($mimetype)) {
3438: if ($$mimetype eq '') {
3439: my $mm = new File::MMagic;
3440: my $type = $mm->checktype_filename($filepath.'/'.$file);
3441: $$mimetype = $type;
3442: }
3443: }
3444: }
1.637 raeburn 3445: if ($parser eq 'parse') {
1.1152 raeburn 3446: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3447: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3448: $allfiles,$codebase);
3449: unless ($parse_result eq 'ok') {
3450: &logthis('Failed to parse '.$filepath.$file.
3451: ' for embedded media: '.$parse_result);
3452: }
1.637 raeburn 3453: }
3454: }
1.860 raeburn 3455: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3456: my $input = $filepath.'/'.$file;
3457: my $output = $filepath.'/'.'tn-'.$file;
3458: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3459: system("convert -sample $thumbsize $input $output");
3460: if (-e $filepath.'/'.'tn-'.$file) {
3461: $fetchthumb = 1;
3462: }
3463: }
1.858 raeburn 3464:
1.259 www 3465: # Notify homeserver to grep it
3466: #
1.984 neumanie 3467: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3468: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3469: if ($fetchresult eq 'ok') {
1.860 raeburn 3470: if ($fetchthumb) {
3471: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3472: if ($thumbresult ne 'ok') {
3473: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3474: $docuhome.': '.$thumbresult);
3475: }
3476: }
1.259 www 3477: #
1.258 www 3478: # Return the URL to it
1.494 albertel 3479: return '/uploaded/'.$path.$file;
1.263 www 3480: } else {
1.494 albertel 3481: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3482: ': '.$fetchresult);
1.263 www 3483: return '/adm/notfound.html';
1.858 raeburn 3484: }
1.493 albertel 3485: }
3486:
1.637 raeburn 3487: sub extract_embedded_items {
1.961 raeburn 3488: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3489: my @state = ();
1.1164 raeburn 3490: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3491: my %javafiles = (
3492: codebase => '',
3493: code => '',
3494: archive => ''
3495: );
3496: my %mediafiles = (
3497: src => '',
3498: movie => '',
3499: );
1.648 raeburn 3500: my $p;
3501: if ($content) {
3502: $p = HTML::LCParser->new($content);
3503: } else {
1.961 raeburn 3504: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3505: }
1.641 albertel 3506: while (my $t=$p->get_token()) {
1.640 albertel 3507: if ($t->[0] eq 'S') {
3508: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3509: push(@state, $tagname);
1.648 raeburn 3510: if (lc($tagname) eq 'allow') {
3511: &add_filetype($allfiles,$attr->{'src'},'src');
3512: }
1.640 albertel 3513: if (lc($tagname) eq 'img') {
3514: &add_filetype($allfiles,$attr->{'src'},'src');
3515: }
1.886 albertel 3516: if (lc($tagname) eq 'a') {
1.1222 raeburn 3517: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3518: &add_filetype($allfiles,$attr->{'href'},'href');
3519: }
1.886 albertel 3520: }
1.645 raeburn 3521: if (lc($tagname) eq 'script') {
1.1164 raeburn 3522: my $src;
1.645 raeburn 3523: if ($attr->{'archive'} =~ /\.jar$/i) {
3524: &add_filetype($allfiles,$attr->{'archive'},'archive');
3525: } else {
1.1164 raeburn 3526: if ($attr->{'src'} ne '') {
3527: $src = $attr->{'src'};
3528: &add_filetype($allfiles,$src,'src');
3529: }
3530: }
3531: my $text = $p->get_trimmed_text();
3532: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3533: my @swfargs = split(/,/,$1);
3534: foreach my $item (@swfargs) {
3535: $item =~ s/["']//g;
3536: $item =~ s/^\s+//;
3537: $item =~ s/\s+$//;
3538: }
3539: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3540: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3541: push(@{$related{$swfargs[0]}},$swfargs[2]);
3542: } else {
3543: $related{$swfargs[0]} = [$swfargs[2]];
3544: }
3545: }
1.645 raeburn 3546: }
3547: }
3548: if (lc($tagname) eq 'link') {
3549: if (lc($attr->{'rel'}) eq 'stylesheet') {
3550: &add_filetype($allfiles,$attr->{'href'},'href');
3551: }
3552: }
1.640 albertel 3553: if (lc($tagname) eq 'object' ||
3554: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3555: foreach my $item (keys(%javafiles)) {
3556: $javafiles{$item} = '';
3557: }
1.1164 raeburn 3558: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3559: $lastids{lc($tagname)} = $attr->{'id'};
3560: }
1.640 albertel 3561: }
3562: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3563: my $name = lc($attr->{'name'});
3564: foreach my $item (keys(%javafiles)) {
3565: if ($name eq $item) {
3566: $javafiles{$item} = $attr->{'value'};
3567: last;
3568: }
3569: }
1.1164 raeburn 3570: my $pathfrom;
1.640 albertel 3571: foreach my $item (keys(%mediafiles)) {
3572: if ($name eq $item) {
1.1164 raeburn 3573: $pathfrom = $attr->{'value'};
3574: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3575: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3576: last;
3577: }
3578: }
1.1164 raeburn 3579: if ($name eq 'flashvars') {
3580: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3581: }
3582: if ($pathfrom ne '') {
3583: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3584: $pathfrom);
3585: }
1.640 albertel 3586: }
3587: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3588: foreach my $item (keys(%javafiles)) {
3589: if ($attr->{$item}) {
3590: $javafiles{$item} = $attr->{$item};
3591: last;
3592: }
3593: }
3594: foreach my $item (keys(%mediafiles)) {
3595: if ($attr->{$item}) {
3596: &add_filetype($allfiles,$attr->{$item},$item);
3597: last;
3598: }
3599: }
1.1164 raeburn 3600: if (lc($tagname) eq 'embed') {
3601: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3602: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3603: $attr->{'src'});
3604: }
3605: }
1.640 albertel 3606: }
1.1243 raeburn 3607: if (lc($tagname) eq 'iframe') {
3608: my $src = $attr->{'src'} ;
3609: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3610: &add_filetype($allfiles,$src,'src');
3611: } elsif ($src =~ m{^/}) {
3612: if ($env{'request.course.id'}) {
3613: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3614: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3615: my $url = &hreflocation('',$fullpath);
3616: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3617: my $relpath = $1;
3618: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3619: &add_filetype($allfiles,$1,'src');
3620: }
3621: }
3622: }
3623: }
3624: }
1.1164 raeburn 3625: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3626: pop(@state);
1.1164 raeburn 3627: }
1.640 albertel 3628: } elsif ($t->[0] eq 'E') {
3629: my ($tagname) = ($t->[1]);
3630: if ($javafiles{'codebase'} ne '') {
3631: $javafiles{'codebase'} .= '/';
3632: }
3633: if (lc($tagname) eq 'applet' ||
3634: lc($tagname) eq 'object' ||
3635: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3636: ) {
3637: foreach my $item (keys(%javafiles)) {
3638: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3639: my $file=$javafiles{'codebase'}.$javafiles{$item};
3640: &add_filetype($allfiles,$file,$item);
3641: }
3642: }
3643: }
3644: pop @state;
3645: }
3646: }
1.1164 raeburn 3647: foreach my $id (sort(keys(%flashvars))) {
3648: if ($shockwave{$id} ne '') {
3649: my @pairs = split(/\&/,$flashvars{$id});
3650: foreach my $pair (@pairs) {
3651: my ($key,$value) = split(/\=/,$pair);
3652: if ($key eq 'thumb') {
3653: &add_filetype($allfiles,$value,$key);
3654: } elsif ($key eq 'content') {
3655: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3656: my ($ext) = ($value =~ /\.([^.]+)$/);
3657: if ($ext ne '') {
3658: &add_filetype($allfiles,$path.$value,$ext);
3659: }
3660: }
3661: }
3662: }
3663: }
1.637 raeburn 3664: return 'ok';
3665: }
3666:
1.639 albertel 3667: sub add_filetype {
3668: my ($allfiles,$file,$type)=@_;
3669: if (exists($allfiles->{$file})) {
3670: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3671: push(@{$allfiles->{$file}}, &escape($type));
3672: }
3673: } else {
3674: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3675: }
3676: }
3677:
1.1164 raeburn 3678: sub embedded_dependency {
3679: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3680: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3681: if (($identifier ne '') &&
3682: (ref($related->{$identifier}) eq 'ARRAY') &&
3683: ($pathfrom ne '')) {
3684: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3685: foreach my $dep (@{$related->{$identifier}}) {
3686: &add_filetype($allfiles,$path.$dep,'object');
3687: }
3688: }
3689: }
3690: return;
3691: }
3692:
1.493 albertel 3693: sub removeuploadedurl {
1.984 neumanie 3694: my ($url)=@_;
3695: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3696: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3697: }
3698:
3699: sub removeuserfile {
3700: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3701: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3702: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3703: if ($result eq 'ok') {
1.798 raeburn 3704: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3705: my $metafile = $fname.'.meta';
3706: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3707: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3708: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3709: my $sqlresult =
1.823 albertel 3710: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3711: 'portfolio_metadata',$group,
3712: 'delete');
1.798 raeburn 3713: }
3714: }
3715: return $result;
1.257 www 3716: }
1.15 www 3717:
1.530 albertel 3718: sub mkdiruserfile {
3719: my ($docuname,$docudom,$dir)=@_;
3720: my $home=&homeserver($docuname,$docudom);
3721: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3722: }
3723:
1.531 albertel 3724: sub renameuserfile {
3725: my ($docuname,$docudom,$old,$new)=@_;
3726: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3727: my $result = &reply("renameuserfile:$docudom:$docuname:".
3728: &escape("$old").':'.&escape("$new"),$home);
3729: if ($result eq 'ok') {
3730: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3731: my $oldmeta = $old.'.meta';
3732: my $newmeta = $new.'.meta';
3733: my $metaresult =
3734: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3735: my $url = "/uploaded/$docudom/$docuname/$old";
3736: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3737: my $sqlresult =
1.823 albertel 3738: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3739: 'portfolio_metadata',$group,
3740: 'delete');
1.798 raeburn 3741: }
3742: }
3743: return $result;
1.531 albertel 3744: }
3745:
1.14 www 3746: # ------------------------------------------------------------------------- Log
3747:
3748: sub log {
3749: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3750: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3751: }
3752:
3753: # ------------------------------------------------------------------ Course Log
1.352 www 3754: #
3755: # This routine flushes several buffers of non-mission-critical nature
3756: #
1.157 www 3757:
3758: sub flushcourselogs {
1.352 www 3759: &logthis('Flushing log buffers');
3760: #
3761: # course logs
3762: # This is a log of all transactions in a course, which can be used
3763: # for data mining purposes
3764: #
3765: # It also collects the courseid database, which lists last transaction
3766: # times and course titles for all courseids
3767: #
3768: my %courseidbuffer=();
1.921 raeburn 3769: foreach my $crsid (keys(%courselogs)) {
1.352 www 3770: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3771: &escape($courselogs{$crsid}),
3772: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3773: delete $courselogs{$crsid};
3774: } else {
3775: &logthis('Failed to flush log buffer for '.$crsid);
3776: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3777: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3778: " exceeded maximum size, deleting.</font>");
3779: delete $courselogs{$crsid};
3780: }
1.352 www 3781: }
1.920 raeburn 3782: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3783: 'description' => $coursedescrbuf{$crsid},
3784: 'inst_code' => $courseinstcodebuf{$crsid},
3785: 'type' => $coursetypebuf{$crsid},
3786: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3787: };
1.191 harris41 3788: }
1.352 www 3789: #
3790: # Write course id database (reverse lookup) to homeserver of courses
3791: # Is used in pickcourse
3792: #
1.840 albertel 3793: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3794: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3795: $courseidbuffer{$crs_home},
3796: $crs_home,'timeonly');
1.352 www 3797: }
3798: #
3799: # File accesses
3800: # Writes to the dynamic metadata of resources to get hit counts, etc.
3801: #
1.449 matthew 3802: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3803: if ($entry =~ /___count$/) {
3804: my ($dom,$name);
1.807 albertel 3805: ($dom,$name,undef)=
1.811 albertel 3806: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3807: if (! defined($dom) || $dom eq '' ||
3808: ! defined($name) || $name eq '') {
1.620 albertel 3809: my $cid = $env{'request.course.id'};
3810: $dom = $env{'request.'.$cid.'.domain'};
3811: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3812: }
1.450 matthew 3813: my $value = $accesshash{$entry};
3814: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3815: my %temphash=($url => $value);
1.449 matthew 3816: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3817: if ($result eq 'ok') {
3818: delete $accesshash{$entry};
3819: }
3820: } else {
1.811 albertel 3821: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3822: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3823: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3824: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3825: delete $accesshash{$entry};
3826: }
1.185 www 3827: }
1.191 harris41 3828: }
1.352 www 3829: #
3830: # Roles
3831: # Reverse lookup of user roles for course faculty/staff and co-authorship
3832: #
1.800 albertel 3833: foreach my $entry (keys(%userrolehash)) {
1.351 www 3834: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3835: split(/\:/,$entry);
3836: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3837: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3838: $rudom,$runame) eq 'ok') {
3839: delete $userrolehash{$entry};
3840: }
3841: }
1.662 raeburn 3842: #
3843: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3844: #
3845: my %domrolebuffer = ();
1.1000 raeburn 3846: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3847: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3848: if ($domrolebuffer{$rudom}) {
3849: $domrolebuffer{$rudom}.='&'.&escape($entry).
3850: '='.&escape($domainrolehash{$entry});
3851: } else {
3852: $domrolebuffer{$rudom}.=&escape($entry).
3853: '='.&escape($domainrolehash{$entry});
3854: }
3855: delete $domainrolehash{$entry};
3856: }
3857: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3858: my %servers = &get_servers($dom,'library');
3859: foreach my $tryserver (keys(%servers)) {
3860: unless (&reply('domroleput:'.$dom.':'.
3861: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3862: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3863: }
1.662 raeburn 3864: }
3865: }
1.186 www 3866: $dumpcount++;
1.157 www 3867: }
3868:
3869: sub courselog {
3870: my $what=shift;
1.158 www 3871: $what=time.':'.$what;
1.620 albertel 3872: unless ($env{'request.course.id'}) { return ''; }
3873: $coursedombuf{$env{'request.course.id'}}=
3874: $env{'course.'.$env{'request.course.id'}.'.domain'};
3875: $coursenumbuf{$env{'request.course.id'}}=
3876: $env{'course.'.$env{'request.course.id'}.'.num'};
3877: $coursehombuf{$env{'request.course.id'}}=
3878: $env{'course.'.$env{'request.course.id'}.'.home'};
3879: $coursedescrbuf{$env{'request.course.id'}}=
3880: $env{'course.'.$env{'request.course.id'}.'.description'};
3881: $courseinstcodebuf{$env{'request.course.id'}}=
3882: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3883: $courseownerbuf{$env{'request.course.id'}}=
3884: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3885: $coursetypebuf{$env{'request.course.id'}}=
3886: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3887: if (defined $courselogs{$env{'request.course.id'}}) {
3888: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3889: } else {
1.620 albertel 3890: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3891: }
1.620 albertel 3892: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3893: &flushcourselogs();
3894: }
1.158 www 3895: }
3896:
3897: sub courseacclog {
3898: my $fnsymb=shift;
1.620 albertel 3899: unless ($env{'request.course.id'}) { return ''; }
3900: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3901: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3902: $what.=':POST';
1.583 matthew 3903: # FIXME: Probably ought to escape things....
1.800 albertel 3904: foreach my $key (keys(%env)) {
3905: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3906: my $formitem = $1;
3907: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3908: $what.=':'.$formitem.'='.$env{$key};
3909: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3910: $what.=':'.$formitem.'='.$env{$key};
3911: }
1.158 www 3912: }
1.191 harris41 3913: }
1.583 matthew 3914: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3915: # FIXME: We should not be depending on a form parameter that someone
3916: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3917: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3918: $what.= ':POST';
3919: # FIXME: Probably ought to escape things....
3920: foreach my $element ('courseexp','crsfulltext','crsrelated',
3921: 'crsdiscuss') {
1.620 albertel 3922: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3923: }
3924: }
1.158 www 3925: }
3926: &courselog($what);
1.149 www 3927: }
3928:
1.185 www 3929: sub countacc {
3930: my $url=&declutter(shift);
1.458 matthew 3931: return if (! defined($url) || $url eq '');
1.620 albertel 3932: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3933: #
3934: # Mark that this url was used in this course
3935: #
1.620 albertel 3936: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3937: #
3938: # Increase the access count for this resource in this child process
3939: #
1.281 www 3940: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3941: $accesshash{$key}++;
1.185 www 3942: }
1.349 www 3943:
1.361 www 3944: sub linklog {
3945: my ($from,$to)=@_;
3946: $from=&declutter($from);
3947: $to=&declutter($to);
3948: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3949: $accesshash{$to.'___'.$from.'___goto'}=1;
3950: }
1.1160 www 3951:
3952: sub statslog {
3953: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3954: if ($users<2) { return; }
3955: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3956: 'course' => $env{'request.course.id'},
3957: 'sections' => '"all"',
3958: 'num_students' => $users,
3959: 'part' => $part,
3960: 'symb' => $symb,
3961: 'mean_tries' => $av_attempts,
3962: 'deg_of_diff' => $degdiff});
3963: foreach my $key (keys(%dynstore)) {
3964: $accesshash{$key}=$dynstore{$key};
3965: }
3966: }
1.361 www 3967:
1.349 www 3968: sub userrolelog {
3969: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3970: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3971: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3972: $userrolehash
3973: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3974: =$tend.':'.$tstart;
1.662 raeburn 3975: }
1.1169 droeschl 3976: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3977: $userrolehash
3978: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3979: =$tend.':'.$tstart;
3980: }
1.1169 droeschl 3981: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3982: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3983: $domainrolehash
3984: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3985: = $tend.':'.$tstart;
3986: }
1.351 www 3987: }
3988:
1.957 raeburn 3989: sub courserolelog {
3990: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3991: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3992: my $cdom = $1;
3993: my $cnum = $2;
3994: my $sec = $3;
3995: my $namespace = 'rolelog';
3996: my %storehash = (
3997: role => $trole,
3998: start => $tstart,
3999: end => $tend,
4000: selfenroll => $selfenroll,
4001: context => $context,
4002: );
4003: if ($trole eq 'gr') {
4004: $namespace = 'groupslog';
4005: $storehash{'group'} = $sec;
4006: } else {
4007: $storehash{'section'} = $sec;
4008: }
1.1188 raeburn 4009: &write_log('course',$namespace,\%storehash,$delflag,$username,
4010: $domain,$cnum,$cdom);
1.1184 raeburn 4011: if (($trole ne 'st') || ($sec ne '')) {
4012: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4013: }
4014: }
4015: return;
4016: }
4017:
1.1184 raeburn 4018: sub domainrolelog {
4019: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4020: if ($area =~ m{^/($match_domain)/$}) {
4021: my $cdom = $1;
4022: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4023: my $namespace = 'rolelog';
4024: my %storehash = (
4025: role => $trole,
4026: start => $tstart,
4027: end => $tend,
4028: context => $context,
4029: );
1.1188 raeburn 4030: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4031: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4032: }
4033: return;
4034:
4035: }
4036:
4037: sub coauthorrolelog {
4038: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4039: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4040: my $audom = $1;
4041: my $auname = $2;
4042: my $namespace = 'rolelog';
4043: my %storehash = (
4044: role => $trole,
4045: start => $tstart,
4046: end => $tend,
4047: context => $context,
4048: );
1.1188 raeburn 4049: &write_log('author',$namespace,\%storehash,$delflag,$username,
4050: $domain,$auname,$audom);
1.1184 raeburn 4051: }
4052: return;
4053: }
4054:
1.351 www 4055: sub get_course_adv_roles {
1.948 raeburn 4056: my ($cid,$codes) = @_;
1.620 albertel 4057: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4058: my %coursehash=&coursedescription($cid);
1.988 raeburn 4059: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4060: my %nothide=();
1.800 albertel 4061: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4062: if ($user !~ /:/) {
4063: $nothide{join(':',split(/[\@]/,$user))}=1;
4064: } else {
4065: $nothide{$user}=1;
4066: }
1.470 www 4067: }
1.1219 raeburn 4068: my @possdoms = ($coursehash{'domain'});
4069: if ($coursehash{'checkforpriv'}) {
4070: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4071: }
1.351 www 4072: my %returnhash=();
4073: my %dumphash=
4074: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4075: my $now=time;
1.997 raeburn 4076: my %privileged;
1.1000 raeburn 4077: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4078: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4079: if (($tstart) && ($tstart<0)) { next; }
4080: if (($tend) && ($tend<$now)) { next; }
4081: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4082: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4083: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4084: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4085: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4086: if ($role eq 'cr') { next; }
1.948 raeburn 4087: if ($codes) {
4088: if ($section) { $role .= ':'.$section; }
4089: if ($returnhash{$role}) {
4090: $returnhash{$role}.=','.$username.':'.$domain;
4091: } else {
4092: $returnhash{$role}=$username.':'.$domain;
4093: }
1.351 www 4094: } else {
1.988 raeburn 4095: my $key=&plaintext($role,$crstype);
1.973 bisitz 4096: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4097: if ($returnhash{$key}) {
4098: $returnhash{$key}.=','.$username.':'.$domain;
4099: } else {
4100: $returnhash{$key}=$username.':'.$domain;
4101: }
1.351 www 4102: }
1.948 raeburn 4103: }
1.400 www 4104: return %returnhash;
4105: }
4106:
4107: sub get_my_roles {
1.937 raeburn 4108: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4109: unless (defined($uname)) { $uname=$env{'user.name'}; }
4110: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4111: my (%dumphash,%nothide);
1.1086 raeburn 4112: if ($context eq 'userroles') {
1.1166 raeburn 4113: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4114: } else {
1.1219 raeburn 4115: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4116: if ($hidepriv) {
4117: my %coursehash=&coursedescription($udom.'_'.$uname);
4118: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4119: if ($user !~ /:/) {
4120: $nothide{join(':',split(/[\@]/,$user))} = 1;
4121: } else {
4122: $nothide{$user} = 1;
4123: }
4124: }
4125: }
1.858 raeburn 4126: }
1.400 www 4127: my %returnhash=();
4128: my $now=time;
1.999 raeburn 4129: my %privileged;
1.800 albertel 4130: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4131: my ($role,$tend,$tstart);
4132: if ($context eq 'userroles') {
1.1149 raeburn 4133: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4134: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4135: } else {
4136: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4137: }
1.400 www 4138: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4139: my $status = 'active';
1.939 raeburn 4140: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4141: $status = 'previous';
4142: }
4143: if (($tstart) && ($now<$tstart)) {
4144: $status = 'future';
4145: }
4146: if (ref($types) eq 'ARRAY') {
4147: if (!grep(/^\Q$status\E$/,@{$types})) {
4148: next;
4149: }
4150: } else {
4151: if ($status ne 'active') {
4152: next;
4153: }
4154: }
1.867 raeburn 4155: my ($rolecode,$username,$domain,$section,$area);
4156: if ($context eq 'userroles') {
1.1186 raeburn 4157: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4158: (undef,$domain,$username,$section) = split(/\//,$area);
4159: } else {
4160: ($role,$username,$domain,$section) = split(/\:/,$entry);
4161: }
1.832 raeburn 4162: if (ref($roledoms) eq 'ARRAY') {
4163: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4164: next;
4165: }
4166: }
4167: if (ref($roles) eq 'ARRAY') {
4168: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4169: if ($role =~ /^cr\//) {
4170: if (!grep(/^cr$/,@{$roles})) {
4171: next;
4172: }
1.1104 raeburn 4173: } elsif ($role =~ /^gr\//) {
4174: if (!grep(/^gr$/,@{$roles})) {
4175: next;
4176: }
1.922 raeburn 4177: } else {
4178: next;
4179: }
1.832 raeburn 4180: }
1.867 raeburn 4181: }
1.937 raeburn 4182: if ($hidepriv) {
1.1219 raeburn 4183: my @privroles = ('dc','su');
1.999 raeburn 4184: if ($context eq 'userroles') {
1.1219 raeburn 4185: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4186: } else {
1.1219 raeburn 4187: my $possdoms = [$domain];
4188: if (ref($roledoms) eq 'ARRAY') {
4189: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4190: }
1.1219 raeburn 4191: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4192: if (!$nothide{$username.':'.$domain}) {
4193: next;
4194: }
4195: }
1.937 raeburn 4196: }
4197: }
1.933 raeburn 4198: if ($withsec) {
4199: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4200: $tstart.':'.$tend;
4201: } else {
4202: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4203: }
1.832 raeburn 4204: }
1.373 www 4205: return %returnhash;
1.399 www 4206: }
4207:
4208: # ----------------------------------------------------- Frontpage Announcements
4209: #
4210: #
4211:
4212: sub postannounce {
4213: my ($server,$text)=@_;
1.844 albertel 4214: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4215: unless ($text=~/\w/) { $text=''; }
4216: return &reply('setannounce:'.&escape($text),$server);
4217: }
4218:
4219: sub getannounce {
1.448 albertel 4220:
4221: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4222: my $announcement='';
1.800 albertel 4223: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4224: close($fh);
1.399 www 4225: if ($announcement=~/\w/) {
4226: return
4227: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4228: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4229: } else {
4230: return '';
4231: }
4232: } else {
4233: return '';
4234: }
1.351 www 4235: }
1.353 www 4236:
4237: # ---------------------------------------------------------- Course ID routines
4238: # Deal with domain's nohist_courseid.db files
4239: #
4240:
4241: sub courseidput {
1.921 raeburn 4242: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4243: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4244: my $outcome;
4245: if ($caller eq 'timeonly') {
4246: my $cids = '';
4247: foreach my $item (keys(%$storehash)) {
4248: $cids.=&escape($item).'&';
4249: }
4250: $cids=~s/\&$//;
4251: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4252: $coursehome);
4253: } else {
4254: my $items = '';
4255: foreach my $item (keys(%$storehash)) {
4256: $items.= &escape($item).'='.
4257: &freeze_escape($$storehash{$item}).'&';
4258: }
4259: $items=~s/\&$//;
4260: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4261: $coursehome);
1.918 raeburn 4262: }
4263: if ($outcome eq 'unknown_cmd') {
4264: my $what;
4265: foreach my $cid (keys(%$storehash)) {
4266: $what .= &escape($cid).'=';
1.921 raeburn 4267: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4268: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4269: }
4270: $what =~ s/\:$/&/;
4271: }
4272: $what =~ s/\&$//;
4273: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4274: } else {
4275: return $outcome;
4276: }
1.353 www 4277: }
4278:
4279: sub courseiddump {
1.921 raeburn 4280: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4281: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4282: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4283: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4284: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4285: my $as_hash = 1;
4286: my %returnhash;
4287: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4288: my %libserv = &all_library();
4289: foreach my $tryserver (keys(%libserv)) {
4290: if ( ( $hostidflag == 1
4291: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4292: || (!defined($hostidflag)) ) {
4293:
1.918 raeburn 4294: if (($domfilter eq '') ||
4295: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4296: my $rep;
4297: if (grep { $_ eq $tryserver } current_machine_ids()) {
4298: $rep = LONCAPA::Lond::dump_course_id_handler(
4299: join(":", (&host_domain($tryserver), $sincefilter,
4300: &escape($descfilter), &escape($instcodefilter),
4301: &escape($ownerfilter), &escape($coursefilter),
4302: &escape($typefilter), &escape($regexp_ok),
4303: $as_hash, &escape($selfenrollonly),
4304: &escape($catfilter), $showhidden, $caller,
4305: &escape($cloner), &escape($cc_clone), $cloneonly,
4306: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4307: &escape($creationcontext),$domcloner,$hasuniquecode,
4308: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4309: } else {
4310: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4311: $sincefilter.':'.&escape($descfilter).':'.
4312: &escape($instcodefilter).':'.&escape($ownerfilter).
4313: ':'.&escape($coursefilter).':'.&escape($typefilter).
4314: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4315: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4316: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4317: &escape($cc_clone).':'.$cloneonly.':'.
4318: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4319: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4320: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4321: }
4322:
1.918 raeburn 4323: my @pairs=split(/\&/,$rep);
4324: foreach my $item (@pairs) {
4325: my ($key,$value)=split(/\=/,$item,2);
4326: $key = &unescape($key);
4327: next if ($key =~ /^error: 2 /);
4328: my $result = &thaw_unescape($value);
4329: if (ref($result) eq 'HASH') {
4330: $returnhash{$key}=$result;
4331: } else {
1.921 raeburn 4332: my @responses = split(/:/,$value);
4333: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4334: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4335: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4336: }
1.1008 raeburn 4337: }
1.353 www 4338: }
4339: }
4340: }
4341: }
4342: return %returnhash;
4343: }
4344:
1.1055 raeburn 4345: sub courselastaccess {
4346: my ($cdom,$cnum,$hostidref) = @_;
4347: my %returnhash;
4348: if ($cdom && $cnum) {
4349: my $chome = &homeserver($cnum,$cdom);
4350: if ($chome ne 'no_host') {
4351: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4352: &extract_lastaccess(\%returnhash,$rep);
4353: }
4354: } else {
4355: if (!$cdom) { $cdom=''; }
4356: my %libserv = &all_library();
4357: foreach my $tryserver (keys(%libserv)) {
4358: if (ref($hostidref) eq 'ARRAY') {
4359: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4360: }
4361: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4362: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4363: &extract_lastaccess(\%returnhash,$rep);
4364: }
4365: }
4366: }
4367: return %returnhash;
4368: }
4369:
4370: sub extract_lastaccess {
4371: my ($returnhash,$rep) = @_;
4372: if (ref($returnhash) eq 'HASH') {
4373: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4374: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4375: $rep eq '') {
4376: my @pairs=split(/\&/,$rep);
4377: foreach my $item (@pairs) {
4378: my ($key,$value)=split(/\=/,$item,2);
4379: $key = &unescape($key);
4380: next if ($key =~ /^error: 2 /);
4381: $returnhash->{$key} = &thaw_unescape($value);
4382: }
4383: }
4384: }
4385: return;
4386: }
4387:
1.658 raeburn 4388: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4389:
4390: sub dcmailput {
1.685 raeburn 4391: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4392: my $status = &Apache::lonnet::critical(
1.740 www 4393: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4394: &escape($message),$server);
1.662 raeburn 4395: return $status;
4396: }
4397:
1.658 raeburn 4398: sub dcmaildump {
4399: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4400: my %returnhash=();
1.846 albertel 4401:
4402: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4403: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4404: &escape($enddate).':';
4405: my @esc_senders=map { &escape($_)} @$senders;
4406: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4407: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4408: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4409: if (($key) && ($value)) {
4410: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4411: }
4412: }
4413: }
4414: return %returnhash;
4415: }
1.662 raeburn 4416: # ---------------------------------------------------------- Domain roles
4417:
4418: sub get_domain_roles {
4419: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4420: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4421: $startdate = '.';
4422: }
1.1018 raeburn 4423: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4424: $enddate = '.';
4425: }
1.922 raeburn 4426: my $rolelist;
4427: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4428: $rolelist = join('&',@{$roles});
1.922 raeburn 4429: }
1.662 raeburn 4430: my %personnel = ();
1.841 albertel 4431:
4432: my %servers = &get_servers($dom,'library');
4433: foreach my $tryserver (keys(%servers)) {
4434: %{$personnel{$tryserver}}=();
4435: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4436: &escape($startdate).':'.
4437: &escape($enddate).':'.
4438: &escape($rolelist), $tryserver))) {
4439: my ($key,$value) = split(/\=/,$line,2);
4440: if (($key) && ($value)) {
4441: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4442: }
4443: }
1.662 raeburn 4444: }
4445: return %personnel;
4446: }
1.658 raeburn 4447:
1.1057 www 4448: # ----------------------------------------------------------- Interval timing
1.149 www 4449:
1.1153 www 4450: {
4451: # Caches needed for speedup of navmaps
4452: # We don't want to cache this for very long at all (5 seconds at most)
4453: #
4454: # The user for whom we cache
4455: my $cachedkey='';
4456: # The cached times for this user
4457: my %cachedtimes=();
4458: # When this was last done
1.1282 raeburn 4459: my $cachedtime='';
1.1153 www 4460:
4461: sub load_all_first_access {
1.1154 raeburn 4462: my ($uname,$udom)=@_;
1.1156 www 4463: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4464: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4465: return;
4466: }
4467: $cachedtime=time;
4468: $cachedkey=$uname.':'.$udom;
4469: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4470: }
4471:
1.504 albertel 4472: sub get_first_access {
1.1162 raeburn 4473: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4474: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4475: if ($argsymb) { $symb=$argsymb; }
4476: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4477: if ($argmap) { $map = $argmap; }
1.926 albertel 4478: if ($type eq 'course') {
4479: $res='course';
4480: } elsif ($type eq 'map') {
1.588 albertel 4481: $res=&symbread($map);
4482: } else {
4483: $res=$symb;
4484: }
1.1153 www 4485: &load_all_first_access($uname,$udom);
4486: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4487: }
4488:
4489: sub set_first_access {
1.1162 raeburn 4490: my ($type,$interval)=@_;
1.790 albertel 4491: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4492: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4493: if ($type eq 'course') {
4494: $res='course';
4495: } elsif ($type eq 'map') {
1.588 albertel 4496: $res=&symbread($map);
4497: } else {
4498: $res=$symb;
4499: }
1.1153 www 4500: $cachedkey='';
1.1162 raeburn 4501: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4502: if (!$firstaccess) {
1.1162 raeburn 4503: my $start = time;
4504: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4505: $udom,$uname);
4506: if ($putres eq 'ok') {
4507: &put('timerinterval',{"$courseid\0$res"=>$interval},
4508: $udom,$uname);
4509: &appenv(
4510: {
4511: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4512: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4513: }
4514: );
4515: }
4516: return $putres;
1.505 albertel 4517: }
4518: return 'already_set';
1.504 albertel 4519: }
1.1153 www 4520: }
1.1282 raeburn 4521:
1.110 www 4522: # --------------------------------------------- Set Expire Date for Spreadsheet
4523:
4524: sub expirespread {
4525: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4526: my $cid=$env{'request.course.id'};
1.110 www 4527: if ($cid) {
4528: my $now=time;
4529: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4530: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4531: $env{'course.'.$cid.'.num'}.
1.110 www 4532: ':nohist_expirationdates:'.
4533: &escape($key).'='.$now,
1.620 albertel 4534: $env{'course.'.$cid.'.home'})
1.110 www 4535: }
4536: return 'ok';
1.14 www 4537: }
4538:
1.109 www 4539: # ----------------------------------------------------- Devalidate Spreadsheets
4540:
4541: sub devalidate {
1.325 www 4542: my ($symb,$uname,$udom)=@_;
1.620 albertel 4543: my $cid=$env{'request.course.id'};
1.109 www 4544: if ($cid) {
1.391 matthew 4545: # delete the stored spreadsheets for
4546: # - the student level sheet of this user in course's homespace
4547: # - the assessment level sheet for this resource
4548: # for this user in user's homespace
1.553 albertel 4549: # - current conditional state info
1.325 www 4550: my $key=$uname.':'.$udom.':';
1.109 www 4551: my $status=
1.299 matthew 4552: &del('nohist_calculatedsheets',
1.391 matthew 4553: [$key.'studentcalc:'],
1.620 albertel 4554: $env{'course.'.$cid.'.domain'},
4555: $env{'course.'.$cid.'.num'})
1.133 albertel 4556: .' '.
4557: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4558: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4559: unless ($status eq 'ok ok') {
4560: &logthis('Could not devalidate spreadsheet '.
1.325 www 4561: $uname.' at '.$udom.' for '.
1.109 www 4562: $symb.': '.$status);
1.133 albertel 4563: }
1.553 albertel 4564: &delenv('user.state.'.$cid);
1.109 www 4565: }
4566: }
4567:
1.265 albertel 4568: sub get_scalar {
4569: my ($string,$end) = @_;
4570: my $value;
4571: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4572: $value = $1;
4573: } elsif ($$string =~ s/^([^&]*?)&//) {
4574: $value = $1;
4575: }
4576: return &unescape($value);
4577: }
4578:
4579: sub array2str {
4580: my (@array) = @_;
4581: my $result=&arrayref2str(\@array);
4582: $result=~s/^__ARRAY_REF__//;
4583: $result=~s/__END_ARRAY_REF__$//;
4584: return $result;
4585: }
4586:
1.204 albertel 4587: sub arrayref2str {
4588: my ($arrayref) = @_;
1.265 albertel 4589: my $result='__ARRAY_REF__';
1.204 albertel 4590: foreach my $elem (@$arrayref) {
1.265 albertel 4591: if(ref($elem) eq 'ARRAY') {
4592: $result.=&arrayref2str($elem).'&';
4593: } elsif(ref($elem) eq 'HASH') {
4594: $result.=&hashref2str($elem).'&';
4595: } elsif(ref($elem)) {
4596: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4597: } else {
4598: $result.=&escape($elem).'&';
4599: }
4600: }
4601: $result=~s/\&$//;
1.265 albertel 4602: $result .= '__END_ARRAY_REF__';
1.204 albertel 4603: return $result;
4604: }
4605:
1.168 albertel 4606: sub hash2str {
1.204 albertel 4607: my (%hash) = @_;
4608: my $result=&hashref2str(\%hash);
1.265 albertel 4609: $result=~s/^__HASH_REF__//;
4610: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4611: return $result;
4612: }
4613:
4614: sub hashref2str {
4615: my ($hashref)=@_;
1.265 albertel 4616: my $result='__HASH_REF__';
1.800 albertel 4617: foreach my $key (sort(keys(%$hashref))) {
4618: if (ref($key) eq 'ARRAY') {
4619: $result.=&arrayref2str($key).'=';
4620: } elsif (ref($key) eq 'HASH') {
4621: $result.=&hashref2str($key).'=';
4622: } elsif (ref($key)) {
1.265 albertel 4623: $result.='=';
1.800 albertel 4624: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4625: } else {
1.1132 raeburn 4626: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4627: }
4628:
1.800 albertel 4629: if(ref($hashref->{$key}) eq 'ARRAY') {
4630: $result.=&arrayref2str($hashref->{$key}).'&';
4631: } elsif(ref($hashref->{$key}) eq 'HASH') {
4632: $result.=&hashref2str($hashref->{$key}).'&';
4633: } elsif(ref($hashref->{$key})) {
1.265 albertel 4634: $result.='&';
1.800 albertel 4635: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4636: } else {
1.800 albertel 4637: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4638: }
4639: }
1.168 albertel 4640: $result=~s/\&$//;
1.265 albertel 4641: $result .= '__END_HASH_REF__';
1.168 albertel 4642: return $result;
4643: }
4644:
4645: sub str2hash {
1.265 albertel 4646: my ($string)=@_;
4647: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4648: return %$hash;
4649: }
4650:
4651: sub str2hashref {
1.168 albertel 4652: my ($string) = @_;
1.265 albertel 4653:
4654: my %hash;
4655:
4656: if($string !~ /^__HASH_REF__/) {
4657: if (! ($string eq '' || !defined($string))) {
4658: $hash{'error'}='Not hash reference';
4659: }
4660: return (\%hash, $string);
4661: }
4662:
4663: $string =~ s/^__HASH_REF__//;
4664:
4665: while($string !~ /^__END_HASH_REF__/) {
4666: #key
4667: my $key='';
4668: if($string =~ /^__HASH_REF__/) {
4669: ($key, $string)=&str2hashref($string);
4670: if(defined($key->{'error'})) {
4671: $hash{'error'}='Bad data';
4672: return (\%hash, $string);
4673: }
4674: } elsif($string =~ /^__ARRAY_REF__/) {
4675: ($key, $string)=&str2arrayref($string);
4676: if($key->[0] eq 'Array reference error') {
4677: $hash{'error'}='Bad data';
4678: return (\%hash, $string);
4679: }
4680: } else {
4681: $string =~ s/^(.*?)=//;
1.267 albertel 4682: $key=&unescape($1);
1.265 albertel 4683: }
4684: $string =~ s/^=//;
4685:
4686: #value
4687: my $value='';
4688: if($string =~ /^__HASH_REF__/) {
4689: ($value, $string)=&str2hashref($string);
4690: if(defined($value->{'error'})) {
4691: $hash{'error'}='Bad data';
4692: return (\%hash, $string);
4693: }
4694: } elsif($string =~ /^__ARRAY_REF__/) {
4695: ($value, $string)=&str2arrayref($string);
4696: if($value->[0] eq 'Array reference error') {
4697: $hash{'error'}='Bad data';
4698: return (\%hash, $string);
4699: }
4700: } else {
4701: $value=&get_scalar(\$string,'__END_HASH_REF__');
4702: }
4703: $string =~ s/^&//;
4704:
4705: $hash{$key}=$value;
1.204 albertel 4706: }
1.265 albertel 4707:
4708: $string =~ s/^__END_HASH_REF__//;
4709:
4710: return (\%hash, $string);
1.204 albertel 4711: }
4712:
4713: sub str2array {
1.265 albertel 4714: my ($string)=@_;
4715: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4716: return @$array;
4717: }
4718:
4719: sub str2arrayref {
1.204 albertel 4720: my ($string) = @_;
1.265 albertel 4721: my @array;
4722:
4723: if($string !~ /^__ARRAY_REF__/) {
4724: if (! ($string eq '' || !defined($string))) {
4725: $array[0]='Array reference error';
4726: }
4727: return (\@array, $string);
4728: }
4729:
4730: $string =~ s/^__ARRAY_REF__//;
4731:
4732: while($string !~ /^__END_ARRAY_REF__/) {
4733: my $value='';
4734: if($string =~ /^__HASH_REF__/) {
4735: ($value, $string)=&str2hashref($string);
4736: if(defined($value->{'error'})) {
4737: $array[0] ='Array reference error';
4738: return (\@array, $string);
4739: }
4740: } elsif($string =~ /^__ARRAY_REF__/) {
4741: ($value, $string)=&str2arrayref($string);
4742: if($value->[0] eq 'Array reference error') {
4743: $array[0] ='Array reference error';
4744: return (\@array, $string);
4745: }
4746: } else {
4747: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4748: }
4749: $string =~ s/^&//;
4750:
4751: push(@array, $value);
1.191 harris41 4752: }
1.265 albertel 4753:
4754: $string =~ s/^__END_ARRAY_REF__//;
4755:
4756: return (\@array, $string);
1.168 albertel 4757: }
4758:
1.167 albertel 4759: # -------------------------------------------------------------------Temp Store
4760:
1.168 albertel 4761: sub tmpreset {
4762: my ($symb,$namespace,$domain,$stuname) = @_;
4763: if (!$symb) {
4764: $symb=&symbread();
1.620 albertel 4765: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4766: }
4767: $symb=escape($symb);
4768:
1.620 albertel 4769: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4770: $namespace=~s/\//\_/g;
4771: $namespace=~s/\W//g;
4772:
1.620 albertel 4773: if (!$domain) { $domain=$env{'user.domain'}; }
4774: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4775: if ($domain eq 'public' && $stuname eq 'public') {
4776: $stuname=$ENV{'REMOTE_ADDR'};
4777: }
1.1117 foxr 4778: my $path=LONCAPA::tempdir();
1.168 albertel 4779: my %hash;
4780: if (tie(%hash,'GDBM_File',
4781: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4782: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4783: foreach my $key (keys(%hash)) {
1.180 albertel 4784: if ($key=~ /:$symb/) {
1.168 albertel 4785: delete($hash{$key});
4786: }
4787: }
4788: }
4789: }
4790:
1.167 albertel 4791: sub tmpstore {
1.168 albertel 4792: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4793:
4794: if (!$symb) {
4795: $symb=&symbread();
1.620 albertel 4796: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4797: }
4798: $symb=escape($symb);
4799:
4800: if (!$namespace) {
4801: # I don't think we would ever want to store this for a course.
4802: # it seems this will only be used if we don't have a course.
1.620 albertel 4803: #$namespace=$env{'request.course.id'};
1.168 albertel 4804: #if (!$namespace) {
1.620 albertel 4805: $namespace=$env{'request.state'};
1.168 albertel 4806: #}
4807: }
4808: $namespace=~s/\//\_/g;
4809: $namespace=~s/\W//g;
1.620 albertel 4810: if (!$domain) { $domain=$env{'user.domain'}; }
4811: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4812: if ($domain eq 'public' && $stuname eq 'public') {
4813: $stuname=$ENV{'REMOTE_ADDR'};
4814: }
1.168 albertel 4815: my $now=time;
4816: my %hash;
1.1117 foxr 4817: my $path=LONCAPA::tempdir();
1.168 albertel 4818: if (tie(%hash,'GDBM_File',
4819: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4820: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4821: $hash{"version:$symb"}++;
4822: my $version=$hash{"version:$symb"};
4823: my $allkeys='';
4824: foreach my $key (keys(%$storehash)) {
4825: $allkeys.=$key.':';
1.591 albertel 4826: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4827: }
4828: $hash{"$version:$symb:timestamp"}=$now;
4829: $allkeys.='timestamp';
4830: $hash{"$version:keys:$symb"}=$allkeys;
4831: if (untie(%hash)) {
4832: return 'ok';
4833: } else {
4834: return "error:$!";
4835: }
4836: } else {
4837: return "error:$!";
4838: }
4839: }
1.167 albertel 4840:
1.168 albertel 4841: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4842:
1.168 albertel 4843: sub tmprestore {
4844: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4845:
1.168 albertel 4846: if (!$symb) {
4847: $symb=&symbread();
1.620 albertel 4848: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4849: }
4850: $symb=escape($symb);
4851:
1.620 albertel 4852: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4853:
1.620 albertel 4854: if (!$domain) { $domain=$env{'user.domain'}; }
4855: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4856: if ($domain eq 'public' && $stuname eq 'public') {
4857: $stuname=$ENV{'REMOTE_ADDR'};
4858: }
1.168 albertel 4859: my %returnhash;
4860: $namespace=~s/\//\_/g;
4861: $namespace=~s/\W//g;
4862: my %hash;
1.1117 foxr 4863: my $path=LONCAPA::tempdir();
1.168 albertel 4864: if (tie(%hash,'GDBM_File',
4865: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4866: &GDBM_READER(),0640)) {
1.168 albertel 4867: my $version=$hash{"version:$symb"};
4868: $returnhash{'version'}=$version;
4869: my $scope;
4870: for ($scope=1;$scope<=$version;$scope++) {
4871: my $vkeys=$hash{"$scope:keys:$symb"};
4872: my @keys=split(/:/,$vkeys);
4873: my $key;
4874: $returnhash{"$scope:keys"}=$vkeys;
4875: foreach $key (@keys) {
1.591 albertel 4876: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4877: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4878: }
4879: }
1.168 albertel 4880: if (!(untie(%hash))) {
4881: return "error:$!";
4882: }
4883: } else {
4884: return "error:$!";
4885: }
4886: return %returnhash;
1.167 albertel 4887: }
4888:
1.9 www 4889: # ----------------------------------------------------------------------- Store
4890:
4891: sub store {
1.1269 raeburn 4892: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4893: my $home='';
4894:
1.168 albertel 4895: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4896:
1.213 www 4897: $symb=&symbclean($symb);
1.122 albertel 4898: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4899:
1.620 albertel 4900: if (!$domain) { $domain=$env{'user.domain'}; }
4901: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4902:
4903: &devalidate($symb,$stuname,$domain);
1.109 www 4904:
4905: $symb=escape($symb);
1.187 www 4906: if (!$namespace) {
1.620 albertel 4907: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4908: return '';
4909: }
4910: }
1.620 albertel 4911: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4912:
4913: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4914: $$storehash{'host'}=$perlvar{'lonHostID'};
4915:
1.12 www 4916: my $namevalue='';
1.800 albertel 4917: foreach my $key (keys(%$storehash)) {
4918: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4919: }
1.12 www 4920: $namevalue=~s/\&$//;
1.187 www 4921: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 4922: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 4923: }
4924:
1.47 www 4925: # -------------------------------------------------------------- Critical Store
4926:
4927: sub cstore {
1.1269 raeburn 4928: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4929: my $home='';
4930:
1.168 albertel 4931: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4932:
1.213 www 4933: $symb=&symbclean($symb);
1.122 albertel 4934: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4935:
1.620 albertel 4936: if (!$domain) { $domain=$env{'user.domain'}; }
4937: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4938:
4939: &devalidate($symb,$stuname,$domain);
1.109 www 4940:
4941: $symb=escape($symb);
1.187 www 4942: if (!$namespace) {
1.620 albertel 4943: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4944: return '';
4945: }
4946: }
1.620 albertel 4947: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4948:
4949: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4950: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4951:
1.47 www 4952: my $namevalue='';
1.800 albertel 4953: foreach my $key (keys(%$storehash)) {
4954: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4955: }
1.47 www 4956: $namevalue=~s/\&$//;
1.187 www 4957: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4958: return critical
1.1269 raeburn 4959: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 4960: }
4961:
1.9 www 4962: # --------------------------------------------------------------------- Restore
4963:
4964: sub restore {
1.124 www 4965: my ($symb,$namespace,$domain,$stuname) = @_;
4966: my $home='';
4967:
1.168 albertel 4968: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4969:
1.122 albertel 4970: if (!$symb) {
1.1224 raeburn 4971: return if ($namespace eq 'courserequests');
4972: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4973: } else {
1.1224 raeburn 4974: unless ($namespace eq 'courserequests') {
4975: $symb=&escape(&symbclean($symb));
4976: }
1.122 albertel 4977: }
1.188 www 4978: if (!$namespace) {
1.620 albertel 4979: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4980: return '';
4981: }
4982: }
1.620 albertel 4983: if (!$domain) { $domain=$env{'user.domain'}; }
4984: if (!$stuname) { $stuname=$env{'user.name'}; }
4985: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4986: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4987:
1.12 www 4988: my %returnhash=();
1.800 albertel 4989: foreach my $line (split(/\&/,$answer)) {
4990: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4991: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4992: }
1.75 www 4993: my $version;
4994: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4995: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4996: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4997: }
1.75 www 4998: }
1.13 www 4999: return %returnhash;
1.34 www 5000: }
5001:
5002: # ---------------------------------------------------------- Course Description
1.1118 foxr 5003: #
5004: #
1.34 www 5005:
5006: sub coursedescription {
1.731 albertel 5007: my ($courseid,$args)=@_;
1.34 www 5008: $courseid=~s/^\///;
1.49 www 5009: $courseid=~s/\_/\//g;
1.34 www 5010: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5011: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5012: my $normalid=$cdomain.'_'.$cnum;
5013: # need to always cache even if we get errors otherwise we keep
5014: # trying and trying and trying to get the course description.
5015: my %envhash=();
5016: my %returnhash=();
1.731 albertel 5017:
5018: my $expiretime=600;
5019: if ($env{'request.course.id'} eq $normalid) {
5020: $expiretime=120;
5021: }
5022:
5023: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5024: if (!$args->{'freshen_cache'}
5025: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5026: foreach my $key (keys(%env)) {
5027: next if ($key !~ /^\Q$prefix\E(.*)/);
5028: my ($setting) = $1;
5029: $returnhash{$setting} = $env{$key};
5030: }
5031: return %returnhash;
5032: }
5033:
1.1118 foxr 5034: # get the data again
5035:
1.731 albertel 5036: if (!$args->{'one_time'}) {
5037: $envhash{'course.'.$normalid.'.last_cache'}=time;
5038: }
1.811 albertel 5039:
1.34 www 5040: if ($chome ne 'no_host') {
1.302 albertel 5041: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5042: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5043: my $username = $env{'user.name'}; # Defult username
5044: if(defined $args->{'user'}) {
5045: $username = $args->{'user'};
5046: }
1.129 albertel 5047: $returnhash{'home'}= $chome;
5048: $returnhash{'domain'} = $cdomain;
5049: $returnhash{'num'} = $cnum;
1.741 raeburn 5050: if (!defined($returnhash{'type'})) {
5051: $returnhash{'type'} = 'Course';
5052: }
1.130 albertel 5053: while (my ($name,$value) = each %returnhash) {
1.53 www 5054: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5055: }
1.270 www 5056: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5057: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5058: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5059: $envhash{'course.'.$normalid.'.home'}=$chome;
5060: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5061: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5062: }
5063: }
1.731 albertel 5064: if (!$args->{'one_time'}) {
1.949 raeburn 5065: &appenv(\%envhash);
1.731 albertel 5066: }
1.302 albertel 5067: return %returnhash;
1.461 www 5068: }
5069:
1.1080 raeburn 5070: sub update_released_required {
5071: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5072: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5073: $cid = $env{'request.course.id'};
5074: $cdom = $env{'course.'.$cid.'.domain'};
5075: $cnum = $env{'course.'.$cid.'.num'};
5076: $chome = $env{'course.'.$cid.'.home'};
5077: }
5078: if ($needsrelease) {
5079: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5080: my $needsupdate;
5081: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5082: $needsupdate = 1;
5083: } else {
5084: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5085: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5086: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5087: $needsupdate = 1;
5088: }
5089: }
5090: if ($needsupdate) {
5091: my %needshash = (
5092: 'internal.releaserequired' => $needsrelease,
5093: );
5094: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5095: if ($putresult eq 'ok') {
5096: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5097: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5098: if (ref($crsinfo{$cid}) eq 'HASH') {
5099: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5100: &courseidput($cdom,\%crsinfo,$chome,'notime');
5101: }
5102: }
5103: }
5104: }
5105: return;
5106: }
5107:
1.461 www 5108: # -------------------------------------------------See if a user is privileged
5109:
5110: sub privileged {
1.1219 raeburn 5111: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5112: my $now = time;
1.1219 raeburn 5113: my $roles;
5114: if (ref($possroles) eq 'ARRAY') {
5115: $roles = $possroles;
5116: } else {
5117: $roles = ['dc','su'];
5118: }
5119: if (ref($possdomains) eq 'ARRAY') {
5120: my %privileged = &privileged_by_domain($possdomains,$roles);
5121: foreach my $dom (@{$possdomains}) {
5122: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5123: (ref($privileged{$dom}) eq 'HASH')) {
5124: foreach my $role (@{$roles}) {
5125: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5126: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5127: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5128: return 1 unless (($end && $end < $now) ||
5129: ($start && $start > $now));
5130: }
5131: }
5132: }
5133: }
5134: }
5135: } else {
5136: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5137: my $now = time;
1.1170 droeschl 5138:
1.1275 musolffc 5139: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5140: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5141: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5142: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5143: or ($tstart && $tstart > $now);
1.1170 droeschl 5144: }
1.1219 raeburn 5145: }
5146: }
5147: return 0;
5148: }
1.1170 droeschl 5149:
1.1219 raeburn 5150: sub privileged_by_domain {
5151: my ($domains,$roles) = @_;
5152: my %privileged = ();
5153: my $cachetime = 60*60*24;
5154: my $now = time;
5155: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5156: return %privileged;
5157: }
5158: foreach my $dom (@{$domains}) {
5159: next if (ref($privileged{$dom}) eq 'HASH');
5160: my $needroles;
5161: foreach my $role (@{$roles}) {
5162: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5163: if (defined($cached)) {
5164: if (ref($result) eq 'HASH') {
5165: $privileged{$dom}{$role} = $result;
5166: }
5167: } else {
5168: $needroles = 1;
5169: }
5170: }
5171: if ($needroles) {
5172: my %dompersonnel = &get_domain_roles($dom,$roles);
5173: $privileged{$dom} = {};
5174: foreach my $server (keys(%dompersonnel)) {
5175: if (ref($dompersonnel{$server}) eq 'HASH') {
5176: foreach my $item (keys(%{$dompersonnel{$server}})) {
5177: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5178: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5179: next if ($end && $end < $now);
5180: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5181: $dompersonnel{$server}{$item};
5182: }
5183: }
5184: }
5185: if (ref($privileged{$dom}) eq 'HASH') {
5186: foreach my $role (@{$roles}) {
5187: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5188: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5189: } else {
5190: my %hash = ();
5191: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5192: }
5193: }
5194: }
5195: }
5196: }
5197: return %privileged;
1.9 www 5198: }
1.1 albertel 5199:
1.103 harris41 5200: # -------------------------------------------------------- Get user privileges
1.11 www 5201:
5202: sub rolesinit {
1.1169 droeschl 5203: my ($domain, $username) = @_;
5204: my %userroles = ('user.login.time' => time);
5205: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5206:
5207: # firstaccess and timerinterval are related to timed maps/resources.
5208: # also, blocking can be triggered by an activating timer
5209: # it's saved in the user's %env.
5210: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5211: my %timerinterval = &dump('timerinterval', $domain, $username);
5212: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5213: %timerintchk, %timerintenv);
5214:
1.1162 raeburn 5215: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5216: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5217: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5218: }
1.1169 droeschl 5219:
1.1162 raeburn 5220: foreach my $key (keys(%timerinterval)) {
5221: my ($cid,$rest) = split(/\0/,$key);
5222: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5223: }
1.1169 droeschl 5224:
1.11 www 5225: my %allroles=();
1.1162 raeburn 5226: my %allgroups=();
1.11 www 5227:
1.1274 raeburn 5228: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5229: my $role = $rolesdump{$area};
5230: $area =~ s/\_\w\w$//;
5231:
5232: my ($trole, $tend, $tstart, $group_privs);
5233:
5234: if ($role =~ /^cr/) {
5235: # Custom role, defined by a user
5236: # e.g., user.role.cr/msu/smith/mynewrole
5237: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5238: $trole = $1;
5239: ($tend, $tstart) = split('_', $2);
5240: } else {
5241: $trole = $role;
5242: }
5243: } elsif ($role =~ m|^gr/|) {
5244: # Role of member in a group, defined within a course/community
5245: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5246: ($trole, $tend, $tstart) = split(/_/, $role);
5247: next if $tstart eq '-1';
5248: ($trole, $group_privs) = split(/\//, $trole);
5249: $group_privs = &unescape($group_privs);
5250: } else {
5251: # Just a normal role, defined in roles.tab
5252: ($trole, $tend, $tstart) = split(/_/,$role);
5253: }
5254:
5255: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5256: $username);
5257: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5258:
5259: # role expired or not available yet?
5260: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5261: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5262:
5263: next if $area eq '' or $trole eq '';
5264:
5265: my $spec = "$trole.$area";
5266: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5267:
5268: if ($trole =~ /^cr\//) {
5269: # Custom role, defined by a user
5270: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5271: } elsif ($trole eq 'gr') {
5272: # Role of a member in a group, defined within a course/community
5273: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5274: next;
5275: } else {
5276: # Normal role, defined in roles.tab
5277: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5278: }
5279:
5280: my $cid = $tdomain.'_'.$trest;
5281: unless ($firstaccchk{$cid}) {
5282: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5283: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5284: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5285: $coursetimerstarts{$cid}{$item};
5286: }
5287: }
5288: $firstaccchk{$cid} = 1;
5289: }
5290: unless ($timerintchk{$cid}) {
5291: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5292: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5293: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5294: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5295: }
1.12 www 5296: }
1.1169 droeschl 5297: $timerintchk{$cid} = 1;
1.191 harris41 5298: }
1.11 www 5299: }
1.1169 droeschl 5300:
5301: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5302: \%allroles, \%allgroups);
5303: $env{'user.adv'} = $userroles{'user.adv'};
5304:
1.1162 raeburn 5305: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5306: }
5307:
1.567 raeburn 5308: sub set_arearole {
1.1215 raeburn 5309: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5310: unless ($nolog) {
1.567 raeburn 5311: # log the associated role with the area
1.1215 raeburn 5312: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5313: }
1.743 albertel 5314: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5315: }
5316:
5317: sub custom_roleprivs {
5318: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5319: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5320: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5321: if (&hostname($homsvr) ne '') {
1.567 raeburn 5322: my ($rdummy,$roledef)=
5323: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5324: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5325: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5326: if (defined($syspriv)) {
1.1043 raeburn 5327: if ($trest =~ /^$match_community$/) {
5328: $syspriv =~ s/bre\&S//;
5329: }
1.567 raeburn 5330: $$allroles{'cm./'}.=':'.$syspriv;
5331: $$allroles{$spec.'./'}.=':'.$syspriv;
5332: }
5333: if ($tdomain ne '') {
5334: if (defined($dompriv)) {
5335: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5336: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5337: }
5338: if (($trest ne '') && (defined($coursepriv))) {
5339: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5340: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5341: }
5342: }
5343: }
5344: }
5345: }
5346:
1.678 raeburn 5347: sub group_roleprivs {
5348: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5349: my $access = 1;
5350: my $now = time;
5351: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5352: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5353: if ($access) {
1.811 albertel 5354: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5355: $$allgroups{$course}{$group} .=':'.$group_privs;
5356: }
5357: }
1.567 raeburn 5358:
5359: sub standard_roleprivs {
5360: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5361: if (defined($pr{$trole.':s'})) {
5362: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5363: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5364: }
5365: if ($tdomain ne '') {
5366: if (defined($pr{$trole.':d'})) {
5367: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5368: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5369: }
5370: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5371: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5372: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5373: }
5374: }
5375: }
5376:
5377: sub set_userprivs {
1.1064 raeburn 5378: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5379: my $author=0;
5380: my $adv=0;
1.678 raeburn 5381: my %grouproles = ();
5382: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5383: my @groupkeys;
1.1000 raeburn 5384: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5385: push(@groupkeys,$role);
5386: }
5387: if (ref($groups_roles) eq 'HASH') {
5388: foreach my $key (keys(%{$groups_roles})) {
5389: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5390: push(@groupkeys,$key);
5391: }
5392: }
5393: }
5394: if (@groupkeys > 0) {
5395: foreach my $role (@groupkeys) {
5396: my ($trole,$area,$sec,$extendedarea);
5397: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5398: $trole = $1;
5399: $area = $2;
5400: $sec = $3;
5401: $extendedarea = $area.$sec;
5402: if (exists($$allgroups{$area})) {
5403: foreach my $group (keys(%{$$allgroups{$area}})) {
5404: my $spec = $trole.'.'.$extendedarea;
5405: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5406: $$allgroups{$area}{$group};
1.1064 raeburn 5407: }
1.678 raeburn 5408: }
5409: }
5410: }
5411: }
5412: }
1.800 albertel 5413: foreach my $group (keys(%grouproles)) {
5414: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5415: }
1.800 albertel 5416: foreach my $role (keys(%{$allroles})) {
5417: my %thesepriv;
1.941 raeburn 5418: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5419: foreach my $item (split(/:/,$$allroles{$role})) {
5420: if ($item ne '') {
5421: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5422: if ($restrictions eq '') {
5423: $thesepriv{$privilege}='F';
5424: } elsif ($thesepriv{$privilege} ne 'F') {
5425: $thesepriv{$privilege}.=$restrictions;
5426: }
5427: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5428: }
5429: }
5430: my $thesestr='';
1.1104 raeburn 5431: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5432: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5433: }
5434: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5435: }
5436: return ($author,$adv);
5437: }
5438:
1.994 raeburn 5439: sub role_status {
1.1104 raeburn 5440: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5441: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5442: my ($one,$two) = split(m{\./},$rolekey,2);
5443: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5444: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5445: $$where = '/'.$two;
1.994 raeburn 5446: $$trolecode=$$role.'.'.$$where;
5447: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5448: $$tstatus='is';
1.1104 raeburn 5449: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5450: $$tstatus='future';
1.1034 raeburn 5451: if ($$tstart<$now) {
5452: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5453: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5454: my (%allroles,%allgroups,$group_privs,
5455: %groups_roles,@rolecodes);
1.1002 raeburn 5456: my %userroles = (
5457: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5458: );
1.1064 raeburn 5459: @rolecodes = ('cm');
1.1002 raeburn 5460: my $spec=$$role.'.'.$$where;
5461: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5462: if ($$role =~ /^cr\//) {
5463: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5464: push(@rolecodes,'cr');
1.1002 raeburn 5465: } elsif ($$role eq 'gr') {
1.1064 raeburn 5466: push(@rolecodes,$$role);
1.1002 raeburn 5467: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5468: $env{'user.name'});
1.1064 raeburn 5469: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5470: (undef,my $group_privs) = split(/\//,$trole);
5471: $group_privs = &unescape($group_privs);
5472: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5473: 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 5474: &get_groups_roles($tdomain,$trest,
5475: \%course_roles,\@rolecodes,
5476: \%groups_roles);
1.1002 raeburn 5477: } else {
1.1064 raeburn 5478: push(@rolecodes,$$role);
1.1002 raeburn 5479: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5480: }
1.1064 raeburn 5481: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5482: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5483: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5484: }
5485: }
1.1034 raeburn 5486: $$tstatus = 'is';
1.1002 raeburn 5487: }
1.994 raeburn 5488: }
5489: if ($$tend) {
1.1104 raeburn 5490: if ($$tend<$update) {
1.994 raeburn 5491: $$tstatus='expired';
5492: } elsif ($$tend<$now) {
5493: $$tstatus='will_not';
5494: }
5495: }
5496: }
5497: }
5498: }
5499:
1.1104 raeburn 5500: sub get_groups_roles {
5501: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5502: return unless((ref($cdom_courseroles) eq 'HASH') &&
5503: (ref($rolecodes) eq 'ARRAY') &&
5504: (ref($groups_roles) eq 'HASH'));
5505: if (keys(%{$cdom_courseroles}) > 0) {
5506: my ($cnum) = ($rest =~ /^($match_courseid)/);
5507: if ($cdom ne '' && $cnum ne '') {
5508: foreach my $key (keys(%{$cdom_courseroles})) {
5509: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5510: my $crsrole = $1;
5511: my $crssec = $2;
5512: if ($crsrole =~ /^cr/) {
5513: unless (grep(/^cr$/,@{$rolecodes})) {
5514: push(@{$rolecodes},'cr');
5515: }
5516: } else {
5517: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5518: push(@{$rolecodes},$crsrole);
5519: }
5520: }
5521: my $rolekey = "$crsrole./$cdom/$cnum";
5522: if ($crssec ne '') {
5523: $rolekey .= "/$crssec";
5524: }
5525: $rolekey .= './';
5526: $groups_roles->{$rolekey} = $rolecodes;
5527: }
5528: }
5529: }
5530: }
5531: return;
5532: }
5533:
5534: sub delete_env_groupprivs {
5535: my ($where,$courseroles,$possroles) = @_;
5536: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5537: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5538: unless (ref($courseroles->{$udom}) eq 'HASH') {
5539: %{$courseroles->{$udom}} =
5540: &get_my_roles('','','userroles',['active'],
5541: $possroles,[$udom],1);
5542: }
5543: if (ref($courseroles->{$udom}) eq 'HASH') {
5544: foreach my $item (keys(%{$courseroles->{$udom}})) {
5545: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5546: my $area = '/'.$cdom.'/'.$cnum;
5547: my $privkey = "user.priv.$crsrole.$area";
5548: if ($crssec ne '') {
5549: $privkey .= '/'.$crssec;
5550: }
5551: $privkey .= ".$area/$group";
5552: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5553: }
5554: }
5555: return;
5556: }
5557:
1.994 raeburn 5558: sub check_adhoc_privs {
1.1104 raeburn 5559: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5560: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5561: my $setprivs;
1.994 raeburn 5562: if ($env{$cckey}) {
5563: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5564: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5565: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5566: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5567: $setprivs = 1;
1.994 raeburn 5568: }
5569: } else {
1.1088 raeburn 5570: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5571: $setprivs = 1;
1.994 raeburn 5572: }
1.1185 raeburn 5573: return $setprivs;
1.994 raeburn 5574: }
5575:
5576: sub set_adhoc_privileges {
5577: # role can be cc or ca
1.1088 raeburn 5578: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5579: my $area = '/'.$dcdom.'/'.$pickedcourse;
5580: my $spec = $role.'.'.$area;
5581: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5582: $env{'user.name'},1);
1.994 raeburn 5583: my %ccrole = ();
5584: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5585: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5586: &appenv(\%userroles,[$role,'cm']);
5587: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5588: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5589: &appenv( {'request.role' => $spec,
5590: 'request.role.domain' => $dcdom,
5591: 'request.course.sec' => ''
5592: }
5593: );
5594: my $tadv=0;
5595: if (&allowed('adv') eq 'F') { $tadv=1; }
5596: &appenv({'request.role.adv' => $tadv});
5597: }
1.994 raeburn 5598: }
5599:
1.12 www 5600: # --------------------------------------------------------------- get interface
5601:
5602: sub get {
1.131 albertel 5603: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5604: my $items='';
1.800 albertel 5605: foreach my $item (@$storearr) {
5606: $items.=&escape($item).'&';
1.191 harris41 5607: }
1.12 www 5608: $items=~s/\&$//;
1.620 albertel 5609: if (!$udomain) { $udomain=$env{'user.domain'}; }
5610: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5611: my $uhome=&homeserver($uname,$udomain);
5612:
1.133 albertel 5613: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5614: my @pairs=split(/\&/,$rep);
1.273 albertel 5615: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5616: return @pairs;
5617: }
1.15 www 5618: my %returnhash=();
1.42 www 5619: my $i=0;
1.800 albertel 5620: foreach my $item (@$storearr) {
5621: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5622: $i++;
1.191 harris41 5623: }
1.15 www 5624: return %returnhash;
1.27 www 5625: }
5626:
5627: # --------------------------------------------------------------- del interface
5628:
5629: sub del {
1.133 albertel 5630: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5631: my $items='';
1.800 albertel 5632: foreach my $item (@$storearr) {
5633: $items.=&escape($item).'&';
1.191 harris41 5634: }
1.984 neumanie 5635:
1.27 www 5636: $items=~s/\&$//;
1.620 albertel 5637: if (!$udomain) { $udomain=$env{'user.domain'}; }
5638: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5639: my $uhome=&homeserver($uname,$udomain);
5640: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5641: }
5642:
5643: # -------------------------------------------------------------- dump interface
5644:
1.1180 droeschl 5645: sub unserialize {
5646: my ($rep, $escapedkeys) = @_;
5647:
5648: return {} if $rep =~ /^error/;
5649:
5650: my %returnhash=();
1.1252 raeburn 5651: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5652: my ($key, $value) = split(/=/, $item, 2);
5653: $key = unescape($key) unless $escapedkeys;
5654: next if $key =~ /^error: 2 /;
1.1252 raeburn 5655: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5656: }
5657: #return %returnhash;
5658: return \%returnhash;
5659: }
5660:
5661: # see Lond::dump_with_regexp
5662: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5663: sub dump {
1.1180 droeschl 5664: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5665: if (!$udomain) { $udomain=$env{'user.domain'}; }
5666: if (!$uname) { $uname=$env{'user.name'}; }
5667: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5668:
1.1266 raeburn 5669: if ($regexp) {
5670: $regexp=&escape($regexp);
5671: } else {
5672: $regexp='.';
5673: }
1.1180 droeschl 5674: if (grep { $_ eq $uhome } current_machine_ids()) {
5675: # user is hosted on this machine
1.1266 raeburn 5676: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5677: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5678: return %{unserialize($reply, $escapedkeys)};
5679: }
1.1166 raeburn 5680: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5681: my @pairs=split(/\&/,$rep);
5682: my %returnhash=();
1.1098 foxr 5683: if (!($rep =~ /^error/ )) {
5684: foreach my $item (@pairs) {
5685: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5686: $key = unescape($key) unless $escapedkeys;
5687: #$key = &unescape($key);
1.1098 foxr 5688: next if ($key =~ /^error: 2 /);
5689: $returnhash{$key}=&thaw_unescape($value);
5690: }
1.755 albertel 5691: }
5692: return %returnhash;
1.407 www 5693: }
5694:
1.1098 foxr 5695:
1.717 albertel 5696: # --------------------------------------------------------- dumpstore interface
5697:
5698: sub dumpstore {
5699: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5700: # same as dump but keys must be escaped. They may contain colon separated
5701: # lists of values that may themself contain colons (e.g. symbs).
5702: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5703: }
5704:
1.407 www 5705: # -------------------------------------------------------------- keys interface
5706:
5707: sub getkeys {
5708: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5709: if (!$udomain) { $udomain=$env{'user.domain'}; }
5710: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5711: my $uhome=&homeserver($uname,$udomain);
5712: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5713: my @keyarray=();
1.800 albertel 5714: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5715: next if ($key =~ /^error: 2 /);
1.800 albertel 5716: push(@keyarray,&unescape($key));
1.407 www 5717: }
5718: return @keyarray;
1.318 matthew 5719: }
5720:
1.319 matthew 5721: # --------------------------------------------------------------- currentdump
5722: sub currentdump {
1.328 matthew 5723: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5724: $courseid = $env{'request.course.id'} if (! defined($courseid));
5725: $sdom = $env{'user.domain'} if (! defined($sdom));
5726: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5727: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5728: my $rep;
5729:
5730: if (grep { $_ eq $uhome } current_machine_ids()) {
5731: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5732: $courseid)));
5733: } else {
5734: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5735: }
5736:
1.318 matthew 5737: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5738: #
1.318 matthew 5739: my %returnhash=();
1.319 matthew 5740: #
5741: if ($rep eq "unknown_cmd") {
5742: # an old lond will not know currentdump
5743: # Do a dump and make it look like a currentdump
1.822 albertel 5744: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5745: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5746: my %hash = @tmp;
5747: @tmp=();
1.424 matthew 5748: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5749: } else {
5750: my @pairs=split(/\&/,$rep);
1.800 albertel 5751: foreach my $pair (@pairs) {
5752: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5753: my ($symb,$param) = split(/:/,$key);
5754: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5755: &thaw_unescape($value);
1.319 matthew 5756: }
1.191 harris41 5757: }
1.12 www 5758: return %returnhash;
1.424 matthew 5759: }
5760:
5761: sub convert_dump_to_currentdump{
5762: my %hash = %{shift()};
5763: my %returnhash;
5764: # Code ripped from lond, essentially. The only difference
5765: # here is the unescaping done by lonnet::dump(). Conceivably
5766: # we might run in to problems with parameter names =~ /^v\./
5767: while (my ($key,$value) = each(%hash)) {
5768: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5769: $symb = &unescape($symb);
5770: $param = &unescape($param);
1.424 matthew 5771: next if ($v eq 'version' || $symb eq 'keys');
5772: next if (exists($returnhash{$symb}) &&
5773: exists($returnhash{$symb}->{$param}) &&
5774: $returnhash{$symb}->{'v.'.$param} > $v);
5775: $returnhash{$symb}->{$param}=$value;
5776: $returnhash{$symb}->{'v.'.$param}=$v;
5777: }
5778: #
5779: # Remove all of the keys in the hashes which keep track of
5780: # the version of the parameter.
5781: while (my ($symb,$param_hash) = each(%returnhash)) {
5782: # use a foreach because we are going to delete from the hash.
5783: foreach my $key (keys(%$param_hash)) {
5784: delete($param_hash->{$key}) if ($key =~ /^v\./);
5785: }
5786: }
5787: return \%returnhash;
1.12 www 5788: }
5789:
1.627 albertel 5790: # ------------------------------------------------------ critical inc interface
5791:
5792: sub cinc {
5793: return &inc(@_,'critical');
5794: }
5795:
1.449 matthew 5796: # --------------------------------------------------------------- inc interface
5797:
5798: sub inc {
1.627 albertel 5799: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5800: if (!$udomain) { $udomain=$env{'user.domain'}; }
5801: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5802: my $uhome=&homeserver($uname,$udomain);
5803: my $items='';
5804: if (! ref($store)) {
5805: # got a single value, so use that instead
5806: $items = &escape($store).'=&';
5807: } elsif (ref($store) eq 'SCALAR') {
5808: $items = &escape($$store).'=&';
5809: } elsif (ref($store) eq 'ARRAY') {
5810: $items = join('=&',map {&escape($_);} @{$store});
5811: } elsif (ref($store) eq 'HASH') {
5812: while (my($key,$value) = each(%{$store})) {
5813: $items.= &escape($key).'='.&escape($value).'&';
5814: }
5815: }
5816: $items=~s/\&$//;
1.627 albertel 5817: if ($critical) {
5818: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5819: } else {
5820: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5821: }
1.449 matthew 5822: }
5823:
1.12 www 5824: # --------------------------------------------------------------- put interface
5825:
5826: sub put {
1.134 albertel 5827: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5828: if (!$udomain) { $udomain=$env{'user.domain'}; }
5829: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5830: my $uhome=&homeserver($uname,$udomain);
1.12 www 5831: my $items='';
1.800 albertel 5832: foreach my $item (keys(%$storehash)) {
5833: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5834: }
1.12 www 5835: $items=~s/\&$//;
1.134 albertel 5836: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5837: }
5838:
1.631 albertel 5839: # ------------------------------------------------------------ newput interface
5840:
5841: sub newput {
5842: my ($namespace,$storehash,$udomain,$uname)=@_;
5843: if (!$udomain) { $udomain=$env{'user.domain'}; }
5844: if (!$uname) { $uname=$env{'user.name'}; }
5845: my $uhome=&homeserver($uname,$udomain);
5846: my $items='';
5847: foreach my $key (keys(%$storehash)) {
5848: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5849: }
5850: $items=~s/\&$//;
5851: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5852: }
5853:
5854: # --------------------------------------------------------- putstore interface
5855:
1.524 raeburn 5856: sub putstore {
1.1269 raeburn 5857: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 5858: if (!$udomain) { $udomain=$env{'user.domain'}; }
5859: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5860: my $uhome=&homeserver($uname,$udomain);
5861: my $items='';
1.715 albertel 5862: foreach my $key (keys(%$storehash)) {
5863: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5864: }
1.715 albertel 5865: $items=~s/\&$//;
1.716 albertel 5866: my $esc_symb=&escape($symb);
5867: my $esc_v=&escape($version);
1.715 albertel 5868: my $reply =
1.716 albertel 5869: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5870: $uhome);
1.1269 raeburn 5871: if (($tolog) && ($reply eq 'ok')) {
5872: my $namevalue='';
5873: foreach my $key (keys(%{$storehash})) {
5874: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5875: }
5876: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
5877: '&host='.&escape($perlvar{'lonHostID'}).
5878: '&version='.$esc_v.
5879: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
5880: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
5881: }
1.715 albertel 5882: if ($reply eq 'unknown_cmd') {
1.716 albertel 5883: # gfall back to way things use to be done
1.715 albertel 5884: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5885: $uname);
1.524 raeburn 5886: }
1.715 albertel 5887: return $reply;
5888: }
5889:
5890: sub old_putstore {
1.716 albertel 5891: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5892: if (!$udomain) { $udomain=$env{'user.domain'}; }
5893: if (!$uname) { $uname=$env{'user.name'}; }
5894: my $uhome=&homeserver($uname,$udomain);
5895: my %newstorehash;
1.800 albertel 5896: foreach my $item (keys(%$storehash)) {
5897: my $key = $version.':'.&escape($symb).':'.$item;
5898: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5899: }
5900: my $items='';
5901: my %allitems = ();
1.800 albertel 5902: foreach my $item (keys(%newstorehash)) {
5903: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5904: my $key = $1.':keys:'.$2;
5905: $allitems{$key} .= $3.':';
5906: }
1.800 albertel 5907: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5908: }
1.800 albertel 5909: foreach my $item (keys(%allitems)) {
5910: $allitems{$item} =~ s/\:$//;
5911: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5912: }
5913: $items=~s/\&$//;
5914: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5915: }
5916:
1.47 www 5917: # ------------------------------------------------------ critical put interface
5918:
5919: sub cput {
1.134 albertel 5920: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5921: if (!$udomain) { $udomain=$env{'user.domain'}; }
5922: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5923: my $uhome=&homeserver($uname,$udomain);
1.47 www 5924: my $items='';
1.800 albertel 5925: foreach my $item (keys(%$storehash)) {
5926: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5927: }
1.47 www 5928: $items=~s/\&$//;
1.134 albertel 5929: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5930: }
5931:
5932: # -------------------------------------------------------------- eget interface
5933:
5934: sub eget {
1.133 albertel 5935: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5936: my $items='';
1.800 albertel 5937: foreach my $item (@$storearr) {
5938: $items.=&escape($item).'&';
1.191 harris41 5939: }
1.12 www 5940: $items=~s/\&$//;
1.620 albertel 5941: if (!$udomain) { $udomain=$env{'user.domain'}; }
5942: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5943: my $uhome=&homeserver($uname,$udomain);
5944: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5945: my @pairs=split(/\&/,$rep);
5946: my %returnhash=();
1.42 www 5947: my $i=0;
1.800 albertel 5948: foreach my $item (@$storearr) {
5949: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5950: $i++;
1.191 harris41 5951: }
1.12 www 5952: return %returnhash;
5953: }
5954:
1.667 albertel 5955: # ------------------------------------------------------------ tmpput interface
5956: sub tmpput {
1.802 raeburn 5957: my ($storehash,$server,$context)=@_;
1.667 albertel 5958: my $items='';
1.800 albertel 5959: foreach my $item (keys(%$storehash)) {
5960: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5961: }
5962: $items=~s/\&$//;
1.802 raeburn 5963: if (defined($context)) {
5964: $items .= ':'.&escape($context);
5965: }
1.667 albertel 5966: return &reply("tmpput:$items",$server);
5967: }
5968:
5969: # ------------------------------------------------------------ tmpget interface
5970: sub tmpget {
1.688 albertel 5971: my ($token,$server)=@_;
5972: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5973: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5974: my %returnhash;
5975: foreach my $item (split(/\&/,$rep)) {
5976: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5977: next if ($key =~ /^error: 2 /);
1.667 albertel 5978: $returnhash{&unescape($key)}=&thaw_unescape($value);
5979: }
5980: return %returnhash;
5981: }
5982:
1.1113 raeburn 5983: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5984: sub tmpdel {
5985: my ($token,$server)=@_;
5986: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5987: return &reply("tmpdel:$token",$server);
5988: }
5989:
1.1198 raeburn 5990: # ------------------------------------------------------------ get_timebased_id
5991:
5992: sub get_timebased_id {
5993: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5994: $maxtries) = @_;
5995: my ($newid,$error,$dellock);
5996: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5997: return ('','ok','invalid call to get suffix');
5998: }
5999:
6000: # set defaults for any optional args for which values were not supplied
6001: if ($who eq '') {
6002: $who = $env{'user.name'}.':'.$env{'user.domain'};
6003: }
6004: if (!$locktries) {
6005: $locktries = 3;
6006: }
6007: if (!$maxtries) {
6008: $maxtries = 10;
6009: }
6010:
6011: if (($cdom eq '') || ($cnum eq '')) {
6012: if ($env{'request.course.id'}) {
6013: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6014: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6015: }
6016: if (($cdom eq '') || ($cnum eq '')) {
6017: return ('','ok','call to get suffix not in course context');
6018: }
6019: }
6020:
6021: # construct locking item
6022: my $lockhash = {
6023: $prefix."\0".'locked_'.$keyid => $who,
6024: };
6025: my $tries = 0;
6026:
6027: # attempt to get lock on nohist_$namespace file
6028: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6029: while (($gotlock ne 'ok') && $tries <$locktries) {
6030: $tries ++;
6031: sleep 1;
6032: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6033: }
6034:
6035: # attempt to get unique identifier, based on current timestamp
6036: if ($gotlock eq 'ok') {
6037: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6038: my $id = time;
6039: $newid = $id;
1.1268 raeburn 6040: if ($idtype eq 'addcode') {
6041: $newid .= &sixnum_code();
6042: }
1.1198 raeburn 6043: my $idtries = 0;
6044: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6045: if ($idtype eq 'concat') {
6046: $newid = $id.$idtries;
1.1268 raeburn 6047: } elsif ($idtype eq 'addcode') {
6048: $newid = $newid.&sixnum_code();
1.1198 raeburn 6049: } else {
6050: $newid ++;
6051: }
6052: $idtries ++;
6053: }
6054: if (!exists($inuse{$prefix."\0".$newid})) {
6055: my %new_item = (
6056: $prefix."\0".$newid => $who,
6057: );
6058: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6059: $cdom,$cnum);
6060: if ($putresult ne 'ok') {
6061: undef($newid);
6062: $error = 'error saving new item: '.$putresult;
6063: }
6064: } else {
1.1268 raeburn 6065: undef($newid);
1.1198 raeburn 6066: $error = ('error: no unique suffix available for the new item ');
6067: }
6068: # remove lock
6069: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6070: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6071: } else {
6072: $error = "error: could not obtain lockfile\n";
6073: $dellock = 'ok';
1.1276 raeburn 6074: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6075: $dellock = 'nolock';
6076: }
1.1198 raeburn 6077: }
6078: return ($newid,$dellock,$error);
6079: }
6080:
1.1268 raeburn 6081: sub sixnum_code {
6082: my $code;
6083: for (0..6) {
6084: $code .= int( rand(9) );
6085: }
6086: return $code;
6087: }
6088:
1.765 albertel 6089: # -------------------------------------------------- portfolio access checking
6090:
6091: sub portfolio_access {
1.1270 raeburn 6092: my ($requrl,$clientip) = @_;
1.765 albertel 6093: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6094: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6095: if ($result) {
6096: my %setters;
6097: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6098: my ($startblock,$endblock) =
6099: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6100: if ($startblock && $endblock) {
6101: return 'B';
6102: }
6103: } else {
6104: my ($startblock,$endblock) =
6105: &Apache::loncommon::blockcheck(\%setters,'port');
6106: if ($startblock && $endblock) {
6107: return 'B';
6108: }
6109: }
6110: }
1.765 albertel 6111: if ($result eq 'ok') {
1.766 albertel 6112: return 'F';
1.765 albertel 6113: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6114: return 'A';
1.765 albertel 6115: }
1.766 albertel 6116: return '';
1.765 albertel 6117: }
6118:
6119: sub get_portfolio_access {
1.1270 raeburn 6120: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6121:
6122: if (!ref($access_hash)) {
6123: my $current_perms = &get_portfile_permissions($udom,$unum);
6124: my %access_controls = &get_access_controls($current_perms,$group,
6125: $file_name);
6126: $access_hash = $access_controls{$file_name};
6127: }
6128:
1.1270 raeburn 6129: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6130: my $now = time;
6131: if (ref($access_hash) eq 'HASH') {
6132: foreach my $key (keys(%{$access_hash})) {
6133: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6134: if ($start > $now) {
6135: next;
6136: }
6137: if ($end && $end<$now) {
6138: next;
6139: }
6140: if ($scope eq 'public') {
6141: $public = $key;
6142: last;
6143: } elsif ($scope eq 'guest') {
6144: $guest = $key;
6145: } elsif ($scope eq 'domains') {
6146: push(@domains,$key);
6147: } elsif ($scope eq 'users') {
6148: push(@users,$key);
6149: } elsif ($scope eq 'course') {
6150: push(@courses,$key);
6151: } elsif ($scope eq 'group') {
6152: push(@groups,$key);
1.1270 raeburn 6153: } elsif ($scope eq 'ip') {
6154: push(@ips,$key);
1.765 albertel 6155: }
6156: }
6157: if ($public) {
6158: return 'ok';
1.1270 raeburn 6159: } elsif (@ips > 0) {
6160: my $allowed;
6161: foreach my $ipkey (@ips) {
6162: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6163: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6164: $allowed = 1;
6165: last;
6166: }
6167: }
6168: }
6169: if ($allowed) {
6170: return 'ok';
6171: }
1.765 albertel 6172: }
6173: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6174: if ($guest) {
6175: return $guest;
6176: }
6177: } else {
6178: if (@domains > 0) {
6179: foreach my $domkey (@domains) {
6180: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6181: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6182: return 'ok';
6183: }
6184: }
6185: }
6186: }
6187: if (@users > 0) {
6188: foreach my $userkey (@users) {
1.865 raeburn 6189: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6190: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6191: if (ref($item) eq 'HASH') {
6192: if (($item->{'uname'} eq $env{'user.name'}) &&
6193: ($item->{'udom'} eq $env{'user.domain'})) {
6194: return 'ok';
6195: }
6196: }
6197: }
6198: }
1.765 albertel 6199: }
6200: }
6201: my %roleshash;
6202: my @courses_and_groups = @courses;
6203: push(@courses_and_groups,@groups);
6204: if (@courses_and_groups > 0) {
6205: my (%allgroups,%allroles);
6206: my ($start,$end,$role,$sec,$group);
6207: foreach my $envkey (%env) {
1.1060 raeburn 6208: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6209: my $cid = $2.'_'.$3;
6210: if ($1 eq 'gr') {
6211: $group = $4;
6212: $allgroups{$cid}{$group} = $env{$envkey};
6213: } else {
6214: if ($4 eq '') {
6215: $sec = 'none';
6216: } else {
6217: $sec = $4;
6218: }
6219: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6220: }
1.811 albertel 6221: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6222: my $cid = $2.'_'.$3;
6223: if ($4 eq '') {
6224: $sec = 'none';
6225: } else {
6226: $sec = $4;
6227: }
6228: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6229: }
6230: }
6231: if (keys(%allroles) == 0) {
6232: return;
6233: }
6234: foreach my $key (@courses_and_groups) {
6235: my %content = %{$$access_hash{$key}};
6236: my $cnum = $content{'number'};
6237: my $cdom = $content{'domain'};
6238: my $cid = $cdom.'_'.$cnum;
6239: if (!exists($allroles{$cid})) {
6240: next;
6241: }
6242: foreach my $role_id (keys(%{$content{'roles'}})) {
6243: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6244: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6245: my @status = @{$content{'roles'}{$role_id}{'access'}};
6246: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6247: foreach my $role (keys(%{$allroles{$cid}})) {
6248: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6249: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6250: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6251: if (grep/^all$/,@sections) {
6252: return 'ok';
6253: } else {
6254: if (grep/^$sec$/,@sections) {
6255: return 'ok';
6256: }
6257: }
6258: }
6259: }
6260: if (keys(%{$allgroups{$cid}}) == 0) {
6261: if (grep/^none$/,@groups) {
6262: return 'ok';
6263: }
6264: } else {
6265: if (grep/^all$/,@groups) {
6266: return 'ok';
6267: }
6268: foreach my $group (keys(%{$allgroups{$cid}})) {
6269: if (grep/^$group$/,@groups) {
6270: return 'ok';
6271: }
6272: }
6273: }
6274: }
6275: }
6276: }
6277: }
6278: }
6279: if ($guest) {
6280: return $guest;
6281: }
6282: }
6283: }
6284: return;
6285: }
6286:
6287: sub course_group_datechecker {
6288: my ($dates,$now,$status) = @_;
6289: my ($start,$end) = split(/\./,$dates);
6290: if (!$start && !$end) {
6291: return 'ok';
6292: }
6293: if (grep/^active$/,@{$status}) {
6294: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6295: return 'ok';
6296: }
6297: }
6298: if (grep/^previous$/,@{$status}) {
6299: if ($end > $now ) {
6300: return 'ok';
6301: }
6302: }
6303: if (grep/^future$/,@{$status}) {
6304: if ($start > $now) {
6305: return 'ok';
6306: }
6307: }
6308: return;
6309: }
6310:
6311: sub parse_portfolio_url {
6312: my ($url) = @_;
6313:
6314: my ($type,$udom,$unum,$group,$file_name);
6315:
1.823 albertel 6316: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6317: $type = 1;
6318: $udom = $1;
6319: $unum = $2;
6320: $file_name = $3;
1.823 albertel 6321: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6322: $type = 2;
6323: $udom = $1;
6324: $unum = $2;
6325: $group = $3;
6326: $file_name = $3.'/'.$4;
6327: }
6328: if (wantarray) {
6329: return ($type,$udom,$unum,$file_name,$group);
6330: }
6331: return $type;
6332: }
6333:
6334: sub is_portfolio_url {
6335: my ($url) = @_;
6336: return scalar(&parse_portfolio_url($url));
6337: }
6338:
1.798 raeburn 6339: sub is_portfolio_file {
6340: my ($file) = @_;
1.820 raeburn 6341: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6342: return 1;
6343: }
6344: return;
6345: }
6346:
1.976 raeburn 6347: sub usertools_access {
1.1084 raeburn 6348: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6349: my ($access,%tools);
6350: if ($context eq '') {
6351: $context = 'tools';
6352: }
6353: if ($context eq 'requestcourses') {
6354: %tools = (
6355: official => 1,
6356: unofficial => 1,
1.1006 raeburn 6357: community => 1,
1.1246 raeburn 6358: textbook => 1,
1.985 raeburn 6359: );
1.1183 raeburn 6360: } elsif ($context eq 'requestauthor') {
6361: %tools = (
6362: requestauthor => 1,
6363: );
1.985 raeburn 6364: } else {
6365: %tools = (
6366: aboutme => 1,
6367: blog => 1,
1.1177 raeburn 6368: webdav => 1,
1.985 raeburn 6369: portfolio => 1,
6370: );
6371: }
1.976 raeburn 6372: return if (!defined($tools{$tool}));
6373:
1.1242 raeburn 6374: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6375: $udom = $env{'user.domain'};
6376: $uname = $env{'user.name'};
6377: }
6378:
1.978 raeburn 6379: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6380: if ($action ne 'reload') {
1.985 raeburn 6381: if ($context eq 'requestcourses') {
6382: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6383: } elsif ($context eq 'requestauthor') {
6384: return $env{'environment.canrequest.author'};
1.985 raeburn 6385: } else {
6386: return $env{'environment.availabletools.'.$tool};
6387: }
6388: }
1.976 raeburn 6389: }
6390:
1.1183 raeburn 6391: my ($toolstatus,$inststatus,$envkey);
6392: if ($context eq 'requestauthor') {
6393: $envkey = $context;
6394: } else {
6395: $envkey = $context.'.'.$tool;
6396: }
1.976 raeburn 6397:
1.985 raeburn 6398: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6399: ($action ne 'reload')) {
1.1183 raeburn 6400: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6401: $inststatus = $env{'environment.inststatus'};
6402: } else {
1.1084 raeburn 6403: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6404: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6405: $inststatus = $userenvref->{'inststatus'};
6406: } else {
1.1183 raeburn 6407: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6408: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6409: $inststatus = $userenv{'inststatus'};
6410: }
1.976 raeburn 6411: }
6412:
6413: if ($toolstatus ne '') {
6414: if ($toolstatus) {
6415: $access = 1;
6416: } else {
6417: $access = 0;
6418: }
6419: return $access;
6420: }
6421:
1.1084 raeburn 6422: my ($is_adv,%domdef);
6423: if (ref($is_advref) eq 'HASH') {
6424: $is_adv = $is_advref->{'is_adv'};
6425: } else {
6426: $is_adv = &is_advanced_user($udom,$uname);
6427: }
6428: if (ref($domdefref) eq 'HASH') {
6429: %domdef = %{$domdefref};
6430: } else {
6431: %domdef = &get_domain_defaults($udom);
6432: }
1.976 raeburn 6433: if (ref($domdef{$tool}) eq 'HASH') {
6434: if ($is_adv) {
6435: if ($domdef{$tool}{'_LC_adv'} ne '') {
6436: if ($domdef{$tool}{'_LC_adv'}) {
6437: $access = 1;
6438: } else {
6439: $access = 0;
6440: }
6441: return $access;
6442: }
6443: }
6444: if ($inststatus ne '') {
6445: my ($hasaccess,$hasnoaccess);
6446: foreach my $affiliation (split(/:/,$inststatus)) {
6447: if ($domdef{$tool}{$affiliation} ne '') {
6448: if ($domdef{$tool}{$affiliation}) {
6449: $hasaccess = 1;
6450: } else {
6451: $hasnoaccess = 1;
6452: }
6453: }
6454: }
6455: if ($hasaccess || $hasnoaccess) {
6456: if ($hasaccess) {
6457: $access = 1;
6458: } elsif ($hasnoaccess) {
6459: $access = 0;
6460: }
6461: return $access;
6462: }
6463: } else {
6464: if ($domdef{$tool}{'default'} ne '') {
6465: if ($domdef{$tool}{'default'}) {
6466: $access = 1;
6467: } elsif ($domdef{$tool}{'default'} == 0) {
6468: $access = 0;
6469: }
6470: return $access;
6471: }
6472: }
6473: } else {
1.1177 raeburn 6474: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6475: $access = 1;
6476: } else {
6477: $access = 0;
6478: }
1.976 raeburn 6479: return $access;
6480: }
6481: }
6482:
1.1050 raeburn 6483: sub is_course_owner {
6484: my ($cdom,$cnum,$udom,$uname) = @_;
6485: if (($udom eq '') || ($uname eq '')) {
6486: $udom = $env{'user.domain'};
6487: $uname = $env{'user.name'};
6488: }
6489: unless (($udom eq '') || ($uname eq '')) {
6490: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6491: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6492: return 1;
6493: } else {
6494: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6495: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6496: return 1;
6497: }
6498: }
6499: }
6500: }
6501: return;
6502: }
6503:
1.976 raeburn 6504: sub is_advanced_user {
6505: my ($udom,$uname) = @_;
1.1085 raeburn 6506: if ($udom ne '' && $uname ne '') {
6507: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6508: if (wantarray) {
6509: return ($env{'user.adv'},$env{'user.author'});
6510: } else {
6511: return $env{'user.adv'};
6512: }
1.1085 raeburn 6513: }
6514: }
1.976 raeburn 6515: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6516: my %allroles;
1.1128 raeburn 6517: my ($is_adv,$is_author);
1.976 raeburn 6518: foreach my $role (keys(%roleshash)) {
6519: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6520: my $area = '/'.$tdomain.'/'.$trest;
6521: if ($sec ne '') {
6522: $area .= '/'.$sec;
6523: }
6524: if (($area ne '') && ($trole ne '')) {
6525: my $spec=$trole.'.'.$area;
6526: if ($trole =~ /^cr\//) {
6527: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6528: } elsif ($trole ne 'gr') {
6529: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6530: }
1.1128 raeburn 6531: if ($trole eq 'au') {
6532: $is_author = 1;
6533: }
1.976 raeburn 6534: }
6535: }
6536: foreach my $role (keys(%allroles)) {
6537: last if ($is_adv);
6538: foreach my $item (split(/:/,$allroles{$role})) {
6539: if ($item ne '') {
6540: my ($privilege,$restrictions)=split(/&/,$item);
6541: if ($privilege eq 'adv') {
6542: $is_adv = 1;
6543: last;
6544: }
6545: }
6546: }
6547: }
1.1128 raeburn 6548: if (wantarray) {
6549: return ($is_adv,$is_author);
6550: }
1.976 raeburn 6551: return $is_adv;
6552: }
1.798 raeburn 6553:
1.1035 raeburn 6554: sub check_can_request {
1.1036 raeburn 6555: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6556: my $canreq = 0;
6557: my ($types,$typename) = &Apache::loncommon::course_types();
6558: my @options = ('approval','validate','autolimit');
6559: my $optregex = join('|',@options);
6560: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6561: foreach my $type (@{$types}) {
6562: if (&usertools_access($env{'user.name'},
6563: $env{'user.domain'},
6564: $type,undef,'requestcourses')) {
6565: $canreq ++;
1.1036 raeburn 6566: if (ref($request_domains) eq 'HASH') {
6567: push(@{$request_domains->{$type}},$env{'user.domain'});
6568: }
1.1035 raeburn 6569: if ($dom eq $env{'user.domain'}) {
6570: $can_request->{$type} = 1;
6571: }
6572: }
6573: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6574: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6575: if (@curr > 0) {
1.1036 raeburn 6576: foreach my $item (@curr) {
6577: if (ref($request_domains) eq 'HASH') {
6578: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6579: if ($otherdom ne '') {
6580: if (ref($request_domains->{$type}) eq 'ARRAY') {
6581: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6582: push(@{$request_domains->{$type}},$otherdom);
6583: }
6584: } else {
6585: push(@{$request_domains->{$type}},$otherdom);
6586: }
6587: }
6588: }
6589: }
6590: unless($dom eq $env{'user.domain'}) {
6591: $canreq ++;
1.1035 raeburn 6592: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6593: $can_request->{$type} = 1;
6594: }
6595: }
6596: }
6597: }
6598: }
6599: }
6600: return $canreq;
6601: }
6602:
1.341 www 6603: # ---------------------------------------------- Custom access rule evaluation
6604:
6605: sub customaccess {
6606: my ($priv,$uri)=@_;
1.807 albertel 6607: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6608: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6609: $udom = &LONCAPA::clean_domain($udom);
6610: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6611: my $access=0;
1.800 albertel 6612: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6613: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6614: if ($type eq 'user') {
6615: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6616: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6617: if ($tdom) {
6618: if ($tdom ne $env{'user.domain'}) { next; }
6619: }
1.896 albertel 6620: if ($tuname) {
6621: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6622: }
6623: $access=($effect eq 'allow');
6624: last;
6625: }
6626: } else {
6627: if ($role) {
6628: if ($role ne $urole) { next; }
6629: }
6630: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6631: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6632: if ($tdom) {
6633: if ($tdom ne $udom) { next; }
6634: }
6635: if ($tcrs) {
6636: if ($tcrs ne $ucrs) { next; }
6637: }
6638: if ($tsec) {
6639: if ($tsec ne $usec) { next; }
6640: }
6641: $access=($effect eq 'allow');
6642: last;
6643: }
6644: if ($realm eq '' && $role eq '') {
6645: $access=($effect eq 'allow');
6646: }
1.402 bowersj2 6647: }
1.341 www 6648: }
6649: return $access;
6650: }
6651:
1.103 harris41 6652: # ------------------------------------------------- Check for a user privilege
1.12 www 6653:
6654: sub allowed {
1.1281 raeburn 6655: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6656: my $ver_orguri=$uri;
1.439 www 6657: $uri=&deversion($uri);
1.152 www 6658: my $orguri=$uri;
1.52 www 6659: $uri=&declutter($uri);
1.809 raeburn 6660:
1.810 raeburn 6661: if ($priv eq 'evb') {
6662: # Evade communication block restrictions for specified role in a course
6663: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6664: return $1;
6665: } else {
6666: return;
6667: }
6668: }
6669:
1.620 albertel 6670: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6671: # Free bre access to adm and meta resources
1.775 albertel 6672: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6673: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6674: && ($priv eq 'bre')) {
1.14 www 6675: return 'F';
1.159 www 6676: }
6677:
1.545 banghart 6678: # Free bre access to user's own portfolio contents
1.714 raeburn 6679: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6680: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6681: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6682: my %setters;
6683: my ($startblock,$endblock) =
6684: &Apache::loncommon::blockcheck(\%setters,'port');
6685: if ($startblock && $endblock) {
6686: return 'B';
6687: } else {
6688: return 'F';
6689: }
1.545 banghart 6690: }
6691:
1.762 raeburn 6692: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6693: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6694: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6695: if (exists($env{'request.course.id'})) {
6696: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6697: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6698: if (($domain eq $cdom) && ($name eq $cnum)) {
6699: my $courseprivid=$env{'request.course.id'};
6700: $courseprivid=~s/\_/\//;
6701: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6702: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6703: return $1;
1.762 raeburn 6704: } else {
6705: if ($env{'request.course.sec'}) {
6706: $courseprivid.='/'.$env{'request.course.sec'};
6707: }
6708: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6709: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6710: return $2;
6711: }
1.714 raeburn 6712: }
6713: }
6714: }
6715: }
6716:
1.159 www 6717: # Free bre to public access
6718:
6719: if ($priv eq 'bre') {
1.238 www 6720: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6721: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6722: return 'F';
6723: }
1.238 www 6724: if ($copyright eq 'priv') {
6725: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6726: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6727: return '';
6728: }
6729: }
6730: if ($copyright eq 'domain') {
6731: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6732: unless (($env{'user.domain'} eq $1) ||
6733: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6734: return '';
6735: }
1.262 matthew 6736: }
1.620 albertel 6737: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6738: # Library role, so allow browsing of resources in this domain.
6739: return 'F';
1.238 www 6740: }
1.341 www 6741: if ($copyright eq 'custom') {
6742: unless (&customaccess($priv,$uri)) { return ''; }
6743: }
1.14 www 6744: }
1.264 matthew 6745: # Domain coordinator is trying to create a course
1.620 albertel 6746: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6747: # uri is the requested domain in this case.
6748: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6749: # a role of dc for the domain in question.
1.620 albertel 6750: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6751: }
1.29 www 6752:
1.52 www 6753: my $thisallowed='';
6754: my $statecond=0;
6755: my $courseprivid='';
6756:
1.1039 raeburn 6757: my $ownaccess;
1.1043 raeburn 6758: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6759: if (($priv eq 'bro') && ($env{'user.author'})) {
6760: if ($uri eq '') {
6761: $ownaccess = 1;
6762: } else {
6763: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6764: my $udom = $env{'user.domain'};
6765: my $uname = $env{'user.name'};
6766: if ($uri =~ m{^\Q$udom\E/?$}) {
6767: $ownaccess = 1;
1.1040 raeburn 6768: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6769: unless ($uri =~ m{\.\./}) {
6770: $ownaccess = 1;
6771: }
6772: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6773: my $now = time;
6774: if ($uri =~ m{^([^/]+)/?$}) {
6775: my $adom = $1;
6776: foreach my $key (keys(%env)) {
1.1042 raeburn 6777: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6778: my ($start,$end) = split('.',$env{$key});
6779: if (($now >= $start) && (!$end || $end < $now)) {
6780: $ownaccess = 1;
6781: last;
6782: }
6783: }
6784: }
6785: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6786: my $adom = $1;
6787: my $aname = $2;
1.1042 raeburn 6788: foreach my $role ('ca','aa') {
6789: if ($env{"user.role.$role./$adom/$aname"}) {
6790: my ($start,$end) =
6791: split('.',$env{"user.role.$role./$adom/$aname"});
6792: if (($now >= $start) && (!$end || $end < $now)) {
6793: $ownaccess = 1;
6794: last;
6795: }
1.1039 raeburn 6796: }
6797: }
6798: }
6799: }
6800: }
6801: }
6802: }
6803:
1.52 www 6804: # Course
6805:
1.620 albertel 6806: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6807: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6808: $thisallowed.=$1;
6809: }
1.52 www 6810: }
1.29 www 6811:
1.52 www 6812: # Domain
6813:
1.620 albertel 6814: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6815: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6816: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6817: $thisallowed.=$1;
6818: }
1.12 www 6819: }
1.52 www 6820:
1.1141 raeburn 6821: # User who is not author or co-author might still be able to edit
6822: # resource of an author in the domain (e.g., if Domain Coordinator).
6823: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6824: (&allowed('mdc',$env{'request.course.id'}))) {
6825: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6826: $thisallowed.=$1;
6827: }
6828: }
6829:
1.52 www 6830: # Course: uri itself is a course
1.66 www 6831: my $courseuri=$uri;
6832: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6833: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6834:
1.620 albertel 6835: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6836: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6837: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6838: $thisallowed.=$1;
6839: }
1.12 www 6840: }
1.29 www 6841:
1.665 albertel 6842: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6843: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6844: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6845: $thisallowed='';
1.671 raeburn 6846: my ($match)=&is_on_map($uri);
6847: if ($match) {
6848: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6849: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 6850: my $value = $1;
6851: if ($noblockcheck) {
6852: $thisallowed.=$value;
1.1162 raeburn 6853: } else {
1.1281 raeburn 6854: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6855: if (@blockers > 0) {
6856: $thisallowed = 'B';
6857: } else {
6858: $thisallowed.=$value;
6859: }
1.1162 raeburn 6860: }
1.671 raeburn 6861: }
6862: } else {
1.705 albertel 6863: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6864: if ($refuri) {
6865: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6866: $thisallowed='F';
1.671 raeburn 6867: } else {
6868: $refuri=&declutter($refuri);
6869: my ($match) = &is_on_map($refuri);
6870: if ($match) {
1.1281 raeburn 6871: if ($noblockcheck) {
6872: $thisallowed='F';
1.1162 raeburn 6873: } else {
1.1281 raeburn 6874: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6875: if (@blockers > 0) {
6876: $thisallowed = 'B';
6877: } else {
6878: $thisallowed='F';
6879: }
1.1162 raeburn 6880: }
1.671 raeburn 6881: }
1.669 raeburn 6882: }
1.671 raeburn 6883: }
6884: }
1.314 www 6885: }
1.492 albertel 6886:
1.766 albertel 6887: if ($priv eq 'bre'
6888: && $thisallowed ne 'F'
6889: && $thisallowed ne '2'
6890: && &is_portfolio_url($uri)) {
1.1270 raeburn 6891: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 6892: }
1.1250 raeburn 6893:
1.52 www 6894: # Full access at system, domain or course-wide level? Exit.
1.29 www 6895: if ($thisallowed=~/F/) {
6896: return 'F';
6897: }
6898:
1.52 www 6899: # If this is generating or modifying users, exit with special codes
1.29 www 6900:
1.643 www 6901: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6902: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6903: my ($audom,$auname)=split('/',$uri);
1.643 www 6904: # no author name given, so this just checks on the general right to make a co-author in this domain
6905: unless ($auname) { return $thisallowed; }
6906: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6907: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6908: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6909: ($audom ne $env{'request.role.domain'}))) { return ''; }
6910: }
1.52 www 6911: return $thisallowed;
6912: }
6913: #
1.103 harris41 6914: # Gathered so far: system, domain and course wide privileges
1.52 www 6915: #
6916: # Course: See if uri or referer is an individual resource that is part of
6917: # the course
6918:
1.620 albertel 6919: if ($env{'request.course.id'}) {
1.232 www 6920:
1.620 albertel 6921: $courseprivid=$env{'request.course.id'};
6922: if ($env{'request.course.sec'}) {
6923: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6924: }
6925: $courseprivid=~s/\_/\//;
6926: my $checkreferer=1;
1.232 www 6927: my ($match,$cond)=&is_on_map($uri);
6928: if ($match) {
6929: $statecond=$cond;
1.620 albertel 6930: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6931: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6932: my $value = $1;
6933: if ($priv eq 'bre') {
1.1281 raeburn 6934: if ($noblockcheck) {
6935: $thisallowed.=$value;
1.1162 raeburn 6936: } else {
1.1281 raeburn 6937: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6938: if (@blockers > 0) {
6939: $thisallowed = 'B';
6940: } else {
6941: $thisallowed.=$value;
6942: }
1.1162 raeburn 6943: }
6944: } else {
6945: $thisallowed.=$value;
6946: }
1.52 www 6947: $checkreferer=0;
6948: }
1.29 www 6949: }
1.83 www 6950:
1.148 www 6951: if ($checkreferer) {
1.620 albertel 6952: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6953: unless ($refuri) {
1.800 albertel 6954: foreach my $key (keys(%env)) {
6955: if ($key=~/^httpref\..*\*/) {
6956: my $pattern=$key;
1.156 www 6957: $pattern=~s/^httpref\.\/res\///;
1.148 www 6958: $pattern=~s/\*/\[\^\/\]\+/g;
6959: $pattern=~s/\//\\\//g;
1.152 www 6960: if ($orguri=~/$pattern/) {
1.800 albertel 6961: $refuri=$env{$key};
1.148 www 6962: }
6963: }
1.191 harris41 6964: }
1.148 www 6965: }
1.232 www 6966:
1.148 www 6967: if ($refuri) {
1.152 www 6968: $refuri=&declutter($refuri);
1.232 www 6969: my ($match,$cond)=&is_on_map($refuri);
6970: if ($match) {
6971: my $refstatecond=$cond;
1.620 albertel 6972: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6973: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6974: my $value = $1;
6975: if ($priv eq 'bre') {
1.1281 raeburn 6976: if ($noblockcheck) {
6977: $thisallowed.=$value;
1.1162 raeburn 6978: } else {
1.1281 raeburn 6979: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6980: if (@blockers > 0) {
6981: $thisallowed = 'B';
6982: } else {
6983: $thisallowed.=$value;
6984: }
1.1162 raeburn 6985: }
6986: } else {
6987: $thisallowed.=$value;
6988: }
1.53 www 6989: $uri=$refuri;
6990: $statecond=$refstatecond;
1.52 www 6991: }
6992: }
1.148 www 6993: }
1.29 www 6994: }
1.52 www 6995: }
1.29 www 6996:
1.52 www 6997: #
1.103 harris41 6998: # Gathered now: all privileges that could apply, and condition number
1.52 www 6999: #
7000: #
7001: # Full or no access?
7002: #
1.29 www 7003:
1.52 www 7004: if ($thisallowed=~/F/) {
7005: return 'F';
7006: }
1.29 www 7007:
1.52 www 7008: unless ($thisallowed) {
7009: return '';
7010: }
1.29 www 7011:
1.52 www 7012: # Restrictions exist, deal with them
7013: #
7014: # C:according to course preferences
7015: # R:according to resource settings
7016: # L:unless locked
7017: # X:according to user session state
7018: #
7019:
7020: # Possibly locked functionality, check all courses
1.54 www 7021: # Locks might take effect only after 10 minutes cache expiration for other
7022: # courses, and 2 minutes for current course
1.52 www 7023:
7024: my $envkey;
7025: if ($thisallowed=~/L/) {
1.1000 raeburn 7026: foreach $envkey (keys(%env)) {
1.54 www 7027: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7028: my $courseid=$2;
7029: my $roleid=$1.'.'.$2;
1.92 www 7030: $courseid=~s/^\///;
1.54 www 7031: my $expiretime=600;
1.620 albertel 7032: if ($env{'request.role'} eq $roleid) {
1.54 www 7033: $expiretime=120;
7034: }
7035: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7036: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7037: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7038: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7039: }
1.620 albertel 7040: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7041: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7042: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7043: &log($env{'user.domain'},$env{'user.name'},
7044: $env{'user.home'},
1.57 www 7045: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7046: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7047: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7048: return '';
7049: }
7050: }
1.620 albertel 7051: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7052: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7053: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7054: &log($env{'user.domain'},$env{'user.name'},
7055: $env{'user.home'},
1.57 www 7056: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7057: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7058: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7059: return '';
7060: }
7061: }
7062: }
1.29 www 7063: }
1.52 www 7064: }
7065:
7066: #
7067: # Rest of the restrictions depend on selected course
7068: #
7069:
1.620 albertel 7070: unless ($env{'request.course.id'}) {
1.766 albertel 7071: if ($thisallowed eq 'A') {
7072: return 'A';
1.814 raeburn 7073: } elsif ($thisallowed eq 'B') {
7074: return 'B';
1.766 albertel 7075: } else {
7076: return '1';
7077: }
1.52 www 7078: }
1.29 www 7079:
1.52 www 7080: #
7081: # Now user is definitely in a course
7082: #
1.53 www 7083:
7084:
7085: # Course preferences
7086:
7087: if ($thisallowed=~/C/) {
1.620 albertel 7088: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7089: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7090: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7091: =~/\Q$rolecode\E/) {
1.1103 raeburn 7092: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7093: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7094: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7095: $env{'request.course.id'});
7096: }
1.237 www 7097: return '';
7098: }
7099:
1.620 albertel 7100: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7101: =~/\Q$unamedom\E/) {
1.1103 raeburn 7102: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7103: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7104: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7105: $env{'request.course.id'});
7106: }
1.54 www 7107: return '';
7108: }
1.53 www 7109: }
7110:
7111: # Resource preferences
7112:
7113: if ($thisallowed=~/R/) {
1.620 albertel 7114: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7115: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7116: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7117: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7118: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7119: }
7120: return '';
1.54 www 7121: }
1.53 www 7122: }
1.30 www 7123:
1.246 www 7124: # Restricted by state or randomout?
1.30 www 7125:
1.52 www 7126: if ($thisallowed=~/X/) {
1.620 albertel 7127: if ($env{'acc.randomout'}) {
1.579 albertel 7128: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7129: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7130: return '';
7131: }
1.247 www 7132: }
7133: if (&condval($statecond)) {
1.52 www 7134: return '2';
7135: } else {
7136: return '';
7137: }
7138: }
1.30 www 7139:
1.766 albertel 7140: if ($thisallowed eq 'A') {
7141: return 'A';
1.814 raeburn 7142: } elsif ($thisallowed eq 'B') {
7143: return 'B';
1.766 albertel 7144: }
1.52 www 7145: return 'F';
1.232 www 7146: }
1.1162 raeburn 7147:
1.1192 raeburn 7148: # ------------------------------------------- Check construction space access
7149:
7150: sub constructaccess {
7151: my ($url,$setpriv)=@_;
7152:
7153: # We do not allow editing of previous versions of files
7154: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7155:
7156: # Get username and domain from URL
7157: my ($ownername,$ownerdomain,$ownerhome);
7158:
7159: ($ownerdomain,$ownername) =
7160: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7161:
7162: # The URL does not really point to any authorspace, forget it
7163: unless (($ownername) && ($ownerdomain)) { return ''; }
7164:
7165: # Now we need to see if the user has access to the authorspace of
7166: # $ownername at $ownerdomain
7167:
7168: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7169: # Real author for this?
7170: $ownerhome = $env{'user.home'};
7171: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7172: return ($ownername,$ownerdomain,$ownerhome);
7173: }
7174: } else {
7175: # Co-author for this?
7176: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7177: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7178: $ownerhome = &homeserver($ownername,$ownerdomain);
7179: return ($ownername,$ownerdomain,$ownerhome);
7180: }
7181: }
7182:
7183: # We don't have any access right now. If we are not possibly going to do anything about this,
7184: # we might as well leave
7185: unless ($setpriv) { return ''; }
7186:
7187: # Backdoor access?
7188: my $allowed=&allowed('eco',$ownerdomain);
7189: # Nope
7190: unless ($allowed) { return ''; }
7191: # Looks like we may have access, but could be locked by the owner of the construction space
7192: if ($allowed eq 'U') {
7193: my %blocked=&get('environment',['domcoord.author'],
7194: $ownerdomain,$ownername);
7195: # Is blocked by owner
7196: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7197: }
7198: if (($allowed eq 'F') || ($allowed eq 'U')) {
7199: # Grant temporary access
7200: my $then=$env{'user.login.time'};
1.1209 raeburn 7201: my $update=$env{'user.update.time'};
1.1192 raeburn 7202: if (!$update) { $update = $then; }
7203: my $refresh=$env{'user.refresh.time'};
7204: if (!$refresh) { $refresh = $update; }
7205: my $now = time;
7206: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7207: $now,'ca','constructaccess');
7208: $ownerhome = &homeserver($ownername,$ownerdomain);
7209: return($ownername,$ownerdomain,$ownerhome);
7210: }
7211: # No business here
7212: return '';
7213: }
7214:
1.1282 raeburn 7215: # ----------------------------------------------------------- Content Blocking
7216:
7217: {
7218: # Caches for faster Course Contents display where content blocking
7219: # is in operation (i.e., interval param set) for timed quiz.
7220: #
7221: # User for whom data are being temporarily cached.
7222: my $cacheduser='';
7223: # Cached blockers for this user (a hash of blocking items).
7224: my %cachedblockers=();
7225: # When the data were last cached.
7226: my $cachedlast='';
7227:
7228: sub load_all_blockers {
7229: my ($uname,$udom,$blocks)=@_;
7230: if (($uname ne '') && ($udom ne '')) {
7231: if (($cacheduser eq $uname.':'.$udom) &&
7232: (abs($cachedlast-time)<5)) {
7233: return;
7234: }
7235: }
7236: $cachedlast=time;
7237: $cacheduser=$uname.':'.$udom;
7238: %cachedblockers = &get_commblock_resources($blocks);
7239: }
7240:
1.1162 raeburn 7241: sub get_comm_blocks {
7242: my ($cdom,$cnum) = @_;
7243: if ($cdom eq '' || $cnum eq '') {
7244: return unless ($env{'request.course.id'});
7245: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7246: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7247: }
7248: my %commblocks;
7249: my $hashid=$cdom.'_'.$cnum;
7250: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7251: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7252: %commblocks = %{$blocksref};
7253: } else {
7254: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7255: my $cachetime = 600;
7256: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7257: }
7258: return %commblocks;
7259: }
7260:
1.1282 raeburn 7261: sub get_commblock_resources {
7262: my ($blocks) = @_;
7263: my %blockers = ();
7264: return %blockers unless ($env{'request.course.id'});
7265: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7266: my %commblocks;
7267: if (ref($blocks) eq 'HASH') {
7268: %commblocks = %{$blocks};
7269: } else {
7270: %commblocks = &get_comm_blocks();
7271: }
1.1282 raeburn 7272: return %blockers unless (keys(%commblocks) > 0);
7273: my $navmap = Apache::lonnavmaps::navmap->new();
7274: return %blockers unless (ref($navmap));
1.1162 raeburn 7275: my $now = time;
7276: foreach my $block (keys(%commblocks)) {
7277: if ($block =~ /^(\d+)____(\d+)$/) {
7278: my ($start,$end) = ($1,$2);
7279: if ($start <= $now && $end >= $now) {
7280: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7281: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7282: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7283: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7284: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7285: }
7286: }
7287: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7288: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7289: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7290: }
7291: }
7292: }
7293: }
7294: }
7295: } elsif ($block =~ /^firstaccess____(.+)$/) {
7296: my $item = $1;
1.1163 raeburn 7297: my @to_test;
1.1162 raeburn 7298: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7299: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7300: my @interval;
7301: my $type = 'map';
7302: if ($item eq 'course') {
7303: $type = 'course';
7304: @interval=&EXT("resource.0.interval");
7305: } else {
7306: if ($item =~ /___\d+___/) {
7307: $type = 'resource';
7308: @interval=&EXT("resource.0.interval",$item);
7309: if (ref($navmap)) {
7310: my $res = $navmap->getBySymb($item);
7311: push(@to_test,$res);
7312: }
1.1162 raeburn 7313: } else {
1.1282 raeburn 7314: my $mapsymb = &symbread($item,1);
7315: if ($mapsymb) {
7316: if (ref($navmap)) {
7317: my $mapres = $navmap->getBySymb($mapsymb);
7318: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7319: foreach my $res (@to_test) {
7320: my $symb = $res->symb();
7321: next if ($symb eq $mapsymb);
7322: if ($symb ne '') {
7323: @interval=&EXT("resource.0.interval",$symb);
7324: if ($interval[1] eq 'map') {
7325: last;
1.1162 raeburn 7326: }
7327: }
7328: }
7329: }
7330: }
7331: }
1.1282 raeburn 7332: }
7333: if ($interval[0] =~ /^\d+$/) {
7334: my $first_access;
7335: if ($type eq 'resource') {
7336: $first_access=&get_first_access($interval[1],$item);
7337: } elsif ($type eq 'map') {
7338: $first_access=&get_first_access($interval[1],undef,$item);
7339: } else {
7340: $first_access=&get_first_access($interval[1]);
7341: }
7342: if ($first_access) {
7343: my $timesup = $first_access+$interval[0];
7344: if ($timesup > $now) {
7345: my $activeblock;
7346: foreach my $res (@to_test) {
1.1283 raeburn 7347: if ($res->answerable()) {
1.1282 raeburn 7348: $activeblock = 1;
7349: last;
7350: }
7351: }
7352: if ($activeblock) {
7353: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7354: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7355: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7356: }
7357: }
7358: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7359: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7360: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7361: }
1.1162 raeburn 7362: }
7363: }
7364: }
7365: }
7366: }
7367: }
7368: }
7369: }
7370: }
1.1282 raeburn 7371: return %blockers;
1.1162 raeburn 7372: }
7373:
1.1282 raeburn 7374: sub has_comm_blocking {
7375: my ($priv,$symb,$uri,$blocks) = @_;
7376: my @blockers;
7377: return unless ($env{'request.course.id'});
7378: return unless ($priv eq 'bre');
7379: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7380: return if ($env{'request.state'} eq 'construct');
7381: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7382: return unless (keys(%cachedblockers) > 0);
7383: my (%possibles,@symbs);
7384: if (!$symb) {
7385: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7386: }
1.1282 raeburn 7387: if ($symb) {
7388: @symbs = ($symb);
7389: } elsif (keys(%possibles)) {
7390: @symbs = keys(%possibles);
7391: }
7392: my $noblock;
7393: foreach my $symb (@symbs) {
7394: last if ($noblock);
7395: my ($map,$resid,$resurl)=&decode_symb($symb);
7396: foreach my $block (keys(%cachedblockers)) {
7397: if ($block =~ /^firstaccess____(.+)$/) {
7398: my $item = $1;
7399: if (($item eq $map) || ($item eq $symb)) {
7400: $noblock = 1;
7401: last;
7402: }
7403: }
7404: if (ref($cachedblockers{$block}) eq 'HASH') {
7405: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7406: if ($cachedblockers{$block}{'resources'}{$symb}) {
7407: unless (grep(/^\Q$block\E$/,@blockers)) {
7408: push(@blockers,$block);
7409: }
7410: }
7411: }
1.1162 raeburn 7412: }
1.1282 raeburn 7413: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7414: if ($cachedblockers{$block}{'maps'}{$map}) {
7415: unless (grep(/^\Q$block\E$/,@blockers)) {
7416: push(@blockers,$block);
7417: }
7418: }
1.1162 raeburn 7419: }
7420: }
7421: }
1.1282 raeburn 7422: return if ($noblock);
7423: return @blockers;
7424: }
1.1162 raeburn 7425: }
7426:
1.1282 raeburn 7427: # -------------------------------- Deversion and split uri into path an filename
7428:
1.1133 foxr 7429: #
1.1282 raeburn 7430: # Removes the version from a URI and
1.1133 foxr 7431: # splits it in to its filename and path to the filename.
7432: # Seems like File::Basename could have done this more clearly.
7433: # Parameters:
7434: # $uri - input URI
7435: # Returns:
7436: # Two element list consisting of
7437: # $pathname - the URI up to and excluding the trailing /
7438: # $filename - The part of the URI following the last /
7439: # NOTE:
7440: # Another realization of this is simply:
7441: # use File::Basename;
7442: # ...
7443: # $uri = shift;
7444: # $filename = basename($uri);
7445: # $path = dirname($uri);
7446: # return ($filename, $path);
7447: #
7448: # The implementation below is probably faster however.
7449: #
1.710 albertel 7450: sub split_uri_for_cond {
7451: my $uri=&deversion(&declutter(shift));
7452: my @uriparts=split(/\//,$uri);
7453: my $filename=pop(@uriparts);
7454: my $pathname=join('/',@uriparts);
7455: return ($pathname,$filename);
7456: }
1.232 www 7457: # --------------------------------------------------- Is a resource on the map?
7458:
7459: sub is_on_map {
1.710 albertel 7460: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7461: #Trying to find the conditional for the file
1.620 albertel 7462: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7463: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7464: if ($match) {
1.289 bowersj2 7465: return (1,$1);
7466: } else {
1.434 www 7467: return (0,0);
1.289 bowersj2 7468: }
1.12 www 7469: }
7470:
1.427 www 7471: # --------------------------------------------------------- Get symb from alias
7472:
7473: sub get_symb_from_alias {
7474: my $symb=shift;
7475: my ($map,$resid,$url)=&decode_symb($symb);
7476: # Already is a symb
7477: if ($url) { return $symb; }
7478: # Must be an alias
7479: my $aliassymb='';
7480: my %bighash;
1.620 albertel 7481: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7482: &GDBM_READER(),0640)) {
7483: my $rid=$bighash{'mapalias_'.$symb};
7484: if ($rid) {
7485: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7486: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7487: $resid,$bighash{'src_'.$rid});
1.427 www 7488: }
7489: untie %bighash;
7490: }
7491: return $aliassymb;
7492: }
7493:
1.12 www 7494: # ----------------------------------------------------------------- Define Role
7495:
7496: sub definerole {
7497: if (allowed('mcr','/')) {
7498: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7499: foreach my $role (split(':',$sysrole)) {
7500: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7501: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7502: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7503: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7504: return "refused:s:$crole&$cqual";
7505: }
7506: }
1.191 harris41 7507: }
1.800 albertel 7508: foreach my $role (split(':',$domrole)) {
7509: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7510: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7511: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7512: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7513: return "refused:d:$crole&$cqual";
7514: }
7515: }
1.191 harris41 7516: }
1.800 albertel 7517: foreach my $role (split(':',$courole)) {
7518: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7519: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7520: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7521: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7522: return "refused:c:$crole&$cqual";
7523: }
7524: }
1.191 harris41 7525: }
1.620 albertel 7526: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7527: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7528: "rolesdef_$rolename=".
7529: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7530: return reply($command,$env{'user.home'});
1.12 www 7531: } else {
7532: return 'refused';
7533: }
1.105 harris41 7534: }
7535:
7536: # ---------------- Make a metadata query against the network of library servers
7537:
7538: sub metadata_query {
1.1237 raeburn 7539: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7540: my %rhash;
1.845 albertel 7541: my %libserv = &all_library();
1.244 matthew 7542: my @server_list = (defined($server_array) ? @$server_array
7543: : keys(%libserv) );
7544: for my $server (@server_list) {
1.1237 raeburn 7545: my $domains = '';
7546: if (ref($domains_hash) eq 'HASH') {
7547: $domains = $domains_hash->{$server};
7548: }
1.118 harris41 7549: unless ($custom or $customshow) {
1.1237 raeburn 7550: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7551: $rhash{$server}=$reply;
7552: }
7553: else {
7554: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7555: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7556: $server);
7557: $rhash{$server}=$reply;
7558: }
1.112 harris41 7559: }
1.118 harris41 7560: return \%rhash;
1.240 www 7561: }
7562:
7563: # ----------------------------------------- Send log queries and wait for reply
7564:
7565: sub log_query {
7566: my ($uname,$udom,$query,%filters)=@_;
7567: my $uhome=&homeserver($uname,$udom);
7568: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7569: my $uhost=&hostname($uhome);
1.800 albertel 7570: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7571: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7572: $uhome);
1.479 albertel 7573: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7574: return get_query_reply($queryid);
7575: }
7576:
1.818 raeburn 7577: # -------------------------- Update MySQL table for portfolio file
7578:
7579: sub update_portfolio_table {
1.821 raeburn 7580: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7581: if ($group ne '') {
7582: $file_name =~s /^\Q$group\E//;
7583: }
1.818 raeburn 7584: my $homeserver = &homeserver($uname,$udom);
7585: my $queryid=
1.821 raeburn 7586: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7587: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7588: my $reply = &get_query_reply($queryid);
7589: return $reply;
7590: }
7591:
1.899 raeburn 7592: # -------------------------- Update MySQL allusers table
7593:
7594: sub update_allusers_table {
7595: my ($uname,$udom,$names) = @_;
7596: my $homeserver = &homeserver($uname,$udom);
7597: my $queryid=
7598: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7599: 'lastname='.&escape($names->{'lastname'}).'%%'.
7600: 'firstname='.&escape($names->{'firstname'}).'%%'.
7601: 'middlename='.&escape($names->{'middlename'}).'%%'.
7602: 'generation='.&escape($names->{'generation'}).'%%'.
7603: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7604: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7605: return;
1.899 raeburn 7606: }
7607:
1.508 raeburn 7608: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7609:
7610: sub fetch_enrollment_query {
1.511 raeburn 7611: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7612: my $homeserver;
1.547 raeburn 7613: my $maxtries = 1;
1.508 raeburn 7614: if ($context eq 'automated') {
7615: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7616: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7617: } else {
7618: $homeserver = &homeserver($cnum,$dom);
7619: }
1.838 albertel 7620: my $host=&hostname($homeserver);
1.506 raeburn 7621: my $cmd = '';
1.1000 raeburn 7622: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7623: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7624: }
7625: $cmd =~ s/%%$//;
7626: $cmd = &escape($cmd);
7627: my $query = 'fetchenrollment';
1.620 albertel 7628: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7629: unless ($queryid=~/^\Q$host\E\_/) {
7630: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7631: return 'error: '.$queryid;
7632: }
1.506 raeburn 7633: my $reply = &get_query_reply($queryid);
1.547 raeburn 7634: my $tries = 1;
7635: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7636: $reply = &get_query_reply($queryid);
7637: $tries ++;
7638: }
1.526 raeburn 7639: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7640: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7641: } else {
1.901 albertel 7642: my @responses = split(/:/,$reply);
1.515 raeburn 7643: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7644: foreach my $line (@responses) {
7645: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7646: $$replyref{$key} = $value;
7647: }
7648: } else {
1.1117 foxr 7649: my $pathname = LONCAPA::tempdir();
1.800 albertel 7650: foreach my $line (@responses) {
7651: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7652: $$replyref{$key} = $value;
7653: if ($value > 0) {
1.800 albertel 7654: foreach my $item (@{$$affiliatesref{$key}}) {
7655: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7656: my $destname = $pathname.'/'.$filename;
7657: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7658: if ($xml_classlist =~ /^error/) {
7659: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7660: } else {
1.506 raeburn 7661: if ( open(FILE,">$destname") ) {
7662: print FILE &unescape($xml_classlist);
7663: close(FILE);
1.526 raeburn 7664: } else {
7665: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7666: }
7667: }
7668: }
7669: }
7670: }
7671: }
7672: return 'ok';
7673: }
7674: return 'error';
7675: }
7676:
1.242 www 7677: sub get_query_reply {
7678: my $queryid=shift;
1.1117 foxr 7679: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7680: my $reply='';
7681: for (1..100) {
1.1288 ! damieng 7682: Time::HiRes::sleep(0.2);
1.240 www 7683: if (-e $replyfile.'.end') {
1.448 albertel 7684: if (open(my $fh,$replyfile)) {
1.904 albertel 7685: $reply = join('',<$fh>);
7686: close($fh);
1.240 www 7687: } else { return 'error: reply_file_error'; }
1.242 www 7688: return &unescape($reply);
7689: }
1.240 www 7690: }
1.242 www 7691: return 'timeout:'.$queryid;
1.240 www 7692: }
7693:
7694: sub courselog_query {
1.241 www 7695: #
7696: # possible filters:
7697: # url: url or symb
7698: # username
7699: # domain
7700: # action: view, submit, grade
7701: # start: timestamp
7702: # end: timestamp
7703: #
1.240 www 7704: my (%filters)=@_;
1.620 albertel 7705: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7706: if ($filters{'url'}) {
7707: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7708: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7709: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7710: }
1.620 albertel 7711: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7712: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7713: return &log_query($cname,$cdom,'courselog',%filters);
7714: }
7715:
7716: sub userlog_query {
1.858 raeburn 7717: #
7718: # possible filters:
7719: # action: log check role
7720: # start: timestamp
7721: # end: timestamp
7722: #
1.240 www 7723: my ($uname,$udom,%filters)=@_;
7724: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7725: }
7726:
1.506 raeburn 7727: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7728:
7729: sub auto_run {
1.508 raeburn 7730: my ($cnum,$cdom) = @_;
1.876 raeburn 7731: my $response = 0;
7732: my $settings;
7733: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7734: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7735: $settings = $domconfig{'autoenroll'};
7736: if ($settings->{'run'} eq '1') {
7737: $response = 1;
7738: }
7739: } else {
1.934 raeburn 7740: my $homeserver;
7741: if (&is_course($cdom,$cnum)) {
7742: $homeserver = &homeserver($cnum,$cdom);
7743: } else {
7744: $homeserver = &domain($cdom,'primary');
7745: }
7746: if ($homeserver ne 'no_host') {
7747: $response = &reply('autorun:'.$cdom,$homeserver);
7748: }
1.876 raeburn 7749: }
1.506 raeburn 7750: return $response;
7751: }
1.776 albertel 7752:
1.506 raeburn 7753: sub auto_get_sections {
1.508 raeburn 7754: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7755: my $homeserver;
7756: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7757: $homeserver = &homeserver($cnum,$cdom);
7758: }
7759: if (!defined($homeserver)) {
7760: if ($cdom =~ /^$match_domain$/) {
7761: $homeserver = &domain($cdom,'primary');
7762: }
7763: }
7764: my @secs;
7765: if (defined($homeserver)) {
7766: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7767: unless ($response eq 'refused') {
7768: @secs = split(/:/,$response);
7769: }
1.506 raeburn 7770: }
7771: return @secs;
7772: }
1.776 albertel 7773:
1.506 raeburn 7774: sub auto_new_course {
1.1099 raeburn 7775: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7776: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7777: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7778: return $response;
7779: }
1.776 albertel 7780:
1.506 raeburn 7781: sub auto_validate_courseID {
1.508 raeburn 7782: my ($cnum,$cdom,$inst_course_id) = @_;
7783: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7784: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7785: return $response;
7786: }
1.776 albertel 7787:
1.1007 raeburn 7788: sub auto_validate_instcode {
1.1020 raeburn 7789: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7790: my ($homeserver,$response);
7791: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7792: $homeserver = &homeserver($cnum,$cdom);
7793: }
7794: if (!defined($homeserver)) {
7795: if ($cdom =~ /^$match_domain$/) {
7796: $homeserver = &domain($cdom,'primary');
7797: }
7798: }
1.1065 raeburn 7799: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7800: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7801: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7802: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7803: }
7804:
1.506 raeburn 7805: sub auto_create_password {
1.873 raeburn 7806: my ($cnum,$cdom,$authparam,$udom) = @_;
7807: my ($homeserver,$response);
1.506 raeburn 7808: my $create_passwd = 0;
7809: my $authchk = '';
1.873 raeburn 7810: if ($udom =~ /^$match_domain$/) {
7811: $homeserver = &domain($udom,'primary');
7812: }
7813: if ($homeserver eq '') {
7814: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7815: $homeserver = &homeserver($cnum,$cdom);
7816: }
7817: }
7818: if ($homeserver eq '') {
7819: $authchk = 'nodomain';
1.506 raeburn 7820: } else {
1.873 raeburn 7821: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7822: if ($response eq 'refused') {
7823: $authchk = 'refused';
7824: } else {
1.901 albertel 7825: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7826: }
1.506 raeburn 7827: }
7828: return ($authparam,$create_passwd,$authchk);
7829: }
7830:
1.706 raeburn 7831: sub auto_photo_permission {
7832: my ($cnum,$cdom,$students) = @_;
7833: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7834: my ($outcome,$perm_reqd,$conditions) =
7835: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7836: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7837: return (undef,undef);
7838: }
1.706 raeburn 7839: return ($outcome,$perm_reqd,$conditions);
7840: }
7841:
7842: sub auto_checkphotos {
7843: my ($uname,$udom,$pid) = @_;
7844: my $homeserver = &homeserver($uname,$udom);
7845: my ($result,$resulttype);
7846: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7847: &escape($uname).':'.&escape($pid),
7848: $homeserver));
1.709 albertel 7849: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7850: return (undef,undef);
7851: }
1.706 raeburn 7852: if ($outcome) {
7853: ($result,$resulttype) = split(/:/,$outcome);
7854: }
7855: return ($result,$resulttype);
7856: }
7857:
7858: sub auto_photochoice {
7859: my ($cnum,$cdom) = @_;
7860: my $homeserver = &homeserver($cnum,$cdom);
7861: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7862: &escape($cdom),
7863: $homeserver)));
1.709 albertel 7864: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7865: return (undef,undef);
7866: }
1.706 raeburn 7867: return ($update,$comment);
7868: }
7869:
7870: sub auto_photoupdate {
7871: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7872: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7873: my $host=&hostname($homeserver);
1.706 raeburn 7874: my $cmd = '';
7875: my $maxtries = 1;
1.800 albertel 7876: foreach my $affiliate (keys(%{$affiliatesref})) {
7877: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7878: }
7879: $cmd =~ s/%%$//;
7880: $cmd = &escape($cmd);
7881: my $query = 'institutionalphotos';
7882: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7883: unless ($queryid=~/^\Q$host\E\_/) {
7884: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7885: return 'error: '.$queryid;
7886: }
7887: my $reply = &get_query_reply($queryid);
7888: my $tries = 1;
7889: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7890: $reply = &get_query_reply($queryid);
7891: $tries ++;
7892: }
7893: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7894: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7895: } else {
7896: my @responses = split(/:/,$reply);
7897: my $outcome = shift(@responses);
7898: foreach my $item (@responses) {
7899: my ($key,$value) = split(/=/,$item);
7900: $$photo{$key} = $value;
7901: }
7902: return $outcome;
7903: }
7904: return 'error';
7905: }
7906:
1.521 raeburn 7907: sub auto_instcode_format {
1.793 albertel 7908: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7909: $cat_order) = @_;
1.521 raeburn 7910: my $courses = '';
1.772 raeburn 7911: my @homeservers;
1.521 raeburn 7912: if ($caller eq 'global') {
1.841 albertel 7913: my %servers = &get_servers($codedom,'library');
7914: foreach my $tryserver (keys(%servers)) {
7915: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7916: push(@homeservers,$tryserver);
7917: }
1.584 raeburn 7918: }
1.1022 raeburn 7919: } elsif ($caller eq 'requests') {
7920: if ($codedom =~ /^$match_domain$/) {
7921: my $chome = &domain($codedom,'primary');
7922: unless ($chome eq 'no_host') {
7923: push(@homeservers,$chome);
7924: }
7925: }
1.521 raeburn 7926: } else {
1.772 raeburn 7927: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7928: }
1.793 albertel 7929: foreach my $code (keys(%{$instcodes})) {
7930: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7931: }
7932: chop($courses);
1.772 raeburn 7933: my $ok_response = 0;
7934: my $response;
7935: while (@homeservers > 0 && $ok_response == 0) {
7936: my $server = shift(@homeservers);
7937: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7938: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7939: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7940: split(/:/,$response);
1.772 raeburn 7941: %{$codes} = (%{$codes},&str2hash($codes_str));
7942: push(@{$codetitles},&str2array($codetitles_str));
7943: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7944: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7945: $ok_response = 1;
7946: }
7947: }
7948: if ($ok_response) {
1.521 raeburn 7949: return 'ok';
1.772 raeburn 7950: } else {
7951: return $response;
1.521 raeburn 7952: }
7953: }
7954:
1.792 raeburn 7955: sub auto_instcode_defaults {
7956: my ($domain,$returnhash,$code_order) = @_;
7957: my @homeservers;
1.841 albertel 7958:
7959: my %servers = &get_servers($domain,'library');
7960: foreach my $tryserver (keys(%servers)) {
7961: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7962: push(@homeservers,$tryserver);
7963: }
1.792 raeburn 7964: }
1.841 albertel 7965:
1.792 raeburn 7966: my $response;
1.841 albertel 7967: foreach my $server (@homeservers) {
1.792 raeburn 7968: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7969: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7970:
7971: foreach my $pair (split(/\&/,$response)) {
7972: my ($name,$value)=split(/\=/,$pair);
7973: if ($name eq 'code_order') {
7974: @{$code_order} = split(/\&/,&unescape($value));
7975: } else {
7976: $returnhash->{&unescape($name)}=&unescape($value);
7977: }
7978: }
7979: return 'ok';
1.792 raeburn 7980: }
1.841 albertel 7981:
7982: return $response;
1.1003 raeburn 7983: }
7984:
7985: sub auto_possible_instcodes {
1.1007 raeburn 7986: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7987: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7988: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7989: return;
7990: }
1.1003 raeburn 7991: my (@homeservers,$uhome);
7992: if (defined(&domain($domain,'primary'))) {
7993: $uhome=&domain($domain,'primary');
7994: push(@homeservers,&domain($domain,'primary'));
7995: } else {
7996: my %servers = &get_servers($domain,'library');
7997: foreach my $tryserver (keys(%servers)) {
7998: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7999: push(@homeservers,$tryserver);
8000: }
8001: }
8002: }
8003: my $response;
8004: foreach my $server (@homeservers) {
8005: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8006: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8007: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8008: split(':',$response);
8009: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8010: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8011: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8012: my ($name,$value)=split('=',$item);
8013: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8014: }
8015: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8016: my ($name,$value)=split('=',$item);
8017: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8018: }
8019: return 'ok';
8020: }
8021: return $response;
8022: }
1.792 raeburn 8023:
1.1010 raeburn 8024: sub auto_courserequest_checks {
8025: my ($dom) = @_;
1.1020 raeburn 8026: my ($homeserver,%validations);
8027: if ($dom =~ /^$match_domain$/) {
8028: $homeserver = &domain($dom,'primary');
8029: }
8030: unless ($homeserver eq 'no_host') {
8031: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8032: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8033: my @items = split(/&/,$response);
8034: foreach my $item (@items) {
8035: my ($key,$value) = split('=',$item);
8036: $validations{&unescape($key)} = &thaw_unescape($value);
8037: }
8038: }
8039: }
1.1010 raeburn 8040: return %validations;
8041: }
8042:
1.1020 raeburn 8043: sub auto_courserequest_validation {
1.1255 raeburn 8044: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8045: my ($homeserver,$response);
8046: if ($dom =~ /^$match_domain$/) {
8047: $homeserver = &domain($dom,'primary');
8048: }
1.1255 raeburn 8049: unless ($homeserver eq 'no_host') {
8050: my $customdata;
8051: if (ref($custominfo) eq 'HASH') {
8052: $customdata = &freeze_escape($custominfo);
8053: }
1.1020 raeburn 8054: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8055: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8056: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8057: $customdata,$homeserver));
1.1020 raeburn 8058: }
8059: return $response;
8060: }
8061:
1.777 albertel 8062: sub auto_validate_class_sec {
1.918 raeburn 8063: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8064: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8065: my $ownerlist;
8066: if (ref($owners) eq 'ARRAY') {
8067: $ownerlist = join(',',@{$owners});
8068: } else {
8069: $ownerlist = $owners;
8070: }
1.773 raeburn 8071: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8072: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8073: return $response;
8074: }
8075:
1.1248 raeburn 8076: sub auto_crsreq_update {
8077: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8078: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8079: my ($homeserver,%crsreqresponse);
8080: if ($cdom =~ /^$match_domain$/) {
8081: $homeserver = &domain($cdom,'primary');
8082: }
8083: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8084: my $info;
8085: if (ref($inbound) eq 'HASH') {
8086: $info = &freeze_escape($inbound);
8087: }
8088: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8089: ':'.&escape($action).':'.&escape($ownername).':'.
8090: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8091: &escape($title).':'.&escape($code).':'.
8092: &escape($accessstart).':'.&escape($accessend).':'.$info,
8093: $homeserver);
1.1248 raeburn 8094: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8095: my @items = split(/&/,$response);
8096: foreach my $item (@items) {
8097: my ($key,$value) = split('=',$item);
8098: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8099: }
8100: }
8101: }
8102: return \%crsreqresponse;
8103: }
8104:
1.1287 raeburn 8105: sub check_instcode_cloning {
8106: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8107: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8108: return;
8109: }
8110: my $canclone;
8111: if (@{$code_order} > 0) {
8112: my $instcoderegexp ='^';
8113: my @clonecodes = split(/\&/,$cloner);
8114: foreach my $item (@{$code_order}) {
8115: if (grep(/^\Q$item\E=/,@clonecodes)) {
8116: foreach my $pair (@clonecodes) {
8117: my ($key,$val) = split(/\=/,$pair,2);
8118: $val = &unescape($val);
8119: if ($key eq $item) {
8120: $instcoderegexp .= '('.$val.')';
8121: last;
8122: }
8123: }
8124: } else {
8125: $instcoderegexp .= $codedefaults->{$item};
8126: }
8127: }
8128: $instcoderegexp .= '$';
8129: my (@from,@to);
8130: eval {
8131: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8132: (@to) = ($clonetocode =~ /$instcoderegexp/);
8133: };
8134: if ((@from > 0) && (@to > 0)) {
8135: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8136: if (!@diffs) {
8137: $canclone = 1;
8138: }
8139: }
8140: }
8141: return $canclone;
8142: }
8143:
8144: sub default_instcode_cloning {
8145: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8146: my (%codedefaults,@code_order,$canclone);
8147: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8148: %codedefaults = %{$codedefaultsref};
8149: @code_order = @{$codeorderref};
8150: } elsif ($clonedom) {
8151: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8152: }
8153: if (($domdefclone) && (@code_order)) {
8154: my @clonecodes = split(/\+/,$domdefclone);
8155: my $instcoderegexp ='^';
8156: foreach my $item (@code_order) {
8157: if (grep(/^\Q$item\E$/,@clonecodes)) {
8158: $instcoderegexp .= '('.$codedefaults{$item}.')';
8159: } else {
8160: $instcoderegexp .= $codedefaults{$item};
8161: }
8162: }
8163: $instcoderegexp .= '$';
8164: my (@from,@to);
8165: eval {
8166: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8167: (@to) = ($clonetocode =~ /$instcoderegexp/);
8168: };
8169: if ((@from > 0) && (@to > 0)) {
8170: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8171: if (!@diffs) {
8172: $canclone = 1;
8173: }
8174: }
8175: }
8176: return $canclone;
8177: }
8178:
1.679 raeburn 8179: # ------------------------------------------------------- Course Group routines
8180:
8181: sub get_coursegroups {
1.809 raeburn 8182: my ($cdom,$cnum,$group,$namespace) = @_;
8183: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8184: }
8185:
1.679 raeburn 8186: sub modify_coursegroup {
8187: my ($cdom,$cnum,$groupsettings) = @_;
8188: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8189: }
8190:
1.809 raeburn 8191: sub toggle_coursegroup_status {
8192: my ($cdom,$cnum,$group,$action) = @_;
8193: my ($from_namespace,$to_namespace);
8194: if ($action eq 'delete') {
8195: $from_namespace = 'coursegroups';
8196: $to_namespace = 'deleted_groups';
8197: } else {
8198: $from_namespace = 'deleted_groups';
8199: $to_namespace = 'coursegroups';
8200: }
8201: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8202: if (my $tmp = &error(%curr_group)) {
8203: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8204: return ('read error',$tmp);
8205: } else {
8206: my %savedsettings = %curr_group;
1.809 raeburn 8207: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8208: my $deloutcome;
8209: if ($result eq 'ok') {
1.809 raeburn 8210: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8211: } else {
8212: return ('write error',$result);
8213: }
8214: if ($deloutcome eq 'ok') {
8215: return 'ok';
8216: } else {
8217: return ('delete error',$deloutcome);
8218: }
8219: }
8220: }
8221:
1.679 raeburn 8222: sub modify_group_roles {
1.957 raeburn 8223: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8224: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8225: my $role = 'gr/'.&escape($userprivs);
8226: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8227: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8228: if ($result eq 'ok') {
8229: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8230: }
1.679 raeburn 8231: return $result;
8232: }
8233:
8234: sub modify_coursegroup_membership {
8235: my ($cdom,$cnum,$membership) = @_;
8236: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8237: return $result;
8238: }
8239:
1.682 raeburn 8240: sub get_active_groups {
8241: my ($udom,$uname,$cdom,$cnum) = @_;
8242: my $now = time;
8243: my %groups = ();
8244: foreach my $key (keys(%env)) {
1.811 albertel 8245: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8246: my ($start,$end) = split(/\./,$env{$key});
8247: if (($end!=0) && ($end<$now)) { next; }
8248: if (($start!=0) && ($start>$now)) { next; }
8249: if ($1 eq $cdom && $2 eq $cnum) {
8250: $groups{$3} = $env{$key} ;
8251: }
8252: }
8253: }
8254: return %groups;
8255: }
8256:
1.683 raeburn 8257: sub get_group_membership {
8258: my ($cdom,$cnum,$group) = @_;
8259: return(&dump('groupmembership',$cdom,$cnum,$group));
8260: }
8261:
8262: sub get_users_groups {
8263: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8264: my @usersgroups;
1.683 raeburn 8265: my $cachetime=1800;
8266:
8267: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8268: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8269: if (defined($cached)) {
1.734 albertel 8270: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8271: } else {
8272: $grouplist = '';
1.816 raeburn 8273: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8274: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8275: my $access_end = $env{'course.'.$courseid.
8276: '.default_enrollment_end_date'};
8277: my $now = time;
8278: foreach my $key (keys(%roleshash)) {
8279: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8280: my $group = $1;
8281: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8282: my $start = $2;
8283: my $end = $1;
8284: if ($start == -1) { next; } # deleted from group
8285: if (($start!=0) && ($start>$now)) { next; }
8286: if (($end!=0) && ($end<$now)) {
8287: if ($access_end && $access_end < $now) {
8288: if ($access_end - $end < 86400) {
8289: push(@usersgroups,$group);
1.733 raeburn 8290: }
8291: }
1.817 raeburn 8292: next;
1.733 raeburn 8293: }
1.817 raeburn 8294: push(@usersgroups,$group);
1.683 raeburn 8295: }
8296: }
8297: }
1.817 raeburn 8298: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8299: $grouplist = join(':',@usersgroups);
8300: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8301: }
1.733 raeburn 8302: return @usersgroups;
1.683 raeburn 8303: }
8304:
8305: sub devalidate_getgroups_cache {
8306: my ($udom,$uname,$cdom,$cnum)=@_;
8307: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8308:
1.683 raeburn 8309: my $hashid="$udom:$uname:$courseid";
8310: &devalidate_cache_new('getgroups',$hashid);
8311: }
8312:
1.12 www 8313: # ------------------------------------------------------------------ Plain Text
8314:
8315: sub plaintext {
1.988 raeburn 8316: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8317: if ($short =~ m{^cr/}) {
1.758 albertel 8318: return (split('/',$short))[-1];
8319: }
1.742 raeburn 8320: if (!defined($cid)) {
8321: $cid = $env{'request.course.id'};
8322: }
8323: my %rolenames = (
1.1008 raeburn 8324: Course => 'std',
8325: Community => 'alt1',
1.742 raeburn 8326: );
1.1037 raeburn 8327: if ($cid ne '') {
8328: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8329: unless ($forcedefault) {
8330: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8331: &Apache::lonlocal::mt_escape(\$roletext);
8332: return &Apache::lonlocal::mt($roletext);
8333: }
8334: }
8335: }
8336: if ((defined($type)) && (defined($rolenames{$type})) &&
8337: (defined($rolenames{$type})) &&
8338: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8339: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8340: } elsif ($cid ne '') {
8341: my $crstype = $env{'course.'.$cid.'.type'};
8342: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8343: (defined($prp{$short}{$rolenames{$crstype}}))) {
8344: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8345: }
1.742 raeburn 8346: }
1.1037 raeburn 8347: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8348: }
8349:
8350: # ----------------------------------------------------------------- Assign Role
8351:
8352: sub assignrole {
1.957 raeburn 8353: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8354: $context)=@_;
1.21 www 8355: my $mrole;
8356: if ($role =~ /^cr\//) {
1.393 www 8357: my $cwosec=$url;
1.811 albertel 8358: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8359: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8360: my $refused = 1;
8361: if ($context eq 'requestcourses') {
8362: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8363: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8364: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8365: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8366: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8367: if ($crsenv{'internal.courseowner'} eq
8368: $env{'user.name'}.':'.$env{'user.domain'}) {
8369: $refused = '';
8370: }
8371: }
8372: }
8373: }
8374: }
8375: if ($refused) {
8376: &logthis('Refused custom assignrole: '.
8377: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8378: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8379: return 'refused';
8380: }
1.104 www 8381: }
1.21 www 8382: $mrole='cr';
1.678 raeburn 8383: } elsif ($role =~ /^gr\//) {
8384: my $cwogrp=$url;
1.811 albertel 8385: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8386: unless (&allowed('mdg',$cwogrp)) {
8387: &logthis('Refused group assignrole: '.
8388: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8389: $env{'user.name'}.' at '.$env{'user.domain'});
8390: return 'refused';
8391: }
8392: $mrole='gr';
1.21 www 8393: } else {
1.82 www 8394: my $cwosec=$url;
1.811 albertel 8395: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8396: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8397: my $refused;
8398: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8399: if (!(&allowed('c'.$role,$url))) {
8400: $refused = 1;
8401: }
8402: } else {
8403: $refused = 1;
8404: }
1.947 raeburn 8405: if ($refused) {
1.1045 raeburn 8406: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8407: if (!$selfenroll && $context eq 'course') {
8408: my %crsenv;
8409: if ($role eq 'cc' || $role eq 'co') {
8410: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8411: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8412: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8413: if ($crsenv{'internal.courseowner'} eq
8414: $env{'user.name'}.':'.$env{'user.domain'}) {
8415: $refused = '';
8416: }
8417: }
8418: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8419: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8420: if ($crsenv{'internal.courseowner'} eq
8421: $env{'user.name'}.':'.$env{'user.domain'}) {
8422: $refused = '';
8423: }
8424: }
8425: }
8426: }
8427: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8428: $refused = '';
1.1017 raeburn 8429: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8430: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8431: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8432: my $wrongcc;
8433: if ($cnum =~ /^$match_community$/) {
8434: $wrongcc = 1 if ($role eq 'cc');
8435: } else {
8436: $wrongcc = 1 if ($role eq 'co');
8437: }
8438: unless ($wrongcc) {
8439: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8440: if ($crsenv{'internal.courseowner'} eq
8441: $env{'user.name'}.':'.$env{'user.domain'}) {
8442: $refused = '';
8443: }
1.1017 raeburn 8444: }
8445: }
1.1183 raeburn 8446: } elsif ($context eq 'requestauthor') {
8447: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8448: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8449: if ($env{'environment.requestauthor'} eq 'automatic') {
8450: $refused = '';
8451: } else {
8452: my %domdefaults = &get_domain_defaults($udom);
8453: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8454: my $checkbystatus;
8455: if ($env{'user.adv'}) {
8456: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8457: if ($disposition eq 'automatic') {
8458: $refused = '';
8459: } elsif ($disposition eq '') {
8460: $checkbystatus = 1;
8461: }
8462: } else {
8463: $checkbystatus = 1;
8464: }
8465: if ($checkbystatus) {
8466: if ($env{'environment.inststatus'}) {
8467: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8468: foreach my $type (@inststatuses) {
8469: if (($type ne '') &&
8470: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8471: $refused = '';
8472: }
8473: }
8474: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8475: $refused = '';
8476: }
8477: }
8478: }
8479: }
8480: }
1.1017 raeburn 8481: }
8482: if ($refused) {
1.947 raeburn 8483: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8484: ' '.$role.' '.$end.' '.$start.' by '.
8485: $env{'user.name'}.' at '.$env{'user.domain'});
8486: return 'refused';
8487: }
1.932 raeburn 8488: }
1.1131 raeburn 8489: } elsif ($role eq 'au') {
8490: if ($url ne '/'.$udom.'/') {
8491: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8492: ' to assign author role for '.$uname.':'.$udom.
8493: ' in domain: '.$url.' refused (wrong domain).');
8494: return 'refused';
8495: }
1.104 www 8496: }
1.21 www 8497: $mrole=$role;
8498: }
1.620 albertel 8499: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8500: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8501: if ($end) { $command.='_'.$end; }
1.21 www 8502: if ($start) {
8503: if ($end) {
1.81 www 8504: $command.='_'.$start;
1.21 www 8505: } else {
1.81 www 8506: $command.='_0_'.$start;
1.21 www 8507: }
8508: }
1.739 raeburn 8509: my $origstart = $start;
8510: my $origend = $end;
1.957 raeburn 8511: my $delflag;
1.357 www 8512: # actually delete
8513: if ($deleteflag) {
1.373 www 8514: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8515: # modify command to delete the role
1.620 albertel 8516: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8517: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8518: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8519: # set start and finish to negative values for userrolelog
8520: $start=-1;
8521: $end=-1;
1.957 raeburn 8522: $delflag = 1;
1.357 www 8523: }
8524: }
8525: # send command
1.349 www 8526: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8527: # log new user role if status is ok
1.349 www 8528: if ($answer eq 'ok') {
1.663 raeburn 8529: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8530: if (($role eq 'cc') || ($role eq 'in') ||
8531: ($role eq 'ep') || ($role eq 'ad') ||
8532: ($role eq 'ta') || ($role eq 'st') ||
8533: ($role=~/^cr/) || ($role eq 'gr') ||
8534: ($role eq 'co')) {
1.1200 raeburn 8535: # for course roles, perform group memberships changes triggered by role change.
8536: unless ($role =~ /^gr/) {
8537: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8538: $origstart,$selfenroll,$context);
8539: }
1.1184 raeburn 8540: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8541: $selfenroll,$context);
8542: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8543: ($role eq 'au') || ($role eq 'dc')) {
8544: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8545: $context);
8546: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8547: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8548: $context);
8549: }
1.1053 raeburn 8550: if ($role eq 'cc') {
8551: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8552: }
1.349 www 8553: }
8554: return $answer;
1.169 harris41 8555: }
8556:
1.1053 raeburn 8557: sub autoupdate_coowners {
8558: my ($url,$end,$start,$uname,$udom) = @_;
8559: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8560: if (($cdom ne '') && ($cnum ne '')) {
8561: my $now = time;
8562: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8563: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8564: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8565: my $instcode = $coursehash{'internal.coursecode'};
8566: if ($instcode ne '') {
1.1056 raeburn 8567: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8568: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8569: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8570: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8571: if ($result eq 'valid') {
8572: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8573: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8574: push(@newcoowners,$coowner);
8575: }
8576: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8577: push(@newcoowners,$uname.':'.$udom);
8578: }
8579: @newcoowners = sort(@newcoowners);
8580: } else {
8581: push(@newcoowners,$uname.':'.$udom);
8582: }
8583: } else {
8584: if ($coursehash{'internal.co-owners'}) {
8585: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8586: unless ($coowner eq $uname.':'.$udom) {
8587: push(@newcoowners,$coowner);
8588: }
8589: }
8590: unless (@newcoowners > 0) {
8591: $delcoowners = 1;
8592: $coowners = '';
8593: }
8594: }
8595: }
8596: if (@newcoowners || $delcoowners) {
8597: &store_coowners($cdom,$cnum,$coursehash{'home'},
8598: $delcoowners,@newcoowners);
8599: }
8600: }
8601: }
8602: }
8603: }
8604: }
8605: }
8606:
8607: sub store_coowners {
8608: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8609: my $cid = $cdom.'_'.$cnum;
8610: my ($coowners,$delresult,$putresult);
8611: if (@newcoowners) {
8612: $coowners = join(',',@newcoowners);
8613: my %coownershash = (
8614: 'internal.co-owners' => $coowners,
8615: );
8616: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8617: if ($putresult eq 'ok') {
8618: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8619: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8620: }
8621: }
8622: }
8623: if ($delcoowners) {
8624: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8625: if ($delresult eq 'ok') {
8626: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8627: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8628: }
8629: }
8630: }
8631: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8632: my %crsinfo =
8633: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8634: if (ref($crsinfo{$cid}) eq 'HASH') {
8635: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8636: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8637: }
8638: }
8639: }
8640:
1.169 harris41 8641: # -------------------------------------------------- Modify user authentication
1.197 www 8642: # Overrides without validation
8643:
1.169 harris41 8644: sub modifyuserauth {
8645: my ($udom,$uname,$umode,$upass)=@_;
8646: my $uhome=&homeserver($uname,$udom);
1.197 www 8647: unless (&allowed('mau',$udom)) { return 'refused'; }
8648: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8649: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8650: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8651: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8652: &escape($upass),$uhome);
1.620 albertel 8653: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8654: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8655: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8656: &log($udom,,$uname,$uhome,
1.620 albertel 8657: 'Authentication changed by '.$env{'user.domain'}.', '.
8658: $env{'user.name'}.', '.$umode.
1.197 www 8659: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8660: unless ($reply eq 'ok') {
1.197 www 8661: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8662: return 'error: '.$reply;
8663: }
1.170 harris41 8664: return 'ok';
1.80 www 8665: }
8666:
1.81 www 8667: # --------------------------------------------------------------- Modify a user
1.80 www 8668:
1.81 www 8669: sub modifyuser {
1.206 matthew 8670: my ($udom, $uname, $uid,
8671: $umode, $upass, $first,
8672: $middle, $last, $gene,
1.1058 raeburn 8673: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8674: $udom= &LONCAPA::clean_domain($udom);
8675: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8676: my $showcandelete = 'none';
8677: if (ref($candelete) eq 'ARRAY') {
8678: if (@{$candelete} > 0) {
8679: $showcandelete = join(', ',@{$candelete});
8680: }
8681: }
1.81 www 8682: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8683: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8684: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8685: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8686: ' desiredhome not specified').
1.620 albertel 8687: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8688: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8689: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8690: my $newuser;
8691: if ($uhome eq 'no_host') {
8692: $newuser = 1;
8693: }
1.80 www 8694: # ----------------------------------------------------------------- Create User
1.406 albertel 8695: if (($uhome eq 'no_host') &&
8696: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8697: my $unhome='';
1.844 albertel 8698: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8699: $unhome = $desiredhome;
1.620 albertel 8700: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8701: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8702: } else { # load balancing routine for determining $unhome
1.81 www 8703: my $loadm=10000000;
1.841 albertel 8704: my %servers = &get_servers($udom,'library');
8705: foreach my $tryserver (keys(%servers)) {
8706: my $answer=reply('load',$tryserver);
8707: if (($answer=~/\d+/) && ($answer<$loadm)) {
8708: $loadm=$answer;
8709: $unhome=$tryserver;
8710: }
1.80 www 8711: }
8712: }
8713: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8714: return 'error: unable to find a home server for '.$uname.
8715: ' in domain '.$udom;
1.80 www 8716: }
8717: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8718: &escape($upass),$unhome);
8719: unless ($reply eq 'ok') {
8720: return 'error: '.$reply;
8721: }
1.230 stredwic 8722: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8723: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8724: return 'error: unable verify users home machine.';
1.80 www 8725: }
1.209 matthew 8726: } # End of creation of new user
1.80 www 8727: # ---------------------------------------------------------------------- Add ID
8728: if ($uid) {
8729: $uid=~tr/A-Z/a-z/;
8730: my %uidhash=&idrget($udom,$uname);
1.196 www 8731: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8732: && (!$forceid)) {
1.80 www 8733: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8734: return 'error: user id "'.$uid.'" does not match '.
8735: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8736: }
8737: } else {
8738: &idput($udom,($uname => $uid));
8739: }
8740: }
8741: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8742: my @tmp=&get('environment',
1.899 raeburn 8743: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8744: 'permanentemail','inststatus'],
1.134 albertel 8745: $udom,$uname);
1.1075 raeburn 8746: my (%names,%oldnames);
1.313 matthew 8747: if ($tmp[0] =~ m/^error:.*/) {
8748: %names=();
8749: } else {
8750: %names = @tmp;
1.1075 raeburn 8751: %oldnames = %names;
1.313 matthew 8752: }
1.388 www 8753: #
1.1058 raeburn 8754: # If name, email and/or uid are blank (e.g., because an uploaded file
8755: # of users did not contain them), do not overwrite existing values
8756: # unless field is in $candelete array ref.
8757: #
8758:
8759: my @fields = ('firstname','middlename','lastname','generation',
8760: 'permanentemail','id');
8761: my %newvalues;
8762: if (ref($candelete) eq 'ARRAY') {
8763: foreach my $field (@fields) {
8764: if (grep(/^\Q$field\E$/,@{$candelete})) {
8765: if ($field eq 'firstname') {
8766: $names{$field} = $first;
8767: } elsif ($field eq 'middlename') {
8768: $names{$field} = $middle;
8769: } elsif ($field eq 'lastname') {
8770: $names{$field} = $last;
8771: } elsif ($field eq 'generation') {
8772: $names{$field} = $gene;
8773: } elsif ($field eq 'permanentemail') {
8774: $names{$field} = $email;
8775: } elsif ($field eq 'id') {
8776: $names{$field} = $uid;
8777: }
8778: }
8779: }
8780: }
1.388 www 8781: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8782: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8783: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8784: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8785: if ($email) {
8786: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8787: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8788: }
1.899 raeburn 8789: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8790: if (defined($inststatus)) {
8791: $names{'inststatus'} = '';
8792: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8793: if (ref($usertypes) eq 'HASH') {
8794: my @okstatuses;
8795: foreach my $item (split(/:/,$inststatus)) {
8796: if (defined($usertypes->{$item})) {
8797: push(@okstatuses,$item);
8798: }
8799: }
8800: if (@okstatuses) {
8801: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8802: }
8803: }
8804: }
1.1075 raeburn 8805: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8806: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8807: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8808: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8809: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8810: } else {
8811: $logmsg .= ' during self creation';
8812: }
1.1075 raeburn 8813: my $changed;
8814: if ($newuser) {
8815: $changed = 1;
8816: } else {
8817: foreach my $field (@fields) {
8818: if ($names{$field} ne $oldnames{$field}) {
8819: $changed = 1;
8820: last;
8821: }
8822: }
8823: }
8824: unless ($changed) {
8825: $logmsg = 'No changes in user information needed for: '.$logmsg;
8826: &logthis($logmsg);
8827: return 'ok';
8828: }
8829: my $reply = &put('environment', \%names, $udom,$uname);
8830: if ($reply ne 'ok') {
8831: return 'error: '.$reply;
8832: }
1.1087 raeburn 8833: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8834: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8835: }
1.1075 raeburn 8836: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8837: &devalidate_cache_new('namescache',$uname.':'.$udom);
8838: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8839: &logthis($logmsg);
1.134 albertel 8840: return 'ok';
1.80 www 8841: }
8842:
1.81 www 8843: # -------------------------------------------------------------- Modify student
1.80 www 8844:
1.81 www 8845: sub modifystudent {
8846: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8847: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8848: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8849: if (!$cid) {
1.620 albertel 8850: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8851: return 'not_in_class';
8852: }
1.80 www 8853: }
8854: # --------------------------------------------------------------- Make the user
1.81 www 8855: my $reply=&modifyuser
1.209 matthew 8856: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8857: $desiredhome,$email,$inststatus);
1.80 www 8858: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8859: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8860: # student's environment
1.297 matthew 8861: $uid = undef if (!$forceid);
1.455 albertel 8862: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8863: $gene,$usec,$end,$start,$type,$locktype,
8864: $cid,$selfenroll,$context,$credits);
1.297 matthew 8865: return $reply;
8866: }
8867:
8868: sub modify_student_enrollment {
1.1216 raeburn 8869: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8870: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8871: my ($cdom,$cnum,$chome);
8872: if (!$cid) {
1.620 albertel 8873: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8874: return 'not_in_class';
8875: }
1.620 albertel 8876: $cdom=$env{'course.'.$cid.'.domain'};
8877: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8878: } else {
8879: ($cdom,$cnum)=split(/_/,$cid);
8880: }
1.620 albertel 8881: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8882: if (!$chome) {
1.457 raeburn 8883: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8884: }
1.455 albertel 8885: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8886: # Make sure the user exists
1.81 www 8887: my $uhome=&homeserver($uname,$udom);
8888: if (($uhome eq '') || ($uhome eq 'no_host')) {
8889: return 'error: no such user';
8890: }
1.297 matthew 8891: # Get student data if we were not given enough information
8892: if (!defined($first) || $first eq '' ||
8893: !defined($last) || $last eq '' ||
8894: !defined($uid) || $uid eq '' ||
8895: !defined($middle) || $middle eq '' ||
8896: !defined($gene) || $gene eq '') {
1.294 matthew 8897: # They did not supply us with enough data to enroll the student, so
8898: # we need to pick up more information.
1.297 matthew 8899: my %tmp = &get('environment',
1.294 matthew 8900: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8901: ,$udom,$uname);
8902:
1.800 albertel 8903: #foreach my $key (keys(%tmp)) {
8904: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8905: #}
1.294 matthew 8906: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8907: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8908: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8909: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8910: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8911: }
1.556 albertel 8912: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8913: my $user = "$uname:$udom";
8914: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8915: my $reply=cput('classlist',
1.1148 raeburn 8916: {$user =>
1.1216 raeburn 8917: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8918: $cdom,$cnum);
1.1148 raeburn 8919: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8920: &devalidate_getsection_cache($udom,$uname,$cid);
8921: } else {
1.81 www 8922: return 'error: '.$reply;
8923: }
1.297 matthew 8924: # Add student role to user
1.83 www 8925: my $uurl='/'.$cid;
1.81 www 8926: $uurl=~s/\_/\//g;
8927: if ($usec) {
8928: $uurl.='/'.$usec;
8929: }
1.1148 raeburn 8930: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8931: $selfenroll,$context);
8932: if ($result ne 'ok') {
8933: if ($old_entry{$user} ne '') {
8934: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8935: } else {
8936: $reply = &del('classlist',[$user],$cdom,$cnum);
8937: }
8938: }
8939: return $result;
1.21 www 8940: }
8941:
1.556 albertel 8942: sub format_name {
8943: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8944: my $name;
8945: if ($first ne 'lastname') {
8946: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8947: } else {
8948: if ($lastname=~/\S/) {
8949: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8950: $name=~s/\s+,/,/;
8951: } else {
8952: $name.= $firstname.' '.$middlename.' '.$generation;
8953: }
8954: }
8955: $name=~s/^\s+//;
8956: $name=~s/\s+$//;
8957: $name=~s/\s+/ /g;
8958: return $name;
8959: }
8960:
1.84 www 8961: # ------------------------------------------------- Write to course preferences
8962:
8963: sub writecoursepref {
8964: my ($courseid,%prefs)=@_;
8965: $courseid=~s/^\///;
8966: $courseid=~s/\_/\//g;
8967: my ($cdomain,$cnum)=split(/\//,$courseid);
8968: my $chome=homeserver($cnum,$cdomain);
8969: if (($chome eq '') || ($chome eq 'no_host')) {
8970: return 'error: no such course';
8971: }
8972: my $cstring='';
1.800 albertel 8973: foreach my $pref (keys(%prefs)) {
8974: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8975: }
1.84 www 8976: $cstring=~s/\&$//;
8977: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8978: }
8979:
8980: # ---------------------------------------------------------- Make/modify course
8981:
8982: sub createcourse {
1.741 raeburn 8983: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8984: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8985: $url=&declutter($url);
8986: my $cid='';
1.1028 raeburn 8987: if ($context eq 'requestcourses') {
8988: my $can_create = 0;
8989: my ($ownername,$ownerdom) = split(':',$course_owner);
8990: if ($udom eq $ownerdom) {
8991: if (&usertools_access($ownername,$ownerdom,$category,undef,
8992: $context)) {
8993: $can_create = 1;
8994: }
8995: } else {
8996: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8997: $category);
8998: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8999: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9000: if (@curr > 0) {
9001: my @options = qw(approval validate autolimit);
9002: my $optregex = join('|',@options);
9003: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9004: $can_create = 1;
9005: }
9006: }
9007: }
9008: }
9009: if ($can_create) {
9010: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9011: unless (&allowed('ccc',$udom)) {
9012: return 'refused';
9013: }
1.1017 raeburn 9014: }
9015: } else {
9016: return 'refused';
9017: }
1.1028 raeburn 9018: } elsif (!&allowed('ccc',$udom)) {
9019: return 'refused';
1.84 www 9020: }
1.1011 raeburn 9021: # --------------------------------------------------------------- Get Unique ID
9022: my $uname;
9023: if ($cnum =~ /^$match_courseid$/) {
9024: my $chome=&homeserver($cnum,$udom,'true');
9025: if (($chome eq '') || ($chome eq 'no_host')) {
9026: $uname = $cnum;
9027: } else {
1.1038 raeburn 9028: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9029: }
9030: } else {
1.1038 raeburn 9031: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9032: }
9033: return $uname if ($uname =~ /^error/);
9034: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9035: if (!defined($course_server)) {
9036: if (defined(&domain($udom,'primary'))) {
9037: $course_server = &domain($udom,'primary');
9038: } else {
9039: $course_server = $env{'user.home'};
9040: }
9041: }
9042: my %host_servers =
9043: &Apache::lonnet::get_servers($udom,'library');
9044: unless ($host_servers{$course_server}) {
9045: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9046: }
1.84 www 9047: # ------------------------------------------------------------- Make the course
9048: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9049: $course_server);
1.84 www 9050: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9051: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9052: if (($uhome eq '') || ($uhome eq 'no_host')) {
9053: return 'error: no such course';
9054: }
1.271 www 9055: # ----------------------------------------------------------------- Course made
1.516 raeburn 9056: # log existence
1.1029 raeburn 9057: my $now = time;
1.918 raeburn 9058: my $newcourse = {
9059: $udom.'_'.$uname => {
1.921 raeburn 9060: description => $description,
9061: inst_code => $inst_code,
9062: owner => $course_owner,
9063: type => $crstype,
1.1029 raeburn 9064: creator => $env{'user.name'}.':'.
9065: $env{'user.domain'},
9066: created => $now,
9067: context => $context,
1.918 raeburn 9068: },
9069: };
1.921 raeburn 9070: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9071: # set toplevel url
1.271 www 9072: my $topurl=$url;
9073: unless ($nonstandard) {
9074: # ------------------------------------------ For standard courses, make top url
9075: my $mapurl=&clutter($url);
1.278 www 9076: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9077: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9078: <map>
9079: <resource id="1" type="start"></resource>
9080: <resource id="2" src="$mapurl"></resource>
9081: <resource id="3" type="finish"></resource>
9082: <link index="1" from="1" to="2"></link>
9083: <link index="2" from="2" to="3"></link>
9084: </map>
9085: ENDINITMAP
9086: $topurl=&declutter(
1.638 albertel 9087: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9088: );
9089: }
9090: # ----------------------------------------------------------- Write preferences
1.84 www 9091: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9092: ('description' => $description,
9093: 'url' => $topurl,
9094: 'internal.creator' => $env{'user.name'}.':'.
9095: $env{'user.domain'},
9096: 'internal.created' => $now,
9097: 'internal.creationcontext' => $context)
9098: );
1.84 www 9099: return '/'.$udom.'/'.$uname;
9100: }
9101:
1.1011 raeburn 9102: # ------------------------------------------------------------------- Create ID
9103: sub generate_coursenum {
1.1038 raeburn 9104: my ($udom,$crstype) = @_;
1.1011 raeburn 9105: my $domdesc = &domain($udom);
9106: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9107: my $first;
9108: if ($crstype eq 'Community') {
9109: $first = '0';
9110: } else {
9111: $first = int(1+rand(9));
9112: }
9113: my $uname=$first.
1.1011 raeburn 9114: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9115: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9116: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9117: # ----------------------------------------------- Make sure that does not exist
9118: my $uhome=&homeserver($uname,$udom,'true');
9119: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9120: if ($crstype eq 'Community') {
9121: $first = '0';
9122: } else {
9123: $first = int(1+rand(9));
9124: }
9125: $uname=$first.
1.1011 raeburn 9126: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9127: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9128: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9129: $uhome=&homeserver($uname,$udom,'true');
9130: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9131: return 'error: unable to generate unique course-ID';
9132: }
9133: }
9134: return $uname;
9135: }
9136:
1.813 albertel 9137: sub is_course {
1.1167 droeschl 9138: my ($cdom, $cnum) = scalar(@_) == 1 ?
9139: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9140:
9141: return unless $cdom and $cnum;
9142:
9143: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9144: '.');
9145:
1.1219 raeburn 9146: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9147: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9148: }
9149:
1.1015 raeburn 9150: sub store_userdata {
9151: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9152: my $result;
1.1016 raeburn 9153: if ($datakey ne '') {
1.1013 raeburn 9154: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9155: if ($udom eq '' || $uname eq '') {
9156: $udom = $env{'user.domain'};
9157: $uname = $env{'user.name'};
9158: }
9159: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9160: if (($uhome eq '') || ($uhome eq 'no_host')) {
9161: $result = 'error: no_host';
9162: } else {
9163: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9164: $storehash->{'host'} = $perlvar{'lonHostID'};
9165:
9166: my $namevalue='';
9167: foreach my $key (keys(%{$storehash})) {
9168: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9169: }
9170: $namevalue=~s/\&$//;
1.1224 raeburn 9171: unless ($namespace eq 'courserequests') {
9172: $datakey = &escape($datakey);
9173: }
1.1105 raeburn 9174: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9175: $namevalue,$uhome);
1.1013 raeburn 9176: }
9177: } else {
9178: $result = 'error: data to store was not a hash reference';
9179: }
9180: } else {
9181: $result= 'error: invalid requestkey';
9182: }
9183: return $result;
9184: }
9185:
1.21 www 9186: # ---------------------------------------------------------- Assign Custom Role
9187:
9188: sub assigncustomrole {
1.957 raeburn 9189: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9190: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9191: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9192: }
9193:
9194: # ----------------------------------------------------------------- Revoke Role
9195:
9196: sub revokerole {
1.957 raeburn 9197: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9198: my $now=time;
1.965 raeburn 9199: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9200: }
9201:
9202: # ---------------------------------------------------------- Revoke Custom Role
9203:
9204: sub revokecustomrole {
1.957 raeburn 9205: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9206: my $now=time;
1.357 www 9207: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9208: $deleteflag,$selfenroll,$context);
1.17 www 9209: }
9210:
1.533 banghart 9211: # ------------------------------------------------------------ Disk usage
1.535 albertel 9212: sub diskusage {
1.955 raeburn 9213: my ($udom,$uname,$directorypath,$getpropath)=@_;
9214: $directorypath =~ s/\/$//;
9215: my $listing=&reply('du2:'.&escape($directorypath).':'
9216: .&escape($getpropath).':'.&escape($uname).':'
9217: .&escape($udom),homeserver($uname,$udom));
9218: if ($listing eq 'unknown_cmd') {
9219: if ($getpropath) {
9220: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9221: }
9222: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9223: }
1.514 albertel 9224: return $listing;
1.512 banghart 9225: }
9226:
1.566 banghart 9227: sub is_locked {
1.1096 raeburn 9228: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9229: my @check;
9230: my $is_locked;
1.1093 raeburn 9231: push (@check,$file_name);
1.613 albertel 9232: my %locked = &get('file_permissions',\@check,
1.620 albertel 9233: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9234: my ($tmp)=keys(%locked);
9235: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9236:
1.566 banghart 9237: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9238: $is_locked = 'false';
9239: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9240: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9241: $is_locked = 'true';
1.1096 raeburn 9242: if (ref($which) eq 'ARRAY') {
9243: push(@{$which},$entry);
9244: } else {
9245: last;
9246: }
1.745 raeburn 9247: }
9248: }
1.566 banghart 9249: } else {
9250: $is_locked = 'false';
9251: }
1.1093 raeburn 9252: return $is_locked;
1.566 banghart 9253: }
9254:
1.759 albertel 9255: sub declutter_portfile {
9256: my ($file) = @_;
1.833 albertel 9257: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9258: return $file;
9259: }
9260:
1.559 banghart 9261: # ------------------------------------------------------------- Mark as Read Only
9262:
9263: sub mark_as_readonly {
9264: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9265: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9266: my ($tmp)=keys(%current_permissions);
9267: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9268: foreach my $file (@{$files}) {
1.759 albertel 9269: $file = &declutter_portfile($file);
1.561 banghart 9270: push(@{$current_permissions{$file}},$what);
1.559 banghart 9271: }
1.613 albertel 9272: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9273: return;
9274: }
9275:
1.572 banghart 9276: # ------------------------------------------------------------Save Selected Files
9277:
9278: sub save_selected_files {
9279: my ($user, $path, @files) = @_;
9280: my $filename = $user."savedfiles";
1.573 banghart 9281: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9282: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9283: foreach my $file (@files) {
1.620 albertel 9284: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9285: }
9286: foreach my $file (@other_files) {
1.574 banghart 9287: print (OUT $file."\n");
1.572 banghart 9288: }
1.574 banghart 9289: close (OUT);
1.572 banghart 9290: return 'ok';
9291: }
9292:
1.574 banghart 9293: sub clear_selected_files {
9294: my ($user) = @_;
9295: my $filename = $user."savedfiles";
1.1117 foxr 9296: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9297: print (OUT undef);
9298: close (OUT);
9299: return ("ok");
9300: }
9301:
1.572 banghart 9302: sub files_in_path {
9303: my ($user, $path) = @_;
9304: my $filename = $user."savedfiles";
9305: my %return_files;
1.1117 foxr 9306: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9307: while (my $line_in = <IN>) {
1.574 banghart 9308: chomp ($line_in);
9309: my @paths_and_file = split (m!/!, $line_in);
9310: my $file_part = pop (@paths_and_file);
9311: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9312: $path_part.='/';
9313: my $path_and_file = $path_part.$file_part;
9314: if ($path_part eq $path) {
9315: $return_files{$file_part}= 'selected';
9316: }
9317: }
1.574 banghart 9318: close (IN);
9319: return (\%return_files);
1.572 banghart 9320: }
9321:
9322: # called in portfolio select mode, to show files selected NOT in current directory
9323: sub files_not_in_path {
9324: my ($user, $path) = @_;
9325: my $filename = $user."savedfiles";
9326: my @return_files;
9327: my $path_part;
1.1117 foxr 9328: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9329: while (my $line = <IN>) {
1.572 banghart 9330: #ok, I know it's clunky, but I want it to work
1.800 albertel 9331: my @paths_and_file = split(m|/|, $line);
9332: my $file_part = pop(@paths_and_file);
9333: chomp($file_part);
9334: my $path_part = join('/', @paths_and_file);
1.572 banghart 9335: $path_part .= '/';
9336: my $path_and_file = $path_part.$file_part;
9337: if ($path_part ne $path) {
1.800 albertel 9338: push(@return_files, ($path_and_file));
1.572 banghart 9339: }
9340: }
1.800 albertel 9341: close(OUT);
1.574 banghart 9342: return (@return_files);
1.572 banghart 9343: }
9344:
1.1273 raeburn 9345: #------------------------------Submitted/Handedback Portfolio Files Versioning
9346:
9347: sub portfiles_versioning {
9348: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9349: my $portfolio_root = '/userfiles/portfolio';
9350: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9351: foreach my $file (@{$portfiles}) {
9352: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9353: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9354: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9355: my $getpropath = 1;
9356: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9357: $stu_name,$getpropath);
9358: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9359: my $new_answer =
9360: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9361: if ($new_answer ne 'problem getting file') {
9362: push(@{$versioned_portfiles}, $directory.$new_answer);
9363: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9364: [$symb,$env{'request.course.id'},'graded']);
9365: }
9366: }
9367: }
9368:
9369: sub get_next_version {
9370: my ($answer_name, $answer_ext, $dir_list) = @_;
9371: my $version;
9372: if (ref($dir_list) eq 'ARRAY') {
9373: foreach my $row (@{$dir_list}) {
9374: my ($file) = split(/\&/,$row,2);
9375: my ($file_name,$file_version,$file_ext) =
9376: &file_name_version_ext($file);
9377: if (($file_name eq $answer_name) &&
9378: ($file_ext eq $answer_ext)) {
9379: # gets here if filename and extension match,
9380: # regardless of version
9381: if ($file_version ne '') {
9382: # a versioned file is found so save it for later
9383: if ($file_version > $version) {
9384: $version = $file_version;
9385: }
9386: }
9387: }
9388: }
9389: }
9390: $version ++;
9391: return($version);
9392: }
9393:
9394: sub version_selected_portfile {
9395: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9396: my ($answer_name,$answer_ver,$answer_ext) =
9397: &file_name_version_ext($file_name);
9398: my $new_answer;
9399: $env{'form.copy'} =
9400: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9401: if($env{'form.copy'} eq '-1') {
9402: $new_answer = 'problem getting file';
9403: } else {
9404: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9405: my $copy_result =
9406: &finishuserfileupload($stu_name,$domain,'copy',
9407: '/portfolio'.$directory.$new_answer);
9408: }
9409: undef($env{'form.copy'});
9410: return ($new_answer);
9411: }
9412:
9413: sub file_name_version_ext {
9414: my ($file)=@_;
9415: my @file_parts = split(/\./, $file);
9416: my ($name,$version,$ext);
9417: if (@file_parts > 1) {
9418: $ext=pop(@file_parts);
9419: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9420: $version=pop(@file_parts);
9421: }
9422: $name=join('.',@file_parts);
9423: } else {
9424: $name=join('.',@file_parts);
9425: }
9426: return($name,$version,$ext);
9427: }
9428:
1.745 raeburn 9429: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9430:
1.745 raeburn 9431: sub get_portfile_permissions {
9432: my ($domain,$user) = @_;
1.613 albertel 9433: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9434: my ($tmp)=keys(%current_permissions);
9435: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9436: return \%current_permissions;
9437: }
9438:
9439: #---------------------------------------------Get portfolio file access controls
9440:
1.749 raeburn 9441: sub get_access_controls {
1.745 raeburn 9442: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9443: my %access;
9444: my $real_file = $file;
9445: $file =~ s/\.meta$//;
1.745 raeburn 9446: if (defined($file)) {
1.749 raeburn 9447: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9448: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9449: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9450: }
9451: }
1.745 raeburn 9452: } else {
1.749 raeburn 9453: foreach my $key (keys(%{$current_permissions})) {
9454: if ($key =~ /\0accesscontrol$/) {
9455: if (defined($group)) {
9456: if ($key !~ m-^\Q$group\E/-) {
9457: next;
9458: }
9459: }
9460: my ($fullpath) = split(/\0/,$key);
9461: if (ref($$current_permissions{$key}) eq 'HASH') {
9462: foreach my $control (keys(%{$$current_permissions{$key}})) {
9463: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9464: }
9465: }
9466: }
9467: }
9468: }
9469: return %access;
9470: }
9471:
9472: sub modify_access_controls {
9473: my ($file_name,$changes,$domain,$user)=@_;
9474: my ($outcome,$deloutcome);
9475: my %store_permissions;
9476: my %new_values;
9477: my %new_control;
9478: my %translation;
9479: my @deletions = ();
9480: my $now = time;
9481: if (exists($$changes{'activate'})) {
9482: if (ref($$changes{'activate'}) eq 'HASH') {
9483: my @newitems = sort(keys(%{$$changes{'activate'}}));
9484: my $numnew = scalar(@newitems);
9485: for (my $i=0; $i<$numnew; $i++) {
9486: my $newkey = $newitems[$i];
9487: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9488: if ($newkey =~ /^\d+:/) {
9489: $newkey =~ s/^(\d+)/$newid/;
9490: $translation{$1} = $newid;
9491: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9492: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9493: $translation{$1} = $newid;
9494: }
1.749 raeburn 9495: $new_values{$file_name."\0".$newkey} =
9496: $$changes{'activate'}{$newitems[$i]};
9497: $new_control{$newkey} = $now;
9498: }
9499: }
9500: }
9501: my %todelete;
9502: my %changed_items;
9503: foreach my $action ('delete','update') {
9504: if (exists($$changes{$action})) {
9505: if (ref($$changes{$action}) eq 'HASH') {
9506: foreach my $key (keys(%{$$changes{$action}})) {
9507: my ($itemnum) = ($key =~ /^([^:]+):/);
9508: if ($action eq 'delete') {
9509: $todelete{$itemnum} = 1;
9510: } else {
9511: $changed_items{$itemnum} = $key;
9512: }
9513: }
1.745 raeburn 9514: }
9515: }
1.749 raeburn 9516: }
9517: # get lock on access controls for file.
9518: my $lockhash = {
9519: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9520: ':'.$env{'user.domain'},
9521: };
9522: my $tries = 0;
9523: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9524:
1.1288 ! damieng 9525: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9526: $tries ++;
1.1288 ! damieng 9527: Time::HiRes::sleep(0.1);
1.749 raeburn 9528: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9529: }
9530: if ($gotlock eq 'ok') {
9531: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9532: my ($tmp)=keys(%curr_permissions);
9533: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9534: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9535: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9536: if (ref($curr_controls) eq 'HASH') {
9537: foreach my $control_item (keys(%{$curr_controls})) {
9538: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9539: if (defined($todelete{$itemnum})) {
9540: push(@deletions,$file_name."\0".$control_item);
9541: } else {
9542: if (defined($changed_items{$itemnum})) {
9543: $new_control{$changed_items{$itemnum}} = $now;
9544: push(@deletions,$file_name."\0".$control_item);
9545: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9546: } else {
9547: $new_control{$control_item} = $$curr_controls{$control_item};
9548: }
9549: }
1.745 raeburn 9550: }
9551: }
9552: }
1.970 raeburn 9553: my ($group);
9554: if (&is_course($domain,$user)) {
9555: ($group,my $file) = split(/\//,$file_name,2);
9556: }
1.749 raeburn 9557: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9558: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9559: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9560: # remove lock
9561: my @del_lock = ($file_name."\0".'locked_access_records');
9562: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9563: my $sqlresult =
1.970 raeburn 9564: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9565: $group);
1.749 raeburn 9566: } else {
9567: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9568: }
1.749 raeburn 9569: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9570: }
9571:
1.827 raeburn 9572: sub make_public_indefinitely {
1.1271 raeburn 9573: my (@requrl) = @_;
9574: return &automated_portfile_access('public',\@requrl);
9575: }
9576:
9577: sub automated_portfile_access {
9578: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9579: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9580: return 'invalid';
9581: }
1.1271 raeburn 9582: my %urls;
9583: if (ref($addsref) eq 'ARRAY') {
9584: foreach my $requrl (@{$addsref}) {
9585: if (&is_portfolio_url($requrl)) {
9586: unless (exists($urls{$requrl})) {
9587: $urls{$requrl} = 'add';
9588: }
9589: }
9590: }
9591: }
9592: if (ref($delsref) eq 'ARRAY') {
9593: foreach my $requrl (@{$delsref}) {
9594: if (&is_portfolio_url($requrl)) {
9595: unless (exists($urls{$requrl})) {
9596: $urls{$requrl} = 'delete';
9597: }
9598: }
9599: }
9600: }
9601: unless (keys(%urls)) {
9602: return 'invalid';
9603: }
9604: my $ip;
9605: if ($accesstype eq 'ip') {
9606: if (ref($info) eq 'HASH') {
9607: if ($info->{'ip'} ne '') {
9608: $ip = $info->{'ip'};
9609: }
9610: }
9611: if ($ip eq '') {
9612: return 'invalid';
9613: }
9614: }
9615: my $errors;
1.827 raeburn 9616: my $now = time;
1.1271 raeburn 9617: my %current_perms;
9618: foreach my $requrl (sort(keys(%urls))) {
9619: my $action;
9620: if ($urls{$requrl} eq 'add') {
9621: $action = 'activate';
9622: } else {
9623: $action = 'none';
9624: }
9625: my $aclnum = 0;
1.827 raeburn 9626: my (undef,$udom,$unum,$file_name,$group) =
9627: &parse_portfolio_url($requrl);
1.1271 raeburn 9628: unless (exists($current_perms{$unum.':'.$udom})) {
9629: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9630: }
9631: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9632: $group,$file_name);
9633: foreach my $key (keys(%{$access_controls{$file_name}})) {
9634: my ($num,$scope,$end,$start) =
9635: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9636: if ($scope eq $accesstype) {
9637: if (($start <= $now) && ($end == 0)) {
9638: if ($accesstype eq 'ip') {
9639: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9640: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9641: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9642: if ($urls{$requrl} eq 'add') {
9643: $action = 'none';
9644: last;
9645: } else {
9646: $action = 'delete';
9647: $aclnum = $num;
9648: last;
9649: }
9650: }
9651: }
9652: }
9653: } elsif ($accesstype eq 'public') {
9654: if ($urls{$requrl} eq 'add') {
9655: $action = 'none';
9656: last;
9657: } else {
9658: $action = 'delete';
9659: $aclnum = $num;
9660: last;
9661: }
9662: }
9663: } elsif ($accesstype eq 'public') {
1.827 raeburn 9664: $action = 'update';
9665: $aclnum = $num;
1.1271 raeburn 9666: last;
1.827 raeburn 9667: }
9668: }
9669: }
9670: if ($action eq 'none') {
1.1271 raeburn 9671: next;
1.827 raeburn 9672: } else {
9673: my %changes;
9674: my $newend = 0;
9675: my $newstart = $now;
1.1271 raeburn 9676: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 9677: $changes{$action}{$newkey} = {
1.1271 raeburn 9678: type => $accesstype,
1.827 raeburn 9679: time => {
9680: start => $newstart,
9681: end => $newend,
9682: },
9683: };
1.1271 raeburn 9684: if ($accesstype eq 'ip') {
9685: $changes{$action}{$newkey}{'ip'} = [$ip];
9686: }
1.827 raeburn 9687: my ($outcome,$deloutcome,$new_values,$translation) =
9688: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 9689: unless ($outcome eq 'ok') {
9690: $errors .= $outcome.' ';
9691: }
1.827 raeburn 9692: }
1.1271 raeburn 9693: }
9694: if ($errors) {
9695: $errors =~ s/\s$//;
9696: return $errors;
1.827 raeburn 9697: } else {
1.1271 raeburn 9698: return 'ok';
1.827 raeburn 9699: }
9700: }
9701:
1.745 raeburn 9702: #------------------------------------------------------Get Marked as Read Only
9703:
9704: sub get_marked_as_readonly {
9705: my ($domain,$user,$what,$group) = @_;
9706: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9707: my @readonly_files;
1.629 banghart 9708: my $cmp1=$what;
9709: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9710: while (my ($file_name,$value) = each(%{$current_permissions})) {
9711: if (defined($group)) {
9712: if ($file_name !~ m-^\Q$group\E/-) {
9713: next;
9714: }
9715: }
1.561 banghart 9716: if (ref($value) eq "ARRAY"){
9717: foreach my $stored_what (@{$value}) {
1.629 banghart 9718: my $cmp2=$stored_what;
1.759 albertel 9719: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9720: $cmp2=join('',@{$stored_what});
1.745 raeburn 9721: }
1.629 banghart 9722: if ($cmp1 eq $cmp2) {
1.561 banghart 9723: push(@readonly_files, $file_name);
1.745 raeburn 9724: last;
1.563 banghart 9725: } elsif (!defined($what)) {
9726: push(@readonly_files, $file_name);
1.745 raeburn 9727: last;
1.561 banghart 9728: }
9729: }
1.745 raeburn 9730: }
1.561 banghart 9731: }
9732: return @readonly_files;
9733: }
1.577 banghart 9734: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9735:
1.577 banghart 9736: sub get_marked_as_readonly_hash {
1.745 raeburn 9737: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9738: my %readonly_files;
1.745 raeburn 9739: while (my ($file_name,$value) = each(%{$current_permissions})) {
9740: if (defined($group)) {
9741: if ($file_name !~ m-^\Q$group\E/-) {
9742: next;
9743: }
9744: }
1.577 banghart 9745: if (ref($value) eq "ARRAY"){
9746: foreach my $stored_what (@{$value}) {
1.745 raeburn 9747: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9748: foreach my $lock_descriptor(@{$stored_what}) {
9749: if ($lock_descriptor eq 'graded') {
9750: $readonly_files{$file_name} = 'graded';
9751: } elsif ($lock_descriptor eq 'handback') {
9752: $readonly_files{$file_name} = 'handback';
9753: } else {
9754: if (!exists($readonly_files{$file_name})) {
9755: $readonly_files{$file_name} = 'locked';
9756: }
9757: }
1.745 raeburn 9758: }
1.750 banghart 9759: }
1.577 banghart 9760: }
9761: }
9762: }
9763: return %readonly_files;
9764: }
1.559 banghart 9765: # ------------------------------------------------------------ Unmark as Read Only
9766:
9767: sub unmark_as_readonly {
1.629 banghart 9768: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9769: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9770: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9771: $file_name = &declutter_portfile($file_name);
1.634 albertel 9772: my $symb_crs = $what;
9773: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9774: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9775: my ($tmp)=keys(%current_permissions);
9776: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9777: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9778: foreach my $file (@readonly_files) {
1.759 albertel 9779: my $clean_file = &declutter_portfile($file);
9780: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9781: my $current_locks = $current_permissions{$file};
1.563 banghart 9782: my @new_locks;
9783: my @del_keys;
9784: if (ref($current_locks) eq "ARRAY"){
9785: foreach my $locker (@{$current_locks}) {
1.632 albertel 9786: my $compare=$locker;
1.749 raeburn 9787: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9788: $compare=join('',@{$locker});
1.746 raeburn 9789: if ($compare ne $symb_crs) {
9790: push(@new_locks, $locker);
9791: }
1.563 banghart 9792: }
9793: }
1.650 albertel 9794: if (scalar(@new_locks) > 0) {
1.563 banghart 9795: $current_permissions{$file} = \@new_locks;
9796: } else {
9797: push(@del_keys, $file);
1.613 albertel 9798: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9799: delete($current_permissions{$file});
1.563 banghart 9800: }
9801: }
1.561 banghart 9802: }
1.613 albertel 9803: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9804: return;
9805: }
1.512 banghart 9806:
1.17 www 9807: # ------------------------------------------------------------ Directory lister
9808:
9809: sub dirlist {
1.955 raeburn 9810: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9811: $uri=~s/^\///;
9812: $uri=~s/\/$//;
1.253 stredwic 9813: my ($udom, $uname);
1.955 raeburn 9814: if ($getuserdir) {
1.253 stredwic 9815: $udom = $userdomain;
9816: $uname = $username;
1.955 raeburn 9817: } else {
9818: (undef,$udom,$uname)=split(/\//,$uri);
9819: if(defined($userdomain)) {
9820: $udom = $userdomain;
9821: }
9822: if(defined($username)) {
9823: $uname = $username;
9824: }
1.253 stredwic 9825: }
1.955 raeburn 9826: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9827:
1.955 raeburn 9828: $dirRoot = $perlvar{'lonDocRoot'};
9829: if (defined($getpropath)) {
9830: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9831: $dirRoot =~ s/\/$//;
1.955 raeburn 9832: } elsif (defined($getuserdir)) {
9833: my $subdir=$uname.'__';
9834: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9835: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9836: ."/$udom/$subdir/$uname";
9837: } elsif (defined($alternateRoot)) {
9838: $dirRoot = $alternateRoot;
1.751 banghart 9839: }
1.253 stredwic 9840:
9841: if($udom) {
9842: if($uname) {
1.1135 raeburn 9843: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9844: if ($uhome eq 'no_host') {
9845: return ([],'no_host');
9846: }
1.955 raeburn 9847: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9848: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9849: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9850: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9851: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9852: } else {
9853: @listing_results = map { &unescape($_); } split(/:/,$listing);
9854: }
1.605 matthew 9855: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9856: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9857: @listing_results = split(/:/,$listing);
9858: } else {
9859: @listing_results = map { &unescape($_); } split(/:/,$listing);
9860: }
1.1135 raeburn 9861: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9862: ($listing eq 'rejected') || ($listing eq 'refused') ||
9863: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9864: return ([],$listing);
9865: } else {
9866: return (\@listing_results);
1.1135 raeburn 9867: }
1.955 raeburn 9868: } elsif(!$alternateRoot) {
1.1136 raeburn 9869: my (%allusers,%listerror);
1.841 albertel 9870: my %servers = &get_servers($udom,'library');
1.955 raeburn 9871: foreach my $tryserver (keys(%servers)) {
9872: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9873: &escape($udom),$tryserver);
9874: if ($listing eq 'unknown_cmd') {
9875: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9876: $udom, $tryserver);
9877: } else {
9878: @listing_results = map { &unescape($_); } split(/:/,$listing);
9879: }
1.841 albertel 9880: if ($listing eq 'unknown_cmd') {
9881: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9882: $udom, $tryserver);
9883: @listing_results = split(/:/,$listing);
9884: } else {
9885: @listing_results =
9886: map { &unescape($_); } split(/:/,$listing);
9887: }
1.1136 raeburn 9888: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9889: ($listing eq 'rejected') || ($listing eq 'refused') ||
9890: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9891: $listerror{$tryserver} = $listing;
9892: } else {
1.841 albertel 9893: foreach my $line (@listing_results) {
9894: my ($entry) = split(/&/,$line,2);
9895: $allusers{$entry} = 1;
9896: }
9897: }
1.253 stredwic 9898: }
1.1136 raeburn 9899: my @alluserslist=();
1.800 albertel 9900: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9901: push(@alluserslist,$user.'&user');
1.253 stredwic 9902: }
1.1136 raeburn 9903: return (\@alluserslist);
1.253 stredwic 9904: } else {
1.1136 raeburn 9905: return ([],'missing username');
1.253 stredwic 9906: }
1.955 raeburn 9907: } elsif(!defined($getpropath)) {
1.1136 raeburn 9908: my $path = $perlvar{'lonDocRoot'}.'/res/';
9909: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9910: return (\@all_domains);
1.955 raeburn 9911: } else {
1.1136 raeburn 9912: return ([],'missing domain');
1.275 stredwic 9913: }
9914: }
9915:
9916: # --------------------------------------------- GetFileTimestamp
9917: # This function utilizes dirlist and returns the date stamp for
9918: # when it was last modified. It will also return an error of -1
9919: # if an error occurs
9920:
9921: sub GetFileTimestamp {
1.955 raeburn 9922: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9923: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9924: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9925: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9926: undef,$getuserdir);
9927: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9928: return -1;
9929: }
9930: if (ref($fileref) eq 'ARRAY') {
9931: my @stats = split('&',$fileref->[0]);
1.375 matthew 9932: # @stats contains first the filename, then the stat output
9933: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9934: } else {
9935: return -1;
1.253 stredwic 9936: }
1.26 www 9937: }
9938:
1.712 albertel 9939: sub stat_file {
9940: my ($uri) = @_;
1.787 albertel 9941: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9942:
1.955 raeburn 9943: my ($udom,$uname,$file);
1.712 albertel 9944: if ($uri =~ m-^/(uploaded|editupload)/-) {
9945: ($udom,$uname,$file) =
1.811 albertel 9946: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9947: $file = 'userfiles/'.$file;
9948: }
9949: if ($uri =~ m-^/res/-) {
9950: ($udom,$uname) =
1.807 albertel 9951: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9952: $file = $uri;
9953: }
9954:
9955: if (!$udom || !$uname || !$file) {
9956: # unable to handle the uri
9957: return ();
9958: }
1.956 raeburn 9959: my $getpropath;
9960: if ($file =~ /^userfiles\//) {
9961: $getpropath = 1;
9962: }
1.1136 raeburn 9963: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9964: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9965: return ();
9966: } else {
9967: if (ref($listref) eq 'ARRAY') {
9968: my @stats = split('&',$listref->[0]);
9969: shift(@stats); #filename is first
9970: return @stats;
9971: }
1.712 albertel 9972: }
9973: return ();
9974: }
9975:
1.26 www 9976: # -------------------------------------------------------- Value of a Condition
9977:
1.713 albertel 9978: # gets the value of a specific preevaluated condition
9979: # stored in the string $env{user.state.<cid>}
9980: # or looks up a condition reference in the bighash and if if hasn't
9981: # already been evaluated recurses into docondval to get the value of
9982: # the condition, then memoizing it to
9983: # $env{user.state.<cid>.<condition>}
1.40 www 9984: sub directcondval {
9985: my $number=shift;
1.620 albertel 9986: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9987: &Apache::lonuserstate::evalstate();
9988: }
1.713 albertel 9989: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9990: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9991: } elsif ($number =~ /^_/) {
9992: my $sub_condition;
9993: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9994: &GDBM_READER(),0640)) {
9995: $sub_condition=$bighash{'conditions'.$number};
9996: untie(%bighash);
9997: }
9998: my $value = &docondval($sub_condition);
1.949 raeburn 9999: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10000: return $value;
10001: }
1.620 albertel 10002: if ($env{'user.state.'.$env{'request.course.id'}}) {
10003: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10004: } else {
10005: return 2;
10006: }
10007: }
10008:
1.713 albertel 10009: # get the collection of conditions for this resource
1.26 www 10010: sub condval {
10011: my $condidx=shift;
1.54 www 10012: my $allpathcond='';
1.713 albertel 10013: foreach my $cond (split(/\|/,$condidx)) {
10014: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10015: $allpathcond.=
10016: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10017: }
1.191 harris41 10018: }
1.54 www 10019: $allpathcond=~s/\|$//;
1.713 albertel 10020: return &docondval($allpathcond);
10021: }
10022:
10023: #evaluates an expression of conditions
10024: sub docondval {
10025: my ($allpathcond) = @_;
10026: my $result=0;
10027: if ($env{'request.course.id'}
10028: && defined($allpathcond)) {
10029: my $operand='|';
10030: my @stack;
10031: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10032: if ($chunk eq '(') {
10033: push @stack,($operand,$result);
10034: } elsif ($chunk eq ')') {
10035: my $before=pop @stack;
10036: if (pop @stack eq '&') {
10037: $result=$result>$before?$before:$result;
10038: } else {
10039: $result=$result>$before?$result:$before;
10040: }
10041: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10042: $operand=$chunk;
10043: } else {
10044: my $new=directcondval($chunk);
10045: if ($operand eq '&') {
10046: $result=$result>$new?$new:$result;
10047: } else {
10048: $result=$result>$new?$result:$new;
10049: }
10050: }
10051: }
1.26 www 10052: }
10053: return $result;
1.421 albertel 10054: }
10055:
10056: # ---------------------------------------------------- Devalidate courseresdata
10057:
10058: sub devalidatecourseresdata {
10059: my ($coursenum,$coursedomain)=@_;
10060: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10061: &devalidate_cache_new('courseres',$hashid);
1.28 www 10062: }
10063:
1.763 www 10064:
1.200 www 10065: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10066: #
10067: # Parameters:
10068: # $coursenum - Number of the course.
10069: # $coursedomain - Domain at which the course was created.
10070: # Returns:
10071: # A hash of the course parameters along (I think) with timestamps
10072: # and version info.
1.877 foxr 10073:
1.624 albertel 10074: sub get_courseresdata {
10075: my ($coursenum,$coursedomain)=@_;
1.200 www 10076: my $coursehom=&homeserver($coursenum,$coursedomain);
10077: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10078: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10079: my %dumpreply;
1.417 albertel 10080: unless (defined($cached)) {
1.624 albertel 10081: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10082: $result=\%dumpreply;
1.251 albertel 10083: my ($tmp) = keys(%dumpreply);
10084: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10085: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10086: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10087: return $tmp;
1.416 albertel 10088: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10089: $result=undef;
1.599 albertel 10090: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10091: }
10092: }
1.624 albertel 10093: return $result;
10094: }
10095:
1.633 albertel 10096: sub devalidateuserresdata {
10097: my ($uname,$udom)=@_;
10098: my $hashid="$udom:$uname";
10099: &devalidate_cache_new('userres',$hashid);
10100: }
10101:
1.624 albertel 10102: sub get_userresdata {
10103: my ($uname,$udom)=@_;
10104: #most student don\'t have any data set, check if there is some data
10105: if (&EXT_cache_status($udom,$uname)) { return undef; }
10106:
10107: my $hashid="$udom:$uname";
10108: my ($result,$cached)=&is_cached_new('userres',$hashid);
10109: if (!defined($cached)) {
10110: my %resourcedata=&dump('resourcedata',$udom,$uname);
10111: $result=\%resourcedata;
10112: &do_cache_new('userres',$hashid,$result,600);
10113: }
10114: my ($tmp)=keys(%$result);
10115: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10116: return $result;
10117: }
10118: #error 2 occurs when the .db doesn't exist
10119: if ($tmp!~/error: 2 /) {
1.672 albertel 10120: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 10121: " Trying to get resource data for ".
10122: $uname." at ".$udom.": ".
10123: $tmp."</font>");
10124: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10125: #&EXT_cache_set($udom,$uname);
10126: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10127: undef($tmp); # not really an error so don't send it back
1.624 albertel 10128: }
10129: return $tmp;
10130: }
1.879 foxr 10131: #----------------------------------------------- resdata - return resource data
10132: # Purpose:
10133: # Return resource data for either users or for a course.
10134: # Parameters:
10135: # $name - Course/user name.
10136: # $domain - Name of the domain the user/course is registered on.
10137: # $type - Type of thing $name is (must be 'course' or 'user'
10138: # @which - Array of names of resources desired.
10139: # Returns:
10140: # The value of the first reasource in @which that is found in the
10141: # resource hash.
10142: # Exceptional Conditions:
10143: # If the $type passed in is not valid (not the string 'course' or
10144: # 'user', an undefined reference is returned.
10145: # If none of the resources are found, an undef is returned
1.624 albertel 10146: sub resdata {
10147: my ($name,$domain,$type,@which)=@_;
10148: my $result;
10149: if ($type eq 'course') {
10150: $result=&get_courseresdata($name,$domain);
10151: } elsif ($type eq 'user') {
10152: $result=&get_userresdata($name,$domain);
10153: }
10154: if (!ref($result)) { return $result; }
1.251 albertel 10155: foreach my $item (@which) {
1.927 albertel 10156: if (defined($result->{$item->[0]})) {
10157: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10158: }
1.250 albertel 10159: }
1.291 albertel 10160: return undef;
1.200 www 10161: }
10162:
1.1236 raeburn 10163: sub get_numsuppfiles {
10164: my ($cnum,$cdom,$ignorecache)=@_;
10165: my $hashid=$cnum.':'.$cdom;
10166: my ($suppcount,$cached);
10167: unless ($ignorecache) {
10168: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10169: }
10170: unless (defined($cached)) {
10171: my $chome=&homeserver($cnum,$cdom);
10172: unless ($chome eq 'no_host') {
10173: ($suppcount,my $errors) = (0,0);
10174: my $suppmap = 'supplemental.sequence';
10175: ($suppcount,$errors) =
10176: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10177: }
10178: &do_cache_new('suppcount',$hashid,$suppcount,600);
10179: }
10180: return $suppcount;
10181: }
10182:
1.379 matthew 10183: #
10184: # EXT resource caching routines
10185: #
10186:
10187: sub clear_EXT_cache_status {
1.383 albertel 10188: &delenv('cache.EXT.');
1.379 matthew 10189: }
10190:
10191: sub EXT_cache_status {
10192: my ($target_domain,$target_user) = @_;
1.383 albertel 10193: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10194: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10195: # We know already the user has no data
10196: return 1;
10197: } else {
10198: return 0;
10199: }
10200: }
10201:
10202: sub EXT_cache_set {
10203: my ($target_domain,$target_user) = @_;
1.383 albertel 10204: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10205: #&appenv({$cachename => time});
1.379 matthew 10206: }
10207:
1.28 www 10208: # --------------------------------------------------------- Value of a Variable
1.58 www 10209: sub EXT {
1.715 albertel 10210:
1.1228 raeburn 10211: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10212: unless ($varname) { return ''; }
1.218 albertel 10213: #get real user name/domain, courseid and symb
10214: my $courseid;
1.359 albertel 10215: my $publicuser;
1.427 www 10216: if ($symbparm) {
10217: $symbparm=&get_symb_from_alias($symbparm);
10218: }
1.218 albertel 10219: if (!($uname && $udom)) {
1.790 albertel 10220: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10221: if (!$symbparm) { $symbparm=$cursymb; }
10222: } else {
1.620 albertel 10223: $courseid=$env{'request.course.id'};
1.218 albertel 10224: }
1.48 www 10225: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10226: my $rest;
1.320 albertel 10227: if (defined($therest[0])) {
1.48 www 10228: $rest=join('.',@therest);
10229: } else {
10230: $rest='';
10231: }
1.320 albertel 10232:
1.57 www 10233: my $qualifierrest=$qualifier;
10234: if ($rest) { $qualifierrest.='.'.$rest; }
10235: my $spacequalifierrest=$space;
10236: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10237: if ($realm eq 'user') {
1.48 www 10238: # --------------------------------------------------------------- user.resource
10239: if ($space eq 'resource') {
1.651 albertel 10240: if ( (defined($Apache::lonhomework::parsing_a_problem)
10241: || defined($Apache::lonhomework::parsing_a_task))
10242: &&
1.744 albertel 10243: ($symbparm eq &symbread()) ) {
10244: # if we are in the middle of processing the resource the
10245: # get the value we are planning on committing
10246: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10247: return $Apache::lonhomework::results{$qualifierrest};
10248: } else {
10249: return $Apache::lonhomework::history{$qualifierrest};
10250: }
1.335 albertel 10251: } else {
1.359 albertel 10252: my %restored;
1.620 albertel 10253: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10254: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10255: } else {
10256: %restored=&restore($symbparm,$courseid,$udom,$uname);
10257: }
1.335 albertel 10258: return $restored{$qualifierrest};
10259: }
1.48 www 10260: # ----------------------------------------------------------------- user.access
10261: } elsif ($space eq 'access') {
1.218 albertel 10262: # FIXME - not supporting calls for a specific user
1.48 www 10263: return &allowed($qualifier,$rest);
10264: # ------------------------------------------ user.preferences, user.environment
10265: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10266: if (($uname eq $env{'user.name'}) &&
10267: ($udom eq $env{'user.domain'})) {
10268: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10269: } else {
1.359 albertel 10270: my %returnhash;
10271: if (!$publicuser) {
10272: %returnhash=&userenvironment($udom,$uname,
10273: $qualifierrest);
10274: }
1.218 albertel 10275: return $returnhash{$qualifierrest};
10276: }
1.48 www 10277: # ----------------------------------------------------------------- user.course
10278: } elsif ($space eq 'course') {
1.218 albertel 10279: # FIXME - not supporting calls for a specific user
1.620 albertel 10280: return $env{join('.',('request.course',$qualifier))};
1.48 www 10281: # ------------------------------------------------------------------- user.role
10282: } elsif ($space eq 'role') {
1.218 albertel 10283: # FIXME - not supporting calls for a specific user
1.620 albertel 10284: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10285: if ($qualifier eq 'value') {
10286: return $role;
10287: } elsif ($qualifier eq 'extent') {
10288: return $where;
10289: }
10290: # ----------------------------------------------------------------- user.domain
10291: } elsif ($space eq 'domain') {
1.218 albertel 10292: return $udom;
1.48 www 10293: # ------------------------------------------------------------------- user.name
10294: } elsif ($space eq 'name') {
1.218 albertel 10295: return $uname;
1.48 www 10296: # ---------------------------------------------------- Any other user namespace
1.29 www 10297: } else {
1.359 albertel 10298: my %reply;
10299: if (!$publicuser) {
10300: %reply=&get($space,[$qualifierrest],$udom,$uname);
10301: }
10302: return $reply{$qualifierrest};
1.48 www 10303: }
1.236 www 10304: } elsif ($realm eq 'query') {
10305: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10306: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10307: [$spacequalifierrest]);
1.620 albertel 10308: return $env{'form.'.$spacequalifierrest};
1.236 www 10309: } elsif ($realm eq 'request') {
1.48 www 10310: # ------------------------------------------------------------- request.browser
10311: if ($space eq 'browser') {
1.1145 bisitz 10312: return $env{'browser.'.$qualifier};
1.57 www 10313: # ------------------------------------------------------------ request.filename
10314: } else {
1.620 albertel 10315: return $env{'request.'.$spacequalifierrest};
1.29 www 10316: }
1.28 www 10317: } elsif ($realm eq 'course') {
1.48 www 10318: # ---------------------------------------------------------- course.description
1.620 albertel 10319: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10320: } elsif ($realm eq 'resource') {
1.165 www 10321:
1.620 albertel 10322: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10323: if (!$symbparm) { $symbparm=&symbread(); }
10324: }
1.693 albertel 10325:
1.1232 raeburn 10326: if ($qualifier eq '') {
10327: if ($space eq 'title') {
10328: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10329: return &gettitle($symbparm);
10330: }
1.693 albertel 10331:
1.1232 raeburn 10332: if ($space eq 'map') {
10333: my ($map) = &decode_symb($symbparm);
10334: return &symbread($map);
10335: }
10336: if ($space eq 'maptitle') {
10337: my ($map) = &decode_symb($symbparm);
10338: return &gettitle($map);
10339: }
10340: if ($space eq 'filename') {
10341: if ($symbparm) {
10342: return &clutter((&decode_symb($symbparm))[2]);
10343: }
10344: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10345: }
1.1232 raeburn 10346:
1.1233 raeburn 10347: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10348: if ($space eq 'visibleparts') {
10349: my $navmap = Apache::lonnavmaps::navmap->new();
10350: my $item;
10351: if (ref($navmap)) {
10352: my $res = $navmap->getBySymb($symbparm);
10353: my $parts = $res->parts();
10354: if (ref($parts) eq 'ARRAY') {
10355: $item = join(',',@{$parts});
10356: }
10357: undef($navmap);
1.1232 raeburn 10358: }
1.1233 raeburn 10359: return $item;
1.1232 raeburn 10360: }
10361: }
10362: }
1.693 albertel 10363:
10364: my ($section, $group, @groups);
1.593 albertel 10365: my ($courselevelm,$courselevel);
1.1228 raeburn 10366: if (($courseid eq '') && ($cid)) {
10367: $courseid = $cid;
10368: }
10369: if (($symbparm && $courseid) &&
10370: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10371:
1.218 albertel 10372: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10373:
1.60 www 10374: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10375: my $symbp=$symbparm;
1.735 albertel 10376: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10377:
10378: my $symbparm=$symbp.'.'.$spacequalifierrest;
10379: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10380:
1.620 albertel 10381: if (($env{'user.name'} eq $uname) &&
10382: ($env{'user.domain'} eq $udom)) {
10383: $section=$env{'request.course.sec'};
1.733 raeburn 10384: @groups = split(/:/,$env{'request.course.groups'});
10385: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10386: } else {
1.539 albertel 10387: if (! defined($usection)) {
1.551 albertel 10388: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10389: } else {
10390: $section = $usection;
10391: }
1.733 raeburn 10392: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10393: }
10394:
10395: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10396: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10397: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10398:
1.593 albertel 10399: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10400: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10401: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10402:
1.60 www 10403: # ----------------------------------------------------------- first, check user
1.624 albertel 10404:
10405: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10406: ([$courselevelr,'resource'],
10407: [$courselevelm,'map' ],
10408: [$courselevel, 'course' ]));
1.931 albertel 10409: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10410:
1.594 albertel 10411: # ------------------------------------------------ second, check some of course
1.684 raeburn 10412: my $coursereply;
1.691 raeburn 10413: if (@groups > 0) {
10414: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10415: $mapparm,$spacequalifierrest);
1.927 albertel 10416: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10417: }
1.96 www 10418:
1.684 raeburn 10419: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10420: $env{'course.'.$courseid.'.domain'},
10421: 'course',
10422: ([$seclevelr, 'resource'],
10423: [$seclevelm, 'map' ],
10424: [$seclevel, 'course' ],
10425: [$courselevelr,'resource']));
10426: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10427:
1.60 www 10428: # ------------------------------------------------------ third, check map parms
1.218 albertel 10429: my %parmhash=();
10430: my $thisparm='';
10431: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10432: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10433: &GDBM_READER(),0640)) {
1.218 albertel 10434: $thisparm=$parmhash{$symbparm};
10435: untie(%parmhash);
10436: }
1.927 albertel 10437: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10438: }
1.594 albertel 10439: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10440:
1.218 albertel 10441: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10442: my $filename;
10443: if (!$symbparm) { $symbparm=&symbread(); }
10444: if ($symbparm) {
1.409 www 10445: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10446: } else {
1.620 albertel 10447: $filename=$env{'request.filename'};
1.282 albertel 10448: }
10449: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10450: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10451: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10452: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10453:
1.927 albertel 10454: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10455: if ($symbparm && defined($courseid) &&
1.620 albertel 10456: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10457: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10458: $env{'course.'.$courseid.'.domain'},
10459: 'course',
1.927 albertel 10460: ([$courselevelm,'map' ],
10461: [$courselevel, 'course']));
10462: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10463: }
1.145 www 10464: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10465: unless ($space eq '0') {
1.336 albertel 10466: my @parts=split(/_/,$space);
10467: my $id=pop(@parts);
10468: my $part=join('_',@parts);
10469: if ($part eq '') { $part='0'; }
1.927 albertel 10470: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10471: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10472: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10473: }
1.395 albertel 10474: if ($recurse) { return undef; }
10475: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10476: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10477: # ---------------------------------------------------- Any other user namespace
10478: } elsif ($realm eq 'environment') {
10479: # ----------------------------------------------------------------- environment
1.620 albertel 10480: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10481: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10482: } else {
1.770 albertel 10483: if ($uname eq 'anonymous' && $udom eq '') {
10484: return '';
10485: }
1.219 albertel 10486: my %returnhash=&userenvironment($udom,$uname,
10487: $spacequalifierrest);
10488: return $returnhash{$spacequalifierrest};
10489: }
1.28 www 10490: } elsif ($realm eq 'system') {
1.48 www 10491: # ----------------------------------------------------------------- system.time
10492: if ($space eq 'time') {
10493: return time;
10494: }
1.696 albertel 10495: } elsif ($realm eq 'server') {
10496: # ----------------------------------------------------------------- system.time
10497: if ($space eq 'name') {
10498: return $ENV{'SERVER_NAME'};
10499: }
1.28 www 10500: }
1.48 www 10501: return '';
1.61 www 10502: }
10503:
1.927 albertel 10504: sub get_reply {
10505: my ($reply_value) = @_;
1.940 raeburn 10506: if (ref($reply_value) eq 'ARRAY') {
10507: if (wantarray) {
10508: return @$reply_value;
10509: }
10510: return $reply_value->[0];
10511: } else {
10512: return $reply_value;
1.927 albertel 10513: }
10514: }
10515:
1.691 raeburn 10516: sub check_group_parms {
10517: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10518: my @groupitems = ();
10519: my $resultitem;
1.927 albertel 10520: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10521: foreach my $group (@{$groups}) {
10522: foreach my $level (@levels) {
1.927 albertel 10523: my $item = $courseid.'.['.$group.'].'.$level->[0];
10524: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10525: }
10526: }
10527: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10528: $env{'course.'.$courseid.'.domain'},
10529: 'course',@groupitems);
10530: return $coursereply;
10531: }
10532:
10533: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10534: my ($courseid,@groups) = @_;
10535: @groups = sort(@groups);
1.691 raeburn 10536: return @groups;
10537: }
10538:
1.395 albertel 10539: sub packages_tab_default {
10540: my ($uri,$varname)=@_;
10541: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10542:
10543: my (@extension,@specifics,$do_default);
10544: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10545: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10546: if ($pack_type eq 'default') {
10547: $do_default=1;
10548: } elsif ($pack_type eq 'extension') {
10549: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10550: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10551: # only look at packages defaults for packages that this id is
1.738 albertel 10552: push(@specifics,[$package,$pack_type,$pack_part]);
10553: }
10554: }
10555: # first look for a package that matches the requested part id
10556: foreach my $package (@specifics) {
10557: my (undef,$pack_type,$pack_part)=@{$package};
10558: next if ($pack_part ne $part);
10559: if (defined($packagetab{"$pack_type&$name&default"})) {
10560: return $packagetab{"$pack_type&$name&default"};
10561: }
10562: }
10563: # look for any possible matching non extension_ package
10564: foreach my $package (@specifics) {
10565: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10566: if (defined($packagetab{"$pack_type&$name&default"})) {
10567: return $packagetab{"$pack_type&$name&default"};
10568: }
1.585 albertel 10569: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10570: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10571: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10572: }
10573: }
1.738 albertel 10574: # look for any posible extension_ match
10575: foreach my $package (@extension) {
10576: my ($package,$pack_type)=@{$package};
10577: if (defined($packagetab{"$pack_type&$name&default"})) {
10578: return $packagetab{"$pack_type&$name&default"};
10579: }
10580: if (defined($packagetab{$package."&$name&default"})) {
10581: return $packagetab{$package."&$name&default"};
10582: }
10583: }
10584: # look for a global default setting
10585: if ($do_default && defined($packagetab{"default&$name&default"})) {
10586: return $packagetab{"default&$name&default"};
10587: }
1.395 albertel 10588: return undef;
10589: }
10590:
1.334 albertel 10591: sub add_prefix_and_part {
10592: my ($prefix,$part)=@_;
10593: my $keyroot;
10594: if (defined($prefix) && $prefix !~ /^__/) {
10595: # prefix that has a part already
10596: $keyroot=$prefix;
10597: } elsif (defined($prefix)) {
10598: # prefix that is missing a part
10599: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10600: } else {
10601: # no prefix at all
10602: if (defined($part)) { $keyroot='_'.$part; }
10603: }
10604: return $keyroot;
10605: }
10606:
1.71 www 10607: # ---------------------------------------------------------------- Get metadata
10608:
1.599 albertel 10609: my %metaentry;
1.1070 www 10610: my %importedpartids;
1.71 www 10611: sub metadata {
1.176 www 10612: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10613: $uri=&declutter($uri);
1.288 albertel 10614: # if it is a non metadata possible uri return quickly
1.529 albertel 10615: if (($uri eq '') ||
10616: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10617: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10618: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10619: return undef;
10620: }
1.1261 raeburn 10621: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10622: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10623: return undef;
1.288 albertel 10624: }
1.73 www 10625: my $filename=$uri;
10626: $uri=~s/\.meta$//;
1.172 www 10627: #
10628: # Is the metadata already cached?
1.177 www 10629: # Look at timestamp of caching
1.172 www 10630: # Everything is cached by the main uri, libraries are never directly cached
10631: #
1.428 albertel 10632: if (!defined($liburi)) {
1.599 albertel 10633: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10634: if (defined($cached)) { return $result->{':'.$what}; }
10635: }
10636: {
1.1069 www 10637: # Imported parts would go here
1.1070 www 10638: my %importedids=();
10639: my @origfileimportpartids=();
1.1069 www 10640: my $importedparts=0;
1.172 www 10641: #
10642: # Is this a recursive call for a library?
10643: #
1.599 albertel 10644: # if (! exists($metacache{$uri})) {
10645: # $metacache{$uri}={};
10646: # }
1.924 albertel 10647: my $cachetime = 60*60;
1.171 www 10648: if ($liburi) {
10649: $liburi=&declutter($liburi);
10650: $filename=$liburi;
1.401 bowersj2 10651: } else {
1.599 albertel 10652: &devalidate_cache_new('meta',$uri);
10653: undef(%metaentry);
1.401 bowersj2 10654: }
1.140 www 10655: my %metathesekeys=();
1.73 www 10656: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10657: my $metastring;
1.1140 www 10658: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10659: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10660: $metastring =
1.929 albertel 10661: &Apache::lonnet::ssi_body($which,
1.924 albertel 10662: ('grade_target' => 'meta'));
10663: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10664: } elsif (($uri !~ m -^(editupload)/-) &&
10665: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10666: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10667: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10668: $metastring=&getfile($file);
1.489 albertel 10669: }
1.208 albertel 10670: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10671: my $token;
1.140 www 10672: undef %metathesekeys;
1.71 www 10673: while ($token=$parser->get_token) {
1.339 albertel 10674: if ($token->[0] eq 'S') {
10675: if (defined($token->[2]->{'package'})) {
1.172 www 10676: #
10677: # This is a package - get package info
10678: #
1.339 albertel 10679: my $package=$token->[2]->{'package'};
10680: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10681: if (defined($token->[2]->{'id'})) {
10682: $keyroot.='_'.$token->[2]->{'id'};
10683: }
1.599 albertel 10684: if ($metaentry{':packages'}) {
10685: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10686: } else {
1.599 albertel 10687: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10688: }
1.736 albertel 10689: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10690: my $part=$keyroot;
10691: $part=~s/^\_//;
1.736 albertel 10692: if ($pack_entry=~/^\Q$package\E\&/ ||
10693: $pack_entry=~/^\Q$package\E_0\&/) {
10694: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10695: # ignore package.tab specified default values
10696: # here &package_tab_default() will fetch those
10697: if ($subp eq 'default') { next; }
1.736 albertel 10698: my $value=$packagetab{$pack_entry};
1.432 albertel 10699: my $unikey;
10700: if ($pack =~ /_0$/) {
10701: $unikey='parameter_0_'.$name;
10702: $part=0;
10703: } else {
10704: $unikey='parameter'.$keyroot.'_'.$name;
10705: }
1.339 albertel 10706: if ($subp eq 'display') {
10707: $value.=' [Part: '.$part.']';
10708: }
1.599 albertel 10709: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10710: $metathesekeys{$unikey}=1;
1.599 albertel 10711: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10712: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10713: }
1.599 albertel 10714: if (defined($metaentry{':'.$unikey.'.default'})) {
10715: $metaentry{':'.$unikey}=
10716: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10717: }
1.339 albertel 10718: }
10719: }
10720: } else {
1.172 www 10721: #
10722: # This is not a package - some other kind of start tag
1.339 albertel 10723: #
10724: my $entry=$token->[1];
1.1068 www 10725: my $unikey='';
1.175 www 10726:
1.339 albertel 10727: if ($entry eq 'import') {
1.175 www 10728: #
10729: # Importing a library here
1.339 albertel 10730: #
1.1067 www 10731: my $location=$parser->get_text('/import');
10732: my $dir=$filename;
10733: $dir=~s|[^/]*$||;
10734: $location=&filelocation($dir,$location);
1.1069 www 10735:
1.1068 www 10736: my $importmode=$token->[2]->{'importmode'};
10737: if ($importmode eq 'problem') {
1.1069 www 10738: # Import as problem/response
1.1068 www 10739: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10740: } elsif ($importmode eq 'part') {
10741: # Import as part(s)
1.1069 www 10742: $importedparts=1;
10743: # We need to get the original file and the imported file to get the part order correct
10744: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10745: # Load and inspect original file
1.1070 www 10746: if ($#origfileimportpartids<0) {
10747: undef(%importedpartids);
10748: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10749: my $origfile=&getfile($origfilelocation);
10750: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10751: }
10752:
1.1069 www 10753: # Load and inspect imported file
10754: my $impfile=&getfile($location);
10755: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10756: if ($#impfilepartids>=0) {
10757: # This problem had parts
1.1070 www 10758: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10759: } else {
10760: # Importing by turning a single problem into a problem part
10761: # It gets the import-tags ID as part-ID
10762: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10763: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10764: }
1.1068 www 10765: } else {
10766: # Normal import
10767: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10768: if (defined($token->[2]->{'id'})) {
10769: $unikey.='_'.$token->[2]->{'id'};
10770: }
1.1067 www 10771: }
10772:
1.339 albertel 10773: if ($depthcount<20) {
1.736 albertel 10774: my $metadata =
10775: &metadata($uri,'keys', $location,$unikey,
10776: $depthcount+1);
10777: foreach my $meta (split(',',$metadata)) {
10778: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10779: $metathesekeys{$meta}=1;
1.339 albertel 10780: }
1.1068 www 10781:
10782: }
1.1067 www 10783: } else {
10784: #
10785: # Not importing, some other kind of non-package, non-library start tag
10786: #
10787: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10788: if (defined($token->[2]->{'id'})) {
10789: $unikey.='_'.$token->[2]->{'id'};
10790: }
1.339 albertel 10791: if (defined($token->[2]->{'name'})) {
10792: $unikey.='_'.$token->[2]->{'name'};
10793: }
10794: $metathesekeys{$unikey}=1;
1.736 albertel 10795: foreach my $param (@{$token->[3]}) {
10796: $metaentry{':'.$unikey.'.'.$param} =
10797: $token->[2]->{$param};
1.339 albertel 10798: }
10799: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10800: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10801: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10802: # only ws inside the tag, and not in default, so use default
10803: # as value
1.599 albertel 10804: $metaentry{':'.$unikey}=$default;
1.908 albertel 10805: } elsif ( $internaltext =~ /\S/ ) {
10806: # something interesting inside the tag
10807: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10808: } else {
1.908 albertel 10809: # no interesting values, don't set a default
1.339 albertel 10810: }
1.172 www 10811: # end of not-a-package not-a-library import
1.339 albertel 10812: }
1.172 www 10813: # end of not-a-package start tag
1.339 albertel 10814: }
1.172 www 10815: # the next is the end of "start tag"
1.339 albertel 10816: }
10817: }
1.483 albertel 10818: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10819: $extension = lc($extension);
10820: if ($extension eq 'htm') { $extension='html'; }
10821:
1.737 albertel 10822: foreach my $key (keys(%packagetab)) {
1.483 albertel 10823: #no specific packages #how's our extension
10824: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10825: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10826: \%metathesekeys);
10827: }
1.883 albertel 10828:
10829: if (!exists($metaentry{':packages'})
10830: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10831: foreach my $key (keys(%packagetab)) {
1.483 albertel 10832: #no specific packages well let's get default then
10833: if ($key!~/^default&/) { next; }
1.488 albertel 10834: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10835: \%metathesekeys);
10836: }
10837: }
1.338 www 10838: # are there custom rights to evaluate
1.599 albertel 10839: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10840:
1.338 www 10841: #
10842: # Importing a rights file here
1.339 albertel 10843: #
10844: unless ($depthcount) {
1.599 albertel 10845: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10846: my $dir=$filename;
10847: $dir=~s|[^/]*$||;
10848: $location=&filelocation($dir,$location);
1.736 albertel 10849: my $rights_metadata =
10850: &metadata($uri,'keys',$location,'_rights',
10851: $depthcount+1);
10852: foreach my $rights (split(',',$rights_metadata)) {
10853: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10854: $metathesekeys{$rights}=1;
1.339 albertel 10855: }
10856: }
10857: }
1.737 albertel 10858: # uniqifiy package listing
10859: my %seen;
10860: my @uniq_packages =
10861: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10862: $metaentry{':packages'} = join(',',@uniq_packages);
10863:
1.1070 www 10864: if ($importedparts) {
10865: # We had imported parts and need to rebuild partorder
10866: $metaentry{':partorder'}='';
10867: $metathesekeys{'partorder'}=1;
10868: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10869: if ($origfileimportpartids[$index] eq 'part') {
10870: # original part, part of the problem
10871: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10872: } else {
10873: # we have imported parts at this position
10874: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10875: }
10876: }
10877: $metaentry{':partorder'}=~s/^\,//;
10878: }
10879:
1.737 albertel 10880: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10881: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 10882: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10883: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10884: # this is the end of "was not already recently cached
1.71 www 10885: }
1.599 albertel 10886: return $metaentry{':'.$what};
1.261 albertel 10887: }
10888:
1.488 albertel 10889: sub metadata_create_package_def {
1.483 albertel 10890: my ($uri,$key,$package,$metathesekeys)=@_;
10891: my ($pack,$name,$subp)=split(/\&/,$key);
10892: if ($subp eq 'default') { next; }
10893:
1.599 albertel 10894: if (defined($metaentry{':packages'})) {
10895: $metaentry{':packages'}.=','.$package;
1.483 albertel 10896: } else {
1.599 albertel 10897: $metaentry{':packages'}=$package;
1.483 albertel 10898: }
10899: my $value=$packagetab{$key};
10900: my $unikey;
10901: $unikey='parameter_0_'.$name;
1.599 albertel 10902: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10903: $$metathesekeys{$unikey}=1;
1.599 albertel 10904: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10905: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10906: }
1.599 albertel 10907: if (defined($metaentry{':'.$unikey.'.default'})) {
10908: $metaentry{':'.$unikey}=
10909: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10910: }
10911: }
10912:
1.261 albertel 10913: sub metadata_generate_part0 {
10914: my ($metadata,$metacache,$uri) = @_;
10915: my %allnames;
1.737 albertel 10916: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10917: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10918: my $part=$$metacache{':'.$metakey.'.part'};
10919: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10920: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10921: $allnames{$name}=$part;
10922: }
10923: }
10924: }
10925: foreach my $name (keys(%allnames)) {
10926: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10927: my $key=":parameter_0_$name";
1.261 albertel 10928: $$metacache{"$key.part"}='0';
10929: $$metacache{"$key.name"}=$name;
1.428 albertel 10930: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10931: $allnames{$name}.'_'.$name.
10932: '.type'};
1.428 albertel 10933: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10934: '.display'};
1.644 www 10935: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10936: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10937: $$metacache{"$key.display"}=$olddis;
10938: }
1.71 www 10939: }
10940:
1.764 albertel 10941: # ------------------------------------------------------ Devalidate title cache
10942:
10943: sub devalidate_title_cache {
10944: my ($url)=@_;
10945: if (!$env{'request.course.id'}) { return; }
10946: my $symb=&symbread($url);
10947: if (!$symb) { return; }
10948: my $key=$env{'request.course.id'}."\0".$symb;
10949: &devalidate_cache_new('title',$key);
10950: }
10951:
1.1014 droeschl 10952: # ------------------------------------------------- Get the title of a course
10953:
10954: sub current_course_title {
10955: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10956: }
1.301 www 10957: # ------------------------------------------------- Get the title of a resource
10958:
10959: sub gettitle {
10960: my $urlsymb=shift;
10961: my $symb=&symbread($urlsymb);
1.534 albertel 10962: if ($symb) {
1.620 albertel 10963: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10964: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10965: if (defined($cached)) {
10966: return $result;
10967: }
1.534 albertel 10968: my ($map,$resid,$url)=&decode_symb($symb);
10969: my $title='';
1.907 albertel 10970: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10971: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10972: } else {
10973: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10974: &GDBM_READER(),0640)) {
10975: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10976: $title=$bighash{'title_'.$mapid.'.'.$resid};
10977: untie(%bighash);
10978: }
1.534 albertel 10979: }
10980: $title=~s/\&colon\;/\:/gs;
10981: if ($title) {
1.1159 www 10982: # Remember both $symb and $title for dynamic metadata
10983: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10984: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10985: # Cache this title and then return it
1.599 albertel 10986: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10987: }
10988: $urlsymb=$url;
10989: }
10990: my $title=&metadata($urlsymb,'title');
10991: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10992: return $title;
1.301 www 10993: }
1.613 albertel 10994:
1.614 albertel 10995: sub get_slot {
10996: my ($which,$cnum,$cdom)=@_;
10997: if (!$cnum || !$cdom) {
1.790 albertel 10998: (undef,my $courseid)=&whichuser();
1.620 albertel 10999: $cdom=$env{'course.'.$courseid.'.domain'};
11000: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11001: }
1.703 albertel 11002: my $key=join("\0",'slots',$cdom,$cnum,$which);
11003: my %slotinfo;
11004: if (exists($remembered{$key})) {
11005: $slotinfo{$which} = $remembered{$key};
11006: } else {
11007: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11008: &Apache::lonhomework::showhash(%slotinfo);
11009: my ($tmp)=keys(%slotinfo);
11010: if ($tmp=~/^error:/) { return (); }
11011: $remembered{$key} = $slotinfo{$which};
11012: }
1.616 albertel 11013: if (ref($slotinfo{$which}) eq 'HASH') {
11014: return %{$slotinfo{$which}};
11015: }
11016: return $slotinfo{$which};
1.614 albertel 11017: }
1.1150 raeburn 11018:
11019: sub get_reservable_slots {
11020: my ($cnum,$cdom,$uname,$udom) = @_;
11021: my $now = time;
11022: my $reservable_info;
11023: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11024: if (exists($remembered{$key})) {
11025: $reservable_info = $remembered{$key};
11026: } else {
11027: my %resv;
11028: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11029: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11030: $reservable_info = \%resv;
11031: $remembered{$key} = $reservable_info;
11032: }
11033: return $reservable_info;
11034: }
11035:
11036: sub get_course_slots {
11037: my ($cnum,$cdom) = @_;
11038: my $hashid=$cnum.':'.$cdom;
11039: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11040: if (defined($cached)) {
11041: if (ref($result) eq 'HASH') {
11042: return %{$result};
11043: }
11044: } else {
11045: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11046: my ($tmp) = keys(%slots);
11047: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11048: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11049: return %slots;
11050: }
11051: }
11052: return;
11053: }
11054:
11055: sub devalidate_slots_cache {
11056: my ($cnum,$cdom)=@_;
11057: my $hashid=$cnum.':'.$cdom;
11058: &devalidate_cache_new('allslots',$hashid);
11059: }
11060:
1.1181 raeburn 11061: sub get_coursechange {
11062: my ($cdom,$cnum) = @_;
11063: if ($cdom eq '' || $cnum eq '') {
11064: return unless ($env{'request.course.id'});
11065: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11066: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11067: }
11068: my $hashid=$cdom.'_'.$cnum;
11069: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11070: if ((defined($cached)) && ($change ne '')) {
11071: return $change;
11072: } else {
11073: my %crshash;
11074: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11075: if ($crshash{'internal.contentchange'} eq '') {
11076: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11077: if ($change eq '') {
11078: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11079: $change = $crshash{'internal.created'};
11080: }
11081: } else {
11082: $change = $crshash{'internal.contentchange'};
11083: }
11084: my $cachetime = 600;
11085: &do_cache_new('crschange',$hashid,$change,$cachetime);
11086: }
11087: return $change;
11088: }
11089:
11090: sub devalidate_coursechange_cache {
11091: my ($cnum,$cdom)=@_;
11092: my $hashid=$cnum.':'.$cdom;
11093: &devalidate_cache_new('crschange',$hashid);
11094: }
11095:
1.31 www 11096: # ------------------------------------------------- Update symbolic store links
11097:
11098: sub symblist {
11099: my ($mapname,%newhash)=@_;
1.438 www 11100: $mapname=&deversion(&declutter($mapname));
1.31 www 11101: my %hash;
1.620 albertel 11102: if (($env{'request.course.fn'}) && (%newhash)) {
11103: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11104: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11105: foreach my $url (keys(%newhash)) {
1.711 albertel 11106: next if ($url eq 'last_known'
11107: && $env{'form.no_update_last_known'});
11108: $hash{declutter($url)}=&encode_symb($mapname,
11109: $newhash{$url}->[1],
11110: $newhash{$url}->[0]);
1.191 harris41 11111: }
1.31 www 11112: if (untie(%hash)) {
11113: return 'ok';
11114: }
11115: }
11116: }
11117: return 'error';
1.212 www 11118: }
11119:
11120: # --------------------------------------------------------------- Verify a symb
11121:
11122: sub symbverify {
1.1190 raeburn 11123: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11124: my $thisfn=$thisurl;
1.439 www 11125: $thisfn=&declutter($thisfn);
1.215 www 11126: # direct jump to resource in page or to a sequence - will construct own symbs
11127: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11128: # check URL part
1.409 www 11129: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11130:
1.431 www 11131: unless ($url eq $thisfn) { return 0; }
1.213 www 11132:
1.216 www 11133: $symb=&symbclean($symb);
1.510 www 11134: $thisurl=&deversion($thisurl);
1.439 www 11135: $thisfn=&deversion($thisfn);
1.213 www 11136:
11137: my %bighash;
11138: my $okay=0;
1.431 www 11139:
1.620 albertel 11140: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11141: &GDBM_READER(),0640)) {
1.1204 raeburn 11142: my $noclutter;
1.1032 raeburn 11143: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11144: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11145: if ($map =~ m{^uploaded/.+\.page$}) {
11146: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11147: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11148: $noclutter = 1;
11149: }
11150: }
11151: my $ids;
11152: if ($noclutter) {
11153: $ids=$bighash{'ids_'.$thisurl};
11154: } else {
11155: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11156: }
1.1102 raeburn 11157: unless ($ids) {
11158: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11159: $ids=$bighash{$idkey};
1.216 www 11160: }
11161: if ($ids) {
11162: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11163: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11164: $symb =~ s/\?.+$//;
1.1202 raeburn 11165: }
1.800 albertel 11166: foreach my $id (split(/\,/,$ids)) {
11167: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11168: if (
11169: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11170: eq $symb) {
11171: if (ref($encstate)) {
11172: $$encstate = $bighash{'encrypted_'.$id};
11173: }
1.620 albertel 11174: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11175: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11176: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11177: $okay=1;
1.1202 raeburn 11178: last;
1.582 albertel 11179: }
11180: }
1.216 www 11181: }
11182: }
1.213 www 11183: untie(%bighash);
11184: }
11185: return $okay;
1.31 www 11186: }
11187:
1.210 www 11188: # --------------------------------------------------------------- Clean-up symb
11189:
11190: sub symbclean {
11191: my $symb=shift;
1.568 albertel 11192: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11193: # remove version from map
11194: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11195:
1.210 www 11196: # remove version from URL
11197: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11198:
1.507 www 11199: # remove wrapper
11200:
1.510 www 11201: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11202: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11203: return $symb;
1.409 www 11204: }
11205:
11206: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11207:
11208: sub encode_symb {
11209: my ($map,$resid,$url)=@_;
11210: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11211: }
1.409 www 11212:
11213: sub decode_symb {
1.568 albertel 11214: my $symb=shift;
11215: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11216: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11217: return (&fixversion($map),$resid,&fixversion($url));
11218: }
11219:
11220: sub fixversion {
11221: my $fn=shift;
1.609 banghart 11222: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11223: my %bighash;
11224: my $uri=&clutter($fn);
1.620 albertel 11225: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11226: # is this cached?
1.599 albertel 11227: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11228: if (defined($cached)) { return $result; }
11229: # unfortunately not cached, or expired
1.620 albertel 11230: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11231: &GDBM_READER(),0640)) {
11232: if ($bighash{'version_'.$uri}) {
11233: my $version=$bighash{'version_'.$uri};
1.444 www 11234: unless (($version eq 'mostrecent') ||
11235: ($version==&getversion($uri))) {
1.440 www 11236: $uri=~s/\.(\w+)$/\.$version\.$1/;
11237: }
11238: }
11239: untie %bighash;
1.413 www 11240: }
1.599 albertel 11241: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11242: }
11243:
11244: sub deversion {
11245: my $url=shift;
11246: $url=~s/\.\d+\.(\w+)$/\.$1/;
11247: return $url;
1.210 www 11248: }
11249:
1.31 www 11250: # ------------------------------------------------------ Return symb list entry
11251:
11252: sub symbread {
1.1282 raeburn 11253: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 11254: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 11255: if (defined($env{$cache_str})) {
11256: if ($ignorecachednull) {
11257: return $env{$cache_str} unless ($env{$cache_str} eq '');
11258: } else {
11259: return $env{$cache_str};
11260: }
11261: }
1.242 www 11262: # no filename provided? try from environment
1.1265 raeburn 11263: unless ($thisfn) {
1.620 albertel 11264: if ($env{'request.symb'}) {
11265: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11266: }
1.620 albertel 11267: $thisfn=$env{'request.filename'};
1.44 www 11268: }
1.569 albertel 11269: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11270: # is that filename actually a symb? Verify, clean, and return
11271: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11272: if (&symbverify($thisfn,$1)) {
1.620 albertel 11273: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11274: }
1.242 www 11275: }
1.44 www 11276: $thisfn=declutter($thisfn);
1.31 www 11277: my %hash;
1.37 www 11278: my %bighash;
11279: my $syval='';
1.620 albertel 11280: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11281: my $targetfn = $thisfn;
1.609 banghart 11282: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11283: $targetfn = 'adm/wrapper/'.$thisfn;
11284: }
1.687 albertel 11285: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11286: $targetfn=$1;
11287: }
1.620 albertel 11288: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11289: &GDBM_READER(),0640)) {
1.481 raeburn 11290: $syval=$hash{$targetfn};
1.37 www 11291: untie(%hash);
11292: }
11293: # ---------------------------------------------------------- There was an entry
11294: if ($syval) {
1.601 albertel 11295: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11296: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11297: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11298: #return $env{$cache_str}='';
1.601 albertel 11299: #}
11300: #$syval.=$1;
11301: #}
1.37 www 11302: } else {
11303: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11304: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11305: &GDBM_READER(),0640)) {
1.37 www 11306: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11307: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11308: unless ($ids) {
11309: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11310: }
11311: unless ($ids) {
11312: # alias?
11313: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11314: }
1.37 www 11315: if ($ids) {
11316: # ------------------------------------------------------------------- Has ID(s)
11317: my @possibilities=split(/\,/,$ids);
1.39 www 11318: if ($#possibilities==0) {
11319: # ----------------------------------------------- There is only one possibility
1.37 www 11320: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11321: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11322: $resid,$thisfn);
1.1282 raeburn 11323: if (ref($possibles) eq 'HASH') {
11324: $possibles->{$syval} = 1;
11325: }
11326: if ($checkforblock) {
11327: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11328: if (@blockers) {
11329: $syval = '';
11330: return;
11331: }
11332: }
11333: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11334: # ------------------------------------------ There is more than one possibility
11335: my $realpossible=0;
1.800 albertel 11336: foreach my $id (@possibilities) {
11337: my $file=$bighash{'src_'.$id};
1.1282 raeburn 11338: my $canaccess;
11339: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11340: $canaccess = 1;
11341: } else {
11342: $canaccess = &allowed('bre',$file);
11343: }
11344: if ($canaccess) {
11345: my ($mapid,$resid)=split(/\./,$id);
11346: if ($bighash{'map_type_'.$mapid} ne 'page') {
11347: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11348: $resid,$thisfn);
11349: if (ref($possibles) eq 'HASH') {
11350: $possibles->{$syval} = 1;
11351: }
11352: if ($checkforblock) {
11353: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11354: unless (@blockers > 0) {
11355: $syval = $poss_syval;
11356: $realpossible++;
11357: }
11358: } else {
11359: $syval = $poss_syval;
11360: $realpossible++;
11361: }
11362: }
1.39 www 11363: }
1.191 harris41 11364: }
1.39 www 11365: if ($realpossible!=1) { $syval=''; }
1.249 www 11366: } else {
11367: $syval='';
1.37 www 11368: }
11369: }
1.1282 raeburn 11370: untie(%bighash);
1.481 raeburn 11371: }
1.31 www 11372: }
1.62 www 11373: if ($syval) {
1.620 albertel 11374: return $env{$cache_str}=$syval;
1.62 www 11375: }
1.31 www 11376: }
1.949 raeburn 11377: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11378: return $env{$cache_str}='';
1.31 www 11379: }
11380:
11381: # ---------------------------------------------------------- Return random seed
11382:
1.32 www 11383: sub numval {
11384: my $txt=shift;
11385: $txt=~tr/A-J/0-9/;
11386: $txt=~tr/a-j/0-9/;
11387: $txt=~tr/K-T/0-9/;
11388: $txt=~tr/k-t/0-9/;
11389: $txt=~tr/U-Z/0-5/;
11390: $txt=~tr/u-z/0-5/;
11391: $txt=~s/\D//g;
1.564 albertel 11392: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11393: return int($txt);
1.368 albertel 11394: }
11395:
1.484 albertel 11396: sub numval2 {
11397: my $txt=shift;
11398: $txt=~tr/A-J/0-9/;
11399: $txt=~tr/a-j/0-9/;
11400: $txt=~tr/K-T/0-9/;
11401: $txt=~tr/k-t/0-9/;
11402: $txt=~tr/U-Z/0-5/;
11403: $txt=~tr/u-z/0-5/;
11404: $txt=~s/\D//g;
11405: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11406: my $total;
11407: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11408: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11409: return int($total);
11410: }
11411:
1.575 albertel 11412: sub numval3 {
11413: use integer;
11414: my $txt=shift;
11415: $txt=~tr/A-J/0-9/;
11416: $txt=~tr/a-j/0-9/;
11417: $txt=~tr/K-T/0-9/;
11418: $txt=~tr/k-t/0-9/;
11419: $txt=~tr/U-Z/0-5/;
11420: $txt=~tr/u-z/0-5/;
11421: $txt=~s/\D//g;
11422: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11423: my $total;
11424: foreach my $val (@txts) { $total+=$val; }
11425: if ($_64bit) { $total=(($total<<32)>>32); }
11426: return $total;
11427: }
11428:
1.675 albertel 11429: sub digest {
11430: my ($data)=@_;
11431: my $digest=&Digest::MD5::md5($data);
11432: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11433: my ($e,$f);
11434: {
11435: use integer;
11436: $e=($a+$b);
11437: $f=($c+$d);
11438: if ($_64bit) {
11439: $e=(($e<<32)>>32);
11440: $f=(($f<<32)>>32);
11441: }
11442: }
11443: if (wantarray) {
11444: return ($e,$f);
11445: } else {
11446: my $g;
11447: {
11448: use integer;
11449: $g=($e+$f);
11450: if ($_64bit) {
11451: $g=(($g<<32)>>32);
11452: }
11453: }
11454: return $g;
11455: }
11456: }
11457:
1.368 albertel 11458: sub latest_rnd_algorithm_id {
1.675 albertel 11459: return '64bit5';
1.366 albertel 11460: }
1.32 www 11461:
1.503 albertel 11462: sub get_rand_alg {
11463: my ($courseid)=@_;
1.790 albertel 11464: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11465: if ($courseid) {
1.620 albertel 11466: return $env{"course.$courseid.rndseed"};
1.503 albertel 11467: }
11468: return &latest_rnd_algorithm_id();
11469: }
11470:
1.562 albertel 11471: sub validCODE {
11472: my ($CODE)=@_;
11473: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11474: return 0;
11475: }
11476:
1.491 albertel 11477: sub getCODE {
1.620 albertel 11478: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11479: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11480: defined($Apache::lonhomework::parsing_a_task) ) &&
11481: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11482: return $Apache::lonhomework::history{'resource.CODE'};
11483: }
11484: return undef;
11485: }
1.1133 foxr 11486: #
11487: # Determines the random seed for a specific context:
11488: #
11489: # parameters:
11490: # symb - in course context the symb for the seed.
11491: # course_id - The course id of the form domain_coursenum.
11492: # domain - Domain for the user.
11493: # course - Course for the user.
11494: # cenv - environment of the course.
11495: #
11496: # NOTE:
11497: # All parameters are picked out of the environment if missing
11498: # or not defined.
11499: # If a symb cannot be determined the current time is used instead.
11500: #
11501: # For a given well defined symb, courside, domain, username,
11502: # and course environment, the seed is reproducible.
11503: #
1.31 www 11504: sub rndseed {
1.1133 foxr 11505: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11506: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11507: if (!defined($symb)) {
1.366 albertel 11508: unless ($symb=$wsymb) { return time; }
11509: }
1.1146 foxr 11510: if (!defined $courseid) {
11511: $courseid=$wcourseid;
11512: }
11513: if (!defined $domain) { $domain=$wdomain; }
11514: if (!defined $username) { $username=$wusername }
1.1133 foxr 11515:
11516: my $which;
11517: if (defined($cenv->{'rndseed'})) {
11518: $which = $cenv->{'rndseed'};
11519: } else {
11520: $which =&get_rand_alg($courseid);
11521: }
1.491 albertel 11522: if (defined(&getCODE())) {
1.1133 foxr 11523:
1.675 albertel 11524: if ($which eq '64bit5') {
11525: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11526: } elsif ($which eq '64bit4') {
1.575 albertel 11527: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11528: } else {
11529: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11530: }
1.675 albertel 11531: } elsif ($which eq '64bit5') {
11532: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11533: } elsif ($which eq '64bit4') {
11534: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11535: } elsif ($which eq '64bit3') {
11536: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11537: } elsif ($which eq '64bit2') {
11538: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11539: } elsif ($which eq '64bit') {
11540: return &rndseed_64bit($symb,$courseid,$domain,$username);
11541: }
11542: return &rndseed_32bit($symb,$courseid,$domain,$username);
11543: }
11544:
11545: sub rndseed_32bit {
11546: my ($symb,$courseid,$domain,$username)=@_;
11547: {
11548: use integer;
11549: my $symbchck=unpack("%32C*",$symb) << 27;
11550: my $symbseed=numval($symb) << 22;
11551: my $namechck=unpack("%32C*",$username) << 17;
11552: my $nameseed=numval($username) << 12;
11553: my $domainseed=unpack("%32C*",$domain) << 7;
11554: my $courseseed=unpack("%32C*",$courseid);
11555: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11556: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11557: #&logthis("rndseed :$num:$symb");
1.564 albertel 11558: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11559: return $num;
11560: }
11561: }
11562:
11563: sub rndseed_64bit {
11564: my ($symb,$courseid,$domain,$username)=@_;
11565: {
11566: use integer;
11567: my $symbchck=unpack("%32S*",$symb) << 21;
11568: my $symbseed=numval($symb) << 10;
11569: my $namechck=unpack("%32S*",$username);
11570:
11571: my $nameseed=numval($username) << 21;
11572: my $domainseed=unpack("%32S*",$domain) << 10;
11573: my $courseseed=unpack("%32S*",$courseid);
11574:
11575: my $num1=$symbchck+$symbseed+$namechck;
11576: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11577: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11578: #&logthis("rndseed :$num:$symb");
1.564 albertel 11579: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11580: return "$num1,$num2";
1.155 albertel 11581: }
1.366 albertel 11582: }
11583:
1.443 albertel 11584: sub rndseed_64bit2 {
11585: my ($symb,$courseid,$domain,$username)=@_;
11586: {
11587: use integer;
11588: # strings need to be an even # of cahracters long, it it is odd the
11589: # last characters gets thrown away
11590: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11591: my $symbseed=numval($symb) << 10;
11592: my $namechck=unpack("%32S*",$username.' ');
11593:
11594: my $nameseed=numval($username) << 21;
1.501 albertel 11595: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11596: my $courseseed=unpack("%32S*",$courseid.' ');
11597:
11598: my $num1=$symbchck+$symbseed+$namechck;
11599: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11600: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11601: #&logthis("rndseed :$num:$symb");
1.803 albertel 11602: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11603: return "$num1,$num2";
11604: }
11605: }
11606:
11607: sub rndseed_64bit3 {
11608: my ($symb,$courseid,$domain,$username)=@_;
11609: {
11610: use integer;
11611: # strings need to be an even # of cahracters long, it it is odd the
11612: # last characters gets thrown away
11613: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11614: my $symbseed=numval2($symb) << 10;
11615: my $namechck=unpack("%32S*",$username.' ');
11616:
11617: my $nameseed=numval2($username) << 21;
1.443 albertel 11618: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11619: my $courseseed=unpack("%32S*",$courseid.' ');
11620:
11621: my $num1=$symbchck+$symbseed+$namechck;
11622: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11623: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11624: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11625: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11626:
1.503 albertel 11627: return "$num1:$num2";
1.443 albertel 11628: }
11629: }
11630:
1.575 albertel 11631: sub rndseed_64bit4 {
11632: my ($symb,$courseid,$domain,$username)=@_;
11633: {
11634: use integer;
11635: # strings need to be an even # of cahracters long, it it is odd the
11636: # last characters gets thrown away
11637: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11638: my $symbseed=numval3($symb) << 10;
11639: my $namechck=unpack("%32S*",$username.' ');
11640:
11641: my $nameseed=numval3($username) << 21;
11642: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11643: my $courseseed=unpack("%32S*",$courseid.' ');
11644:
11645: my $num1=$symbchck+$symbseed+$namechck;
11646: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11647: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11648: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11649: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11650:
1.575 albertel 11651: return "$num1:$num2";
11652: }
11653: }
11654:
1.675 albertel 11655: sub rndseed_64bit5 {
11656: my ($symb,$courseid,$domain,$username)=@_;
11657: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11658: return "$num1:$num2";
11659: }
11660:
1.366 albertel 11661: sub rndseed_CODE_64bit {
11662: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11663: {
1.366 albertel 11664: use integer;
1.443 albertel 11665: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11666: my $symbseed=numval2($symb);
1.491 albertel 11667: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11668: my $CODEseed=numval(&getCODE());
1.443 albertel 11669: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11670: my $num1=$symbseed+$CODEchck;
11671: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11672: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11673: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11674: if ($_64bit) { $num1=(($num1<<32)>>32); }
11675: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11676: return "$num1:$num2";
1.366 albertel 11677: }
11678: }
11679:
1.575 albertel 11680: sub rndseed_CODE_64bit4 {
11681: my ($symb,$courseid,$domain,$username)=@_;
11682: {
11683: use integer;
11684: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11685: my $symbseed=numval3($symb);
11686: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11687: my $CODEseed=numval3(&getCODE());
11688: my $courseseed=unpack("%32S*",$courseid.' ');
11689: my $num1=$symbseed+$CODEchck;
11690: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11691: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11692: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11693: if ($_64bit) { $num1=(($num1<<32)>>32); }
11694: if ($_64bit) { $num2=(($num2<<32)>>32); }
11695: return "$num1:$num2";
11696: }
11697: }
11698:
1.675 albertel 11699: sub rndseed_CODE_64bit5 {
11700: my ($symb,$courseid,$domain,$username)=@_;
11701: my $code = &getCODE();
11702: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11703: return "$num1:$num2";
11704: }
11705:
1.366 albertel 11706: sub setup_random_from_rndseed {
11707: my ($rndseed)=@_;
1.503 albertel 11708: if ($rndseed =~/([,:])/) {
1.1262 raeburn 11709: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11710: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11711: &Math::Random::random_set_seed_from_phrase($rndseed);
11712: } else {
11713: &Math::Random::random_set_seed($num1,$num2);
11714: }
1.366 albertel 11715: } else {
11716: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11717: }
1.36 albertel 11718: }
11719:
1.474 albertel 11720: sub latest_receipt_algorithm_id {
1.835 albertel 11721: return 'receipt3';
1.474 albertel 11722: }
11723:
1.480 www 11724: sub recunique {
11725: my $fucourseid=shift;
11726: my $unique;
1.835 albertel 11727: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11728: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11729: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11730: } else {
11731: $unique=$perlvar{'lonReceipt'};
11732: }
11733: return unpack("%32C*",$unique);
11734: }
11735:
11736: sub recprefix {
11737: my $fucourseid=shift;
11738: my $prefix;
1.835 albertel 11739: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11740: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11741: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11742: } else {
11743: $prefix=$perlvar{'lonHostID'};
11744: }
11745: return unpack("%32C*",$prefix);
11746: }
11747:
1.76 www 11748: sub ireceipt {
1.474 albertel 11749: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11750:
11751: my $return =&recprefix($fucourseid).'-';
11752:
11753: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11754: $env{'request.state'} eq 'construct') {
11755: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11756: return $return;
11757: }
11758:
1.76 www 11759: my $cuname=unpack("%32C*",$funame);
11760: my $cudom=unpack("%32C*",$fudom);
11761: my $cucourseid=unpack("%32C*",$fucourseid);
11762: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11763: my $cunique=&recunique($fucourseid);
1.474 albertel 11764: my $cpart=unpack("%32S*",$part);
1.835 albertel 11765: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11766:
1.790 albertel 11767: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11768:
11769: $return.= ($cunique%$cuname+
11770: $cunique%$cudom+
11771: $cusymb%$cuname+
11772: $cusymb%$cudom+
11773: $cucourseid%$cuname+
11774: $cucourseid%$cudom+
11775: $cpart%$cuname+
11776: $cpart%$cudom);
11777: } else {
11778: $return.= ($cunique%$cuname+
11779: $cunique%$cudom+
11780: $cusymb%$cuname+
11781: $cusymb%$cudom+
11782: $cucourseid%$cuname+
11783: $cucourseid%$cudom);
11784: }
11785: return $return;
1.76 www 11786: }
11787:
11788: sub receipt {
1.474 albertel 11789: my ($part)=@_;
1.790 albertel 11790: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11791: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11792: }
1.260 ng 11793:
1.790 albertel 11794: sub whichuser {
11795: my ($passedsymb)=@_;
11796: my ($symb,$courseid,$domain,$name,$publicuser);
11797: if (defined($env{'form.grade_symb'})) {
11798: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11799: my $allowed=&allowed('vgr',$tmp_courseid);
11800: if (!$allowed &&
11801: exists($env{'request.course.sec'}) &&
11802: $env{'request.course.sec'} !~ /^\s*$/) {
11803: $allowed=&allowed('vgr',$tmp_courseid.
11804: '/'.$env{'request.course.sec'});
11805: }
11806: if ($allowed) {
11807: ($symb)=&get_env_multiple('form.grade_symb');
11808: $courseid=$tmp_courseid;
11809: ($domain)=&get_env_multiple('form.grade_domain');
11810: ($name)=&get_env_multiple('form.grade_username');
11811: return ($symb,$courseid,$domain,$name,$publicuser);
11812: }
11813: }
11814: if (!$passedsymb) {
11815: $symb=&symbread();
11816: } else {
11817: $symb=$passedsymb;
11818: }
11819: $courseid=$env{'request.course.id'};
11820: $domain=$env{'user.domain'};
11821: $name=$env{'user.name'};
11822: if ($name eq 'public' && $domain eq 'public') {
11823: if (!defined($env{'form.username'})) {
11824: $env{'form.username'}.=time.rand(10000000);
11825: }
11826: $name.=$env{'form.username'};
11827: }
11828: return ($symb,$courseid,$domain,$name,$publicuser);
11829:
11830: }
11831:
1.36 albertel 11832: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11833: # returns either the contents of the file or
11834: # -1 if the file doesn't exist
1.481 raeburn 11835: #
11836: # if the target is a file that was uploaded via DOCS,
11837: # a check will be made to see if a current copy exists on the local server,
11838: # if it does this will be served, otherwise a copy will be retrieved from
11839: # the home server for the course and stored in /home/httpd/html/userfiles on
11840: # the local server.
1.472 albertel 11841:
1.36 albertel 11842: sub getfile {
1.538 albertel 11843: my ($file) = @_;
1.609 banghart 11844: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11845: &repcopy($file);
11846: return &readfile($file);
11847: }
11848:
11849: sub repcopy_userfile {
11850: my ($file)=@_;
1.1142 raeburn 11851: my $londocroot = $perlvar{'lonDocRoot'};
11852: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11853: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11854: my ($cdom,$cnum,$filename) =
1.811 albertel 11855: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11856: my $uri="/uploaded/$cdom/$cnum/$filename";
11857: if (-e "$file") {
1.828 www 11858: # we already have a local copy, check it out
1.538 albertel 11859: my @fileinfo = stat($file);
1.828 www 11860: my $rtncode;
11861: my $info;
1.538 albertel 11862: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11863: if ($lwpresp ne 'ok') {
1.828 www 11864: # there is no such file anymore, even though we had a local copy
1.482 albertel 11865: if ($rtncode eq '404') {
1.538 albertel 11866: unlink($file);
1.482 albertel 11867: }
11868: return -1;
11869: }
11870: if ($info < $fileinfo[9]) {
1.828 www 11871: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11872: return 'ok';
1.828 www 11873: } else {
11874: # the file is outdated, get rid of it
11875: unlink($file);
1.482 albertel 11876: }
1.828 www 11877: }
11878: # one way or the other, at this point, we don't have the file
11879: # construct the correct path for the file
11880: my @parts = ($cdom,$cnum);
11881: if ($filename =~ m|^(.+)/[^/]+$|) {
11882: push @parts, split(/\//,$1);
11883: }
11884: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11885: foreach my $part (@parts) {
11886: $path .= '/'.$part;
11887: if (!-e $path) {
11888: mkdir($path,0770);
1.482 albertel 11889: }
11890: }
1.828 www 11891: # now the path exists for sure
11892: # get a user agent
11893: my $ua=new LWP::UserAgent;
11894: my $transferfile=$file.'.in.transfer';
11895: # FIXME: this should flock
11896: if (-e $transferfile) { return 'ok'; }
11897: my $request;
11898: $uri=~s/^\///;
1.980 raeburn 11899: my $homeserver = &homeserver($cnum,$cdom);
11900: my $protocol = $protocol{$homeserver};
11901: $protocol = 'http' if ($protocol ne 'https');
11902: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11903: my $response=$ua->request($request,$transferfile);
11904: # did it work?
11905: if ($response->is_error()) {
11906: unlink($transferfile);
11907: &logthis("Userfile repcopy failed for $uri");
11908: return -1;
11909: }
11910: # worked, rename the transfer file
11911: rename($transferfile,$file);
1.607 raeburn 11912: return 'ok';
1.481 raeburn 11913: }
11914:
1.517 albertel 11915: sub tokenwrapper {
11916: my $uri=shift;
1.980 raeburn 11917: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11918: $uri=~s|^/||;
1.620 albertel 11919: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11920: my $token=$1;
1.552 albertel 11921: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11922: if ($udom && $uname && $file) {
11923: $file=~s|(\?\.*)*$||;
1.949 raeburn 11924: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11925: my $homeserver = &homeserver($uname,$udom);
11926: my $protocol = $protocol{$homeserver};
11927: $protocol = 'http' if ($protocol ne 'https');
11928: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11929: (($uri=~/\?/)?'&':'?').'token='.$token.
11930: '&tokenissued='.$perlvar{'lonHostID'};
11931: } else {
11932: return '/adm/notfound.html';
11933: }
11934: }
11935:
1.828 www 11936: # call with reqtype HEAD: get last modification time
11937: # call with reqtype GET: get the file contents
11938: # Do not call this with reqtype GET for large files! It loads everything into memory
11939: #
1.481 raeburn 11940: sub getuploaded {
11941: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11942: $uri=~s/^\///;
1.980 raeburn 11943: my $homeserver = &homeserver($cnum,$cdom);
11944: my $protocol = $protocol{$homeserver};
11945: $protocol = 'http' if ($protocol ne 'https');
11946: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11947: my $ua=new LWP::UserAgent;
11948: my $request=new HTTP::Request($reqtype,$uri);
11949: my $response=$ua->request($request);
11950: $$rtncode = $response->code;
1.482 albertel 11951: if (! $response->is_success()) {
11952: return 'failed';
11953: }
11954: if ($reqtype eq 'HEAD') {
1.486 www 11955: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11956: } elsif ($reqtype eq 'GET') {
11957: $$info = $response->content;
1.472 albertel 11958: }
1.482 albertel 11959: return 'ok';
1.36 albertel 11960: }
11961:
1.481 raeburn 11962: sub readfile {
11963: my $file = shift;
11964: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11965: my $fh;
11966: open($fh,"<$file");
11967: my $a='';
1.800 albertel 11968: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11969: return $a;
11970: }
11971:
1.36 albertel 11972: sub filelocation {
1.590 banghart 11973: my ($dir,$file) = @_;
11974: my $location;
11975: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11976:
11977: if ($file =~ m-^/adm/-) {
11978: $file=~s-^/adm/wrapper/-/-;
11979: $file=~s-^/adm/coursedocs/showdoc/-/-;
11980: }
1.882 albertel 11981:
1.1139 www 11982: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11983: $location = $file;
1.609 banghart 11984: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11985: my ($udom,$uname,$filename)=
1.811 albertel 11986: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11987: my $home=&homeserver($uname,$udom);
11988: my $is_me=0;
11989: my @ids=¤t_machine_ids();
11990: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11991: if ($is_me) {
1.1117 foxr 11992: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11993: } else {
11994: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11995: $udom.'/'.$uname.'/'.$filename;
11996: }
1.882 albertel 11997: } elsif ($file =~ m-^/adm/-) {
11998: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11999: } else {
12000: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12001: $file=~s:^/(res|priv)/:/:;
12002: my $space=$1;
1.590 banghart 12003: if ( !( $file =~ m:^/:) ) {
12004: $location = $dir. '/'.$file;
12005: } else {
1.1142 raeburn 12006: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12007: }
1.59 albertel 12008: }
1.590 banghart 12009: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12010: while ($location=~m{/\.\./}) {
12011: if ($location =~ m{/[^/]+/\.\./}) {
12012: $location=~ s{/[^/]+/\.\./}{/}g;
12013: } else {
12014: $location=~ s{/\.\./}{/}g;
12015: }
12016: } #remove dir/..
1.590 banghart 12017: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12018: return $location;
1.46 www 12019: }
1.36 albertel 12020:
1.46 www 12021: sub hreflocation {
12022: my ($dir,$file)=@_;
1.980 raeburn 12023: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12024: $file=filelocation($dir,$file);
1.700 albertel 12025: } elsif ($file=~m-^/adm/-) {
12026: $file=~s-^/adm/wrapper/-/-;
12027: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12028: }
12029: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12030: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12031: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12032: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12033: {/uploaded/$1/$2/}x;
1.46 www 12034: }
1.913 albertel 12035: if ($file=~ m{^/userfiles/}) {
12036: $file =~ s{^/userfiles/}{/uploaded/};
12037: }
1.462 albertel 12038: return $file;
1.465 albertel 12039: }
12040:
1.1139 www 12041:
12042:
12043:
12044:
1.465 albertel 12045: sub current_machine_domains {
1.853 albertel 12046: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12047: }
12048:
12049: sub machine_domains {
12050: my ($hostname) = @_;
1.465 albertel 12051: my @domains;
1.838 albertel 12052: my %hostname = &all_hostnames();
1.465 albertel 12053: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12054: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12055: if ($hostname eq $name) {
1.844 albertel 12056: push(@domains,&host_domain($id));
1.465 albertel 12057: }
12058: }
12059: return @domains;
12060: }
12061:
12062: sub current_machine_ids {
1.853 albertel 12063: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12064: }
12065:
12066: sub machine_ids {
12067: my ($hostname) = @_;
12068: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12069: my @ids;
1.888 albertel 12070: my %name_to_host = &all_names();
1.889 albertel 12071: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12072: return @{ $name_to_host{$hostname} };
12073: }
12074: return;
1.31 www 12075: }
12076:
1.824 raeburn 12077: sub additional_machine_domains {
12078: my @domains;
12079: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12080: while( my $line = <$fh>) {
12081: $line =~ s/\s//g;
12082: push(@domains,$line);
12083: }
12084: return @domains;
12085: }
12086:
12087: sub default_login_domain {
12088: my $domain = $perlvar{'lonDefDomain'};
12089: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12090: foreach my $posdom (¤t_machine_domains(),
12091: &additional_machine_domains()) {
12092: if (lc($posdom) eq lc($testdomain)) {
12093: $domain=$posdom;
12094: last;
12095: }
12096: }
12097: return $domain;
12098: }
12099:
1.31 www 12100: # ------------------------------------------------------------- Declutters URLs
12101:
12102: sub declutter {
12103: my $thisfn=shift;
1.569 albertel 12104: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12105: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12106: $thisfn=~s{^/home/httpd/html}{};
12107: }
1.31 www 12108: $thisfn=~s/^\///;
1.697 albertel 12109: $thisfn=~s|^adm/wrapper/||;
12110: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12111: $thisfn=~s/^res\///;
1.1172 bisitz 12112: $thisfn=~s/^priv\///;
1.1032 raeburn 12113: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12114: $thisfn=~s/\?.+$//;
12115: }
1.268 www 12116: return $thisfn;
12117: }
12118:
12119: # ------------------------------------------------------------- Clutter up URLs
12120:
12121: sub clutter {
12122: my $thisfn='/'.&declutter(shift);
1.887 albertel 12123: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12124: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12125: $thisfn='/res'.$thisfn;
12126: }
1.1031 raeburn 12127: if ($thisfn !~m|^/adm|) {
12128: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12129: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12130: } else {
12131: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12132: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12133: if ($embstyle eq 'ssi'
12134: || ($embstyle eq 'hdn')
12135: || ($embstyle eq 'rat')
12136: || ($embstyle eq 'prv')
12137: || ($embstyle eq 'ign')) {
12138: #do nothing with these
12139: } elsif (($embstyle eq 'img')
1.695 albertel 12140: || ($embstyle eq 'emb')
12141: || ($embstyle eq 'wrp')) {
12142: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12143: } elsif ($embstyle eq 'unk'
12144: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12145: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12146: } else {
1.718 www 12147: # &logthis("Got a blank emb style");
1.695 albertel 12148: }
1.694 albertel 12149: }
12150: }
1.31 www 12151: return $thisfn;
1.12 www 12152: }
12153:
1.787 albertel 12154: sub clutter_with_no_wrapper {
12155: my $uri = &clutter(shift);
12156: if ($uri =~ m-^/adm/-) {
12157: $uri =~ s-^/adm/wrapper/-/-;
12158: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12159: }
12160: return $uri;
12161: }
12162:
1.557 albertel 12163: sub freeze_escape {
12164: my ($value)=@_;
12165: if (ref($value)) {
12166: $value=&nfreeze($value);
12167: return '__FROZEN__'.&escape($value);
12168: }
12169: return &escape($value);
12170: }
12171:
1.11 www 12172:
1.557 albertel 12173: sub thaw_unescape {
12174: my ($value)=@_;
12175: if ($value =~ /^__FROZEN__/) {
12176: substr($value,0,10,undef);
12177: $value=&unescape($value);
12178: return &thaw($value);
12179: }
12180: return &unescape($value);
12181: }
12182:
1.436 albertel 12183: sub correct_line_ends {
12184: my ($result)=@_;
12185: $$result =~s/\r\n/\n/mg;
12186: $$result =~s/\r/\n/mg;
1.415 albertel 12187: }
1.1 albertel 12188: # ================================================================ Main Program
12189:
1.184 www 12190: sub goodbye {
1.204 albertel 12191: &logthis("Starting Shut down");
1.443 albertel 12192: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12193: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12194: #converted
1.599 albertel 12195: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12196: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12197: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12198: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12199: #1.1 only
1.870 albertel 12200: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12201: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12202: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12203: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12204: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12205: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12206: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12207: &flushcourselogs();
12208: &logthis("Shutting down");
12209: }
12210:
1.852 albertel 12211: sub get_dns {
1.1210 raeburn 12212: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12213: if (!$ignore_cache) {
12214: my ($content,$cached)=
12215: &Apache::lonnet::is_cached_new('dns',$url);
12216: if ($cached) {
1.1210 raeburn 12217: &$func($content,$hashref);
1.869 albertel 12218: return;
12219: }
12220: }
12221:
12222: my %alldns;
1.852 albertel 12223: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12224: foreach my $dns (<$config>) {
12225: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12226: my $line = $1;
12227: my ($host,$protocol) = split(/:/,$line);
12228: if ($protocol ne 'https') {
12229: $protocol = 'http';
12230: }
12231: $alldns{$host} = $protocol;
1.869 albertel 12232: }
12233: while (%alldns) {
1.1263 raeburn 12234: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12235: my $ua=new LWP::UserAgent;
1.1134 raeburn 12236: $ua->timeout(30);
1.979 raeburn 12237: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12238: my $response=$ua->request($request);
1.979 raeburn 12239: delete($alldns{$dns});
1.852 albertel 12240: next if ($response->is_error());
12241: my @content = split("\n",$response->content);
1.1210 raeburn 12242: unless ($nocache) {
1.1219 raeburn 12243: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12244: }
12245: &$func(\@content,$hashref);
1.869 albertel 12246: return;
1.852 albertel 12247: }
12248: close($config);
1.871 albertel 12249: my $which = (split('/',$url))[3];
12250: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12251: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12252: my @content = <$config>;
1.1210 raeburn 12253: &$func(\@content,$hashref);
12254: return;
12255: }
12256:
12257: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12258: sub parse_dns_checksums_tab {
1.1210 raeburn 12259: my ($lines,$hashref) = @_;
1.1264 raeburn 12260: my $lonhost = $perlvar{'lonHostID'};
12261: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12262: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12263: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12264: my $webconfdir = '/etc/httpd/conf';
12265: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12266: $webconfdir = '/etc/apache2';
12267: } elsif ($distro =~ /^sles(\d+)$/) {
12268: if ($1 >= 10) {
12269: $webconfdir = '/etc/apache2';
12270: }
12271: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12272: if ($1 >= 10.0) {
12273: $webconfdir = '/etc/apache2';
12274: }
12275: }
1.1210 raeburn 12276: my ($release,$timestamp) = split(/\-/,$loncaparev);
12277: my (%chksum,%revnum);
12278: if (ref($lines) eq 'ARRAY') {
12279: chomp(@{$lines});
1.1238 raeburn 12280: my $version = shift(@{$lines});
12281: if ($version eq $release) {
1.1210 raeburn 12282: foreach my $line (@{$lines}) {
1.1238 raeburn 12283: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12284: if ($file =~ m{^/etc/httpd/conf}) {
12285: if ($webconfdir eq '/etc/apache2') {
12286: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12287: }
12288: }
1.1238 raeburn 12289: $chksum{$file} = $shasum;
12290: $revnum{$file} = $version;
1.1210 raeburn 12291: }
12292: if (ref($hashref) eq 'HASH') {
12293: %{$hashref} = (
12294: sums => \%chksum,
12295: versions => \%revnum,
12296: );
12297: }
12298: }
12299: }
1.869 albertel 12300: return;
1.852 albertel 12301: }
1.1210 raeburn 12302:
12303: sub fetch_dns_checksums {
1.1238 raeburn 12304: my %checksums;
12305: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12306: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12307: my ($release,$timestamp) = split(/\-/,$loncaparev);
12308: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12309: \%checksums);
1.1210 raeburn 12310: return \%checksums;
12311: }
12312:
1.327 albertel 12313: # ------------------------------------------------------------ Read domain file
12314: {
1.852 albertel 12315: my $loaded;
1.846 albertel 12316: my %domain;
12317:
1.852 albertel 12318: sub parse_domain_tab {
12319: my ($lines) = @_;
12320: foreach my $line (@$lines) {
12321: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12322:
1.846 albertel 12323: chomp($line);
1.852 albertel 12324: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12325: my %this_domain;
12326: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12327: 'lang_def', 'city', 'longi', 'lati',
12328: 'primary') {
12329: $this_domain{$field} = shift(@elements);
12330: }
12331: $domain{$name} = \%this_domain;
1.852 albertel 12332: }
12333: }
1.864 albertel 12334:
12335: sub reset_domain_info {
12336: undef($loaded);
12337: undef(%domain);
12338: }
12339:
1.852 albertel 12340: sub load_domain_tab {
1.869 albertel 12341: my ($ignore_cache) = @_;
12342: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 12343: my $fh;
12344: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12345: my @lines = <$fh>;
12346: &parse_domain_tab(\@lines);
1.448 albertel 12347: }
1.852 albertel 12348: close($fh);
12349: $loaded = 1;
1.327 albertel 12350: }
1.846 albertel 12351:
12352: sub domain {
1.852 albertel 12353: &load_domain_tab() if (!$loaded);
12354:
1.846 albertel 12355: my ($name,$what) = @_;
12356: return if ( !exists($domain{$name}) );
12357:
12358: if (!$what) {
12359: return $domain{$name}{'description'};
12360: }
12361: return $domain{$name}{$what};
12362: }
1.974 raeburn 12363:
12364: sub domain_info {
12365: &load_domain_tab() if (!$loaded);
12366: return %domain;
12367: }
12368:
1.327 albertel 12369: }
12370:
12371:
1.1 albertel 12372: # ------------------------------------------------------------- Read hosts file
12373: {
1.838 albertel 12374: my %hostname;
1.844 albertel 12375: my %hostdom;
1.845 albertel 12376: my %libserv;
1.852 albertel 12377: my $loaded;
1.888 albertel 12378: my %name_to_host;
1.1074 raeburn 12379: my %internetdom;
1.1107 raeburn 12380: my %LC_dns_serv;
1.852 albertel 12381:
12382: sub parse_hosts_tab {
12383: my ($file) = @_;
12384: foreach my $configline (@$file) {
12385: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12386: chomp($configline);
12387: if ($configline =~ /^\^/) {
12388: if ($configline =~ /^\^([\w.\-]+)/) {
12389: $LC_dns_serv{$1} = 1;
12390: }
12391: next;
12392: }
1.1074 raeburn 12393: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12394: $name=~s/\s//g;
12395: if ($id && $domain && $role && $name) {
12396: $hostname{$id}=$name;
1.888 albertel 12397: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12398: $hostdom{$id}=$domain;
12399: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12400: if (defined($protocol)) {
12401: if ($protocol eq 'https') {
12402: $protocol{$id} = $protocol;
12403: } else {
12404: $protocol{$id} = 'http';
12405: }
1.968 raeburn 12406: } else {
1.969 raeburn 12407: $protocol{$id} = 'http';
1.968 raeburn 12408: }
1.1074 raeburn 12409: if (defined($intdom)) {
12410: $internetdom{$id} = $intdom;
12411: }
1.852 albertel 12412: }
12413: }
12414: }
1.864 albertel 12415:
12416: sub reset_hosts_info {
1.897 albertel 12417: &purge_remembered();
1.864 albertel 12418: &reset_domain_info();
12419: &reset_hosts_ip_info();
1.892 albertel 12420: undef(%name_to_host);
1.864 albertel 12421: undef(%hostname);
12422: undef(%hostdom);
12423: undef(%libserv);
12424: undef($loaded);
12425: }
1.1 albertel 12426:
1.852 albertel 12427: sub load_hosts_tab {
1.869 albertel 12428: my ($ignore_cache) = @_;
12429: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12430: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12431: my @config = <$config>;
12432: &parse_hosts_tab(\@config);
12433: close($config);
12434: $loaded=1;
1.1 albertel 12435: }
1.852 albertel 12436:
1.838 albertel 12437: sub hostname {
1.852 albertel 12438: &load_hosts_tab() if (!$loaded);
12439:
1.838 albertel 12440: my ($lonid) = @_;
12441: return $hostname{$lonid};
12442: }
1.845 albertel 12443:
1.838 albertel 12444: sub all_hostnames {
1.852 albertel 12445: &load_hosts_tab() if (!$loaded);
12446:
1.838 albertel 12447: return %hostname;
12448: }
1.845 albertel 12449:
1.888 albertel 12450: sub all_names {
12451: &load_hosts_tab() if (!$loaded);
12452:
12453: return %name_to_host;
12454: }
12455:
1.974 raeburn 12456: sub all_host_domain {
12457: &load_hosts_tab() if (!$loaded);
12458: return %hostdom;
12459: }
12460:
1.845 albertel 12461: sub is_library {
1.852 albertel 12462: &load_hosts_tab() if (!$loaded);
12463:
1.845 albertel 12464: return exists($libserv{$_[0]});
12465: }
12466:
12467: sub all_library {
1.852 albertel 12468: &load_hosts_tab() if (!$loaded);
12469:
1.845 albertel 12470: return %libserv;
12471: }
12472:
1.1062 droeschl 12473: sub unique_library {
12474: #2x reverse removes all hostnames that appear more than once
12475: my %unique = reverse &all_library();
12476: return reverse %unique;
12477: }
12478:
1.841 albertel 12479: sub get_servers {
1.852 albertel 12480: &load_hosts_tab() if (!$loaded);
12481:
1.841 albertel 12482: my ($domain,$type) = @_;
12483: my %possible_hosts = ($type eq 'library') ? %libserv
12484: : %hostname;
12485: my %result;
1.842 albertel 12486: if (ref($domain) eq 'ARRAY') {
12487: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12488: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12489: $result{$host} = $hostname;
12490: }
12491: }
12492: } else {
12493: while ( my ($host,$hostname) = each(%possible_hosts)) {
12494: if ($hostdom{$host} eq $domain) {
12495: $result{$host} = $hostname;
12496: }
1.841 albertel 12497: }
12498: }
12499: return %result;
12500: }
1.845 albertel 12501:
1.1062 droeschl 12502: sub get_unique_servers {
12503: my %unique = reverse &get_servers(@_);
12504: return reverse %unique;
12505: }
12506:
1.844 albertel 12507: sub host_domain {
1.852 albertel 12508: &load_hosts_tab() if (!$loaded);
12509:
1.844 albertel 12510: my ($lonid) = @_;
12511: return $hostdom{$lonid};
12512: }
12513:
1.841 albertel 12514: sub all_domains {
1.852 albertel 12515: &load_hosts_tab() if (!$loaded);
12516:
1.841 albertel 12517: my %seen;
12518: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12519: return @uniq;
12520: }
1.1074 raeburn 12521:
12522: sub internet_dom {
12523: &load_hosts_tab() if (!$loaded);
12524:
12525: my ($lonid) = @_;
12526: return $internetdom{$lonid};
12527: }
1.1107 raeburn 12528:
12529: sub is_LC_dns {
12530: &load_hosts_tab() if (!$loaded);
12531:
12532: my ($hostname) = @_;
12533: return exists($LC_dns_serv{$hostname});
12534: }
12535:
1.1 albertel 12536: }
12537:
1.847 albertel 12538: {
12539: my %iphost;
1.856 albertel 12540: my %name_to_ip;
12541: my %lonid_to_ip;
1.869 albertel 12542:
1.847 albertel 12543: sub get_hosts_from_ip {
12544: my ($ip) = @_;
12545: my %iphosts = &get_iphost();
12546: if (ref($iphosts{$ip})) {
12547: return @{$iphosts{$ip}};
12548: }
12549: return;
1.839 albertel 12550: }
1.864 albertel 12551:
12552: sub reset_hosts_ip_info {
12553: undef(%iphost);
12554: undef(%name_to_ip);
12555: undef(%lonid_to_ip);
12556: }
1.856 albertel 12557:
12558: sub get_host_ip {
12559: my ($lonid) = @_;
12560: if (exists($lonid_to_ip{$lonid})) {
12561: return $lonid_to_ip{$lonid};
12562: }
12563: my $name=&hostname($lonid);
12564: my $ip = gethostbyname($name);
12565: return if (!$ip || length($ip) ne 4);
12566: $ip=inet_ntoa($ip);
12567: $name_to_ip{$name} = $ip;
12568: $lonid_to_ip{$lonid} = $ip;
12569: return $ip;
12570: }
1.847 albertel 12571:
12572: sub get_iphost {
1.869 albertel 12573: my ($ignore_cache) = @_;
1.894 albertel 12574:
1.869 albertel 12575: if (!$ignore_cache) {
12576: if (%iphost) {
12577: return %iphost;
12578: }
12579: my ($ip_info,$cached)=
12580: &Apache::lonnet::is_cached_new('iphost','iphost');
12581: if ($cached) {
12582: %iphost = %{$ip_info->[0]};
12583: %name_to_ip = %{$ip_info->[1]};
12584: %lonid_to_ip = %{$ip_info->[2]};
12585: return %iphost;
12586: }
12587: }
1.894 albertel 12588:
12589: # get yesterday's info for fallback
12590: my %old_name_to_ip;
12591: my ($ip_info,$cached)=
12592: &Apache::lonnet::is_cached_new('iphost','iphost');
12593: if ($cached) {
12594: %old_name_to_ip = %{$ip_info->[1]};
12595: }
12596:
1.888 albertel 12597: my %name_to_host = &all_names();
12598: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12599: my $ip;
12600: if (!exists($name_to_ip{$name})) {
12601: $ip = gethostbyname($name);
12602: if (!$ip || length($ip) ne 4) {
1.894 albertel 12603: if (defined($old_name_to_ip{$name})) {
12604: $ip = $old_name_to_ip{$name};
12605: &logthis("Can't find $name defaulting to old $ip");
12606: } else {
12607: &logthis("Name $name no IP found");
12608: next;
12609: }
12610: } else {
12611: $ip=inet_ntoa($ip);
1.847 albertel 12612: }
12613: $name_to_ip{$name} = $ip;
12614: } else {
12615: $ip = $name_to_ip{$name};
1.653 albertel 12616: }
1.888 albertel 12617: foreach my $id (@{ $name_to_host{$name} }) {
12618: $lonid_to_ip{$id} = $ip;
12619: }
12620: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12621: }
1.1219 raeburn 12622: &do_cache_new('iphost','iphost',
12623: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12624: 48*60*60);
1.869 albertel 12625:
1.847 albertel 12626: return %iphost;
1.598 albertel 12627: }
12628:
1.992 raeburn 12629: #
12630: # Given a DNS returns the loncapa host name for that DNS
12631: #
12632: sub host_from_dns {
12633: my ($dns) = @_;
12634: my @hosts;
12635: my $ip;
12636:
1.993 raeburn 12637: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12638: $ip = $name_to_ip{$dns};
12639: }
12640: if (!$ip) {
12641: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12642: if (length($ip) == 4) {
12643: $ip = &IO::Socket::inet_ntoa($ip);
12644: }
12645: }
12646: if ($ip) {
12647: @hosts = get_hosts_from_ip($ip);
12648: return $hosts[0];
12649: }
12650: return undef;
1.986 foxr 12651: }
1.992 raeburn 12652:
1.1074 raeburn 12653: sub get_internet_names {
12654: my ($lonid) = @_;
12655: return if ($lonid eq '');
12656: my ($idnref,$cached)=
12657: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12658: if ($cached) {
12659: return $idnref;
12660: }
12661: my $ip = &get_host_ip($lonid);
12662: my @hosts = &get_hosts_from_ip($ip);
12663: my %iphost = &get_iphost();
12664: my (@idns,%seen);
12665: foreach my $id (@hosts) {
12666: my $dom = &host_domain($id);
12667: my $prim_id = &domain($dom,'primary');
12668: my $prim_ip = &get_host_ip($prim_id);
12669: next if ($seen{$prim_ip});
12670: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12671: foreach my $id (@{$iphost{$prim_ip}}) {
12672: my $intdom = &internet_dom($id);
12673: unless (grep(/^\Q$intdom\E$/,@idns)) {
12674: push(@idns,$intdom);
12675: }
12676: }
12677: }
12678: $seen{$prim_ip} = 1;
12679: }
1.1219 raeburn 12680: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12681: }
12682:
1.986 foxr 12683: }
12684:
1.1079 raeburn 12685: sub all_loncaparevs {
1.1249 raeburn 12686: 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 12687: }
12688:
1.1227 raeburn 12689: # ---------------------------------------------------------- Read loncaparev table
12690: {
12691: sub load_loncaparevs {
12692: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12693: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12694: while (my $configline=<$config>) {
12695: chomp($configline);
12696: my ($hostid,$loncaparev)=split(/:/,$configline);
12697: $loncaparevs{$hostid}=$loncaparev;
12698: }
12699: close($config);
12700: }
12701: }
12702: }
12703: }
12704:
12705: # ---------------------------------------------------------- Read serverhostID table
12706: {
12707: sub load_serverhomeIDs {
12708: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12709: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12710: while (my $configline=<$config>) {
12711: chomp($configline);
12712: my ($name,$id)=split(/:/,$configline);
12713: $serverhomeIDs{$name}=$id;
12714: }
12715: close($config);
12716: }
12717: }
12718: }
12719: }
12720:
12721:
1.862 albertel 12722: BEGIN {
12723:
12724: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12725: unless ($readit) {
12726: {
12727: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12728: %perlvar = (%perlvar,%{$configvars});
12729: }
12730:
12731:
1.1 albertel 12732: # ------------------------------------------------------ Read spare server file
12733: {
1.448 albertel 12734: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12735:
12736: while (my $configline=<$config>) {
12737: chomp($configline);
1.284 matthew 12738: if ($configline) {
1.784 albertel 12739: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12740: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12741: push(@{ $spareid{$type} }, $host);
1.1 albertel 12742: }
12743: }
1.448 albertel 12744: close($config);
1.1 albertel 12745: }
1.11 www 12746: # ------------------------------------------------------------ Read permissions
12747: {
1.448 albertel 12748: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12749:
12750: while (my $configline=<$config>) {
1.448 albertel 12751: chomp($configline);
12752: if ($configline) {
12753: my ($role,$perm)=split(/ /,$configline);
12754: if ($perm ne '') { $pr{$role}=$perm; }
12755: }
1.11 www 12756: }
1.448 albertel 12757: close($config);
1.11 www 12758: }
12759:
12760: # -------------------------------------------- Read plain texts for permissions
12761: {
1.448 albertel 12762: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12763:
12764: while (my $configline=<$config>) {
1.448 albertel 12765: chomp($configline);
12766: if ($configline) {
1.742 raeburn 12767: my ($short,@plain)=split(/:/,$configline);
12768: %{$prp{$short}} = ();
12769: if (@plain > 0) {
12770: $prp{$short}{'std'} = $plain[0];
12771: for (my $i=1; $i<@plain; $i++) {
12772: $prp{$short}{'alt'.$i} = $plain[$i];
12773: }
12774: }
1.448 albertel 12775: }
1.135 www 12776: }
1.448 albertel 12777: close($config);
1.135 www 12778: }
12779:
12780: # ---------------------------------------------------------- Read package table
12781: {
1.448 albertel 12782: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12783:
12784: while (my $configline=<$config>) {
1.483 albertel 12785: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12786: chomp($configline);
12787: my ($short,$plain)=split(/:/,$configline);
12788: my ($pack,$name)=split(/\&/,$short);
12789: if ($plain ne '') {
12790: $packagetab{$pack.'&'.$name.'&name'}=$name;
12791: $packagetab{$short}=$plain;
12792: }
1.11 www 12793: }
1.448 albertel 12794: close($config);
1.329 matthew 12795: }
12796:
1.1073 raeburn 12797: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12798:
12799: &load_loncaparevs();
1.1073 raeburn 12800:
1.1074 raeburn 12801: # ---------------------------------------------------------- Read serverhostID table
12802:
1.1227 raeburn 12803: &load_serverhomeIDs();
12804:
12805: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12806: {
12807: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12808: if (-e $file) {
12809: my $parser = HTML::LCParser->new($file);
12810: while (my $token = $parser->get_token()) {
12811: if ($token->[0] eq 'S') {
12812: my $item = $token->[1];
12813: my $name = $token->[2]{'name'};
12814: my $value = $token->[2]{'value'};
1.1285 raeburn 12815: my $valuematch = $token->[2]{'valuematch'};
12816: if ($item ne '' && $name ne '' && ($value ne '' || $valuematch ne '')) {
1.1079 raeburn 12817: my $release = $parser->get_text();
12818: $release =~ s/(^\s*|\s*$ )//gx;
1.1285 raeburn 12819: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch} = $release;
1.1079 raeburn 12820: }
12821: }
12822: }
12823: }
1.1073 raeburn 12824: }
12825:
1.1138 raeburn 12826: # ---------------------------------------------------------- Read managers table
12827: {
12828: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12829: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12830: while (my $configline=<$config>) {
12831: chomp($configline);
12832: next if ($configline =~ /^\#/);
12833: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12834: $managerstab{$configline} = 1;
12835: }
12836: }
12837: close($config);
12838: }
12839: }
12840: }
12841:
1.329 matthew 12842: # ------------- set up temporary directory
12843: {
1.1117 foxr 12844: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12845:
1.11 www 12846: }
12847:
1.794 albertel 12848: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12849: 'compress_threshold'=> 20_000,
12850: });
1.185 www 12851:
1.281 www 12852: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12853: $dumpcount=0;
1.958 www 12854: $locknum=0;
1.22 www 12855:
1.163 harris41 12856: &logtouch();
1.672 albertel 12857: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12858: $readit=1;
1.564 albertel 12859: {
12860: use integer;
12861: my $test=(2**32)+1;
1.568 albertel 12862: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12863: &logthis(" Detected 64bit platform ($_64bit)");
12864: }
1.195 www 12865: }
1.1 albertel 12866: }
1.179 www 12867:
1.1 albertel 12868: 1;
1.191 harris41 12869: __END__
12870:
1.243 albertel 12871: =pod
12872:
1.191 harris41 12873: =head1 NAME
12874:
1.243 albertel 12875: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12876:
12877: =head1 SYNOPSIS
12878:
1.243 albertel 12879: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12880:
12881: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12882:
1.243 albertel 12883: Common parameters:
12884:
12885: =over 4
12886:
12887: =item *
12888:
12889: $uname : an internal username (if $cname expecting a course Id specifically)
12890:
12891: =item *
12892:
12893: $udom : a domain (if $cdom expecting a course's domain specifically)
12894:
12895: =item *
12896:
12897: $symb : a resource instance identifier
12898:
12899: =item *
12900:
12901: $namespace : the name of a .db file that contains the data needed or
12902: being set.
12903:
12904: =back
12905:
1.394 bowersj2 12906: =head1 OVERVIEW
1.191 harris41 12907:
1.394 bowersj2 12908: lonnet provides subroutines which interact with the
12909: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12910: about classes, users, and resources.
1.243 albertel 12911:
12912: For many of these objects you can also use this to store data about
12913: them or modify them in various ways.
1.191 harris41 12914:
1.394 bowersj2 12915: =head2 Symbs
1.191 harris41 12916:
1.394 bowersj2 12917: To identify a specific instance of a resource, LON-CAPA uses symbols
12918: or "symbs"X<symb>. These identifiers are built from the URL of the
12919: map, the resource number of the resource in the map, and the URL of
12920: the resource itself. The latter is somewhat redundant, but might help
12921: if maps change.
12922:
12923: An example is
12924:
12925: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12926:
12927: The respective map entry is
12928:
12929: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12930: title="Problem 2">
12931: </resource>
12932:
12933: Symbs are used by the random number generator, as well as to store and
12934: restore data specific to a certain instance of for example a problem.
12935:
12936: =head2 Storing And Retrieving Data
12937:
12938: X<store()>X<cstore()>X<restore()>Three of the most important functions
12939: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12940: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12941: is is the non-critical message twin of cstore. These functions are for
12942: handlers to store a perl hash to a user's permanent data space in an
12943: easy manner, and to retrieve it again on another call. It is expected
12944: that a handler would use this once at the beginning to retrieve data,
12945: and then again once at the end to send only the new data back.
12946:
12947: The data is stored in the user's data directory on the user's
12948: homeserver under the ID of the course.
12949:
12950: The hash that is returned by restore will have all of the previous
12951: value for all of the elements of the hash.
12952:
12953: Example:
12954:
12955: #creating a hash
12956: my %hash;
12957: $hash{'foo'}='bar';
12958:
12959: #storing it
12960: &Apache::lonnet::cstore(\%hash);
12961:
12962: #changing a value
12963: $hash{'foo'}='notbar';
12964:
12965: #adding a new value
12966: $hash{'bar'}='foo';
12967: &Apache::lonnet::cstore(\%hash);
12968:
12969: #retrieving the hash
12970: my %history=&Apache::lonnet::restore();
12971:
12972: #print the hash
12973: foreach my $key (sort(keys(%history))) {
12974: print("\%history{$key} = $history{$key}");
12975: }
12976:
12977: Will print out:
1.191 harris41 12978:
1.394 bowersj2 12979: %history{1:foo} = bar
12980: %history{1:keys} = foo:timestamp
12981: %history{1:timestamp} = 990455579
12982: %history{2:bar} = foo
12983: %history{2:foo} = notbar
12984: %history{2:keys} = foo:bar:timestamp
12985: %history{2:timestamp} = 990455580
12986: %history{bar} = foo
12987: %history{foo} = notbar
12988: %history{timestamp} = 990455580
12989: %history{version} = 2
12990:
12991: Note that the special hash entries C<keys>, C<version> and
12992: C<timestamp> were added to the hash. C<version> will be equal to the
12993: total number of versions of the data that have been stored. The
12994: C<timestamp> attribute will be the UNIX time the hash was
12995: stored. C<keys> is available in every historical section to list which
12996: keys were added or changed at a specific historical revision of a
12997: hash.
12998:
12999: B<Warning>: do not store the hash that restore returns directly. This
13000: will cause a mess since it will restore the historical keys as if the
13001: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13002:
1.394 bowersj2 13003: Calling convention:
1.191 harris41 13004:
1.1225 raeburn 13005: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13006: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13007:
1.394 bowersj2 13008: For more detailed information, see lonnet specific documentation.
1.191 harris41 13009:
1.394 bowersj2 13010: =head1 RETURN MESSAGES
1.191 harris41 13011:
1.394 bowersj2 13012: =over 4
1.191 harris41 13013:
1.394 bowersj2 13014: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13015:
1.394 bowersj2 13016: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13017: when the connection is brought back up
1.191 harris41 13018:
1.394 bowersj2 13019: =item * B<con_failed>: unable to contact remote host and unable to save message
13020: for later delivery
1.191 harris41 13021:
1.967 bisitz 13022: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13023:
1.394 bowersj2 13024: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13025: that was requested
1.191 harris41 13026:
1.243 albertel 13027: =back
1.191 harris41 13028:
1.243 albertel 13029: =head1 PUBLIC SUBROUTINES
1.191 harris41 13030:
1.243 albertel 13031: =head2 Session Environment Functions
1.191 harris41 13032:
1.243 albertel 13033: =over 4
1.191 harris41 13034:
1.394 bowersj2 13035: =item *
13036: X<appenv()>
1.949 raeburn 13037: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13038: the user envirnoment file, and will be restored for each access this
1.620 albertel 13039: user makes during this session, also modifies the %env for the current
1.949 raeburn 13040: process. Optional rolesarrayref - if defined contains a reference to an array
13041: of roles which are exempt from the restriction on modifying user.role entries
13042: in the user's environment.db and in %env.
1.191 harris41 13043:
13044: =item *
1.394 bowersj2 13045: X<delenv()>
1.987 raeburn 13046: B<delenv($delthis,$regexp)>: removes all items from the session
13047: environment file that begin with $delthis. If the
13048: optional second arg - $regexp - is true, $delthis is treated as a
13049: regular expression, otherwise \Q$delthis\E is used.
13050: The values are also deleted from the current processes %env.
1.191 harris41 13051:
1.795 albertel 13052: =item * get_env_multiple($name)
13053:
13054: gets $name from the %env hash, it seemlessly handles the cases where multiple
13055: values may be defined and end up as an array ref.
13056:
13057: returns an array of values
13058:
1.243 albertel 13059: =back
13060:
13061: =head2 User Information
1.191 harris41 13062:
1.243 albertel 13063: =over 4
1.191 harris41 13064:
13065: =item *
1.394 bowersj2 13066: X<queryauthenticate()>
13067: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13068: authentication scheme
13069:
13070: =item *
1.394 bowersj2 13071: X<authenticate()>
1.1073 raeburn 13072: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13073: authenticate user from domain's lib servers (first use the current
13074: one). C<$upass> should be the users password.
1.1073 raeburn 13075: $checkdefauth is optional (value is 1 if a check should be made to
13076: authenticate user using default authentication method, and allow
13077: account creation if username does not have account in the domain).
13078: $clientcancheckhost is optional (value is 1 if checking whether the
13079: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13080:
13081: =item *
1.394 bowersj2 13082: X<homeserver()>
13083: B<homeserver($uname,$udom)>: find the server which has
13084: the user's directory and files (there must be only one), this caches
13085: the answer, and also caches if there is a borken connection.
1.191 harris41 13086:
13087: =item *
1.394 bowersj2 13088: X<idget()>
13089: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13090: (IDs are a unique resource in a domain, there must be only 1 ID per
13091: username, and only 1 username per ID in a specific domain) (returns
13092: hash: id=>name,id=>name)
1.191 harris41 13093:
13094: =item *
1.394 bowersj2 13095: X<idrget()>
13096: B<idrget($udom,@unames)>: find the IDs behind a list of
13097: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13098:
13099: =item *
1.394 bowersj2 13100: X<idput()>
13101: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13102:
13103: =item *
1.394 bowersj2 13104: X<rolesinit()>
1.1169 droeschl 13105: B<rolesinit($udom,$username)>: get user privileges.
13106: returns user role, first access and timer interval hashes
1.243 albertel 13107:
13108: =item *
1.1171 droeschl 13109: X<privileged()>
13110: B<privileged($username,$domain)>: returns a true if user has a
13111: privileged and active role (i.e. su or dc), false otherwise.
13112:
13113: =item *
1.551 albertel 13114: X<getsection()>
13115: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13116: course $cname, return section name/number or '' for "not in course"
13117: and '-1' for "no section"
13118:
13119: =item *
1.394 bowersj2 13120: X<userenvironment()>
13121: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13122: passed in @what from the requested user's environment, returns a hash
13123:
1.858 raeburn 13124: =item *
13125: X<userlog_query()>
1.859 albertel 13126: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13127: activity.log file. %filters defines filters applied when parsing the
13128: log file. These can be start or end timestamps, or the type of action
13129: - log to look for Login or Logout events, check for Checkin or
13130: Checkout, role for role selection. The response is in the form
13131: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13132: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13133:
1.243 albertel 13134: =back
13135:
13136: =head2 User Roles
13137:
13138: =over 4
13139:
13140: =item *
13141:
1.1284 raeburn 13142: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13143: returns codes for allowed actions.
13144:
13145: The first argument is required, all others are optional.
13146:
13147: $priv is the privilege being checked.
13148: $uri contains additional information about what is being checked for access (e.g.,
13149: URL, course ID etc.).
13150: $symb is the unique resource instance identifier in a course; if needed,
13151: but not provided, it will be retrieved via a call to &symbread().
13152: $role is the role for which a priv is being checked (only used if priv is evb).
13153: $clientip is the user's IP address (only used when checking for access to portfolio
13154: files).
13155: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13156: prevents recursive calls to &allowed.
13157:
1.243 albertel 13158: F: full access
13159: U,I,K: authentication modes (cxx only)
13160: '': forbidden
13161: 1: user needs to choose course
13162: 2: browse allowed
1.766 albertel 13163: A: passphrase authentication needed
1.1284 raeburn 13164: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13165:
13166: =item *
13167:
1.1192 raeburn 13168: constructaccess($url,$setpriv) : check for access to construction space URL
13169:
13170: See if the owner domain and name in the URL match those in the
13171: expected environment. If so, return three element list
13172: ($ownername,$ownerdomain,$ownerhome).
13173:
13174: Otherwise return the null string.
13175:
13176: If second argument 'setpriv' is true, it assigns the privileges,
13177: and returns the same three element list, unless the owner has
13178: blocked "ad hoc" Domain Coordinator access to the Author Space,
13179: in which case the null string is returned.
13180:
13181: =item *
13182:
1.243 albertel 13183: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13184: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13185: and course level
13186:
13187: =item *
13188:
1.988 raeburn 13189: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13190: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13191: $type is Course (default) or Community.
1.988 raeburn 13192: If $forcedefault evaluates to true, text returned will be default
13193: text for $type. Otherwise, if this is a course, the text returned
13194: will be a custom name for the role (if defined in the course's
13195: environment). If no custom name is defined the default is returned.
13196:
1.832 raeburn 13197: =item *
13198:
1.1219 raeburn 13199: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13200: All arguments are optional. Returns a hash of a roles, either for
13201: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13202: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13203: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13204: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13205: For each key, value is set to colon-separated start and end times for
13206: the role. If no username and domain are specified, will default to
1.934 raeburn 13207: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13208: of role statuses (active, future or previous), roles
13209: (e.g., cc,in, st etc.) and domains of the roles which can be used
13210: to restrict the list of roles reported. If no array ref is
13211: provided for types, will default to return only active roles.
1.834 albertel 13212:
1.1195 raeburn 13213: =item *
13214:
13215: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 13216: user: $uname:$udom has a role in the course: $cdom_$cnum.
13217:
13218: Additional optional arguments are: $type (if role checking is to be restricted
13219: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13220: available roles) or future (roles available in the future), and
13221: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13222: have active Domain Coordinator role in course's domain or in additional
13223: domains (specified in 'Domains to check for privileged users' in course
13224: environment -- set via: Course Settings -> Classlists and staff listing).
13225:
13226: =item *
13227:
13228: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13229: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13230: $possdomains and $possroles are optional array refs -- to domains to check and
13231: roles to check. If $possdomains is not specified, a dump will be done of the
13232: users' roles.db to check for a dc or su role in any domain. This can be
13233: time consuming if &privileged is called repeatedly (e.g., when displaying a
13234: classlist), so in such cases, supplying a $possdomains array is preferred, as
13235: this then allows &privileged_by_domain() to be used, which caches the identity
13236: of privileged users, eliminating the need for repeated calls to &dump().
13237:
13238: =item *
13239:
13240: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13241: where the outer hash keys are domains specified in the $possdomains array ref,
13242: next inner hash keys are privileged roles specified in the $roles array ref,
13243: and the innermost hash contains key = value pairs for username:domain = end:start
13244: for active or future "privileged" users with that role in that domain. To avoid
13245: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13246: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13247:
1.243 albertel 13248: =back
13249:
13250: =head2 User Modification
13251:
13252: =over 4
13253:
13254: =item *
13255:
1.957 raeburn 13256: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13257: user for the level given by URL. Optional start and end dates (leave empty
13258: string or zero for "no date")
1.191 harris41 13259:
13260: =item *
13261:
1.243 albertel 13262: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13263: change a users, password, possible return values are: ok,
13264: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13265: refused
1.191 harris41 13266:
13267: =item *
13268:
1.243 albertel 13269: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13270:
13271: =item *
13272:
1.1058 raeburn 13273: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13274: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13275:
13276: will update user information (firstname,middlename,lastname,generation,
13277: permanentemail), and if forceid is true, student/employee ID also.
13278: A user's institutional affiliation(s) can also be updated.
13279: User information fields will not be overwritten with empty entries
13280: unless the field is included in the $candelete array reference.
13281: This array is included when a single user is modified via "Manage Users",
13282: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13283:
13284: =item *
13285:
1.286 matthew 13286: modifystudent
13287:
1.957 raeburn 13288: modify a student's enrollment and identification information.
1.1235 raeburn 13289: The course id is resolved based on the current user's environment.
13290: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13291: associated with a course.
13292:
1.297 matthew 13293: This call is essentially a wrapper for lonnet::modifyuser and
13294: lonnet::modify_student_enrollment
1.286 matthew 13295:
13296: Inputs:
13297:
13298: =over 4
13299:
1.957 raeburn 13300: =item B<$udom> Student's loncapa domain
1.286 matthew 13301:
1.957 raeburn 13302: =item B<$uname> Student's loncapa login name
1.286 matthew 13303:
1.964 bisitz 13304: =item B<$uid> Student/Employee ID
1.286 matthew 13305:
1.957 raeburn 13306: =item B<$umode> Student's authentication mode
1.286 matthew 13307:
1.957 raeburn 13308: =item B<$upass> Student's password
1.286 matthew 13309:
1.957 raeburn 13310: =item B<$first> Student's first name
1.286 matthew 13311:
1.957 raeburn 13312: =item B<$middle> Student's middle name
1.286 matthew 13313:
1.957 raeburn 13314: =item B<$last> Student's last name
1.286 matthew 13315:
1.957 raeburn 13316: =item B<$gene> Student's generation
1.286 matthew 13317:
1.957 raeburn 13318: =item B<$usec> Student's section in course
1.286 matthew 13319:
13320: =item B<$end> Unix time of the roles expiration
13321:
13322: =item B<$start> Unix time of the roles start date
13323:
13324: =item B<$forceid> If defined, allow $uid to be changed
13325:
13326: =item B<$desiredhome> server to use as home server for student
13327:
1.957 raeburn 13328: =item B<$email> Student's permanent e-mail address
13329:
13330: =item B<$type> Type of enrollment (auto or manual)
13331:
1.963 raeburn 13332: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13333:
13334: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13335:
1.963 raeburn 13336: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13337:
1.963 raeburn 13338: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13339:
1.1216 raeburn 13340: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13341:
13342: =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 13343:
1.286 matthew 13344: =back
1.297 matthew 13345:
13346: =item *
13347:
13348: modify_student_enrollment
13349:
1.1235 raeburn 13350: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13351: 'role.request.course' must be defined for this function to proceed.
13352:
13353: Inputs:
13354:
13355: =over 4
13356:
1.1235 raeburn 13357: =item $udom, student's domain
1.297 matthew 13358:
1.1235 raeburn 13359: =item $uname, student's name
1.297 matthew 13360:
1.1235 raeburn 13361: =item $uid, student's user id
1.297 matthew 13362:
1.1235 raeburn 13363: =item $first, student's first name
1.297 matthew 13364:
13365: =item $middle
13366:
13367: =item $last
13368:
13369: =item $gene
13370:
13371: =item $usec
13372:
13373: =item $end
13374:
13375: =item $start
13376:
1.957 raeburn 13377: =item $type
13378:
13379: =item $locktype
13380:
13381: =item $cid
13382:
13383: =item $selfenroll
13384:
13385: =item $context
13386:
1.1216 raeburn 13387: =item $credits, number of credits student will earn from this class
13388:
1.297 matthew 13389: =back
13390:
1.191 harris41 13391:
13392: =item *
13393:
1.243 albertel 13394: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13395: custom role; give a custom role to a user for the level given by URL. Specify
13396: name and domain of role author, and role name
1.191 harris41 13397:
13398: =item *
13399:
1.243 albertel 13400: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13401:
13402: =item *
13403:
1.243 albertel 13404: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13405:
13406: =back
13407:
13408: =head2 Course Infomation
13409:
13410: =over 4
1.191 harris41 13411:
13412: =item *
13413:
1.1118 foxr 13414: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13415: specified course id, including all environment settings for the
13416: course, the description of the course will be in the hash under the
13417: key 'description'
1.191 harris41 13418:
1.1118 foxr 13419: $options is an optional parameter that if supplied is a hash reference that controls
13420: what how this function works. It has the following key/values:
13421:
13422: =over 4
13423:
13424: =item freshen_cache
13425:
13426: If defined, and the environment cache for the course is valid, it is
13427: returned in the returned hash.
13428:
13429: =item one_time
13430:
13431: If defined, the last cache time is set to _now_
13432:
13433: =item user
13434:
13435: If defined, the supplied username is used instead of the current user.
13436:
13437:
13438: =back
13439:
1.191 harris41 13440: =item *
13441:
1.624 albertel 13442: resdata($name,$domain,$type,@which) : request for current parameter
13443: setting for a specific $type, where $type is either 'course' or 'user',
13444: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 13445: answers for 10 minutes.
1.243 albertel 13446:
1.877 foxr 13447: =item *
13448:
13449: get_courseresdata($courseid, $domain) : dump the entire course resource
13450: data base, returning a hash that is keyed by the resource name and has
13451: values that are the resource value. I believe that the timestamps and
13452: versions are also returned.
13453:
1.1236 raeburn 13454: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13455: supplemental content area. This routine caches the number of files for
13456: 10 minutes.
13457:
1.243 albertel 13458: =back
13459:
13460: =head2 Course Modification
13461:
13462: =over 4
1.191 harris41 13463:
13464: =item *
13465:
1.243 albertel 13466: writecoursepref($courseid,%prefs) : write preferences (environment
13467: database) for a course
1.191 harris41 13468:
13469: =item *
13470:
1.1011 raeburn 13471: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13472:
13473: =item *
13474:
1.1038 raeburn 13475: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13476:
1.1167 droeschl 13477: =item *
13478:
13479: is_course($courseid), is_course($cdom, $cnum)
13480:
13481: Accepts either a combined $courseid (in the form of domain_courseid) or the
13482: two component version $cdom, $cnum. It checks if the specified course exists.
13483:
13484: Returns:
13485: undef if the course doesn't exist, otherwise
13486: in scalar context the combined courseid.
13487: in list context the two components of the course identifier, domain and
13488: courseid.
13489:
1.243 albertel 13490: =back
13491:
13492: =head2 Resource Subroutines
13493:
13494: =over 4
1.191 harris41 13495:
13496: =item *
13497:
1.243 albertel 13498: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13499:
13500: =item *
13501:
1.243 albertel 13502: repcopy($filename) : subscribes to the requested file, and attempts to
13503: replicate from the owning library server, Might return
1.607 raeburn 13504: 'unavailable', 'not_found', 'forbidden', 'ok', or
13505: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13506: resource. Expects the local filesystem pathname
13507: (/home/httpd/html/res/....)
13508:
13509: =back
13510:
13511: =head2 Resource Information
13512:
13513: =over 4
1.191 harris41 13514:
13515: =item *
13516:
1.1228 raeburn 13517: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13518: and returns the value of a variety of different possible values,
13519: $varname should be a request string, and the other parameters can be
13520: used to specify who and what one is asking about. Ordinarily, $cid
13521: does not need to be specified, as it is retrived from
13522: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13523: within lonuserstate::loadmap() when initializing a course, before
13524: $env{'request.course.id'} has been set, so it needs to be provided
13525: in that one case.
1.243 albertel 13526:
13527: Possible values for $varname are environment.lastname (or other item
13528: from the envirnment hash), user.name (or someother aspect about the
13529: user), resource.0.maxtries (or some other part and parameter of a
13530: resource)
1.204 albertel 13531:
13532: =item *
13533:
1.243 albertel 13534: directcondval($number) : get current value of a condition; reads from a state
13535: string
1.204 albertel 13536:
13537: =item *
13538:
1.243 albertel 13539: condval($condidx) : value of condition index based on state
1.204 albertel 13540:
13541: =item *
13542:
1.243 albertel 13543: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13544: resource's metadata, $what should be either a specific key, or either
13545: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13546: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13547:
13548: this function automatically caches all requests
1.191 harris41 13549:
13550: =item *
13551:
1.243 albertel 13552: metadata_query($query,$custom,$customshow) : make a metadata query against the
13553: network of library servers; returns file handle of where SQL and regex results
13554: will be stored for query
1.191 harris41 13555:
13556: =item *
13557:
1.1282 raeburn 13558: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13559: return symbolic list entry (all arguments optional).
13560:
13561: Args: filename is the filename (including path) for the file for which a symb
13562: is required; donotrecurse, if true will prevent calls to allowed() being made
13563: to check access status if more than one resource was found in the bighash
13564: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13565: a randompick); ignorecachednull, if true will prevent a symb of '' being
13566: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13567: cause possible symbs to be checked to determine if they are subject to content
13568: blocking, if so they will not be included as possible symbs; possibles is a
13569: ref to a hash, which, as a side effect, will be populated with all possible
13570: symbs (content blocking not tested).
13571:
1.243 albertel 13572: returns the data handle
1.191 harris41 13573:
13574: =item *
13575:
1.1190 raeburn 13576: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13577: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13578: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13579: on failure, user must be in a course, as it assumes the existence of
13580: the course initial hash, and uses $env('request.course.id'}. The third
13581: arg is an optional reference to a scalar. If this arg is passed in the
13582: call to symbverify, it will be set to 1 if the symb has been set to be
13583: encrypted; otherwise it will be null.
1.191 harris41 13584:
13585: =item *
13586:
1.243 albertel 13587: symbclean($symb) : removes versions numbers from a symb, returns the
13588: cleaned symb
1.191 harris41 13589:
13590: =item *
13591:
1.243 albertel 13592: is_on_map($uri) : checks if the $uri is somewhere on the current
13593: course map, user must be in a course for it to work.
1.191 harris41 13594:
13595: =item *
13596:
1.243 albertel 13597: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13598:
13599: =item *
13600:
1.243 albertel 13601: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13602: a random seed, all arguments are optional, if they aren't sent it uses the
13603: environment to derive them. Note: if symb isn't sent and it can't get one
13604: from &symbread it will use the current time as its return value
1.191 harris41 13605:
13606: =item *
13607:
1.243 albertel 13608: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13609: unfakeable, receipt
1.191 harris41 13610:
13611: =item *
13612:
1.620 albertel 13613: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13614:
13615: =item *
13616:
1.243 albertel 13617: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13618:
13619: =item *
13620:
1.243 albertel 13621: 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 13622:
13623: =item *
13624:
1.243 albertel 13625: 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 13626:
13627: =item *
13628:
1.243 albertel 13629: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13630:
13631: =item *
13632:
1.243 albertel 13633: devalidate($symb) : devalidate temporary spreadsheet calculations,
13634: forcing spreadsheet to reevaluate the resource scores next time.
13635:
1.1195 raeburn 13636: =item *
13637:
1.1196 raeburn 13638: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13639: when viewing in course context.
1.1195 raeburn 13640:
1.1196 raeburn 13641: input: six args -- filename (decluttered), course number, course domain,
13642: url, symb (if registered) and group (if this is a
13643: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13644:
1.1196 raeburn 13645: output: array of five scalars --
1.1195 raeburn 13646: $cfile -- url for file editing if editable on current server
13647: $home -- homeserver of resource (i.e., for author if published,
13648: or course if uploaded.).
13649: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13650: $forceedit -- 1 if icon/link should be to go to edit mode
13651: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13652:
13653: =item *
13654:
13655: is_course_upload($file,$cnum,$cdom)
13656:
13657: Used in course context to determine if current file was uploaded to
13658: the course (i.e., would be found in /userfiles/docs on the course's
13659: homeserver.
13660:
13661: input: 3 args -- filename (decluttered), course number and course domain.
13662: output: boolean -- 1 if file was uploaded.
13663:
1.243 albertel 13664: =back
13665:
13666: =head2 Storing/Retreiving Data
13667:
13668: =over 4
1.191 harris41 13669:
13670: =item *
13671:
1.1269 raeburn 13672: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13673: permanently for this url; hashref needs to be given and should be a \%hashname;
13674: the remaining args aren't required and if they aren't passed or are '' they will
13675: be derived from the env (with the exception of $laststore, which is an
13676: optional arg used when a user's submission is stored in grading).
13677: $laststore is $version=$timestamp, where $version is the most recent version
13678: number retrieved for the corresponding $symb in the $namespace db file, and
13679: $timestamp is the timestamp for that transaction (UNIX time).
13680: $laststore is currently only passed when cstore() is called by
13681: structuretags::finalize_storage().
1.191 harris41 13682:
13683: =item *
13684:
1.1269 raeburn 13685: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13686: but uses critical subroutine
1.191 harris41 13687:
13688: =item *
13689:
1.243 albertel 13690: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13691: all args are optional
1.191 harris41 13692:
13693: =item *
13694:
1.717 albertel 13695: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13696: dumps the complete (or key matching regexp) namespace into a hash
13697: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13698: normally &store()ed into
13699:
13700: $range should be either an integer '100' (give me the first 100
13701: matching records)
13702: or be two integers sperated by a - with no spaces
13703: '30-50' (give me the 30th through the 50th matching
13704: records)
13705:
13706:
13707: =item *
13708:
1.1269 raeburn 13709: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13710: replaces a &store() version of data with a replacement set of data
13711: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 13712: reference. If $tolog is true, the transaction is logged in the courselog
13713: with an action=PUTSTORE.
1.717 albertel 13714:
13715: =item *
13716:
1.243 albertel 13717: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13718: works very similar to store/cstore, but all data is stored in a
13719: temporary location and can be reset using tmpreset, $storehash should
13720: be a hash reference, returns nothing on success
1.191 harris41 13721:
13722: =item *
13723:
1.243 albertel 13724: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13725: similar to restore, but all data is stored in a temporary location and
13726: can be reset using tmpreset. Returns a hash of values on success,
13727: error string otherwise.
1.191 harris41 13728:
13729: =item *
13730:
1.243 albertel 13731: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13732: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13733:
13734: =item *
13735:
1.243 albertel 13736: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13737: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13738:
13739: =item *
13740:
1.243 albertel 13741: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13742: namesp ($udom and $uname are optional)
1.191 harris41 13743:
13744: =item *
13745:
1.702 albertel 13746: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13747: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13748: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13749:
1.702 albertel 13750: $range should be either an integer '100' (give me the first 100
13751: matching records)
13752: or be two integers sperated by a - with no spaces
13753: '30-50' (give me the 30th through the 50th matching
13754: records)
1.449 matthew 13755: =item *
13756:
13757: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13758: $store can be a scalar, an array reference, or if the amount to be
13759: incremented is > 1, a hash reference.
13760:
13761: ($udom and $uname are optional)
1.191 harris41 13762:
13763: =item *
13764:
1.243 albertel 13765: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13766: ($udom and $uname are optional)
1.191 harris41 13767:
13768: =item *
13769:
1.243 albertel 13770: cput($namespace,$storehash,$udom,$uname) : critical put
13771: ($udom and $uname are optional)
1.191 harris41 13772:
13773: =item *
13774:
1.748 albertel 13775: newput($namespace,$storehash,$udom,$uname) :
13776:
13777: Attempts to store the items in the $storehash, but only if they don't
13778: currently exist, if this succeeds you can be certain that you have
13779: successfully created a new key value pair in the $namespace db.
13780:
13781:
13782: Args:
13783: $namespace: name of database to store values to
13784: $storehash: hashref to store to the db
13785: $udom: (optional) domain of user containing the db
13786: $uname: (optional) name of user caontaining the db
13787:
13788: Returns:
13789: 'ok' -> succeeded in storing all keys of $storehash
13790: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13791: least <key> already existed in the db (other
13792: requested keys may also already exist)
1.967 bisitz 13793: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13794: 'con_lost' -> unable to contact request server
13795: 'refused' -> action was not allowed by remote machine
13796:
13797:
13798: =item *
13799:
1.243 albertel 13800: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13801: reference filled in from namesp (encrypts the return communication)
13802: ($udom and $uname are optional)
1.191 harris41 13803:
13804: =item *
13805:
1.243 albertel 13806: log($udom,$name,$home,$message) : write to permanent log for user; use
13807: critical subroutine
13808:
1.806 raeburn 13809: =item *
13810:
1.860 raeburn 13811: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13812: array reference filled in from namespace found in domain level on either
13813: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13814:
13815: =item *
13816:
1.860 raeburn 13817: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13818: domain level either on specified domain server ($uhome) or primary domain
13819: server ($udom and $uhome are optional)
1.806 raeburn 13820:
1.943 raeburn 13821: =item *
13822:
1.1240 raeburn 13823: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13824: for: authentication, language, quotas, timezone, date locale, and portal URL in
13825: the target domain.
13826:
13827: May also include additional key => value pairs for the following groups:
13828:
13829: =over
13830:
13831: =item
13832: disk quotas (MB allocated by default to portfolios and authoring spaces).
13833:
13834: =over
13835:
13836: =item defaultquota, authorquota
13837:
13838: =back
13839:
13840: =item
13841: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13842: portfolio for users).
13843:
13844: =over
13845:
13846: =item
13847: aboutme, blog, webdav, portfolio
13848:
13849: =back
13850:
13851: =item
13852: requestcourses: ability to request courses, and how requests are processed.
13853:
13854: =over
13855:
13856: =item
1.1246 raeburn 13857: official, unofficial, community, textbook
1.1240 raeburn 13858:
13859: =back
13860:
13861: =item
13862: inststatus: types of institutional affiliation, and order in which they are displayed.
13863:
13864: =over
13865:
13866: =item
1.1256 raeburn 13867: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 13868:
13869: =back
13870:
13871: =item
13872: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13873: for course's uploaded content.
13874:
13875: =over
13876:
13877: =item
1.1246 raeburn 13878: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13879: communityquota, textbookquota
1.1240 raeburn 13880:
13881: =back
13882:
13883: =item
13884: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13885: on your servers.
13886:
13887: =over
13888:
13889: =item
13890: remotesessions, hostedsessions
13891:
13892: =back
13893:
13894: =back
13895:
13896: In cases where a domain coordinator has never used the "Set Domain Configuration"
13897: utility to create a configuration.db file on a domain's primary library server
13898: only the following domain defaults: auth_def, auth_arg_def, lang_def
13899: -- corresponding values are authentication type (internal, krb4, krb5,
13900: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13901: will be available. Values are retrieved from cache (if current), unless the
13902: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13903: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13904:
13905: Typical usage:
1.943 raeburn 13906:
1.1240 raeburn 13907: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13908:
1.243 albertel 13909: =back
13910:
13911: =head2 Network Status Functions
13912:
13913: =over 4
1.191 harris41 13914:
13915: =item *
13916:
1.1137 raeburn 13917: dirlist() : return directory list based on URI (first arg).
13918:
13919: Inputs: 1 required, 5 optional.
13920:
13921: =over
13922:
13923: =item
13924: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13925:
13926: =item
13927: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13928:
13929: =item
13930: $username - username of user/course to be listed. Extracted from $uri if absent.
13931:
13932: =item
13933: $getpropath - boolean: 1 if prepend path using &propath().
13934:
13935: =item
13936: $getuserdir - boolean: 1 if prepend path for "userfiles".
13937:
13938: =item
13939: $alternateRoot - path to prepend in place of path from $uri.
13940:
13941: =back
13942:
13943: Returns: Array of up to two items.
13944:
13945: =over
13946:
13947: a reference to an array of files/subdirectories
13948:
13949: =over
13950:
13951: Each element in the array of files/subdirectories is a & separated list of
13952: item name and the result of running stat on the item. If dirlist was requested
13953: for a file instead of a directory, the item name will be ''. For a directory
13954: listing, if the item is a metadata file, the element will end &N&M
13955: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13956: default copyright set (1).
13957:
13958: =back
13959:
13960: a scalar containing error condition (if encountered).
13961:
13962: =over
13963:
13964: =item
13965: no_host (no homeserver identified for $username:$domain).
13966:
13967: =item
13968: no_such_host (server contacted for listing not identified as valid host).
13969:
13970: =item
13971: con_lost (connection to remote server failed).
13972:
13973: =item
13974: refused (invalid $username:$domain received on lond side).
13975:
13976: =item
13977: no_such_dir (directory at specified path on lond side does not exist).
13978:
13979: =item
13980: empty (directory at specified path on lond side is empty).
13981:
13982: =over
13983:
13984: This is currently not encountered because the &ls3, &ls2,
13985: &ls (_handler) routines on the lond side do not filter out
13986: . and .. from a directory listing.
13987:
13988: =back
13989:
13990: =back
13991:
13992: =back
1.191 harris41 13993:
13994: =item *
13995:
1.243 albertel 13996: spareserver() : find server with least workload from spare.tab
13997:
1.986 foxr 13998:
13999: =item *
14000:
14001: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14002: if there is no corresponding loncapa host.
14003:
1.243 albertel 14004: =back
14005:
1.986 foxr 14006:
1.243 albertel 14007: =head2 Apache Request
14008:
14009: =over 4
1.191 harris41 14010:
14011: =item *
14012:
1.243 albertel 14013: ssi($url,%hash) : server side include, does a complete request cycle on url to
14014: localhost, posts hash
14015:
14016: =back
14017:
14018: =head2 Data to String to Data
14019:
14020: =over 4
1.191 harris41 14021:
14022: =item *
14023:
1.243 albertel 14024: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14025: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14026:
14027: =item *
14028:
1.243 albertel 14029: hashref2str($hashref) : convert a hashref into a string complete with
14030: escaping and '=' and '&' separators, supports elements that are
14031: arrayrefs and hashrefs
1.191 harris41 14032:
14033: =item *
14034:
1.243 albertel 14035: arrayref2str($arrayref) : convert an arrayref into a string complete
14036: with escaping and '&' separators, supports elements that are arrayrefs
14037: and hashrefs
1.191 harris41 14038:
14039: =item *
14040:
1.243 albertel 14041: str2hash($string) : convert string to hash using unescaping and
14042: splitting on '=' and '&', supports elements that are arrayrefs and
14043: hashrefs
1.191 harris41 14044:
14045: =item *
14046:
1.243 albertel 14047: str2array($string) : convert string to hash using unescaping and
14048: splitting on '&', supports elements that are arrayrefs and hashrefs
14049:
14050: =back
14051:
14052: =head2 Logging Routines
14053:
14054:
14055: These routines allow one to make log messages in the lonnet.log and
14056: lonnet.perm logfiles.
1.191 harris41 14057:
1.1119 foxr 14058: =over 4
14059:
1.191 harris41 14060: =item *
14061:
1.243 albertel 14062: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14063:
14064: =item *
14065:
1.243 albertel 14066: logthis() : append message to the normal lonnet.log file, it gets
14067: preiodically rolled over and deleted.
1.191 harris41 14068:
14069: =item *
14070:
1.243 albertel 14071: logperm() : append a permanent message to lonnet.perm.log, this log
14072: file never gets deleted by any automated portion of the system, only
14073: messages of critical importance should go in here.
14074:
1.1119 foxr 14075:
1.243 albertel 14076: =back
14077:
14078: =head2 General File Helper Routines
14079:
14080: =over 4
1.191 harris41 14081:
14082: =item *
14083:
1.481 raeburn 14084: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14085: (a) files in /uploaded
14086: (i) If a local copy of the file exists -
14087: compares modification date of local copy with last-modified date for
14088: definitive version stored on home server for course. If local copy is
14089: stale, requests a new version from the home server and stores it.
14090: If the original has been removed from the home server, then local copy
14091: is unlinked.
14092: (ii) If local copy does not exist -
14093: requests the file from the home server and stores it.
14094:
14095: If $caller is 'uploadrep':
14096: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14097: for request for files originally uploaded via DOCS.
14098: - returns 'ok' if fresh local copy now available, -1 otherwise.
14099:
14100: Otherwise:
14101: This indicates a call from the content generation phase of the request.
14102: - returns the entire contents of the file or -1.
14103:
14104: (b) files in /res
14105: - returns the entire contents of a file or -1;
14106: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14107:
1.712 albertel 14108:
14109: =item *
14110:
14111: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14112: reference
14113:
14114: returns either a stat() list of data about the file or an empty list
14115: if the file doesn't exist or couldn't find out about it (connection
14116: problems or user unknown)
14117:
1.191 harris41 14118: =item *
14119:
1.243 albertel 14120: filelocation($dir,$file) : returns file system location of a file
14121: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14122: directory that relative $file lookups are to looked in ($dir of /a/dir
14123: and a file of ../bob will become /a/bob)
1.191 harris41 14124:
14125: =item *
14126:
14127: hreflocation($dir,$file) : returns file system location or a URL; same as
14128: filelocation except for hrefs
14129:
14130: =item *
14131:
1.1261 raeburn 14132: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14133: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14134:
1.243 albertel 14135: =back
14136:
1.608 albertel 14137: =head2 Usererfile file routines (/uploaded*)
14138:
14139: =over 4
14140:
14141: =item *
14142:
14143: userfileupload(): main rotine for putting a file in a user or course's
14144: filespace, arguments are,
14145:
1.620 albertel 14146: formname - required - this is the name of the element in $env where the
1.608 albertel 14147: filename, and the contents of the file to create/modifed exist
1.620 albertel 14148: the filename is in $env{'form.'.$formname.'.filename'} and the
14149: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14150: context - if coursedoc, store the file in the course of the active role
14151: of the current user;
14152: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14153: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14154: subdir - required - subdirectory to put the file in under ../userfiles/
14155: if undefined, it will be placed in "unknown"
14156:
14157: (This routine calls clean_filename() to remove any dangerous
14158: characters from the filename, and then calls finuserfileupload() to
14159: complete the transaction)
14160:
14161: returns either the url of the uploaded file (/uploaded/....) if successful
14162: and /adm/notfound.html if unsuccessful
14163:
14164: =item *
14165:
14166: clean_filename(): routine for cleaing a filename up for storage in
14167: userfile space, argument is:
14168:
14169: filename - proposed filename
14170:
14171: returns: the new clean filename
14172:
14173: =item *
14174:
1.1090 raeburn 14175: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14176: userspace, probably shouldn't be called directly
14177:
14178: docuname: username or courseid of destination for the file
14179: docudom: domain of user/course of destination for the file
14180: formname: same as for userfileupload()
1.1090 raeburn 14181: fname: filename (including subdirectories) for the file
14182: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14183: allfiles: reference to hash used to store objects found by parser
14184: codebase: reference to hash used for codebases of java objects found by parser
14185: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14186: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14187: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14188: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14189: context: if 'overwrite', will move the uploaded file from its temporary location to
14190: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14191: mimetype: reference to scalar to accommodate mime type determined
14192: from File::MMagic if $parser = parse.
1.608 albertel 14193:
14194: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14195: and /adm/notfound.html if unsuccessful (or an error message if context
14196: was 'overwrite').
14197:
1.608 albertel 14198:
14199: =item *
14200:
14201: renameuserfile(): renames an existing userfile to a new name
14202:
14203: Args:
14204: docuname: username or courseid of destination for the file
14205: docudom: domain of user/course of destination for the file
14206: old: current file name (including any subdirs under userfiles)
14207: new: desired file name (including any subdirs under userfiles)
14208:
14209: =item *
14210:
14211: mkdiruserfile(): creates a directory is a userfiles dir
14212:
14213: Args:
14214: docuname: username or courseid of destination for the file
14215: docudom: domain of user/course of destination for the file
14216: dir: dir to create (including any subdirs under userfiles)
14217:
14218: =item *
14219:
14220: removeuserfile(): removes a file that exists in userfiles
14221:
14222: Args:
14223: docuname: username or courseid of destination for the file
14224: docudom: domain of user/course of destination for the file
14225: fname: filname to delete (including any subdirs under userfiles)
14226:
14227: =item *
14228:
14229: removeuploadedurl(): convience function for removeuserfile()
14230:
14231: Args:
14232: url: a full /uploaded/... url to delete
14233:
1.747 albertel 14234: =item *
14235:
14236: get_portfile_permissions():
14237: Args:
14238: domain: domain of user or course contain the portfolio files
14239: user: name of user or num of course contain the portfolio files
14240: Returns:
14241: hashref of a dump of the proper file_permissions.db
14242:
14243:
14244: =item *
14245:
14246: get_access_controls():
14247:
14248: Args:
14249: current_permissions: the hash ref returned from get_portfile_permissions()
14250: group: (optional) the group you want the files associated with
14251: file: (optional) the file you want access info on
14252:
14253: Returns:
1.749 raeburn 14254: a hash (keys are file names) of hashes containing
14255: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14256: values are XML containing access control settings (see below)
1.747 albertel 14257:
14258: Internal notes:
14259:
1.749 raeburn 14260: access controls are stored in file_permissions.db as key=value pairs.
14261: key -> path to file/file_name\0uniqueID:scope_end_start
14262: where scope -> public,guest,course,group,domains or users.
14263: end -> UNIX time for end of access (0 -> no end date)
14264: start -> UNIX time for start of access
14265:
14266: value -> XML description of access control
14267: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14268: <start></start>
14269: <end></end>
14270:
14271: <password></password> for scope type = guest
14272:
14273: <domain></domain> for scope type = course or group
14274: <number></number>
14275: <roles id="">
14276: <role></role>
14277: <access></access>
14278: <section></section>
14279: <group></group>
14280: </roles>
14281:
14282: <dom></dom> for scope type = domains
14283:
14284: <users> for scope type = users
14285: <user>
14286: <uname></uname>
14287: <udom></udom>
14288: </user>
14289: </users>
14290: </scope>
14291:
14292: Access data is also aggregated for each file in an additional key=value pair:
14293: key -> path to file/file_name\0accesscontrol
14294: value -> reference to hash
14295: hash contains key = value pairs
14296: where key = uniqueID:scope_end_start
14297: value = UNIX time record was last updated
14298:
14299: Used to improve speed of look-ups of access controls for each file.
14300:
14301: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14302:
1.1198 raeburn 14303: =item *
14304:
1.749 raeburn 14305: modify_access_controls():
14306:
14307: Modifies access controls for a portfolio file
14308: Args
14309: 1. file name
14310: 2. reference to hash of required changes,
14311: 3. domain
14312: 4. username
14313: where domain,username are the domain of the portfolio owner
14314: (either a user or a course)
14315:
14316: Returns:
14317: 1. result of additions or updates ('ok' or 'error', with error message).
14318: 2. result of deletions ('ok' or 'error', with error message).
14319: 3. reference to hash of any new or updated access controls.
14320: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14321: key = integer (inbound ID)
1.1198 raeburn 14322: value = uniqueID
14323:
14324: =item *
14325:
14326: get_timebased_id():
14327:
14328: Attempts to get a unique timestamp-based suffix for use with items added to a
14329: course via the Course Editor (e.g., folders, composite pages,
14330: group bulletin boards).
14331:
14332: Args: (first three required; six others optional)
14333:
14334: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14335: docssequence, or name of group
14336:
14337: 2. keyid (alphanumeric): name of temporary locking key in hash,
14338: e.g., num, boardids
14339:
14340: 3. namespace: name of gdbm file used to store suffixes already assigned;
14341: file will be named nohist_namespace.db
14342:
14343: 4. cdom: domain of course; default is current course domain from %env
14344:
14345: 5. cnum: course number; default is current course number from %env
14346:
14347: 6. idtype: set to concat if an additional digit is to be appended to the
14348: unix timestamp to form the suffix, if the plain timestamp is already
14349: in use. Default is to not do this, but simply increment the unix
14350: timestamp by 1 until a unique key is obtained.
14351:
14352: 7. who: holder of locking key; defaults to user:domain for user.
14353:
14354: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14355: retrying); default is 3.
14356:
14357: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14358:
14359: Returns:
14360:
14361: 1. suffix obtained (numeric)
14362:
14363: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14364:
14365: 3. error: contains (localized) error message if an error occurred.
14366:
1.747 albertel 14367:
1.608 albertel 14368: =back
14369:
1.243 albertel 14370: =head2 HTTP Helper Routines
14371:
14372: =over 4
14373:
1.191 harris41 14374: =item *
14375:
14376: escape() : unpack non-word characters into CGI-compatible hex codes
14377:
14378: =item *
14379:
14380: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14381:
1.243 albertel 14382: =back
14383:
14384: =head1 PRIVATE SUBROUTINES
14385:
14386: =head2 Underlying communication routines (Shouldn't call)
14387:
14388: =over 4
14389:
14390: =item *
14391:
14392: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14393:
14394: =item *
14395:
14396: reply() : uses subreply to send a message to remote machine, logs all failures
14397:
14398: =item *
14399:
14400: critical() : passes a critical message to another server; if cannot
14401: get through then place message in connection buffer directory and
14402: returns con_delayed, if incapable of saving message, returns
14403: con_failed
14404:
14405: =item *
14406:
14407: reconlonc() : tries to reconnect lonc client processes.
14408:
14409: =back
14410:
14411: =head2 Resource Access Logging
14412:
14413: =over 4
14414:
14415: =item *
14416:
14417: flushcourselogs() : flush (save) buffer logs and access logs
14418:
14419: =item *
14420:
14421: courselog($what) : save message for course in hash
14422:
14423: =item *
14424:
14425: courseacclog($what) : save message for course using &courselog(). Perform
14426: special processing for specific resource types (problems, exams, quizzes, etc).
14427:
1.191 harris41 14428: =item *
14429:
14430: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14431: as a PerlChildExitHandler
1.243 albertel 14432:
14433: =back
14434:
14435: =head2 Other
14436:
14437: =over 4
14438:
14439: =item *
14440:
14441: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14442:
14443: =back
14444:
14445: =cut
1.877 foxr 14446:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>