Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1282
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1282 ! raeburn 4: # $Id: lonnet.pm,v 1.1281 2015/04/13 16:30:32 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.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.550 foxr 108: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1187 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1187 raeburn 119: sub write_log {
1.1188 raeburn 120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1184 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 143: }
144: }
1.1 albertel 145:
1.163 harris41 146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
1.1 albertel 156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
1.448 albertel 161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
1.448 albertel 164: close($fh);
165: }
1.1 albertel 166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
1.448 albertel 174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
1.1 albertel 178: return 1;
179: }
180:
1.850 albertel 181: sub create_connection {
1.853 albertel 182: my ($hostname,$lonid) = @_;
1.851 albertel 183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
1.890 albertel 187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
1.983 raeburn 194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
1.850 albertel 208:
1.1106 raeburn 209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
1.993 raeburn 232: sub get_server_loncaparev {
1.1073 raeburn 233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
1.1073 raeburn 248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
1.1082 raeburn 267: $ua->timeout(4);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
1.1241 raeburn 359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 364: return $response;
365: }
366:
1.1 albertel 367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
1.838 albertel 370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
378: sleep(1);
379: }
380: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 381: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 382: #
1.550 foxr 383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
1.869 albertel 391: if ($client) {
1.550 foxr 392: last; # Connected!
1.850 albertel 393: } else {
1.853 albertel 394: &create_connection(&hostname($server),$server);
1.550 foxr 395: }
1.850 albertel 396: sleep(1); # Try again later if failed connection.
1.550 foxr 397: }
398: my $answer;
399: if ($client) {
1.704 albertel 400: print $client "sethost:$server:$cmd\n";
1.550 foxr 401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
1.1 albertel 407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
1.838 albertel 412: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 413: my $answer=subreply($cmd,$server);
1.65 www 414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 415: &logthis("<font color=\"blue\">WARNING:".
1.12 www 416: " $cmd to $server returned $answer</font>");
417: }
1.1 albertel 418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
1.891 albertel 424: my ($lonid) = @_;
425: my $hostname = &hostname($lonid);
426: if ($lonid) {
427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
1.836 www 442: &logthis("Trying to reconnect lonc");
1.1 albertel 443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 444: if (open(my $fh,"<$loncfile")) {
1.1 albertel 445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
1.836 www 451: } else {
1.12 www 452: &logthis(
1.672 albertel 453: "<font color=\"blue\">WARNING:".
1.12 www 454: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 455: }
456: } else {
1.836 www 457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
1.12 www 462:
1.1 albertel 463: sub critical {
464: my ($cmd,$server)=@_;
1.838 albertel 465: unless (&hostname($server)) {
1.672 albertel 466: &logthis("<font color=\"blue\">WARNING:".
1.89 www 467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
1.1 albertel 470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 473: my $answer=reply($cmd,$server);
1.1 albertel 474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
1.5 www 477: $middlename=substr($middlename,0,16);
1.1 albertel 478: $middlename=~s/\W//g;
479: my $dfilename=
1.305 www 480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
1.1 albertel 482: {
1.448 albertel 483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
1.1 albertel 488: }
489: sleep 2;
490: my $wcmd='';
491: {
1.448 albertel 492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
1.1 albertel 497: }
498: chomp($wcmd);
1.7 www 499: if ($wcmd eq $cmd) {
1.672 albertel 500: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 501: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
1.672 albertel 505: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 506: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
1.405 albertel 513: }
514:
1.755 albertel 515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
1.756 albertel 519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
1.783 albertel 526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
1.917 albertel 530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
1.915 albertel 532: return 0;
533: }
1.783 albertel 534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
1.786 albertel 540: if ($line !~ m/=/) {
541: return 0;
542: }
1.783 albertel 543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
1.786 albertel 554: return 1;
1.783 albertel 555: }
556:
1.374 www 557: # ------------------------------------------- Transfer profile into environment
1.780 albertel 558: my $env_loaded;
559: sub transfer_profile_to_env {
1.788 albertel 560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
1.374 www 562:
1.720 albertel 563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
1.786 albertel 570: my $convert;
571: {
1.917 albertel 572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
1.915 albertel 574: return;
575: }
1.786 albertel 576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
1.374 www 589: }
1.783 albertel 590:
1.786 albertel 591: my %remove;
1.783 albertel 592: while ( my $envname = each(%env) ) {
1.433 matthew 593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
1.783 albertel 595: $remove{$key}++;
1.433 matthew 596: }
597: }
598: }
1.783 albertel 599:
1.619 albertel 600: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 601: $env_loaded=1;
1.783 albertel 602: foreach my $expired_key (keys(%remove)) {
1.433 matthew 603: &delenv($expired_key);
1.374 www 604: }
1.1 albertel 605: }
606:
1.916 albertel 607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
1.1245 raeburn 609: my ($r,$name,$userhashref) = @_;
1.916 albertel 610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
1.916 albertel 615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
1.916 albertel 624: return undef if (!-e "$lonidsdir/$handle.id");
625:
1.917 albertel 626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
1.916 albertel 628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
1.1245 raeburn 640:
641: if (ref($userhashref) eq 'HASH') {
642: $userhashref->{'name'} = $disk_env{'user.name'};
643: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 644: }
1.1245 raeburn 645:
1.916 albertel 646: return $handle;
647: }
648:
1.830 albertel 649: sub timed_flock {
650: my ($file,$lock_type) = @_;
651: my $failed=0;
652: eval {
653: local $SIG{__DIE__}='DEFAULT';
654: local $SIG{ALRM}=sub {
655: $failed=1;
656: die("failed lock");
657: };
658: alarm(13);
659: flock($file,$lock_type);
660: alarm(0);
661: };
662: if ($failed) {
663: return undef;
664: } else {
665: return 1;
666: }
667: }
668:
1.5 www 669: # ---------------------------------------------------------- Append Environment
670:
671: sub appenv {
1.949 raeburn 672: my ($newenv,$roles) = @_;
673: if (ref($newenv) eq 'HASH') {
674: foreach my $key (keys(%{$newenv})) {
675: my $refused = 0;
676: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
677: $refused = 1;
678: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 679: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 680: if (grep(/^\Q$role\E$/,@{$roles})) {
681: $refused = 0;
682: }
683: }
684: }
685: if ($refused) {
686: &logthis("<font color=\"blue\">WARNING: ".
687: "Attempt to modify environment ".$key." to ".$newenv->{$key}
688: .'</font>');
689: delete($newenv->{$key});
690: } else {
691: $env{$key}=$newenv->{$key};
692: }
693: }
694: my $opened = open(my $env_file,'+<',$env{'user.environment'});
695: if ($opened
696: && &timed_flock($env_file,LOCK_EX)
697: &&
698: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
699: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
700: while (my ($key,$value) = each(%{$newenv})) {
701: $disk_env{$key} = $value;
702: }
703: untie(%disk_env);
1.35 www 704: }
1.191 harris41 705: }
1.56 www 706: return 'ok';
707: }
708: # ----------------------------------------------------- Delete from Environment
709:
710: sub delenv {
1.1104 raeburn 711: my ($delthis,$regexp,$roles) = @_;
712: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
713: my $refused = 1;
714: if (ref($roles) eq 'ARRAY') {
715: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
716: if (grep(/^\Q$role\E$/,@{$roles})) {
717: $refused = 0;
718: }
719: }
720: if ($refused) {
721: &logthis("<font color=\"blue\">WARNING: ".
722: "Attempt to delete from environment ".$delthis);
723: return 'error';
724: }
1.56 www 725: }
1.917 albertel 726: my $opened = open(my $env_file,'+<',$env{'user.environment'});
727: if ($opened
1.915 albertel 728: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 729: &&
730: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
731: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 732: foreach my $key (keys(%disk_env)) {
1.987 raeburn 733: if ($regexp) {
734: if ($key=~/^$delthis/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: } else {
739: if ($key=~/^\Q$delthis\E/) {
740: delete($env{$key});
741: delete($disk_env{$key});
742: }
743: }
1.448 albertel 744: }
1.783 albertel 745: untie(%disk_env);
1.5 www 746: }
747: return 'ok';
1.369 albertel 748: }
749:
1.790 albertel 750: sub get_env_multiple {
751: my ($name) = @_;
752: my @values;
753: if (defined($env{$name})) {
754: # exists is it an array
755: if (ref($env{$name})) {
756: @values=@{ $env{$name} };
757: } else {
758: $values[0]=$env{$name};
759: }
760: }
761: return(@values);
762: }
763:
1.958 www 764: # ------------------------------------------------------------------- Locking
765:
766: sub set_lock {
767: my ($text)=@_;
768: $locknum++;
769: my $id=$$.'-'.$locknum;
770: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
771: 'session.lock.'.$id => $text});
772: return $id;
773: }
774:
775: sub get_locks {
776: my $num=0;
777: my %texts=();
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if ($lock=~/\w/) {
780: $num++;
781: $texts{$lock}=$env{'session.lock.'.$lock};
782: }
783: }
784: return ($num,%texts);
785: }
786:
787: sub remove_lock {
788: my ($id)=@_;
789: my $newlocks='';
790: foreach my $lock (split(/\,/,$env{'session.locks'})) {
791: if (($lock=~/\w/) && ($lock ne $id)) {
792: $newlocks.=','.$lock;
793: }
794: }
795: &appenv({'session.locks' => $newlocks});
796: &delenv('session.lock.'.$id);
797: }
798:
799: sub remove_all_locks {
800: my $activelocks=$env{'session.locks'};
801: foreach my $lock (split(/\,/,$env{'session.locks'})) {
802: if ($lock=~/\w/) {
803: &remove_lock($lock);
804: }
805: }
806: }
807:
808:
1.369 albertel 809: # ------------------------------------------ Find out current server userload
810: sub userload {
811: my $numusers=0;
812: {
813: opendir(LONIDS,$perlvar{'lonIDsDir'});
814: my $filename;
815: my $curtime=time;
816: while ($filename=readdir(LONIDS)) {
1.925 albertel 817: next if ($filename eq '.' || $filename eq '..');
818: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 819: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 820: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 821: }
822: closedir(LONIDS);
823: }
824: my $userloadpercent=0;
825: my $maxuserload=$perlvar{'lonUserLoadLim'};
826: if ($maxuserload) {
1.371 albertel 827: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 828: }
1.372 albertel 829: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 830: return $userloadpercent;
1.283 www 831: }
832:
1.1 albertel 833: # ------------------------------ Find server with least workload from spare.tab
1.11 www 834:
1.1 albertel 835: sub spareserver {
1.1083 raeburn 836: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 837: my $spare_server;
1.370 albertel 838: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 839: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
840: : $userloadpercent;
1.1083 raeburn 841: my ($uint_dom,$remotesessions);
842: if (($udom ne '') && (&domain($udom) ne '')) {
843: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
844: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
845: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
846: $remotesessions = $udomdefaults{'remotesessions'};
847: }
1.1123 raeburn 848: my $spareshash = &this_host_spares($udom);
849: if (ref($spareshash) eq 'HASH') {
850: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 852: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
853: $try_server));
1.1123 raeburn 854: ($spare_server, $lowest_load) =
855: &compare_server_load($try_server, $spare_server, $lowest_load);
856: }
1.1083 raeburn 857: }
1.784 albertel 858:
1.1123 raeburn 859: my $found_server = ($spare_server ne '' && $lowest_load < 100);
860:
861: if (!$found_server) {
862: if (ref($spareshash->{'default'}) eq 'ARRAY') {
863: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 864: next unless (&spare_can_host($udom,$uint_dom,
865: $remotesessions,$try_server));
1.1123 raeburn 866: ($spare_server, $lowest_load) =
867: &compare_server_load($try_server, $spare_server, $lowest_load);
868: }
869: }
870: }
1.784 albertel 871: }
872:
873: if (!$want_server_name) {
1.968 raeburn 874: my $protocol = 'http';
875: if ($protocol{$spare_server} eq 'https') {
876: $protocol = $protocol{$spare_server};
877: }
1.1001 raeburn 878: if (defined($spare_server)) {
879: my $hostname = &hostname($spare_server);
1.1083 raeburn 880: if (defined($hostname)) {
1.1001 raeburn 881: $spare_server = $protocol.'://'.$hostname;
882: }
883: }
1.784 albertel 884: }
885: return $spare_server;
886: }
887:
888: sub compare_server_load {
1.1253 raeburn 889: my ($try_server, $spare_server, $lowest_load, $required) = @_;
890:
891: if ($required) {
892: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
893: my $remoterev = &get_server_loncaparev(undef,$try_server);
894: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
895: if (($major eq '' && $minor eq '') ||
896: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
897: return ($spare_server,$lowest_load);
898: }
899: }
1.784 albertel 900:
901: my $loadans = &reply('load', $try_server);
902: my $userloadans = &reply('userload',$try_server);
903:
904: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 905: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 906: }
907:
908: my $load;
909: if ($loadans =~ /\d/) {
910: if ($userloadans =~ /\d/) {
911: #both are numbers, pick the bigger one
912: $load = ($loadans > $userloadans) ? $loadans
913: : $userloadans;
1.411 albertel 914: } else {
1.784 albertel 915: $load = $loadans;
1.411 albertel 916: }
1.784 albertel 917: } else {
918: $load = $userloadans;
919: }
920:
921: if (($load =~ /\d/) && ($load < $lowest_load)) {
922: $spare_server = $try_server;
923: $lowest_load = $load;
1.370 albertel 924: }
1.784 albertel 925: return ($spare_server,$lowest_load);
1.202 matthew 926: }
1.914 albertel 927:
928: # --------------------------- ask offload servers if user already has a session
929: sub find_existing_session {
930: my ($udom,$uname) = @_;
1.1123 raeburn 931: my $spareshash = &this_host_spares($udom);
932: if (ref($spareshash) eq 'HASH') {
933: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'primary'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
938: if (ref($spareshash->{'default'}) eq 'ARRAY') {
939: foreach my $try_server (@{ $spareshash->{'default'} }) {
940: return $try_server if (&has_user_session($try_server, $udom, $uname));
941: }
942: }
1.914 albertel 943: }
944: return;
945: }
946:
947: # -------------------------------- ask if server already has a session for user
948: sub has_user_session {
949: my ($lonid,$udom,$uname) = @_;
950: my $result = &reply(join(':','userhassession',
951: map {&escape($_)} ($udom,$uname)),$lonid);
952: return 1 if ($result eq 'ok');
953:
954: return 0;
955: }
956:
1.1076 raeburn 957: # --------- determine least loaded server in a user's domain which allows login
958:
959: sub choose_server {
1.1259 raeburn 960: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 961: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 962: my %servers = &get_servers($udom);
1.1076 raeburn 963: my $lowest_load = 30000;
1.1259 raeburn 964: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
965: if ($skiploadbal) {
966: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
967: unless (defined($cached)) {
968: my $cachetime = 60*60*24;
969: my %domconfig =
970: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
971: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
972: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
973: $cachetime);
974: }
975: }
976: }
1.1076 raeburn 977: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 978: if ($skiploadbal) {
979: if (ref($balancers) eq 'HASH') {
980: next if (exists($balancers->{$lonhost}));
981: }
982: }
1.1115 raeburn 983: my $loginvia;
984: if ($checkloginvia) {
985: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 986: if ($loginvia) {
987: my ($server,$path) = split(/:/,$loginvia);
988: ($login_host, $lowest_load) =
1.1253 raeburn 989: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 990: if ($login_host eq $server) {
991: $portal_path = $path;
1.1151 raeburn 992: $isredirect = 1;
1.1116 raeburn 993: }
994: } else {
995: ($login_host, $lowest_load) =
1.1253 raeburn 996: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 997: if ($login_host eq $lonhost) {
998: $portal_path = '';
1.1151 raeburn 999: $isredirect = '';
1.1116 raeburn 1000: }
1001: }
1002: } else {
1.1076 raeburn 1003: ($login_host, $lowest_load) =
1.1253 raeburn 1004: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1005: }
1006: }
1007: if ($login_host ne '') {
1.1116 raeburn 1008: $hostname = &hostname($login_host);
1.1076 raeburn 1009: }
1.1151 raeburn 1010: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1011: }
1012:
1.202 matthew 1013: # --------------------------------------------- Try to change a user's password
1014:
1015: sub changepass {
1.799 raeburn 1016: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1017: $currentpass = &escape($currentpass);
1018: $newpass = &escape($newpass);
1.1030 raeburn 1019: my $lonhost = $perlvar{'lonHostID'};
1020: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1021: $server);
1022: if (! $answer) {
1023: &logthis("No reply on password change request to $server ".
1024: "by $uname in domain $udom.");
1025: } elsif ($answer =~ "^ok") {
1026: &logthis("$uname in $udom successfully changed their password ".
1027: "on $server.");
1028: } elsif ($answer =~ "^pwchange_failure") {
1029: &logthis("$uname in $udom was unable to change their password ".
1030: "on $server. The action was blocked by either lcpasswd ".
1031: "or pwchange");
1032: } elsif ($answer =~ "^non_authorized") {
1033: &logthis("$uname in $udom did not get their password correct when ".
1034: "attempting to change it on $server.");
1035: } elsif ($answer =~ "^auth_mode_error") {
1036: &logthis("$uname in $udom attempted to change their password despite ".
1037: "not being locally or internally authenticated on $server.");
1038: } elsif ($answer =~ "^unknown_user") {
1039: &logthis("$uname in $udom attempted to change their password ".
1040: "on $server but were unable to because $server is not ".
1041: "their home server.");
1042: } elsif ($answer =~ "^refused") {
1043: &logthis("$server refused to change $uname in $udom password because ".
1044: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1045: } elsif ($answer =~ "invalid_client") {
1046: &logthis("$server refused to change $uname in $udom password because ".
1047: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1048: }
1049: return $answer;
1.1 albertel 1050: }
1051:
1.169 harris41 1052: # ----------------------- Try to determine user's current authentication scheme
1053:
1054: sub queryauthenticate {
1055: my ($uname,$udom)=@_;
1.456 albertel 1056: my $uhome=&homeserver($uname,$udom);
1057: if (!$uhome) {
1058: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1059: return 'no_host';
1060: }
1061: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1062: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1063: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1064: }
1.456 albertel 1065: return $answer;
1.169 harris41 1066: }
1067:
1.1 albertel 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1069:
1.1 albertel 1070: sub authenticate {
1.1073 raeburn 1071: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1072: $upass=&escape($upass);
1073: $uname= &LONCAPA::clean_username($uname);
1.836 www 1074: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1075: my $newhome;
1.836 www 1076: if ((!$uhome) || ($uhome eq 'no_host')) {
1077: # Maybe the machine was offline and only re-appeared again recently?
1078: &reconlonc();
1079: # One more
1.952 raeburn 1080: $uhome=&homeserver($uname,$udom,1);
1081: if (($uhome eq 'no_host') && $checkdefauth) {
1082: if (defined(&domain($udom,'primary'))) {
1083: $newhome=&domain($udom,'primary');
1084: }
1085: if ($newhome ne '') {
1086: $uhome = $newhome;
1087: }
1088: }
1.836 www 1089: if ((!$uhome) || ($uhome eq 'no_host')) {
1090: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1091: return 'no_host';
1092: }
1.1 albertel 1093: }
1.1073 raeburn 1094: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1095: if ($answer eq 'authorized') {
1.952 raeburn 1096: if ($newhome) {
1097: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1098: return 'no_account_on_host';
1099: } else {
1100: &logthis("User $uname at $udom authorized by $uhome");
1101: return $uhome;
1102: }
1.471 albertel 1103: }
1104: if ($answer eq 'non_authorized') {
1105: &logthis("User $uname at $udom rejected by $uhome");
1106: return 'no_host';
1.9 www 1107: }
1.471 albertel 1108: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1109: return 'no_host';
1110: }
1111:
1.1073 raeburn 1112: sub can_host_session {
1.1074 raeburn 1113: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1114: my $canhost = 1;
1.1074 raeburn 1115: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1116: if (ref($remotesessions) eq 'HASH') {
1117: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1118: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1119: $canhost = 0;
1120: } else {
1121: $canhost = 1;
1122: }
1123: }
1124: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1125: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1126: $canhost = 1;
1127: } else {
1128: $canhost = 0;
1129: }
1130: }
1131: if ($canhost) {
1132: if ($remotesessions->{'version'} ne '') {
1133: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1134: if ($reqmajor ne '' && $reqminor ne '') {
1135: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1136: my $major = $1;
1137: my $minor = $2;
1138: if (($major < $reqmajor ) ||
1139: (($major == $reqmajor) && ($minor < $reqminor))) {
1140: $canhost = 0;
1141: }
1142: } else {
1143: $canhost = 0;
1144: }
1145: }
1146: }
1147: }
1148: }
1149: if ($canhost) {
1150: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1151: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1152: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1153: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1154: if (($uint_dom ne '') &&
1155: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1156: $canhost = 0;
1157: } else {
1158: $canhost = 1;
1159: }
1160: }
1161: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1162: if (($uint_dom ne '') &&
1163: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1164: $canhost = 1;
1165: } else {
1166: $canhost = 0;
1167: }
1168: }
1169: }
1170: }
1171: return $canhost;
1172: }
1173:
1.1083 raeburn 1174: sub spare_can_host {
1175: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1176: my $canhost=1;
1.1279 raeburn 1177: my $try_server_hostname = &hostname($try_server);
1178: my $serverhomeID = &get_server_homeID($try_server_hostname);
1179: my $serverhomedom = &host_domain($serverhomeID);
1180: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1181: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1182: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1183: $canhost = 0;
1184: }
1185: }
1186: if (($canhost) && ($uint_dom)) {
1187: my @intdoms;
1188: my $internet_names = &get_internet_names($try_server);
1189: if (ref($internet_names) eq 'ARRAY') {
1190: @intdoms = @{$internet_names};
1191: }
1192: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1193: my $remoterev = &get_server_loncaparev(undef,$try_server);
1194: $canhost = &can_host_session($udom,$try_server,$remoterev,
1195: $remotesessions,
1196: $defdomdefaults{'hostedsessions'});
1197: }
1.1083 raeburn 1198: }
1199: return $canhost;
1200: }
1201:
1.1123 raeburn 1202: sub this_host_spares {
1203: my ($dom) = @_;
1.1126 raeburn 1204: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1205: my @hosts = ¤t_machine_ids();
1206: foreach my $lonhost (@hosts) {
1207: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1208: $dom_in_use = $dom;
1209: $lonhost_in_use = $lonhost;
1.1123 raeburn 1210: last;
1211: }
1212: }
1.1126 raeburn 1213: if ($dom_in_use ne '') {
1214: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1215: }
1216: if (ref($result) ne 'HASH') {
1217: $lonhost_in_use = $perlvar{'lonHostID'};
1218: $dom_in_use = &host_domain($lonhost_in_use);
1219: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1220: if (ref($result) ne 'HASH') {
1221: $result = \%spareid;
1222: }
1223: }
1224: return $result;
1225: }
1226:
1227: sub spares_for_offload {
1228: my ($dom_in_use,$lonhost_in_use) = @_;
1229: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1230: if (defined($cached)) {
1231: return $result;
1232: } else {
1.1126 raeburn 1233: my $cachetime = 60*60*24;
1234: my %domconfig =
1235: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1236: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1237: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1238: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1239: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1240: }
1241: }
1242: }
1243: }
1.1126 raeburn 1244: return;
1.1123 raeburn 1245: }
1246:
1.1129 raeburn 1247: sub get_lonbalancer_config {
1248: my ($servers) = @_;
1249: my ($currbalancer,$currtargets);
1250: if (ref($servers) eq 'HASH') {
1251: foreach my $server (keys(%{$servers})) {
1252: my %what = (
1253: spareid => 1,
1254: perlvar => 1,
1255: );
1256: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1257: if ($result eq 'ok') {
1258: if (ref($returnhash) eq 'HASH') {
1259: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1260: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1261: $currbalancer = $server;
1262: $currtargets = {};
1263: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1264: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1265: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1266: }
1267: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1268: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1269: }
1270: }
1271: last;
1272: }
1273: }
1274: }
1275: }
1276: }
1277: }
1278: return ($currbalancer,$currtargets);
1279: }
1280:
1281: sub check_loadbalancing {
1282: my ($uname,$udom) = @_;
1.1191 raeburn 1283: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1284: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1285: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1286: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1287: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1288: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1289: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1290: my $serverhomedom = &host_domain($lonhost);
1291:
1292: my $cachetime = 60*60*24;
1293:
1294: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1295: $dom_in_use = $udom;
1296: $homeintdom = 1;
1297: } else {
1298: $dom_in_use = $serverhomedom;
1299: }
1300: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1301: unless (defined($cached)) {
1302: my %domconfig =
1303: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1304: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1305: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1306: }
1307: }
1308: if (ref($result) eq 'HASH') {
1.1191 raeburn 1309: ($is_balancer,$currtargets,$currrules) =
1310: &check_balancer_result($result,@hosts);
1.1129 raeburn 1311: if ($is_balancer) {
1312: if (ref($currrules) eq 'HASH') {
1313: if ($homeintdom) {
1314: if ($uname ne '') {
1315: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1316: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1317: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1318: $rule_in_effect = $currrules->{'_LC_author'};
1319: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1320: $rule_in_effect = $currrules->{'_LC_adv'}
1321: }
1322: }
1323: if ($rule_in_effect eq '') {
1324: my %userenv = &userenvironment($udom,$uname,'inststatus');
1325: if ($userenv{'inststatus'} ne '') {
1326: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1327: my ($othertitle,$usertypes,$types) =
1328: &Apache::loncommon::sorted_inst_types($udom);
1329: if (ref($types) eq 'ARRAY') {
1330: foreach my $type (@{$types}) {
1331: if (grep(/^\Q$type\E$/,@statuses)) {
1332: if (exists($currrules->{$type})) {
1333: $rule_in_effect = $currrules->{$type};
1334: }
1335: }
1336: }
1337: }
1338: } else {
1339: if (exists($currrules->{'default'})) {
1340: $rule_in_effect = $currrules->{'default'};
1341: }
1342: }
1343: }
1344: } else {
1345: if (exists($currrules->{'default'})) {
1346: $rule_in_effect = $currrules->{'default'};
1347: }
1348: }
1349: } else {
1350: if ($currrules->{'_LC_external'} ne '') {
1351: $rule_in_effect = $currrules->{'_LC_external'};
1352: }
1353: }
1354: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1355: $uname,$udom);
1356: }
1357: }
1358: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1359: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1360: unless (defined($cached)) {
1361: my %domconfig =
1362: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1363: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1364: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1365: }
1366: }
1367: if (ref($result) eq 'HASH') {
1.1191 raeburn 1368: ($is_balancer,$currtargets,$currrules) =
1369: &check_balancer_result($result,@hosts);
1370: if ($is_balancer) {
1.1129 raeburn 1371: if (ref($currrules) eq 'HASH') {
1372: if ($currrules->{'_LC_internetdom'} ne '') {
1373: $rule_in_effect = $currrules->{'_LC_internetdom'};
1374: }
1375: }
1376: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1377: $uname,$udom);
1378: }
1379: } else {
1380: if ($perlvar{'lonBalancer'} eq 'yes') {
1381: $is_balancer = 1;
1382: $offloadto = &this_host_spares($dom_in_use);
1383: }
1384: }
1385: } else {
1386: if ($perlvar{'lonBalancer'} eq 'yes') {
1387: $is_balancer = 1;
1388: $offloadto = &this_host_spares($dom_in_use);
1389: }
1390: }
1.1176 raeburn 1391: if ($is_balancer) {
1392: my $lowest_load = 30000;
1393: if (ref($offloadto) eq 'HASH') {
1394: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1395: foreach my $try_server (@{$offloadto->{'primary'}}) {
1396: ($otherserver,$lowest_load) =
1397: &compare_server_load($try_server,$otherserver,$lowest_load);
1398: }
1.1129 raeburn 1399: }
1.1176 raeburn 1400: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1401:
1.1176 raeburn 1402: if (!$found_server) {
1403: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1404: foreach my $try_server (@{$offloadto->{'default'}}) {
1405: ($otherserver,$lowest_load) =
1406: &compare_server_load($try_server,$otherserver,$lowest_load);
1407: }
1408: }
1409: }
1410: } elsif (ref($offloadto) eq 'ARRAY') {
1411: if (@{$offloadto} == 1) {
1412: $otherserver = $offloadto->[0];
1413: } elsif (@{$offloadto} > 1) {
1414: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1415: ($otherserver,$lowest_load) =
1416: &compare_server_load($try_server,$otherserver,$lowest_load);
1417: }
1418: }
1419: }
1.1176 raeburn 1420: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1421: $is_balancer = 0;
1422: if ($uname ne '' && $udom ne '') {
1423: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1424:
1425: &appenv({'user.loadbalexempt' => $lonhost,
1426: 'user.loadbalcheck.time' => time});
1427: }
1.1129 raeburn 1428: }
1429: }
1430: }
1431: return ($is_balancer,$otherserver);
1432: }
1433:
1.1191 raeburn 1434: sub check_balancer_result {
1435: my ($result,@hosts) = @_;
1436: my ($is_balancer,$currtargets,$currrules);
1437: if (ref($result) eq 'HASH') {
1438: if ($result->{'lonhost'} ne '') {
1439: my $currbalancer = $result->{'lonhost'};
1440: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1441: $is_balancer = 1;
1442: $currtargets = $result->{'targets'};
1443: $currrules = $result->{'rules'};
1444: }
1445: } else {
1446: foreach my $key (keys(%{$result})) {
1447: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1448: (ref($result->{$key}) eq 'HASH')) {
1449: $is_balancer = 1;
1450: $currrules = $result->{$key}{'rules'};
1451: $currtargets = $result->{$key}{'targets'};
1452: last;
1453: }
1454: }
1455: }
1456: }
1457: return ($is_balancer,$currtargets,$currrules);
1458: }
1459:
1.1129 raeburn 1460: sub get_loadbalancer_targets {
1461: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1462: my $offloadto;
1.1175 raeburn 1463: if ($rule_in_effect eq 'none') {
1464: return [$perlvar{'lonHostID'}];
1465: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1466: $offloadto = $currtargets;
1467: } else {
1468: if ($rule_in_effect eq 'homeserver') {
1469: my $homeserver = &homeserver($uname,$udom);
1470: if ($homeserver ne 'no_host') {
1471: $offloadto = [$homeserver];
1472: }
1473: } elsif ($rule_in_effect eq 'externalbalancer') {
1474: my %domconfig =
1475: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1476: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1477: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1478: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1479: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1480: }
1481: }
1482: } else {
1.1178 raeburn 1483: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1484: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1485: if (&hostname($remotebalancer) ne '') {
1486: $offloadto = [$remotebalancer];
1487: }
1488: }
1489: } elsif (&hostname($rule_in_effect) ne '') {
1490: $offloadto = [$rule_in_effect];
1491: }
1492: }
1493: return $offloadto;
1494: }
1495:
1.1127 raeburn 1496: sub internet_dom_servers {
1497: my ($dom) = @_;
1498: my (%uniqservers,%servers);
1499: my $primaryserver = &hostname(&domain($dom,'primary'));
1500: my @machinedoms = &machine_domains($primaryserver);
1501: foreach my $mdom (@machinedoms) {
1502: my %currservers = %servers;
1503: my %server = &get_servers($mdom);
1504: %servers = (%currservers,%server);
1505: }
1506: my %by_hostname;
1507: foreach my $id (keys(%servers)) {
1508: push(@{$by_hostname{$servers{$id}}},$id);
1509: }
1510: foreach my $hostname (sort(keys(%by_hostname))) {
1511: if (@{$by_hostname{$hostname}} > 1) {
1512: my $match = 0;
1513: foreach my $id (@{$by_hostname{$hostname}}) {
1514: if (&host_domain($id) eq $dom) {
1515: $uniqservers{$id} = $hostname;
1516: $match = 1;
1517: }
1518: }
1519: unless ($match) {
1520: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1521: }
1522: } else {
1523: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1524: }
1525: }
1526: return %uniqservers;
1527: }
1528:
1.1 albertel 1529: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1530:
1.599 albertel 1531: my %homecache;
1.1 albertel 1532: sub homeserver {
1.230 stredwic 1533: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1534: my $index="$uname:$udom";
1.426 albertel 1535:
1.599 albertel 1536: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1537:
1538: my %servers = &get_servers($udom,'library');
1539: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1540: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1541: exists($badServerCache{$tryserver}));
1.841 albertel 1542:
1543: my $answer=reply("home:$udom:$uname",$tryserver);
1544: if ($answer eq 'found') {
1545: delete($badServerCache{$tryserver});
1546: return $homecache{$index}=$tryserver;
1547: } elsif ($answer eq 'no_host') {
1548: $badServerCache{$tryserver}=1;
1549: }
1.1 albertel 1550: }
1551: return 'no_host';
1.70 www 1552: }
1553:
1554: # ------------------------------------- Find the usernames behind a list of IDs
1555:
1556: sub idget {
1557: my ($udom,@ids)=@_;
1558: my %returnhash=();
1559:
1.841 albertel 1560: my %servers = &get_servers($udom,'library');
1561: foreach my $tryserver (keys(%servers)) {
1562: my $idlist=join('&',@ids);
1563: $idlist=~tr/A-Z/a-z/;
1564: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1565: my @answer=();
1566: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1567: @answer=split(/\&/,$reply);
1568: } ;
1569: my $i;
1570: for ($i=0;$i<=$#ids;$i++) {
1571: if ($answer[$i]) {
1572: $returnhash{$ids[$i]}=$answer[$i];
1573: }
1574: }
1575: }
1.70 www 1576: return %returnhash;
1577: }
1578:
1579: # ------------------------------------- Find the IDs behind a list of usernames
1580:
1581: sub idrget {
1582: my ($udom,@unames)=@_;
1583: my %returnhash=();
1.800 albertel 1584: foreach my $uname (@unames) {
1585: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1586: }
1.70 www 1587: return %returnhash;
1588: }
1589:
1590: # ------------------------------- Store away a list of names and associated IDs
1591:
1592: sub idput {
1593: my ($udom,%ids)=@_;
1594: my %servers=();
1.800 albertel 1595: foreach my $uname (keys(%ids)) {
1596: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1597: my $uhom=&homeserver($uname,$udom);
1.70 www 1598: if ($uhom ne 'no_host') {
1.800 albertel 1599: my $id=&escape($ids{$uname});
1.70 www 1600: $id=~tr/A-Z/a-z/;
1.800 albertel 1601: my $esc_unam=&escape($uname);
1.70 www 1602: if ($servers{$uhom}) {
1.800 albertel 1603: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1604: } else {
1.800 albertel 1605: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1606: }
1607: }
1.191 harris41 1608: }
1.800 albertel 1609: foreach my $server (keys(%servers)) {
1610: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1611: }
1.344 www 1612: }
1613:
1.1231 raeburn 1614: # ---------------------------------------- Delete unwanted IDs from ids.db file
1615:
1616: sub iddel {
1617: my ($udom,$idshashref,$uhome)=@_;
1618: my %result=();
1619: unless (ref($idshashref) eq 'HASH') {
1620: return %result;
1621: }
1622: my %servers=();
1623: while (my ($id,$uname) = each(%{$idshashref})) {
1624: my $uhom;
1625: if ($uhome) {
1626: $uhom = $uhome;
1627: } else {
1628: $uhom=&homeserver($uname,$udom);
1629: }
1630: if ($uhom ne 'no_host') {
1631: if ($servers{$uhom}) {
1632: $servers{$uhom}.='&'.&escape($id);
1633: } else {
1634: $servers{$uhom}=&escape($id);
1635: }
1636: }
1637: }
1638: foreach my $server (keys(%servers)) {
1639: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1640: }
1641: return %result;
1642: }
1643:
1.1023 raeburn 1644: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1645: sub dump_dom {
1.1165 droeschl 1646: my ($namespace, $udom, $regexp) = @_;
1647:
1648: $udom ||= $env{'user.domain'};
1649:
1650: return () unless $udom;
1651:
1652: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1653: }
1654:
1.1023 raeburn 1655: # ------------------------------------------ get items from domain db files
1.806 raeburn 1656:
1657: sub get_dom {
1.860 raeburn 1658: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1659: return if ($udom eq 'public');
1.806 raeburn 1660: my $items='';
1661: foreach my $item (@$storearr) {
1662: $items.=&escape($item).'&';
1663: }
1664: $items=~s/\&$//;
1.860 raeburn 1665: if (!$udom) {
1666: $udom=$env{'user.domain'};
1.1267 raeburn 1667: return if ($udom eq 'public');
1.860 raeburn 1668: if (defined(&domain($udom,'primary'))) {
1669: $uhome=&domain($udom,'primary');
1670: } else {
1.874 albertel 1671: undef($uhome);
1.860 raeburn 1672: }
1673: } else {
1674: if (!$uhome) {
1675: if (defined(&domain($udom,'primary'))) {
1676: $uhome=&domain($udom,'primary');
1677: }
1678: }
1679: }
1680: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1681: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1682: my %returnhash;
1.875 albertel 1683: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1684: return %returnhash;
1685: }
1.806 raeburn 1686: my @pairs=split(/\&/,$rep);
1687: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1688: return @pairs;
1689: }
1690: my $i=0;
1691: foreach my $item (@$storearr) {
1692: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1693: $i++;
1694: }
1695: return %returnhash;
1696: } else {
1.880 banghart 1697: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1698: }
1699: }
1700:
1701: # -------------------------------------------- put items in domain db files
1702:
1703: sub put_dom {
1.860 raeburn 1704: my ($namespace,$storehash,$udom,$uhome)=@_;
1705: if (!$udom) {
1706: $udom=$env{'user.domain'};
1707: if (defined(&domain($udom,'primary'))) {
1708: $uhome=&domain($udom,'primary');
1709: } else {
1.874 albertel 1710: undef($uhome);
1.860 raeburn 1711: }
1712: } else {
1713: if (!$uhome) {
1714: if (defined(&domain($udom,'primary'))) {
1715: $uhome=&domain($udom,'primary');
1716: }
1717: }
1718: }
1719: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1720: my $items='';
1721: foreach my $item (keys(%$storehash)) {
1722: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1723: }
1724: $items=~s/\&$//;
1725: return &reply("putdom:$udom:$namespace:$items",$uhome);
1726: } else {
1.860 raeburn 1727: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1728: }
1729: }
1730:
1.1023 raeburn 1731: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1732: sub newput_dom {
1.1023 raeburn 1733: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1734: my $result;
1735: if (!$udom) {
1736: $udom=$env{'user.domain'};
1737: }
1.1023 raeburn 1738: if ($udom) {
1739: my $uname = &get_domainconfiguser($udom);
1740: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1741: }
1742: return $result;
1743: }
1744:
1.1023 raeburn 1745: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1746: sub del_dom {
1.1023 raeburn 1747: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1748: if (ref($storearr) eq 'ARRAY') {
1749: if (!$udom) {
1750: $udom=$env{'user.domain'};
1751: }
1.1023 raeburn 1752: if ($udom) {
1753: my $uname = &get_domainconfiguser($udom);
1754: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1755: }
1756: }
1757: }
1758:
1.1023 raeburn 1759: # ----------------------------------construct domainconfig user for a domain
1760: sub get_domainconfiguser {
1761: my ($udom) = @_;
1762: return $udom.'-domainconfig';
1763: }
1764:
1.837 raeburn 1765: sub retrieve_inst_usertypes {
1766: my ($udom) = @_;
1767: my (%returnhash,@order);
1.989 raeburn 1768: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1769: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1770: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1771: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1772: } else {
1773: if (defined(&domain($udom,'primary'))) {
1774: my $uhome=&domain($udom,'primary');
1775: my $rep=&reply("inst_usertypes:$udom",$uhome);
1776: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1777: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1778: return (\%returnhash,\@order);
1779: }
1780: my ($hashitems,$orderitems) = split(/:/,$rep);
1781: my @pairs=split(/\&/,$hashitems);
1782: foreach my $item (@pairs) {
1783: my ($key,$value)=split(/=/,$item,2);
1784: $key = &unescape($key);
1785: next if ($key =~ /^error: 2 /);
1786: $returnhash{$key}=&thaw_unescape($value);
1787: }
1788: my @esc_order = split(/\&/,$orderitems);
1789: foreach my $item (@esc_order) {
1790: push(@order,&unescape($item));
1791: }
1792: } else {
1.1256 raeburn 1793: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1794: }
1.1256 raeburn 1795: return (\%returnhash,\@order);
1.837 raeburn 1796: }
1797: }
1798:
1.868 raeburn 1799: sub is_domainimage {
1800: my ($url) = @_;
1801: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1802: if (&domain($1) ne '') {
1803: return '1';
1804: }
1805: }
1806: return;
1807: }
1808:
1.899 raeburn 1809: sub inst_directory_query {
1810: my ($srch) = @_;
1811: my $udom = $srch->{'srchdomain'};
1812: my %results;
1813: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1814: my $outcome;
1.899 raeburn 1815: if ($homeserver ne '') {
1.904 albertel 1816: my $queryid=&reply("querysend:instdirsearch:".
1817: &escape($srch->{'srchby'}).':'.
1818: &escape($srch->{'srchterm'}).':'.
1819: &escape($srch->{'srchtype'}),$homeserver);
1820: my $host=&hostname($homeserver);
1821: if ($queryid !~/^\Q$host\E\_/) {
1822: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1823: return;
1824: }
1825: my $response = &get_query_reply($queryid);
1826: my $maxtries = 5;
1827: my $tries = 1;
1828: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1829: $response = &get_query_reply($queryid);
1830: $tries ++;
1831: }
1832:
1833: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1834: if ($response eq 'unavailable') {
1835: $outcome = $response;
1836: } else {
1837: $outcome = 'ok';
1838: my @matches = split(/\n/,$response);
1839: foreach my $match (@matches) {
1840: my ($key,$value) = split(/=/,$match);
1841: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1842: }
1.899 raeburn 1843: }
1844: }
1845: }
1.909 raeburn 1846: return ($outcome,%results);
1.899 raeburn 1847: }
1848:
1849: sub usersearch {
1850: my ($srch) = @_;
1851: my $dom = $srch->{'srchdomain'};
1852: my %results;
1853: my %libserv = &all_library();
1854: my $query = 'usersearch';
1855: foreach my $tryserver (keys(%libserv)) {
1856: if (&host_domain($tryserver) eq $dom) {
1857: my $host=&hostname($tryserver);
1858: my $queryid=
1.911 raeburn 1859: &reply("querysend:".&escape($query).':'.
1860: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1861: &escape($srch->{'srchtype'}).':'.
1862: &escape($srch->{'srchterm'}),$tryserver);
1863: if ($queryid !~/^\Q$host\E\_/) {
1864: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1865: next;
1.899 raeburn 1866: }
1867: my $reply = &get_query_reply($queryid);
1868: my $maxtries = 1;
1869: my $tries = 1;
1870: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1871: $reply = &get_query_reply($queryid);
1872: $tries ++;
1873: }
1874: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1875: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1876: } else {
1.911 raeburn 1877: my @matches;
1878: if ($reply =~ /\n/) {
1879: @matches = split(/\n/,$reply);
1880: } else {
1881: @matches = split(/\&/,$reply);
1882: }
1.899 raeburn 1883: foreach my $match (@matches) {
1884: my ($uname,$udom,%userhash);
1.911 raeburn 1885: foreach my $entry (split(/:/,$match)) {
1886: my ($key,$value) =
1887: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1888: $userhash{$key} = $value;
1889: if ($key eq 'username') {
1890: $uname = $value;
1891: } elsif ($key eq 'domain') {
1892: $udom = $value;
1.911 raeburn 1893: }
1.899 raeburn 1894: }
1895: $results{$uname.':'.$udom} = \%userhash;
1896: }
1897: }
1898: }
1899: }
1900: return %results;
1901: }
1902:
1.912 raeburn 1903: sub get_instuser {
1904: my ($udom,$uname,$id) = @_;
1905: my $homeserver = &domain($udom,'primary');
1906: my ($outcome,%results);
1907: if ($homeserver ne '') {
1908: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1909: &escape($id).':'.&escape($udom),$homeserver);
1910: my $host=&hostname($homeserver);
1911: if ($queryid !~/^\Q$host\E\_/) {
1912: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1913: return;
1914: }
1915: my $response = &get_query_reply($queryid);
1916: my $maxtries = 5;
1917: my $tries = 1;
1918: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1919: $response = &get_query_reply($queryid);
1920: $tries ++;
1921: }
1922: if (!&error($response) && $response ne 'refused') {
1923: if ($response eq 'unavailable') {
1924: $outcome = $response;
1925: } else {
1926: $outcome = 'ok';
1927: my @matches = split(/\n/,$response);
1928: foreach my $match (@matches) {
1929: my ($key,$value) = split(/=/,$match);
1930: $results{&unescape($key)} = &thaw_unescape($value);
1931: }
1932: }
1933: }
1934: }
1935: my %userinfo;
1936: if (ref($results{$uname}) eq 'HASH') {
1937: %userinfo = %{$results{$uname}};
1938: }
1939: return ($outcome,%userinfo);
1940: }
1941:
1942: sub inst_rulecheck {
1.923 raeburn 1943: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1944: my %returnhash;
1945: if ($udom ne '') {
1946: if (ref($rules) eq 'ARRAY') {
1947: @{$rules} = map {&escape($_);} (@{$rules});
1948: my $rulestr = join(':',@{$rules});
1949: my $homeserver=&domain($udom,'primary');
1950: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1951: my $response;
1952: if ($item eq 'username') {
1953: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1954: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1955: $homeserver));
1.923 raeburn 1956: } elsif ($item eq 'id') {
1957: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1958: ':'.&escape($id).':'.$rulestr,
1959: $homeserver));
1.945 raeburn 1960: } elsif ($item eq 'selfcreate') {
1961: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1962: &escape($udom).':'.&escape($uname).
1963: ':'.$rulestr,$homeserver));
1.923 raeburn 1964: }
1.912 raeburn 1965: if ($response ne 'refused') {
1966: my @pairs=split(/\&/,$response);
1967: foreach my $item (@pairs) {
1968: my ($key,$value)=split(/=/,$item,2);
1969: $key = &unescape($key);
1970: next if ($key =~ /^error: 2 /);
1971: $returnhash{$key}=&thaw_unescape($value);
1972: }
1973: }
1974: }
1975: }
1976: }
1977: return %returnhash;
1978: }
1979:
1980: sub inst_userrules {
1.923 raeburn 1981: my ($udom,$check) = @_;
1.912 raeburn 1982: my (%ruleshash,@ruleorder);
1983: if ($udom ne '') {
1984: my $homeserver=&domain($udom,'primary');
1985: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1986: my $response;
1987: if ($check eq 'id') {
1988: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1989: $homeserver);
1.943 raeburn 1990: } elsif ($check eq 'email') {
1991: $response=&reply('instemailrules:'.&escape($udom),
1992: $homeserver);
1.923 raeburn 1993: } else {
1994: $response=&reply('instuserrules:'.&escape($udom),
1995: $homeserver);
1996: }
1.912 raeburn 1997: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1998: ($response ne 'unknown_cmd') &&
1.912 raeburn 1999: ($response ne 'no_such_host')) {
2000: my ($hashitems,$orderitems) = split(/:/,$response);
2001: my @pairs=split(/\&/,$hashitems);
2002: foreach my $item (@pairs) {
2003: my ($key,$value)=split(/=/,$item,2);
2004: $key = &unescape($key);
2005: next if ($key =~ /^error: 2 /);
2006: $ruleshash{$key}=&thaw_unescape($value);
2007: }
2008: my @esc_order = split(/\&/,$orderitems);
2009: foreach my $item (@esc_order) {
2010: push(@ruleorder,&unescape($item));
2011: }
2012: }
2013: }
2014: }
2015: return (\%ruleshash,\@ruleorder);
2016: }
2017:
1.976 raeburn 2018: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2019:
2020: sub get_domain_defaults {
1.1240 raeburn 2021: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2022: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2023: my $cachetime = 60*60*24;
1.1240 raeburn 2024: unless ($ignore_cache) {
2025: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2026: if (defined($cached)) {
2027: if (ref($result) eq 'HASH') {
2028: return %{$result};
2029: }
1.943 raeburn 2030: }
2031: }
2032: my %domdefaults;
2033: my %domconfig =
1.989 raeburn 2034: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2035: 'requestcourses','inststatus',
1.1183 raeburn 2036: 'coursedefaults','usersessions',
1.1258 raeburn 2037: 'requestauthor','selfenrollment',
2038: 'coursecategories'],$domain);
1.1254 raeburn 2039: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2040: if (ref($domconfig{'defaults'}) eq 'HASH') {
2041: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2042: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2043: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2044: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2045: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2046: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2047: } else {
2048: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2049: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2050: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2051: }
1.976 raeburn 2052: if (ref($domconfig{'quotas'}) eq 'HASH') {
2053: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2054: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2055: } else {
2056: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2057: }
1.1177 raeburn 2058: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2059: foreach my $item (@usertools) {
2060: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2061: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2062: }
2063: }
1.1229 raeburn 2064: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2065: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2066: }
1.976 raeburn 2067: }
1.985 raeburn 2068: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246 raeburn 2069: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2070: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2071: }
2072: }
1.1183 raeburn 2073: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2074: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2075: }
1.989 raeburn 2076: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2077: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2078: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2079: }
2080: }
1.1047 raeburn 2081: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2082: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2083: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2084: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2085: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2086: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2087: }
1.1254 raeburn 2088: foreach my $type (@coursetypes) {
2089: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2090: unless ($type eq 'community') {
2091: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2092: }
2093: }
2094: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2095: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2096: }
1.1277 raeburn 2097: if ($domdefaults{'postsubmit'} eq 'on') {
2098: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2099: $domdefaults{$type.'postsubtimeout'} =
2100: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2101: }
2102: }
1.1230 raeburn 2103: }
1.1047 raeburn 2104: }
1.1073 raeburn 2105: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2106: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2107: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2108: }
2109: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2110: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2111: }
1.1279 raeburn 2112: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2113: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2114: }
1.1073 raeburn 2115: }
1.1254 raeburn 2116: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2117: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2118: my @settings = ('types','registered','enroll_dates','access_dates','section',
2119: 'approval','limit');
2120: foreach my $type (@coursetypes) {
2121: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2122: my @mgrdc = ();
2123: foreach my $item (@settings) {
2124: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2125: push(@mgrdc,$item);
2126: }
2127: }
2128: if (@mgrdc) {
2129: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2130: }
2131: }
2132: }
2133: }
2134: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2135: foreach my $type (@coursetypes) {
2136: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2137: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2138: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2139: }
2140: }
2141: }
2142: }
2143: }
1.1258 raeburn 2144: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2145: $domdefaults{'catauth'} = 'std';
2146: $domdefaults{'catunauth'} = 'std';
2147: if ($domconfig{'coursecategories'}{'auth'}) {
2148: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2149: }
2150: if ($domconfig{'coursecategories'}{'unauth'}) {
2151: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2152: }
2153: }
1.1219 raeburn 2154: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2155: return %domdefaults;
2156: }
2157:
1.344 www 2158: # --------------------------------------------------- Assign a key to a student
2159:
2160: sub assign_access_key {
1.364 www 2161: #
2162: # a valid key looks like uname:udom#comments
2163: # comments are being appended
2164: #
1.498 www 2165: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2166: $kdom=
1.620 albertel 2167: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2168: $knum=
1.620 albertel 2169: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2170: $cdom=
1.620 albertel 2171: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2172: $cnum=
1.620 albertel 2173: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2174: $udom=$env{'user.name'} unless (defined($udom));
2175: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2176: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2177: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2178: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2179: # assigned to this person
2180: # - this should not happen,
1.345 www 2181: # unless something went wrong
2182: # the first time around
2183: # ready to assign
1.364 www 2184: $logentry=$1.'; '.$logentry;
1.496 www 2185: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2186: $kdom,$knum) eq 'ok') {
1.345 www 2187: # key now belongs to user
1.346 www 2188: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2189: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2190: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2191: return 'ok';
2192: } else {
2193: return
2194: 'error: Count not permanently assign key, will need to be re-entered later.';
2195: }
2196: } else {
2197: return 'error: Could not assign key, try again later.';
2198: }
1.364 www 2199: } elsif (!$existing{$ckey}) {
1.345 www 2200: # the key does not exist
2201: return 'error: The key does not exist';
2202: } else {
2203: # the key is somebody else's
2204: return 'error: The key is already in use';
2205: }
1.344 www 2206: }
2207:
1.364 www 2208: # ------------------------------------------ put an additional comment on a key
2209:
2210: sub comment_access_key {
2211: #
2212: # a valid key looks like uname:udom#comments
2213: # comments are being appended
2214: #
2215: my ($ckey,$cdom,$cnum,$logentry)=@_;
2216: $cdom=
1.620 albertel 2217: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2218: $cnum=
1.620 albertel 2219: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2220: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2221: if ($existing{$ckey}) {
2222: $existing{$ckey}.='; '.$logentry;
2223: # ready to assign
1.367 www 2224: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2225: $cdom,$cnum) eq 'ok') {
2226: return 'ok';
2227: } else {
2228: return 'error: Count not store comment.';
2229: }
2230: } else {
2231: # the key does not exist
2232: return 'error: The key does not exist';
2233: }
2234: }
2235:
1.344 www 2236: # ------------------------------------------------------ Generate a set of keys
2237:
2238: sub generate_access_keys {
1.364 www 2239: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2240: $cdom=
1.620 albertel 2241: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2242: $cnum=
1.620 albertel 2243: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2244: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2245: unless (($cdom) && ($cnum)) { return 0; }
2246: if ($number>10000) { return 0; }
2247: sleep(2); # make sure don't get same seed twice
2248: srand(time()^($$+($$<<15))); # from "Programming Perl"
2249: my $total=0;
2250: for (my $i=1;$i<=$number;$i++) {
2251: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2252: sprintf("%lx",int(100000*rand)).'-'.
2253: sprintf("%lx",int(100000*rand));
2254: $newkey=~s/1/g/g; # folks mix up 1 and l
2255: $newkey=~s/0/h/g; # and also 0 and O
2256: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2257: if ($existing{$newkey}) {
2258: $i--;
2259: } else {
1.364 www 2260: if (&put('accesskeys',
2261: { $newkey => '# generated '.localtime().
1.620 albertel 2262: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2263: '; '.$logentry },
2264: $cdom,$cnum) eq 'ok') {
1.344 www 2265: $total++;
2266: }
2267: }
2268: }
1.620 albertel 2269: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2270: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2271: return $total;
2272: }
2273:
2274: # ------------------------------------------------------- Validate an accesskey
2275:
2276: sub validate_access_key {
2277: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2278: $cdom=
1.620 albertel 2279: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2280: $cnum=
1.620 albertel 2281: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2282: $udom=$env{'user.domain'} unless (defined($udom));
2283: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2284: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2285: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2286: }
2287:
2288: # ------------------------------------- Find the section of student in a course
1.652 albertel 2289: sub devalidate_getsection_cache {
2290: my ($udom,$unam,$courseid)=@_;
2291: my $hashid="$udom:$unam:$courseid";
2292: &devalidate_cache_new('getsection',$hashid);
2293: }
1.298 matthew 2294:
1.815 albertel 2295: sub courseid_to_courseurl {
2296: my ($courseid) = @_;
2297: #already url style courseid
2298: return $courseid if ($courseid =~ m{^/});
2299:
2300: if (exists($env{'course.'.$courseid.'.num'})) {
2301: my $cnum = $env{'course.'.$courseid.'.num'};
2302: my $cdom = $env{'course.'.$courseid.'.domain'};
2303: return "/$cdom/$cnum";
2304: }
2305:
2306: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2307: if (exists($courseinfo{'num'})) {
2308: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2309: }
2310:
2311: return undef;
2312: }
2313:
1.298 matthew 2314: sub getsection {
2315: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2316: my $cachetime=1800;
1.551 albertel 2317:
2318: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2319: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2320: if (defined($cached)) { return $result; }
2321:
1.298 matthew 2322: my %Pending;
2323: my %Expired;
2324: #
2325: # Each role can either have not started yet (pending), be active,
2326: # or have expired.
2327: #
2328: # If there is an active role, we are done.
2329: #
2330: # If there is more than one role which has not started yet,
2331: # choose the one which will start sooner
2332: # If there is one role which has not started yet, return it.
2333: #
2334: # If there is more than one expired role, choose the one which ended last.
2335: # If there is a role which has expired, return it.
2336: #
1.815 albertel 2337: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2338: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2339: foreach my $key (keys(%roleshash)) {
1.479 albertel 2340: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2341: my $section=$1;
2342: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2343: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2344: my $now=time;
1.548 albertel 2345: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2346: $Expired{$end}=$section;
2347: next;
2348: }
1.548 albertel 2349: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2350: $Pending{$start}=$section;
2351: next;
2352: }
1.599 albertel 2353: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2354: }
2355: #
2356: # Presumedly there will be few matching roles from the above
2357: # loop and the sorting time will be negligible.
2358: if (scalar(keys(%Pending))) {
2359: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2360: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2361: }
2362: if (scalar(keys(%Expired))) {
2363: my @sorted = sort {$a <=> $b} keys(%Expired);
2364: my $time = pop(@sorted);
1.599 albertel 2365: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2366: }
1.599 albertel 2367: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2368: }
1.70 www 2369:
1.599 albertel 2370: sub save_cache {
2371: &purge_remembered();
1.722 albertel 2372: #&Apache::loncommon::validate_page();
1.620 albertel 2373: undef(%env);
1.780 albertel 2374: undef($env_loaded);
1.599 albertel 2375: }
1.452 albertel 2376:
1.599 albertel 2377: my $to_remember=-1;
2378: my %remembered;
2379: my %accessed;
2380: my $kicks=0;
2381: my $hits=0;
1.849 albertel 2382: sub make_key {
2383: my ($name,$id) = @_;
1.872 albertel 2384: if (length($id) > 65
2385: && length(&escape($id)) > 200) {
2386: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2387: }
1.849 albertel 2388: return &escape($name.':'.$id);
2389: }
2390:
1.599 albertel 2391: sub devalidate_cache_new {
2392: my ($name,$id,$debug) = @_;
2393: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2394: $id=&make_key($name,$id);
1.599 albertel 2395: $memcache->delete($id);
2396: delete($remembered{$id});
2397: delete($accessed{$id});
2398: }
2399:
2400: sub is_cached_new {
2401: my ($name,$id,$debug) = @_;
1.849 albertel 2402: $id=&make_key($name,$id);
1.599 albertel 2403: if (exists($remembered{$id})) {
1.1133 foxr 2404: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2405: $accessed{$id}=[&gettimeofday()];
2406: $hits++;
2407: return ($remembered{$id},1);
2408: }
2409: my $value = $memcache->get($id);
2410: if (!(defined($value))) {
2411: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2412: return (undef,undef);
1.416 albertel 2413: }
1.599 albertel 2414: if ($value eq '__undef__') {
2415: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2416: $value=undef;
2417: }
2418: &make_room($id,$value,$debug);
2419: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2420: return ($value,1);
2421: }
2422:
2423: sub do_cache_new {
2424: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2425: $id=&make_key($name,$id);
1.599 albertel 2426: my $setvalue=$value;
2427: if (!defined($setvalue)) {
2428: $setvalue='__undef__';
2429: }
1.623 albertel 2430: if (!defined($time) ) {
2431: $time=600;
2432: }
1.599 albertel 2433: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2434: my $result = $memcache->set($id,$setvalue,$time);
2435: if (! $result) {
1.872 albertel 2436: &logthis("caching of id -> $id failed");
1.910 albertel 2437: $memcache->disconnect_all();
1.872 albertel 2438: }
1.600 albertel 2439: # need to make a copy of $value
1.919 albertel 2440: &make_room($id,$value,$debug);
1.599 albertel 2441: return $value;
2442: }
2443:
2444: sub make_room {
2445: my ($id,$value,$debug)=@_;
1.919 albertel 2446:
2447: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2448: : $value;
1.599 albertel 2449: if ($to_remember<0) { return; }
2450: $accessed{$id}=[&gettimeofday()];
2451: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2452: my $to_kick;
2453: my $max_time=0;
2454: foreach my $other (keys(%accessed)) {
2455: if (&tv_interval($accessed{$other}) > $max_time) {
2456: $to_kick=$other;
2457: $max_time=&tv_interval($accessed{$other});
2458: }
2459: }
2460: delete($remembered{$to_kick});
2461: delete($accessed{$to_kick});
2462: $kicks++;
2463: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2464: return;
2465: }
2466:
1.599 albertel 2467: sub purge_remembered {
1.604 albertel 2468: #&logthis("Tossing ".scalar(keys(%remembered)));
2469: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2470: undef(%remembered);
2471: undef(%accessed);
1.428 albertel 2472: }
1.70 www 2473: # ------------------------------------- Read an entry from a user's environment
2474:
2475: sub userenvironment {
2476: my ($udom,$unam,@what)=@_;
1.976 raeburn 2477: my $items;
2478: foreach my $item (@what) {
2479: $items.=&escape($item).'&';
2480: }
2481: $items=~s/\&$//;
1.70 www 2482: my %returnhash=();
1.1009 raeburn 2483: my $uhome = &homeserver($unam,$udom);
2484: unless ($uhome eq 'no_host') {
2485: my @answer=split(/\&/,
2486: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2487: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2488: return %returnhash;
2489: }
1.1009 raeburn 2490: my $i;
2491: for ($i=0;$i<=$#what;$i++) {
2492: $returnhash{$what[$i]}=&unescape($answer[$i]);
2493: }
1.70 www 2494: }
2495: return %returnhash;
1.1 albertel 2496: }
2497:
1.617 albertel 2498: # ---------------------------------------------------------- Get a studentphoto
2499: sub studentphoto {
2500: my ($udom,$unam,$ext) = @_;
2501: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2502: if (defined($env{'request.course.id'})) {
1.708 raeburn 2503: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2504: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2505: return(&retrievestudentphoto($udom,$unam,$ext));
2506: } else {
2507: my ($result,$perm_reqd)=
1.707 albertel 2508: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2509: if ($result eq 'ok') {
2510: if (!($perm_reqd eq 'yes')) {
2511: return(&retrievestudentphoto($udom,$unam,$ext));
2512: }
2513: }
2514: }
2515: }
2516: } else {
2517: my ($result,$perm_reqd) =
1.707 albertel 2518: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2519: if ($result eq 'ok') {
2520: if (!($perm_reqd eq 'yes')) {
2521: return(&retrievestudentphoto($udom,$unam,$ext));
2522: }
2523: }
2524: }
2525: return '/adm/lonKaputt/lonlogo_broken.gif';
2526: }
2527:
2528: sub retrievestudentphoto {
2529: my ($udom,$unam,$ext,$type) = @_;
2530: my $home=&Apache::lonnet::homeserver($unam,$udom);
2531: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2532: if ($ret eq 'ok') {
2533: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2534: if ($type eq 'thumbnail') {
2535: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2536: }
2537: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2538: return $tokenurl;
2539: } else {
2540: if ($type eq 'thumbnail') {
2541: return '/adm/lonKaputt/genericstudent_tn.gif';
2542: } else {
2543: return '/adm/lonKaputt/lonlogo_broken.gif';
2544: }
1.617 albertel 2545: }
2546: }
2547:
1.263 www 2548: # -------------------------------------------------------------------- New chat
2549:
2550: sub chatsend {
1.724 raeburn 2551: my ($newentry,$anon,$group)=@_;
1.620 albertel 2552: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2553: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2554: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2555: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2556: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2557: &escape($newentry)).':'.$group,$chome);
1.292 www 2558: }
2559:
2560: # ------------------------------------------ Find current version of a resource
2561:
2562: sub getversion {
2563: my $fname=&clutter(shift);
1.1189 raeburn 2564: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2565: return ¤tversion(&filelocation('',$fname));
2566: }
2567:
2568: sub currentversion {
2569: my $fname=shift;
2570: my $author=$fname;
2571: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2572: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2573: my $home=&homeserver($uname,$udom);
1.292 www 2574: if ($home eq 'no_host') {
2575: return -1;
2576: }
1.1112 www 2577: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2578: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2579: return -1;
2580: }
1.1112 www 2581: return $answer;
1.263 www 2582: }
2583:
1.1111 www 2584: #
2585: # Return special version number of resource if set by override, empty otherwise
2586: #
2587: sub usedversion {
2588: my $fname=shift;
2589: unless ($fname) { $fname=$env{'request.uri'}; }
2590: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2591: if ($urlversion) { return $urlversion; }
2592: return '';
2593: }
2594:
1.1 albertel 2595: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2596:
1.1 albertel 2597: sub subscribe {
2598: my $fname=shift;
1.761 raeburn 2599: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2600: $fname=~s/[\n\r]//g;
1.1 albertel 2601: my $author=$fname;
2602: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2603: my ($udom,$uname)=split(/\//,$author);
2604: my $home=homeserver($uname,$udom);
1.335 albertel 2605: if ($home eq 'no_host') {
2606: return 'not_found';
1.1 albertel 2607: }
2608: my $answer=reply("sub:$fname",$home);
1.64 www 2609: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2610: $answer.=' by '.$home;
2611: }
1.1 albertel 2612: return $answer;
2613: }
2614:
1.8 www 2615: # -------------------------------------------------------------- Replicate file
2616:
2617: sub repcopy {
2618: my $filename=shift;
1.23 www 2619: $filename=~s/\/+/\//g;
1.1142 raeburn 2620: my $londocroot = $perlvar{'lonDocRoot'};
2621: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2622: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2623: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2624: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2625: return &repcopy_userfile($filename);
2626: }
1.532 albertel 2627: $filename=~s/[\n\r]//g;
1.8 www 2628: my $transname="$filename.in.transfer";
1.828 www 2629: # FIXME: this should flock
1.607 raeburn 2630: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2631: my $remoteurl=subscribe($filename);
1.64 www 2632: if ($remoteurl =~ /^con_lost by/) {
2633: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2634: return 'unavailable';
1.8 www 2635: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2636: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2637: return 'not_found';
1.64 www 2638: } elsif ($remoteurl =~ /^rejected by/) {
2639: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2640: return 'forbidden';
1.20 www 2641: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2642: return 'ok';
1.8 www 2643: } else {
1.290 www 2644: my $author=$filename;
2645: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2646: my ($udom,$uname)=split(/\//,$author);
2647: my $home=homeserver($uname,$udom);
2648: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2649: my @parts=split(/\//,$filename);
2650: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2651: if ($path ne "$londocroot/res") {
1.8 www 2652: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2653: return 'bad_request';
1.8 www 2654: }
2655: my $count;
2656: for ($count=5;$count<$#parts;$count++) {
2657: $path.="/$parts[$count]";
2658: if ((-e $path)!=1) {
2659: mkdir($path,0777);
2660: }
2661: }
2662: my $ua=new LWP::UserAgent;
2663: my $request=new HTTP::Request('GET',"$remoteurl");
2664: my $response=$ua->request($request,$transname);
2665: if ($response->is_error()) {
2666: unlink($transname);
2667: my $message=$response->status_line;
1.672 albertel 2668: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2669: ." LWP get: $message: $filename</font>");
1.607 raeburn 2670: return 'unavailable';
1.8 www 2671: } else {
1.16 www 2672: if ($remoteurl!~/\.meta$/) {
2673: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2674: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2675: if ($mresponse->is_error()) {
2676: unlink($filename.'.meta');
2677: &logthis(
1.672 albertel 2678: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2679: }
2680: }
1.8 www 2681: rename($transname,$filename);
1.607 raeburn 2682: return 'ok';
1.8 www 2683: }
1.290 www 2684: }
1.8 www 2685: }
1.330 www 2686: }
2687:
2688: # ------------------------------------------------ Get server side include body
2689: sub ssi_body {
1.381 albertel 2690: my ($filelink,%form)=@_;
1.606 matthew 2691: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2692: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2693: }
1.953 www 2694: my $output='';
2695: my $response;
1.980 raeburn 2696: if ($filelink=~/^https?\:/) {
1.954 raeburn 2697: ($output,$response)=&externalssi($filelink);
1.953 www 2698: } else {
1.1004 droeschl 2699: $filelink .= $filelink=~/\?/ ? '&' : '?';
2700: $filelink .= 'inhibitmenu=yes';
1.953 www 2701: ($output,$response)=&ssi($filelink,%form);
2702: }
1.778 albertel 2703: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2704: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2705: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2706: if (wantarray) {
2707: return ($output, $response);
2708: } else {
2709: return $output;
2710: }
1.8 www 2711: }
2712:
1.15 www 2713: # --------------------------------------------------------- Server Side Include
2714:
1.782 albertel 2715: sub absolute_url {
2716: my ($host_name) = @_;
2717: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2718: if ($host_name eq '') {
2719: $host_name = $ENV{'SERVER_NAME'};
2720: }
2721: return $protocol.$host_name;
2722: }
2723:
1.942 foxr 2724: #
2725: # Server side include.
2726: # Parameters:
2727: # fn Possibly encrypted resource name/id.
2728: # form Hash that describes how the rendering should be done
2729: # and other things.
1.944 foxr 2730: # Returns:
1.950 raeburn 2731: # Scalar context: The content of the response.
2732: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2733: #
1.15 www 2734: sub ssi {
2735:
1.944 foxr 2736: my ($fn,%form)=@_;
1.15 www 2737: my $ua=new LWP::UserAgent;
1.23 www 2738: my $request;
1.711 albertel 2739:
2740: $form{'no_update_last_known'}=1;
1.895 albertel 2741: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2742: if (%form) {
1.782 albertel 2743: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 2744: $request->content(join('&',map {
2745: my $name = escape($_);
2746: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2747: ? join("&$name=", map {escape($_) } @{$form{$_}})
2748: : &escape($form{$_}) );
2749: } keys(%form)));
1.23 www 2750: } else {
1.782 albertel 2751: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2752: }
2753:
1.15 www 2754: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2755: my $response= $ua->request($request);
1.1182 foxr 2756: my $content = $response->content;
2757:
2758:
1.944 foxr 2759: if (wantarray) {
1.1173 foxr 2760: return ($content, $response);
1.944 foxr 2761: } else {
1.1173 foxr 2762: return $content;
1.942 foxr 2763: }
1.324 www 2764: }
2765:
2766: sub externalssi {
2767: my ($url)=@_;
2768: my $ua=new LWP::UserAgent;
2769: my $request=new HTTP::Request('GET',$url);
2770: my $response=$ua->request($request);
1.954 raeburn 2771: if (wantarray) {
2772: return ($response->content, $response);
2773: } else {
2774: return $response->content;
2775: }
1.15 www 2776: }
1.254 www 2777:
1.492 albertel 2778: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2779:
2780: sub allowuploaded {
2781: my ($srcurl,$url)=@_;
2782: $url=&clutter(&declutter($url));
2783: my $dir=$url;
2784: $dir=~s/\/[^\/]+$//;
2785: my %httpref=();
2786: my $httpurl=&hreflocation('',$url);
2787: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2788: &Apache::lonnet::appenv(\%httpref);
1.254 www 2789: }
1.477 raeburn 2790:
1.1193 raeburn 2791: #
2792: # Determine if the current user should be able to edit a particular resource,
2793: # when viewing in course context.
2794: # (a) When viewing resource used to determine if "Edit" item is included in
2795: # Functions.
2796: # (b) When displaying folder contents in course editor, used to determine if
2797: # "Edit" link will be displayed alongside resource.
2798: #
1.1196 raeburn 2799: # input: six args -- filename (decluttered), course number, course domain,
2800: # url, symb (if registered) and group (if this is a group
2801: # item -- e.g., bulletin board, group page etc.).
2802: # output: array of five scalars --
1.1193 raeburn 2803: # $cfile -- url for file editing if editable on current server
2804: # $home -- homeserver of resource (i.e., for author if published,
2805: # or course if uploaded.).
2806: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2807: # $forceedit -- 1 if icon/link should be to go to edit mode
2808: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2809: #
2810:
2811: sub can_edit_resource {
1.1194 raeburn 2812: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2813: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2814: #
2815: # For aboutme pages user can only edit his/her own.
2816: #
1.1199 raeburn 2817: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2818: my ($sdom,$sname) = ($1,$2);
2819: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2820: $home = $env{'user.home'};
2821: $cfile = $resurl;
2822: if ($env{'form.forceedit'}) {
2823: $forceview = 1;
2824: } else {
2825: $forceedit = 1;
2826: }
2827: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2828: } else {
2829: return;
2830: }
2831: }
2832:
2833: if ($env{'request.course.id'}) {
2834: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2835: if ($group ne '') {
2836: # if this is a group homepage or group bulletin board, check group privs
2837: my $allowed = 0;
1.1197 raeburn 2838: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2839: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2840: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2841: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2842: $allowed = 1;
2843: }
1.1197 raeburn 2844: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2845: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2846: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2847: $allowed = 1;
2848: }
2849: }
2850: if ($allowed) {
2851: $home=&homeserver($cnum,$cdom);
2852: if ($env{'form.forceedit'}) {
2853: $forceview = 1;
2854: } else {
2855: $forceedit = 1;
2856: }
2857: $cfile = $resurl;
2858: } else {
2859: return;
2860: }
2861: } else {
1.1208 raeburn 2862: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2863: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2864: return;
2865: }
2866: } elsif (!$crsedit) {
1.1194 raeburn 2867: #
2868: # No edit allowed where CC has switched to student role.
2869: #
2870: return;
2871: }
2872: }
2873: }
2874:
1.1193 raeburn 2875: if ($file ne '') {
2876: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2877: if (&is_course_upload($file,$cnum,$cdom)) {
2878: $uploaded = 1;
2879: $incourse = 1;
1.1193 raeburn 2880: if ($file =~/\.(htm|html|css|js|txt)$/) {
2881: $cfile = &hreflocation('',$file);
1.1201 raeburn 2882: if ($env{'form.forceedit'}) {
2883: $forceview = 1;
2884: } else {
2885: $forceedit = 1;
2886: }
1.1194 raeburn 2887: }
2888: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2889: $incourse = 1;
2890: if ($env{'form.forceedit'}) {
2891: $forceview = 1;
2892: } else {
2893: $forceedit = 1;
2894: }
2895: $cfile = $resurl;
2896: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2897: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2898: $incourse = 1;
2899: if ($env{'form.forceedit'}) {
2900: $forceview = 1;
2901: } else {
2902: $forceedit = 1;
2903: }
2904: $cfile = $resurl;
1.1199 raeburn 2905: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2906: $incourse = 1;
2907: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2908: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2909: $incourse = 1;
1.1199 raeburn 2910: if ($env{'form.forceedit'}) {
2911: $forceview = 1;
2912: } else {
2913: $forceedit = 1;
2914: }
2915: $cfile = $resurl;
1.1208 raeburn 2916: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2917: $incourse = 1;
2918: if ($env{'form.forceedit'}) {
2919: $forceview = 1;
2920: } else {
2921: $forceedit = 1;
2922: }
2923: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2924: }
2925: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2926: my $template = '/res/lib/templates/simpleproblem.problem';
2927: if (&is_on_map($template)) {
2928: $incourse = 1;
2929: $forceview = 1;
2930: $cfile = $template;
1.1193 raeburn 2931: }
1.1199 raeburn 2932: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2933: $incourse = 1;
2934: if ($env{'form.forceedit'}) {
2935: $forceview = 1;
2936: } else {
2937: $forceedit = 1;
2938: }
2939: $cfile = $resurl;
2940: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2941: $incourse = 1;
2942: $forceview = 1;
2943: if ($symb) {
2944: my ($map,$id,$res)=&decode_symb($symb);
2945: $env{'request.symb'} = $symb;
2946: $cfile = &clutter($res);
2947: } else {
2948: $cfile = $env{'form.suppurl'};
2949: $cfile =~ s{^http://}{};
2950: $cfile = '/adm/wrapper/ext/'.$cfile;
2951: }
1.1234 raeburn 2952: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2953: if ($env{'form.forceedit'}) {
2954: $forceview = 1;
2955: } else {
2956: $forceedit = 1;
2957: }
2958: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2959: }
2960: }
1.1194 raeburn 2961: if ($uploaded || $incourse) {
2962: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2963: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2964: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2965: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2966: # Check that the user has permission to edit this resource
2967: my $setpriv = 1;
2968: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2969: if (defined($cfudom)) {
2970: $home=&homeserver($cfuname,$cfudom);
2971: $cfile=$file;
2972: }
2973: }
1.1194 raeburn 2974: if (($cfile ne '') && (!$incourse || $uploaded) &&
2975: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2976: my @ids=¤t_machine_ids();
2977: unless (grep(/^\Q$home\E$/,@ids)) {
2978: $switchserver=1;
2979: }
2980: }
2981: }
1.1194 raeburn 2982: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2983: }
2984:
2985: sub is_course_upload {
2986: my ($file,$cnum,$cdom) = @_;
2987: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2988: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2989: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2990: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2991: return 1;
2992: }
2993: return;
2994: }
2995:
1.1194 raeburn 2996: sub in_course {
1.1195 raeburn 2997: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2998: if ($hideprivileged) {
2999: my $skipuser;
1.1219 raeburn 3000: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3001: my @possdoms = ($cdom);
3002: if ($coursehash{'checkforpriv'}) {
3003: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3004: }
3005: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3006: $skipuser = 1;
3007: if ($coursehash{'nothideprivileged'}) {
3008: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3009: my $user;
3010: if ($item =~ /:/) {
3011: $user = $item;
3012: } else {
3013: $user = join(':',split(/[\@]/,$item));
3014: }
3015: if ($user eq $uname.':'.$udom) {
3016: undef($skipuser);
3017: last;
3018: }
3019: }
3020: }
3021: if ($skipuser) {
3022: return 0;
3023: }
3024: }
3025: }
1.1194 raeburn 3026: $type ||= 'any';
3027: if (!defined($cdom) || !defined($cnum)) {
3028: my $cid = $env{'request.course.id'};
3029: $cdom = $env{'course.'.$cid.'.domain'};
3030: $cnum = $env{'course.'.$cid.'.num'};
3031: }
3032: my $typesref;
1.1195 raeburn 3033: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3034: $typesref = ['active','previous','future'];
3035: } elsif ($type eq 'previous' || $type eq 'future') {
3036: $typesref = [$type];
3037: }
3038: my %roles = &get_my_roles($uname,$udom,'userroles',
3039: $typesref,undef,[$cdom]);
3040: my ($tmp) = keys(%roles);
3041: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3042: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3043: if (@course_roles > 0) {
3044: return 1;
3045: }
3046: return 0;
3047: }
3048:
1.478 albertel 3049: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3050: # input: action, courseID, current domain, intended
1.637 raeburn 3051: # path to file, source of file, instruction to parse file for objects,
3052: # ref to hash for embedded objects,
3053: # ref to hash for codebase of java objects.
1.1095 raeburn 3054: # reference to scalar to accommodate mime type determined
3055: # from File::MMagic if $parser = parse.
1.637 raeburn 3056: #
1.485 raeburn 3057: # output: url to file (if action was uploaddoc),
3058: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3059: #
1.478 albertel 3060: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3061: # course.
1.477 raeburn 3062: #
1.478 albertel 3063: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3064: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3065: # course's home server.
1.477 raeburn 3066: #
1.478 albertel 3067: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3068: # be copied from $source (current location) to
3069: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3070: # and will then be copied to
3071: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3072: # course's home server.
1.485 raeburn 3073: #
1.481 raeburn 3074: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3075: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3076: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3077: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3078: # in course's home server.
1.637 raeburn 3079: #
1.477 raeburn 3080:
3081: sub process_coursefile {
1.1095 raeburn 3082: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3083: $mimetype)=@_;
1.477 raeburn 3084: my $fetchresult;
1.638 albertel 3085: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3086: if ($action eq 'propagate') {
1.638 albertel 3087: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3088: $home);
1.481 raeburn 3089: } else {
1.477 raeburn 3090: my $fpath = '';
3091: my $fname = $file;
1.478 albertel 3092: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3093: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3094: my $filepath = &build_filepath($fpath);
1.481 raeburn 3095: if ($action eq 'copy') {
3096: if ($source eq '') {
3097: $fetchresult = 'no source file';
3098: return $fetchresult;
3099: } else {
3100: my $destination = $filepath.'/'.$fname;
3101: rename($source,$destination);
3102: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3103: $home);
1.481 raeburn 3104: }
3105: } elsif ($action eq 'uploaddoc') {
3106: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3107: print $fh $env{'form.'.$source};
1.481 raeburn 3108: close($fh);
1.637 raeburn 3109: if ($parser eq 'parse') {
1.1024 raeburn 3110: my $mm = new File::MMagic;
1.1095 raeburn 3111: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3112: if ($type eq 'text/html') {
1.1024 raeburn 3113: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3114: unless ($parse_result eq 'ok') {
3115: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3116: }
1.637 raeburn 3117: }
1.1095 raeburn 3118: if (ref($mimetype)) {
3119: $$mimetype = $type;
3120: }
1.637 raeburn 3121: }
1.477 raeburn 3122: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3123: $home);
1.481 raeburn 3124: if ($fetchresult eq 'ok') {
3125: return '/uploaded/'.$fpath.'/'.$fname;
3126: } else {
3127: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3128: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3129: return '/adm/notfound.html';
3130: }
1.477 raeburn 3131: }
3132: }
1.485 raeburn 3133: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3134: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3135: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3136: }
3137: return $fetchresult;
3138: }
3139:
1.637 raeburn 3140: sub build_filepath {
3141: my ($fpath) = @_;
3142: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3143: unless ($fpath eq '') {
3144: my @parts=split('/',$fpath);
3145: foreach my $part (@parts) {
3146: $filepath.= '/'.$part;
3147: if ((-e $filepath)!=1) {
3148: mkdir($filepath,0777);
3149: }
3150: }
3151: }
3152: return $filepath;
3153: }
3154:
3155: sub store_edited_file {
1.638 albertel 3156: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3157: my $file = $primary_url;
3158: $file =~ s#^/uploaded/$docudom/$docuname/##;
3159: my $fpath = '';
3160: my $fname = $file;
3161: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3162: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3163: my $filepath = &build_filepath($fpath);
3164: open(my $fh,'>'.$filepath.'/'.$fname);
3165: print $fh $content;
3166: close($fh);
1.638 albertel 3167: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3168: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3169: $home);
1.637 raeburn 3170: if ($$fetchresult eq 'ok') {
3171: return '/uploaded/'.$fpath.'/'.$fname;
3172: } else {
1.638 albertel 3173: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3174: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3175: return '/adm/notfound.html';
3176: }
3177: }
3178:
1.531 albertel 3179: sub clean_filename {
1.831 albertel 3180: my ($fname,$args)=@_;
1.315 www 3181: # Replace Windows backslashes by forward slashes
1.257 www 3182: $fname=~s/\\/\//g;
1.831 albertel 3183: if (!$args->{'keep_path'}) {
3184: # Get rid of everything but the actual filename
3185: $fname=~s/^.*\/([^\/]+)$/$1/;
3186: }
1.315 www 3187: # Replace spaces by underscores
3188: $fname=~s/\s+/\_/g;
3189: # Replace all other weird characters by nothing
1.831 albertel 3190: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3191: # Replace all .\d. sequences with _\d. so they no longer look like version
3192: # numbers
3193: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3194: return $fname;
3195: }
1.1051 raeburn 3196: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3197: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3198: # image with the same aspect ratio as the original, but with dimensions which do
3199: # not exceed $resizewidth and $resizeheight.
3200:
1.984 neumanie 3201: sub resizeImage {
1.1051 raeburn 3202: my ($img_path,$resizewidth,$resizeheight) = @_;
3203: my $ima = Image::Magick->new;
3204: my $resized;
3205: if (-e $img_path) {
3206: $ima->Read($img_path);
3207: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3208: my $width = $ima->Get('width');
3209: my $height = $ima->Get('height');
3210: if ($width > $resizewidth) {
3211: my $factor = $width/$resizewidth;
3212: my $newheight = $height/$factor;
3213: $ima->Scale(width=>$resizewidth,height=>$newheight);
3214: $resized = 1;
3215: }
3216: }
3217: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3218: my $width = $ima->Get('width');
3219: my $height = $ima->Get('height');
3220: if ($height > $resizeheight) {
3221: my $factor = $height/$resizeheight;
3222: my $newwidth = $width/$factor;
3223: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3224: $resized = 1;
3225: }
3226: }
3227: if ($resized) {
3228: $ima->Write($img_path);
3229: }
3230: }
3231: return;
1.977 amueller 3232: }
3233:
1.608 albertel 3234: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3235: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3236: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3237: # $context - possible values: coursedoc, existingfile, overwrite,
3238: # canceloverwrite, or ''.
3239: # if 'coursedoc': upload to the current course
3240: # if 'existingfile': write file to tmp/overwrites directory
3241: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3242: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3243: # $subdir - directory in userfile to store the file into
1.858 raeburn 3244: # $parser - instruction to parse file for objects ($parser = parse)
3245: # $allfiles - reference to hash for embedded objects
3246: # $codebase - reference to hash for codebase of java objects
3247: # $desuname - username for permanent storage of uploaded file
3248: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3249: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3250: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3251: # $resizewidth - width (pixels) to which to resize uploaded image
3252: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3253: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3254: # from File::MMagic.
1.858 raeburn 3255: #
1.686 albertel 3256: # output: url of file in userspace, or error: <message>
3257: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3258:
1.531 albertel 3259: sub userfileupload {
1.1090 raeburn 3260: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3261: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3262: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3263: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3264: $fname=&clean_filename($fname);
1.1090 raeburn 3265: # See if there is anything left
1.257 www 3266: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3267: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3268: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3269: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3270: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3271: my $now = time;
1.1090 raeburn 3272: my $filepath;
1.1095 raeburn 3273: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3274: $filepath = 'tmp/helprequests/'.$now;
3275: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3276: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3277: '_'.$env{'user.domain'}.'/pending';
3278: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3279: my ($docuname,$docudom);
3280: if ($destudom) {
3281: $docudom = $destudom;
3282: } else {
3283: $docudom = $env{'user.domain'};
3284: }
3285: if ($destuname) {
3286: $docuname = $destuname;
3287: } else {
3288: $docuname = $env{'user.name'};
3289: }
3290: if (exists($env{'form.group'})) {
3291: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3292: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3293: }
3294: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3295: if ($context eq 'canceloverwrite') {
3296: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3297: if (-e $tempfile) {
3298: my @info = stat($tempfile);
3299: if ($info[9] eq $env{'form.timestamp'}) {
3300: unlink($tempfile);
3301: }
3302: }
3303: return;
1.523 raeburn 3304: }
3305: }
1.1090 raeburn 3306: # Create the directory if not present
1.741 raeburn 3307: my @parts=split(/\//,$filepath);
3308: my $fullpath = $perlvar{'lonDaemons'};
3309: for (my $i=0;$i<@parts;$i++) {
3310: $fullpath .= '/'.$parts[$i];
3311: if ((-e $fullpath)!=1) {
3312: mkdir($fullpath,0777);
3313: }
3314: }
3315: open(my $fh,'>'.$fullpath.'/'.$fname);
3316: print $fh $env{'form.'.$formname};
3317: close($fh);
1.1090 raeburn 3318: if ($context eq 'existingfile') {
3319: my @info = stat($fullpath.'/'.$fname);
3320: return ($fullpath.'/'.$fname,$info[9]);
3321: } else {
3322: return $fullpath.'/'.$fname;
3323: }
1.523 raeburn 3324: }
1.995 raeburn 3325: if ($subdir eq 'scantron') {
3326: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3327: } else {
1.995 raeburn 3328: $fname="$subdir/$fname";
3329: }
1.1090 raeburn 3330: if ($context eq 'coursedoc') {
1.638 albertel 3331: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3332: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3333: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3334: return &finishuserfileupload($docuname,$docudom,
3335: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3336: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3337: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3338: } else {
1.1218 raeburn 3339: if ($env{'form.folder'}) {
3340: $fname=$env{'form.folder'}.'/'.$fname;
3341: }
1.638 albertel 3342: return &process_coursefile('uploaddoc',$docuname,$docudom,
3343: $fname,$formname,$parser,
1.1095 raeburn 3344: $allfiles,$codebase,$mimetype);
1.481 raeburn 3345: }
1.719 banghart 3346: } elsif (defined($destuname)) {
3347: my $docuname=$destuname;
3348: my $docudom=$destudom;
1.860 raeburn 3349: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3350: $parser,$allfiles,$codebase,
1.1051 raeburn 3351: $thumbwidth,$thumbheight,
1.1095 raeburn 3352: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3353: } else {
1.638 albertel 3354: my $docuname=$env{'user.name'};
3355: my $docudom=$env{'user.domain'};
1.1220 raeburn 3356: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3357: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3358: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3359: }
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: }
1.271 www 3365: }
3366:
3367: sub finishuserfileupload {
1.860 raeburn 3368: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3369: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3370: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3371: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3372:
1.860 raeburn 3373: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3374: $file=$fname;
3375: if ($fname=~m|/|) {
3376: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3377: $path.=$fnamepath.'/';
3378: }
1.259 www 3379: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3380: my $count;
3381: for ($count=4;$count<=$#parts;$count++) {
3382: $filepath.="/$parts[$count]";
3383: if ((-e $filepath)!=1) {
3384: mkdir($filepath,0777);
3385: }
3386: }
1.984 neumanie 3387:
1.258 www 3388: # Save the file
3389: {
1.701 albertel 3390: if (!open(FH,'>'.$filepath.'/'.$file)) {
3391: &logthis('Failed to create '.$filepath.'/'.$file);
3392: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3393: return '/adm/notfound.html';
3394: }
1.1090 raeburn 3395: if ($context eq 'overwrite') {
1.1117 foxr 3396: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3397: my $target = $filepath.'/'.$file;
3398: if (-e $source) {
3399: my @info = stat($source);
3400: if ($info[9] eq $env{'form.timestamp'}) {
3401: unless (&File::Copy::move($source,$target)) {
3402: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3403: return "Moving from $source failed";
3404: }
3405: } else {
3406: return "Temporary file: $source had unexpected date/time for last modification";
3407: }
3408: } else {
3409: return "Temporary file: $source missing";
3410: }
3411: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3412: &logthis('Failed to write to '.$filepath.'/'.$file);
3413: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3414: return '/adm/notfound.html';
3415: }
1.570 albertel 3416: close(FH);
1.1051 raeburn 3417: if ($resizewidth && $resizeheight) {
3418: my $mm = new File::MMagic;
3419: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3420: if ($mime_type =~ m{^image/}) {
3421: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3422: }
1.977 amueller 3423: }
1.258 www 3424: }
1.1152 raeburn 3425: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3426: if (ref($mimetype)) {
3427: if ($$mimetype eq '') {
3428: my $mm = new File::MMagic;
3429: my $type = $mm->checktype_filename($filepath.'/'.$file);
3430: $$mimetype = $type;
3431: }
3432: }
3433: }
1.637 raeburn 3434: if ($parser eq 'parse') {
1.1152 raeburn 3435: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3436: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3437: $allfiles,$codebase);
3438: unless ($parse_result eq 'ok') {
3439: &logthis('Failed to parse '.$filepath.$file.
3440: ' for embedded media: '.$parse_result);
3441: }
1.637 raeburn 3442: }
3443: }
1.860 raeburn 3444: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3445: my $input = $filepath.'/'.$file;
3446: my $output = $filepath.'/'.'tn-'.$file;
3447: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3448: system("convert -sample $thumbsize $input $output");
3449: if (-e $filepath.'/'.'tn-'.$file) {
3450: $fetchthumb = 1;
3451: }
3452: }
1.858 raeburn 3453:
1.259 www 3454: # Notify homeserver to grep it
3455: #
1.984 neumanie 3456: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3457: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3458: if ($fetchresult eq 'ok') {
1.860 raeburn 3459: if ($fetchthumb) {
3460: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3461: if ($thumbresult ne 'ok') {
3462: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3463: $docuhome.': '.$thumbresult);
3464: }
3465: }
1.259 www 3466: #
1.258 www 3467: # Return the URL to it
1.494 albertel 3468: return '/uploaded/'.$path.$file;
1.263 www 3469: } else {
1.494 albertel 3470: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3471: ': '.$fetchresult);
1.263 www 3472: return '/adm/notfound.html';
1.858 raeburn 3473: }
1.493 albertel 3474: }
3475:
1.637 raeburn 3476: sub extract_embedded_items {
1.961 raeburn 3477: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3478: my @state = ();
1.1164 raeburn 3479: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3480: my %javafiles = (
3481: codebase => '',
3482: code => '',
3483: archive => ''
3484: );
3485: my %mediafiles = (
3486: src => '',
3487: movie => '',
3488: );
1.648 raeburn 3489: my $p;
3490: if ($content) {
3491: $p = HTML::LCParser->new($content);
3492: } else {
1.961 raeburn 3493: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3494: }
1.641 albertel 3495: while (my $t=$p->get_token()) {
1.640 albertel 3496: if ($t->[0] eq 'S') {
3497: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3498: push(@state, $tagname);
1.648 raeburn 3499: if (lc($tagname) eq 'allow') {
3500: &add_filetype($allfiles,$attr->{'src'},'src');
3501: }
1.640 albertel 3502: if (lc($tagname) eq 'img') {
3503: &add_filetype($allfiles,$attr->{'src'},'src');
3504: }
1.886 albertel 3505: if (lc($tagname) eq 'a') {
1.1222 raeburn 3506: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3507: &add_filetype($allfiles,$attr->{'href'},'href');
3508: }
1.886 albertel 3509: }
1.645 raeburn 3510: if (lc($tagname) eq 'script') {
1.1164 raeburn 3511: my $src;
1.645 raeburn 3512: if ($attr->{'archive'} =~ /\.jar$/i) {
3513: &add_filetype($allfiles,$attr->{'archive'},'archive');
3514: } else {
1.1164 raeburn 3515: if ($attr->{'src'} ne '') {
3516: $src = $attr->{'src'};
3517: &add_filetype($allfiles,$src,'src');
3518: }
3519: }
3520: my $text = $p->get_trimmed_text();
3521: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3522: my @swfargs = split(/,/,$1);
3523: foreach my $item (@swfargs) {
3524: $item =~ s/["']//g;
3525: $item =~ s/^\s+//;
3526: $item =~ s/\s+$//;
3527: }
3528: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3529: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3530: push(@{$related{$swfargs[0]}},$swfargs[2]);
3531: } else {
3532: $related{$swfargs[0]} = [$swfargs[2]];
3533: }
3534: }
1.645 raeburn 3535: }
3536: }
3537: if (lc($tagname) eq 'link') {
3538: if (lc($attr->{'rel'}) eq 'stylesheet') {
3539: &add_filetype($allfiles,$attr->{'href'},'href');
3540: }
3541: }
1.640 albertel 3542: if (lc($tagname) eq 'object' ||
3543: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3544: foreach my $item (keys(%javafiles)) {
3545: $javafiles{$item} = '';
3546: }
1.1164 raeburn 3547: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3548: $lastids{lc($tagname)} = $attr->{'id'};
3549: }
1.640 albertel 3550: }
3551: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3552: my $name = lc($attr->{'name'});
3553: foreach my $item (keys(%javafiles)) {
3554: if ($name eq $item) {
3555: $javafiles{$item} = $attr->{'value'};
3556: last;
3557: }
3558: }
1.1164 raeburn 3559: my $pathfrom;
1.640 albertel 3560: foreach my $item (keys(%mediafiles)) {
3561: if ($name eq $item) {
1.1164 raeburn 3562: $pathfrom = $attr->{'value'};
3563: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3564: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3565: last;
3566: }
3567: }
1.1164 raeburn 3568: if ($name eq 'flashvars') {
3569: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3570: }
3571: if ($pathfrom ne '') {
3572: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3573: $pathfrom);
3574: }
1.640 albertel 3575: }
3576: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3577: foreach my $item (keys(%javafiles)) {
3578: if ($attr->{$item}) {
3579: $javafiles{$item} = $attr->{$item};
3580: last;
3581: }
3582: }
3583: foreach my $item (keys(%mediafiles)) {
3584: if ($attr->{$item}) {
3585: &add_filetype($allfiles,$attr->{$item},$item);
3586: last;
3587: }
3588: }
1.1164 raeburn 3589: if (lc($tagname) eq 'embed') {
3590: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3591: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3592: $attr->{'src'});
3593: }
3594: }
1.640 albertel 3595: }
1.1243 raeburn 3596: if (lc($tagname) eq 'iframe') {
3597: my $src = $attr->{'src'} ;
3598: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3599: &add_filetype($allfiles,$src,'src');
3600: } elsif ($src =~ m{^/}) {
3601: if ($env{'request.course.id'}) {
3602: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3603: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3604: my $url = &hreflocation('',$fullpath);
3605: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3606: my $relpath = $1;
3607: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3608: &add_filetype($allfiles,$1,'src');
3609: }
3610: }
3611: }
3612: }
3613: }
1.1164 raeburn 3614: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3615: pop(@state);
1.1164 raeburn 3616: }
1.640 albertel 3617: } elsif ($t->[0] eq 'E') {
3618: my ($tagname) = ($t->[1]);
3619: if ($javafiles{'codebase'} ne '') {
3620: $javafiles{'codebase'} .= '/';
3621: }
3622: if (lc($tagname) eq 'applet' ||
3623: lc($tagname) eq 'object' ||
3624: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3625: ) {
3626: foreach my $item (keys(%javafiles)) {
3627: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3628: my $file=$javafiles{'codebase'}.$javafiles{$item};
3629: &add_filetype($allfiles,$file,$item);
3630: }
3631: }
3632: }
3633: pop @state;
3634: }
3635: }
1.1164 raeburn 3636: foreach my $id (sort(keys(%flashvars))) {
3637: if ($shockwave{$id} ne '') {
3638: my @pairs = split(/\&/,$flashvars{$id});
3639: foreach my $pair (@pairs) {
3640: my ($key,$value) = split(/\=/,$pair);
3641: if ($key eq 'thumb') {
3642: &add_filetype($allfiles,$value,$key);
3643: } elsif ($key eq 'content') {
3644: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3645: my ($ext) = ($value =~ /\.([^.]+)$/);
3646: if ($ext ne '') {
3647: &add_filetype($allfiles,$path.$value,$ext);
3648: }
3649: }
3650: }
3651: }
3652: }
1.637 raeburn 3653: return 'ok';
3654: }
3655:
1.639 albertel 3656: sub add_filetype {
3657: my ($allfiles,$file,$type)=@_;
3658: if (exists($allfiles->{$file})) {
3659: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3660: push(@{$allfiles->{$file}}, &escape($type));
3661: }
3662: } else {
3663: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3664: }
3665: }
3666:
1.1164 raeburn 3667: sub embedded_dependency {
3668: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3669: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3670: if (($identifier ne '') &&
3671: (ref($related->{$identifier}) eq 'ARRAY') &&
3672: ($pathfrom ne '')) {
3673: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3674: foreach my $dep (@{$related->{$identifier}}) {
3675: &add_filetype($allfiles,$path.$dep,'object');
3676: }
3677: }
3678: }
3679: return;
3680: }
3681:
1.493 albertel 3682: sub removeuploadedurl {
1.984 neumanie 3683: my ($url)=@_;
3684: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3685: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3686: }
3687:
3688: sub removeuserfile {
3689: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3690: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3691: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3692: if ($result eq 'ok') {
1.798 raeburn 3693: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3694: my $metafile = $fname.'.meta';
3695: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3696: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3697: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3698: my $sqlresult =
1.823 albertel 3699: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3700: 'portfolio_metadata',$group,
3701: 'delete');
1.798 raeburn 3702: }
3703: }
3704: return $result;
1.257 www 3705: }
1.15 www 3706:
1.530 albertel 3707: sub mkdiruserfile {
3708: my ($docuname,$docudom,$dir)=@_;
3709: my $home=&homeserver($docuname,$docudom);
3710: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3711: }
3712:
1.531 albertel 3713: sub renameuserfile {
3714: my ($docuname,$docudom,$old,$new)=@_;
3715: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3716: my $result = &reply("renameuserfile:$docudom:$docuname:".
3717: &escape("$old").':'.&escape("$new"),$home);
3718: if ($result eq 'ok') {
3719: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3720: my $oldmeta = $old.'.meta';
3721: my $newmeta = $new.'.meta';
3722: my $metaresult =
3723: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3724: my $url = "/uploaded/$docudom/$docuname/$old";
3725: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3726: my $sqlresult =
1.823 albertel 3727: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3728: 'portfolio_metadata',$group,
3729: 'delete');
1.798 raeburn 3730: }
3731: }
3732: return $result;
1.531 albertel 3733: }
3734:
1.14 www 3735: # ------------------------------------------------------------------------- Log
3736:
3737: sub log {
3738: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3739: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3740: }
3741:
3742: # ------------------------------------------------------------------ Course Log
1.352 www 3743: #
3744: # This routine flushes several buffers of non-mission-critical nature
3745: #
1.157 www 3746:
3747: sub flushcourselogs {
1.352 www 3748: &logthis('Flushing log buffers');
3749: #
3750: # course logs
3751: # This is a log of all transactions in a course, which can be used
3752: # for data mining purposes
3753: #
3754: # It also collects the courseid database, which lists last transaction
3755: # times and course titles for all courseids
3756: #
3757: my %courseidbuffer=();
1.921 raeburn 3758: foreach my $crsid (keys(%courselogs)) {
1.352 www 3759: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3760: &escape($courselogs{$crsid}),
3761: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3762: delete $courselogs{$crsid};
3763: } else {
3764: &logthis('Failed to flush log buffer for '.$crsid);
3765: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3766: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3767: " exceeded maximum size, deleting.</font>");
3768: delete $courselogs{$crsid};
3769: }
1.352 www 3770: }
1.920 raeburn 3771: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3772: 'description' => $coursedescrbuf{$crsid},
3773: 'inst_code' => $courseinstcodebuf{$crsid},
3774: 'type' => $coursetypebuf{$crsid},
3775: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3776: };
1.191 harris41 3777: }
1.352 www 3778: #
3779: # Write course id database (reverse lookup) to homeserver of courses
3780: # Is used in pickcourse
3781: #
1.840 albertel 3782: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3783: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3784: $courseidbuffer{$crs_home},
3785: $crs_home,'timeonly');
1.352 www 3786: }
3787: #
3788: # File accesses
3789: # Writes to the dynamic metadata of resources to get hit counts, etc.
3790: #
1.449 matthew 3791: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3792: if ($entry =~ /___count$/) {
3793: my ($dom,$name);
1.807 albertel 3794: ($dom,$name,undef)=
1.811 albertel 3795: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3796: if (! defined($dom) || $dom eq '' ||
3797: ! defined($name) || $name eq '') {
1.620 albertel 3798: my $cid = $env{'request.course.id'};
3799: $dom = $env{'request.'.$cid.'.domain'};
3800: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3801: }
1.450 matthew 3802: my $value = $accesshash{$entry};
3803: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3804: my %temphash=($url => $value);
1.449 matthew 3805: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3806: if ($result eq 'ok') {
3807: delete $accesshash{$entry};
3808: }
3809: } else {
1.811 albertel 3810: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3811: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3812: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3813: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3814: delete $accesshash{$entry};
3815: }
1.185 www 3816: }
1.191 harris41 3817: }
1.352 www 3818: #
3819: # Roles
3820: # Reverse lookup of user roles for course faculty/staff and co-authorship
3821: #
1.800 albertel 3822: foreach my $entry (keys(%userrolehash)) {
1.351 www 3823: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3824: split(/\:/,$entry);
3825: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3826: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3827: $rudom,$runame) eq 'ok') {
3828: delete $userrolehash{$entry};
3829: }
3830: }
1.662 raeburn 3831: #
3832: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3833: #
3834: my %domrolebuffer = ();
1.1000 raeburn 3835: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3836: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3837: if ($domrolebuffer{$rudom}) {
3838: $domrolebuffer{$rudom}.='&'.&escape($entry).
3839: '='.&escape($domainrolehash{$entry});
3840: } else {
3841: $domrolebuffer{$rudom}.=&escape($entry).
3842: '='.&escape($domainrolehash{$entry});
3843: }
3844: delete $domainrolehash{$entry};
3845: }
3846: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3847: my %servers = &get_servers($dom,'library');
3848: foreach my $tryserver (keys(%servers)) {
3849: unless (&reply('domroleput:'.$dom.':'.
3850: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3851: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3852: }
1.662 raeburn 3853: }
3854: }
1.186 www 3855: $dumpcount++;
1.157 www 3856: }
3857:
3858: sub courselog {
3859: my $what=shift;
1.158 www 3860: $what=time.':'.$what;
1.620 albertel 3861: unless ($env{'request.course.id'}) { return ''; }
3862: $coursedombuf{$env{'request.course.id'}}=
3863: $env{'course.'.$env{'request.course.id'}.'.domain'};
3864: $coursenumbuf{$env{'request.course.id'}}=
3865: $env{'course.'.$env{'request.course.id'}.'.num'};
3866: $coursehombuf{$env{'request.course.id'}}=
3867: $env{'course.'.$env{'request.course.id'}.'.home'};
3868: $coursedescrbuf{$env{'request.course.id'}}=
3869: $env{'course.'.$env{'request.course.id'}.'.description'};
3870: $courseinstcodebuf{$env{'request.course.id'}}=
3871: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3872: $courseownerbuf{$env{'request.course.id'}}=
3873: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3874: $coursetypebuf{$env{'request.course.id'}}=
3875: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3876: if (defined $courselogs{$env{'request.course.id'}}) {
3877: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3878: } else {
1.620 albertel 3879: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3880: }
1.620 albertel 3881: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3882: &flushcourselogs();
3883: }
1.158 www 3884: }
3885:
3886: sub courseacclog {
3887: my $fnsymb=shift;
1.620 albertel 3888: unless ($env{'request.course.id'}) { return ''; }
3889: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3890: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3891: $what.=':POST';
1.583 matthew 3892: # FIXME: Probably ought to escape things....
1.800 albertel 3893: foreach my $key (keys(%env)) {
3894: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3895: my $formitem = $1;
3896: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3897: $what.=':'.$formitem.'='.$env{$key};
3898: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3899: $what.=':'.$formitem.'='.$env{$key};
3900: }
1.158 www 3901: }
1.191 harris41 3902: }
1.583 matthew 3903: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3904: # FIXME: We should not be depending on a form parameter that someone
3905: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3906: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3907: $what.= ':POST';
3908: # FIXME: Probably ought to escape things....
3909: foreach my $element ('courseexp','crsfulltext','crsrelated',
3910: 'crsdiscuss') {
1.620 albertel 3911: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3912: }
3913: }
1.158 www 3914: }
3915: &courselog($what);
1.149 www 3916: }
3917:
1.185 www 3918: sub countacc {
3919: my $url=&declutter(shift);
1.458 matthew 3920: return if (! defined($url) || $url eq '');
1.620 albertel 3921: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3922: #
3923: # Mark that this url was used in this course
3924: #
1.620 albertel 3925: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3926: #
3927: # Increase the access count for this resource in this child process
3928: #
1.281 www 3929: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3930: $accesshash{$key}++;
1.185 www 3931: }
1.349 www 3932:
1.361 www 3933: sub linklog {
3934: my ($from,$to)=@_;
3935: $from=&declutter($from);
3936: $to=&declutter($to);
3937: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3938: $accesshash{$to.'___'.$from.'___goto'}=1;
3939: }
1.1160 www 3940:
3941: sub statslog {
3942: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3943: if ($users<2) { return; }
3944: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3945: 'course' => $env{'request.course.id'},
3946: 'sections' => '"all"',
3947: 'num_students' => $users,
3948: 'part' => $part,
3949: 'symb' => $symb,
3950: 'mean_tries' => $av_attempts,
3951: 'deg_of_diff' => $degdiff});
3952: foreach my $key (keys(%dynstore)) {
3953: $accesshash{$key}=$dynstore{$key};
3954: }
3955: }
1.361 www 3956:
1.349 www 3957: sub userrolelog {
3958: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3959: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3960: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3961: $userrolehash
3962: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3963: =$tend.':'.$tstart;
1.662 raeburn 3964: }
1.1169 droeschl 3965: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3966: $userrolehash
3967: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3968: =$tend.':'.$tstart;
3969: }
1.1169 droeschl 3970: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3971: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3972: $domainrolehash
3973: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3974: = $tend.':'.$tstart;
3975: }
1.351 www 3976: }
3977:
1.957 raeburn 3978: sub courserolelog {
3979: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3980: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3981: my $cdom = $1;
3982: my $cnum = $2;
3983: my $sec = $3;
3984: my $namespace = 'rolelog';
3985: my %storehash = (
3986: role => $trole,
3987: start => $tstart,
3988: end => $tend,
3989: selfenroll => $selfenroll,
3990: context => $context,
3991: );
3992: if ($trole eq 'gr') {
3993: $namespace = 'groupslog';
3994: $storehash{'group'} = $sec;
3995: } else {
3996: $storehash{'section'} = $sec;
3997: }
1.1188 raeburn 3998: &write_log('course',$namespace,\%storehash,$delflag,$username,
3999: $domain,$cnum,$cdom);
1.1184 raeburn 4000: if (($trole ne 'st') || ($sec ne '')) {
4001: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4002: }
4003: }
4004: return;
4005: }
4006:
1.1184 raeburn 4007: sub domainrolelog {
4008: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4009: if ($area =~ m{^/($match_domain)/$}) {
4010: my $cdom = $1;
4011: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4012: my $namespace = 'rolelog';
4013: my %storehash = (
4014: role => $trole,
4015: start => $tstart,
4016: end => $tend,
4017: context => $context,
4018: );
1.1188 raeburn 4019: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4020: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4021: }
4022: return;
4023:
4024: }
4025:
4026: sub coauthorrolelog {
4027: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4028: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4029: my $audom = $1;
4030: my $auname = $2;
4031: my $namespace = 'rolelog';
4032: my %storehash = (
4033: role => $trole,
4034: start => $tstart,
4035: end => $tend,
4036: context => $context,
4037: );
1.1188 raeburn 4038: &write_log('author',$namespace,\%storehash,$delflag,$username,
4039: $domain,$auname,$audom);
1.1184 raeburn 4040: }
4041: return;
4042: }
4043:
1.351 www 4044: sub get_course_adv_roles {
1.948 raeburn 4045: my ($cid,$codes) = @_;
1.620 albertel 4046: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4047: my %coursehash=&coursedescription($cid);
1.988 raeburn 4048: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4049: my %nothide=();
1.800 albertel 4050: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4051: if ($user !~ /:/) {
4052: $nothide{join(':',split(/[\@]/,$user))}=1;
4053: } else {
4054: $nothide{$user}=1;
4055: }
1.470 www 4056: }
1.1219 raeburn 4057: my @possdoms = ($coursehash{'domain'});
4058: if ($coursehash{'checkforpriv'}) {
4059: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4060: }
1.351 www 4061: my %returnhash=();
4062: my %dumphash=
4063: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4064: my $now=time;
1.997 raeburn 4065: my %privileged;
1.1000 raeburn 4066: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4067: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4068: if (($tstart) && ($tstart<0)) { next; }
4069: if (($tend) && ($tend<$now)) { next; }
4070: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4071: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4072: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4073: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4074: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4075: if ($role eq 'cr') { next; }
1.948 raeburn 4076: if ($codes) {
4077: if ($section) { $role .= ':'.$section; }
4078: if ($returnhash{$role}) {
4079: $returnhash{$role}.=','.$username.':'.$domain;
4080: } else {
4081: $returnhash{$role}=$username.':'.$domain;
4082: }
1.351 www 4083: } else {
1.988 raeburn 4084: my $key=&plaintext($role,$crstype);
1.973 bisitz 4085: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4086: if ($returnhash{$key}) {
4087: $returnhash{$key}.=','.$username.':'.$domain;
4088: } else {
4089: $returnhash{$key}=$username.':'.$domain;
4090: }
1.351 www 4091: }
1.948 raeburn 4092: }
1.400 www 4093: return %returnhash;
4094: }
4095:
4096: sub get_my_roles {
1.937 raeburn 4097: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4098: unless (defined($uname)) { $uname=$env{'user.name'}; }
4099: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4100: my (%dumphash,%nothide);
1.1086 raeburn 4101: if ($context eq 'userroles') {
1.1166 raeburn 4102: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4103: } else {
1.1219 raeburn 4104: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4105: if ($hidepriv) {
4106: my %coursehash=&coursedescription($udom.'_'.$uname);
4107: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4108: if ($user !~ /:/) {
4109: $nothide{join(':',split(/[\@]/,$user))} = 1;
4110: } else {
4111: $nothide{$user} = 1;
4112: }
4113: }
4114: }
1.858 raeburn 4115: }
1.400 www 4116: my %returnhash=();
4117: my $now=time;
1.999 raeburn 4118: my %privileged;
1.800 albertel 4119: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4120: my ($role,$tend,$tstart);
4121: if ($context eq 'userroles') {
1.1149 raeburn 4122: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4123: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4124: } else {
4125: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4126: }
1.400 www 4127: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4128: my $status = 'active';
1.939 raeburn 4129: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4130: $status = 'previous';
4131: }
4132: if (($tstart) && ($now<$tstart)) {
4133: $status = 'future';
4134: }
4135: if (ref($types) eq 'ARRAY') {
4136: if (!grep(/^\Q$status\E$/,@{$types})) {
4137: next;
4138: }
4139: } else {
4140: if ($status ne 'active') {
4141: next;
4142: }
4143: }
1.867 raeburn 4144: my ($rolecode,$username,$domain,$section,$area);
4145: if ($context eq 'userroles') {
1.1186 raeburn 4146: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4147: (undef,$domain,$username,$section) = split(/\//,$area);
4148: } else {
4149: ($role,$username,$domain,$section) = split(/\:/,$entry);
4150: }
1.832 raeburn 4151: if (ref($roledoms) eq 'ARRAY') {
4152: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4153: next;
4154: }
4155: }
4156: if (ref($roles) eq 'ARRAY') {
4157: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4158: if ($role =~ /^cr\//) {
4159: if (!grep(/^cr$/,@{$roles})) {
4160: next;
4161: }
1.1104 raeburn 4162: } elsif ($role =~ /^gr\//) {
4163: if (!grep(/^gr$/,@{$roles})) {
4164: next;
4165: }
1.922 raeburn 4166: } else {
4167: next;
4168: }
1.832 raeburn 4169: }
1.867 raeburn 4170: }
1.937 raeburn 4171: if ($hidepriv) {
1.1219 raeburn 4172: my @privroles = ('dc','su');
1.999 raeburn 4173: if ($context eq 'userroles') {
1.1219 raeburn 4174: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4175: } else {
1.1219 raeburn 4176: my $possdoms = [$domain];
4177: if (ref($roledoms) eq 'ARRAY') {
4178: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4179: }
1.1219 raeburn 4180: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4181: if (!$nothide{$username.':'.$domain}) {
4182: next;
4183: }
4184: }
1.937 raeburn 4185: }
4186: }
1.933 raeburn 4187: if ($withsec) {
4188: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4189: $tstart.':'.$tend;
4190: } else {
4191: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4192: }
1.832 raeburn 4193: }
1.373 www 4194: return %returnhash;
1.399 www 4195: }
4196:
4197: # ----------------------------------------------------- Frontpage Announcements
4198: #
4199: #
4200:
4201: sub postannounce {
4202: my ($server,$text)=@_;
1.844 albertel 4203: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4204: unless ($text=~/\w/) { $text=''; }
4205: return &reply('setannounce:'.&escape($text),$server);
4206: }
4207:
4208: sub getannounce {
1.448 albertel 4209:
4210: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4211: my $announcement='';
1.800 albertel 4212: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4213: close($fh);
1.399 www 4214: if ($announcement=~/\w/) {
4215: return
4216: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4217: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4218: } else {
4219: return '';
4220: }
4221: } else {
4222: return '';
4223: }
1.351 www 4224: }
1.353 www 4225:
4226: # ---------------------------------------------------------- Course ID routines
4227: # Deal with domain's nohist_courseid.db files
4228: #
4229:
4230: sub courseidput {
1.921 raeburn 4231: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4232: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4233: my $outcome;
4234: if ($caller eq 'timeonly') {
4235: my $cids = '';
4236: foreach my $item (keys(%$storehash)) {
4237: $cids.=&escape($item).'&';
4238: }
4239: $cids=~s/\&$//;
4240: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4241: $coursehome);
4242: } else {
4243: my $items = '';
4244: foreach my $item (keys(%$storehash)) {
4245: $items.= &escape($item).'='.
4246: &freeze_escape($$storehash{$item}).'&';
4247: }
4248: $items=~s/\&$//;
4249: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4250: $coursehome);
1.918 raeburn 4251: }
4252: if ($outcome eq 'unknown_cmd') {
4253: my $what;
4254: foreach my $cid (keys(%$storehash)) {
4255: $what .= &escape($cid).'=';
1.921 raeburn 4256: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4257: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4258: }
4259: $what =~ s/\:$/&/;
4260: }
4261: $what =~ s/\&$//;
4262: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4263: } else {
4264: return $outcome;
4265: }
1.353 www 4266: }
4267:
4268: sub courseiddump {
1.921 raeburn 4269: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4270: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4271: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4272: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4273: $hasuniquecode)=@_;
1.918 raeburn 4274: my $as_hash = 1;
4275: my %returnhash;
4276: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4277: my %libserv = &all_library();
4278: foreach my $tryserver (keys(%libserv)) {
4279: if ( ( $hostidflag == 1
4280: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4281: || (!defined($hostidflag)) ) {
4282:
1.918 raeburn 4283: if (($domfilter eq '') ||
4284: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4285: my $rep;
4286: if (grep { $_ eq $tryserver } current_machine_ids()) {
4287: $rep = LONCAPA::Lond::dump_course_id_handler(
4288: join(":", (&host_domain($tryserver), $sincefilter,
4289: &escape($descfilter), &escape($instcodefilter),
4290: &escape($ownerfilter), &escape($coursefilter),
4291: &escape($typefilter), &escape($regexp_ok),
4292: $as_hash, &escape($selfenrollonly),
4293: &escape($catfilter), $showhidden, $caller,
4294: &escape($cloner), &escape($cc_clone), $cloneonly,
4295: &escape($createdbefore), &escape($createdafter),
1.1247 raeburn 4296: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180 droeschl 4297: } else {
4298: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4299: $sincefilter.':'.&escape($descfilter).':'.
4300: &escape($instcodefilter).':'.&escape($ownerfilter).
4301: ':'.&escape($coursefilter).':'.&escape($typefilter).
4302: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4303: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4304: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4305: &escape($cc_clone).':'.$cloneonly.':'.
4306: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247 raeburn 4307: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180 droeschl 4308: $tryserver);
4309: }
4310:
1.918 raeburn 4311: my @pairs=split(/\&/,$rep);
4312: foreach my $item (@pairs) {
4313: my ($key,$value)=split(/\=/,$item,2);
4314: $key = &unescape($key);
4315: next if ($key =~ /^error: 2 /);
4316: my $result = &thaw_unescape($value);
4317: if (ref($result) eq 'HASH') {
4318: $returnhash{$key}=$result;
4319: } else {
1.921 raeburn 4320: my @responses = split(/:/,$value);
4321: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4322: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4323: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4324: }
1.1008 raeburn 4325: }
1.353 www 4326: }
4327: }
4328: }
4329: }
4330: return %returnhash;
4331: }
4332:
1.1055 raeburn 4333: sub courselastaccess {
4334: my ($cdom,$cnum,$hostidref) = @_;
4335: my %returnhash;
4336: if ($cdom && $cnum) {
4337: my $chome = &homeserver($cnum,$cdom);
4338: if ($chome ne 'no_host') {
4339: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4340: &extract_lastaccess(\%returnhash,$rep);
4341: }
4342: } else {
4343: if (!$cdom) { $cdom=''; }
4344: my %libserv = &all_library();
4345: foreach my $tryserver (keys(%libserv)) {
4346: if (ref($hostidref) eq 'ARRAY') {
4347: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4348: }
4349: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4350: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4351: &extract_lastaccess(\%returnhash,$rep);
4352: }
4353: }
4354: }
4355: return %returnhash;
4356: }
4357:
4358: sub extract_lastaccess {
4359: my ($returnhash,$rep) = @_;
4360: if (ref($returnhash) eq 'HASH') {
4361: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4362: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4363: $rep eq '') {
4364: my @pairs=split(/\&/,$rep);
4365: foreach my $item (@pairs) {
4366: my ($key,$value)=split(/\=/,$item,2);
4367: $key = &unescape($key);
4368: next if ($key =~ /^error: 2 /);
4369: $returnhash->{$key} = &thaw_unescape($value);
4370: }
4371: }
4372: }
4373: return;
4374: }
4375:
1.658 raeburn 4376: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4377:
4378: sub dcmailput {
1.685 raeburn 4379: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4380: my $status = &Apache::lonnet::critical(
1.740 www 4381: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4382: &escape($message),$server);
1.662 raeburn 4383: return $status;
4384: }
4385:
1.658 raeburn 4386: sub dcmaildump {
4387: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4388: my %returnhash=();
1.846 albertel 4389:
4390: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4391: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4392: &escape($enddate).':';
4393: my @esc_senders=map { &escape($_)} @$senders;
4394: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4395: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4396: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4397: if (($key) && ($value)) {
4398: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4399: }
4400: }
4401: }
4402: return %returnhash;
4403: }
1.662 raeburn 4404: # ---------------------------------------------------------- Domain roles
4405:
4406: sub get_domain_roles {
4407: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4408: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4409: $startdate = '.';
4410: }
1.1018 raeburn 4411: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4412: $enddate = '.';
4413: }
1.922 raeburn 4414: my $rolelist;
4415: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4416: $rolelist = join('&',@{$roles});
1.922 raeburn 4417: }
1.662 raeburn 4418: my %personnel = ();
1.841 albertel 4419:
4420: my %servers = &get_servers($dom,'library');
4421: foreach my $tryserver (keys(%servers)) {
4422: %{$personnel{$tryserver}}=();
4423: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4424: &escape($startdate).':'.
4425: &escape($enddate).':'.
4426: &escape($rolelist), $tryserver))) {
4427: my ($key,$value) = split(/\=/,$line,2);
4428: if (($key) && ($value)) {
4429: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4430: }
4431: }
1.662 raeburn 4432: }
4433: return %personnel;
4434: }
1.658 raeburn 4435:
1.1057 www 4436: # ----------------------------------------------------------- Interval timing
1.149 www 4437:
1.1153 www 4438: {
4439: # Caches needed for speedup of navmaps
4440: # We don't want to cache this for very long at all (5 seconds at most)
4441: #
4442: # The user for whom we cache
4443: my $cachedkey='';
4444: # The cached times for this user
4445: my %cachedtimes=();
4446: # When this was last done
1.1282 ! raeburn 4447: my $cachedtime='';
1.1153 www 4448:
4449: sub load_all_first_access {
1.1154 raeburn 4450: my ($uname,$udom)=@_;
1.1156 www 4451: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4452: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4453: return;
4454: }
4455: $cachedtime=time;
4456: $cachedkey=$uname.':'.$udom;
4457: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4458: }
4459:
1.504 albertel 4460: sub get_first_access {
1.1162 raeburn 4461: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4462: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4463: if ($argsymb) { $symb=$argsymb; }
4464: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4465: if ($argmap) { $map = $argmap; }
1.926 albertel 4466: if ($type eq 'course') {
4467: $res='course';
4468: } elsif ($type eq 'map') {
1.588 albertel 4469: $res=&symbread($map);
4470: } else {
4471: $res=$symb;
4472: }
1.1153 www 4473: &load_all_first_access($uname,$udom);
4474: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4475: }
4476:
4477: sub set_first_access {
1.1162 raeburn 4478: my ($type,$interval)=@_;
1.790 albertel 4479: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4480: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4481: if ($type eq 'course') {
4482: $res='course';
4483: } elsif ($type eq 'map') {
1.588 albertel 4484: $res=&symbread($map);
4485: } else {
4486: $res=$symb;
4487: }
1.1153 www 4488: $cachedkey='';
1.1162 raeburn 4489: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4490: if (!$firstaccess) {
1.1162 raeburn 4491: my $start = time;
4492: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4493: $udom,$uname);
4494: if ($putres eq 'ok') {
4495: &put('timerinterval',{"$courseid\0$res"=>$interval},
4496: $udom,$uname);
4497: &appenv(
4498: {
4499: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4500: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4501: }
4502: );
4503: }
4504: return $putres;
1.505 albertel 4505: }
4506: return 'already_set';
1.504 albertel 4507: }
1.1153 www 4508: }
1.1282 ! raeburn 4509:
1.110 www 4510: # --------------------------------------------- Set Expire Date for Spreadsheet
4511:
4512: sub expirespread {
4513: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4514: my $cid=$env{'request.course.id'};
1.110 www 4515: if ($cid) {
4516: my $now=time;
4517: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4518: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4519: $env{'course.'.$cid.'.num'}.
1.110 www 4520: ':nohist_expirationdates:'.
4521: &escape($key).'='.$now,
1.620 albertel 4522: $env{'course.'.$cid.'.home'})
1.110 www 4523: }
4524: return 'ok';
1.14 www 4525: }
4526:
1.109 www 4527: # ----------------------------------------------------- Devalidate Spreadsheets
4528:
4529: sub devalidate {
1.325 www 4530: my ($symb,$uname,$udom)=@_;
1.620 albertel 4531: my $cid=$env{'request.course.id'};
1.109 www 4532: if ($cid) {
1.391 matthew 4533: # delete the stored spreadsheets for
4534: # - the student level sheet of this user in course's homespace
4535: # - the assessment level sheet for this resource
4536: # for this user in user's homespace
1.553 albertel 4537: # - current conditional state info
1.325 www 4538: my $key=$uname.':'.$udom.':';
1.109 www 4539: my $status=
1.299 matthew 4540: &del('nohist_calculatedsheets',
1.391 matthew 4541: [$key.'studentcalc:'],
1.620 albertel 4542: $env{'course.'.$cid.'.domain'},
4543: $env{'course.'.$cid.'.num'})
1.133 albertel 4544: .' '.
4545: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4546: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4547: unless ($status eq 'ok ok') {
4548: &logthis('Could not devalidate spreadsheet '.
1.325 www 4549: $uname.' at '.$udom.' for '.
1.109 www 4550: $symb.': '.$status);
1.133 albertel 4551: }
1.553 albertel 4552: &delenv('user.state.'.$cid);
1.109 www 4553: }
4554: }
4555:
1.265 albertel 4556: sub get_scalar {
4557: my ($string,$end) = @_;
4558: my $value;
4559: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4560: $value = $1;
4561: } elsif ($$string =~ s/^([^&]*?)&//) {
4562: $value = $1;
4563: }
4564: return &unescape($value);
4565: }
4566:
4567: sub array2str {
4568: my (@array) = @_;
4569: my $result=&arrayref2str(\@array);
4570: $result=~s/^__ARRAY_REF__//;
4571: $result=~s/__END_ARRAY_REF__$//;
4572: return $result;
4573: }
4574:
1.204 albertel 4575: sub arrayref2str {
4576: my ($arrayref) = @_;
1.265 albertel 4577: my $result='__ARRAY_REF__';
1.204 albertel 4578: foreach my $elem (@$arrayref) {
1.265 albertel 4579: if(ref($elem) eq 'ARRAY') {
4580: $result.=&arrayref2str($elem).'&';
4581: } elsif(ref($elem) eq 'HASH') {
4582: $result.=&hashref2str($elem).'&';
4583: } elsif(ref($elem)) {
4584: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4585: } else {
4586: $result.=&escape($elem).'&';
4587: }
4588: }
4589: $result=~s/\&$//;
1.265 albertel 4590: $result .= '__END_ARRAY_REF__';
1.204 albertel 4591: return $result;
4592: }
4593:
1.168 albertel 4594: sub hash2str {
1.204 albertel 4595: my (%hash) = @_;
4596: my $result=&hashref2str(\%hash);
1.265 albertel 4597: $result=~s/^__HASH_REF__//;
4598: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4599: return $result;
4600: }
4601:
4602: sub hashref2str {
4603: my ($hashref)=@_;
1.265 albertel 4604: my $result='__HASH_REF__';
1.800 albertel 4605: foreach my $key (sort(keys(%$hashref))) {
4606: if (ref($key) eq 'ARRAY') {
4607: $result.=&arrayref2str($key).'=';
4608: } elsif (ref($key) eq 'HASH') {
4609: $result.=&hashref2str($key).'=';
4610: } elsif (ref($key)) {
1.265 albertel 4611: $result.='=';
1.800 albertel 4612: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4613: } else {
1.1132 raeburn 4614: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4615: }
4616:
1.800 albertel 4617: if(ref($hashref->{$key}) eq 'ARRAY') {
4618: $result.=&arrayref2str($hashref->{$key}).'&';
4619: } elsif(ref($hashref->{$key}) eq 'HASH') {
4620: $result.=&hashref2str($hashref->{$key}).'&';
4621: } elsif(ref($hashref->{$key})) {
1.265 albertel 4622: $result.='&';
1.800 albertel 4623: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4624: } else {
1.800 albertel 4625: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4626: }
4627: }
1.168 albertel 4628: $result=~s/\&$//;
1.265 albertel 4629: $result .= '__END_HASH_REF__';
1.168 albertel 4630: return $result;
4631: }
4632:
4633: sub str2hash {
1.265 albertel 4634: my ($string)=@_;
4635: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4636: return %$hash;
4637: }
4638:
4639: sub str2hashref {
1.168 albertel 4640: my ($string) = @_;
1.265 albertel 4641:
4642: my %hash;
4643:
4644: if($string !~ /^__HASH_REF__/) {
4645: if (! ($string eq '' || !defined($string))) {
4646: $hash{'error'}='Not hash reference';
4647: }
4648: return (\%hash, $string);
4649: }
4650:
4651: $string =~ s/^__HASH_REF__//;
4652:
4653: while($string !~ /^__END_HASH_REF__/) {
4654: #key
4655: my $key='';
4656: if($string =~ /^__HASH_REF__/) {
4657: ($key, $string)=&str2hashref($string);
4658: if(defined($key->{'error'})) {
4659: $hash{'error'}='Bad data';
4660: return (\%hash, $string);
4661: }
4662: } elsif($string =~ /^__ARRAY_REF__/) {
4663: ($key, $string)=&str2arrayref($string);
4664: if($key->[0] eq 'Array reference error') {
4665: $hash{'error'}='Bad data';
4666: return (\%hash, $string);
4667: }
4668: } else {
4669: $string =~ s/^(.*?)=//;
1.267 albertel 4670: $key=&unescape($1);
1.265 albertel 4671: }
4672: $string =~ s/^=//;
4673:
4674: #value
4675: my $value='';
4676: if($string =~ /^__HASH_REF__/) {
4677: ($value, $string)=&str2hashref($string);
4678: if(defined($value->{'error'})) {
4679: $hash{'error'}='Bad data';
4680: return (\%hash, $string);
4681: }
4682: } elsif($string =~ /^__ARRAY_REF__/) {
4683: ($value, $string)=&str2arrayref($string);
4684: if($value->[0] eq 'Array reference error') {
4685: $hash{'error'}='Bad data';
4686: return (\%hash, $string);
4687: }
4688: } else {
4689: $value=&get_scalar(\$string,'__END_HASH_REF__');
4690: }
4691: $string =~ s/^&//;
4692:
4693: $hash{$key}=$value;
1.204 albertel 4694: }
1.265 albertel 4695:
4696: $string =~ s/^__END_HASH_REF__//;
4697:
4698: return (\%hash, $string);
1.204 albertel 4699: }
4700:
4701: sub str2array {
1.265 albertel 4702: my ($string)=@_;
4703: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4704: return @$array;
4705: }
4706:
4707: sub str2arrayref {
1.204 albertel 4708: my ($string) = @_;
1.265 albertel 4709: my @array;
4710:
4711: if($string !~ /^__ARRAY_REF__/) {
4712: if (! ($string eq '' || !defined($string))) {
4713: $array[0]='Array reference error';
4714: }
4715: return (\@array, $string);
4716: }
4717:
4718: $string =~ s/^__ARRAY_REF__//;
4719:
4720: while($string !~ /^__END_ARRAY_REF__/) {
4721: my $value='';
4722: if($string =~ /^__HASH_REF__/) {
4723: ($value, $string)=&str2hashref($string);
4724: if(defined($value->{'error'})) {
4725: $array[0] ='Array reference error';
4726: return (\@array, $string);
4727: }
4728: } elsif($string =~ /^__ARRAY_REF__/) {
4729: ($value, $string)=&str2arrayref($string);
4730: if($value->[0] eq 'Array reference error') {
4731: $array[0] ='Array reference error';
4732: return (\@array, $string);
4733: }
4734: } else {
4735: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4736: }
4737: $string =~ s/^&//;
4738:
4739: push(@array, $value);
1.191 harris41 4740: }
1.265 albertel 4741:
4742: $string =~ s/^__END_ARRAY_REF__//;
4743:
4744: return (\@array, $string);
1.168 albertel 4745: }
4746:
1.167 albertel 4747: # -------------------------------------------------------------------Temp Store
4748:
1.168 albertel 4749: sub tmpreset {
4750: my ($symb,$namespace,$domain,$stuname) = @_;
4751: if (!$symb) {
4752: $symb=&symbread();
1.620 albertel 4753: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4754: }
4755: $symb=escape($symb);
4756:
1.620 albertel 4757: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4758: $namespace=~s/\//\_/g;
4759: $namespace=~s/\W//g;
4760:
1.620 albertel 4761: if (!$domain) { $domain=$env{'user.domain'}; }
4762: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4763: if ($domain eq 'public' && $stuname eq 'public') {
4764: $stuname=$ENV{'REMOTE_ADDR'};
4765: }
1.1117 foxr 4766: my $path=LONCAPA::tempdir();
1.168 albertel 4767: my %hash;
4768: if (tie(%hash,'GDBM_File',
4769: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4770: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4771: foreach my $key (keys(%hash)) {
1.180 albertel 4772: if ($key=~ /:$symb/) {
1.168 albertel 4773: delete($hash{$key});
4774: }
4775: }
4776: }
4777: }
4778:
1.167 albertel 4779: sub tmpstore {
1.168 albertel 4780: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4781:
4782: if (!$symb) {
4783: $symb=&symbread();
1.620 albertel 4784: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4785: }
4786: $symb=escape($symb);
4787:
4788: if (!$namespace) {
4789: # I don't think we would ever want to store this for a course.
4790: # it seems this will only be used if we don't have a course.
1.620 albertel 4791: #$namespace=$env{'request.course.id'};
1.168 albertel 4792: #if (!$namespace) {
1.620 albertel 4793: $namespace=$env{'request.state'};
1.168 albertel 4794: #}
4795: }
4796: $namespace=~s/\//\_/g;
4797: $namespace=~s/\W//g;
1.620 albertel 4798: if (!$domain) { $domain=$env{'user.domain'}; }
4799: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4800: if ($domain eq 'public' && $stuname eq 'public') {
4801: $stuname=$ENV{'REMOTE_ADDR'};
4802: }
1.168 albertel 4803: my $now=time;
4804: my %hash;
1.1117 foxr 4805: my $path=LONCAPA::tempdir();
1.168 albertel 4806: if (tie(%hash,'GDBM_File',
4807: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4808: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4809: $hash{"version:$symb"}++;
4810: my $version=$hash{"version:$symb"};
4811: my $allkeys='';
4812: foreach my $key (keys(%$storehash)) {
4813: $allkeys.=$key.':';
1.591 albertel 4814: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4815: }
4816: $hash{"$version:$symb:timestamp"}=$now;
4817: $allkeys.='timestamp';
4818: $hash{"$version:keys:$symb"}=$allkeys;
4819: if (untie(%hash)) {
4820: return 'ok';
4821: } else {
4822: return "error:$!";
4823: }
4824: } else {
4825: return "error:$!";
4826: }
4827: }
1.167 albertel 4828:
1.168 albertel 4829: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4830:
1.168 albertel 4831: sub tmprestore {
4832: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4833:
1.168 albertel 4834: if (!$symb) {
4835: $symb=&symbread();
1.620 albertel 4836: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4837: }
4838: $symb=escape($symb);
4839:
1.620 albertel 4840: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4841:
1.620 albertel 4842: if (!$domain) { $domain=$env{'user.domain'}; }
4843: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4844: if ($domain eq 'public' && $stuname eq 'public') {
4845: $stuname=$ENV{'REMOTE_ADDR'};
4846: }
1.168 albertel 4847: my %returnhash;
4848: $namespace=~s/\//\_/g;
4849: $namespace=~s/\W//g;
4850: my %hash;
1.1117 foxr 4851: my $path=LONCAPA::tempdir();
1.168 albertel 4852: if (tie(%hash,'GDBM_File',
4853: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4854: &GDBM_READER(),0640)) {
1.168 albertel 4855: my $version=$hash{"version:$symb"};
4856: $returnhash{'version'}=$version;
4857: my $scope;
4858: for ($scope=1;$scope<=$version;$scope++) {
4859: my $vkeys=$hash{"$scope:keys:$symb"};
4860: my @keys=split(/:/,$vkeys);
4861: my $key;
4862: $returnhash{"$scope:keys"}=$vkeys;
4863: foreach $key (@keys) {
1.591 albertel 4864: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4865: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4866: }
4867: }
1.168 albertel 4868: if (!(untie(%hash))) {
4869: return "error:$!";
4870: }
4871: } else {
4872: return "error:$!";
4873: }
4874: return %returnhash;
1.167 albertel 4875: }
4876:
1.9 www 4877: # ----------------------------------------------------------------------- Store
4878:
4879: sub store {
1.1269 raeburn 4880: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4881: my $home='';
4882:
1.168 albertel 4883: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4884:
1.213 www 4885: $symb=&symbclean($symb);
1.122 albertel 4886: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4887:
1.620 albertel 4888: if (!$domain) { $domain=$env{'user.domain'}; }
4889: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4890:
4891: &devalidate($symb,$stuname,$domain);
1.109 www 4892:
4893: $symb=escape($symb);
1.187 www 4894: if (!$namespace) {
1.620 albertel 4895: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4896: return '';
4897: }
4898: }
1.620 albertel 4899: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4900:
4901: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4902: $$storehash{'host'}=$perlvar{'lonHostID'};
4903:
1.12 www 4904: my $namevalue='';
1.800 albertel 4905: foreach my $key (keys(%$storehash)) {
4906: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4907: }
1.12 www 4908: $namevalue=~s/\&$//;
1.187 www 4909: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 4910: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 4911: }
4912:
1.47 www 4913: # -------------------------------------------------------------- Critical Store
4914:
4915: sub cstore {
1.1269 raeburn 4916: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4917: my $home='';
4918:
1.168 albertel 4919: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4920:
1.213 www 4921: $symb=&symbclean($symb);
1.122 albertel 4922: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4923:
1.620 albertel 4924: if (!$domain) { $domain=$env{'user.domain'}; }
4925: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4926:
4927: &devalidate($symb,$stuname,$domain);
1.109 www 4928:
4929: $symb=escape($symb);
1.187 www 4930: if (!$namespace) {
1.620 albertel 4931: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4932: return '';
4933: }
4934: }
1.620 albertel 4935: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4936:
4937: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4938: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4939:
1.47 www 4940: my $namevalue='';
1.800 albertel 4941: foreach my $key (keys(%$storehash)) {
4942: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4943: }
1.47 www 4944: $namevalue=~s/\&$//;
1.187 www 4945: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4946: return critical
1.1269 raeburn 4947: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 4948: }
4949:
1.9 www 4950: # --------------------------------------------------------------------- Restore
4951:
4952: sub restore {
1.124 www 4953: my ($symb,$namespace,$domain,$stuname) = @_;
4954: my $home='';
4955:
1.168 albertel 4956: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4957:
1.122 albertel 4958: if (!$symb) {
1.1224 raeburn 4959: return if ($namespace eq 'courserequests');
4960: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4961: } else {
1.1224 raeburn 4962: unless ($namespace eq 'courserequests') {
4963: $symb=&escape(&symbclean($symb));
4964: }
1.122 albertel 4965: }
1.188 www 4966: if (!$namespace) {
1.620 albertel 4967: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4968: return '';
4969: }
4970: }
1.620 albertel 4971: if (!$domain) { $domain=$env{'user.domain'}; }
4972: if (!$stuname) { $stuname=$env{'user.name'}; }
4973: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4974: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4975:
1.12 www 4976: my %returnhash=();
1.800 albertel 4977: foreach my $line (split(/\&/,$answer)) {
4978: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4979: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4980: }
1.75 www 4981: my $version;
4982: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4983: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4984: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4985: }
1.75 www 4986: }
1.13 www 4987: return %returnhash;
1.34 www 4988: }
4989:
4990: # ---------------------------------------------------------- Course Description
1.1118 foxr 4991: #
4992: #
1.34 www 4993:
4994: sub coursedescription {
1.731 albertel 4995: my ($courseid,$args)=@_;
1.34 www 4996: $courseid=~s/^\///;
1.49 www 4997: $courseid=~s/\_/\//g;
1.34 www 4998: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4999: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5000: my $normalid=$cdomain.'_'.$cnum;
5001: # need to always cache even if we get errors otherwise we keep
5002: # trying and trying and trying to get the course description.
5003: my %envhash=();
5004: my %returnhash=();
1.731 albertel 5005:
5006: my $expiretime=600;
5007: if ($env{'request.course.id'} eq $normalid) {
5008: $expiretime=120;
5009: }
5010:
5011: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5012: if (!$args->{'freshen_cache'}
5013: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5014: foreach my $key (keys(%env)) {
5015: next if ($key !~ /^\Q$prefix\E(.*)/);
5016: my ($setting) = $1;
5017: $returnhash{$setting} = $env{$key};
5018: }
5019: return %returnhash;
5020: }
5021:
1.1118 foxr 5022: # get the data again
5023:
1.731 albertel 5024: if (!$args->{'one_time'}) {
5025: $envhash{'course.'.$normalid.'.last_cache'}=time;
5026: }
1.811 albertel 5027:
1.34 www 5028: if ($chome ne 'no_host') {
1.302 albertel 5029: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5030: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5031: my $username = $env{'user.name'}; # Defult username
5032: if(defined $args->{'user'}) {
5033: $username = $args->{'user'};
5034: }
1.129 albertel 5035: $returnhash{'home'}= $chome;
5036: $returnhash{'domain'} = $cdomain;
5037: $returnhash{'num'} = $cnum;
1.741 raeburn 5038: if (!defined($returnhash{'type'})) {
5039: $returnhash{'type'} = 'Course';
5040: }
1.130 albertel 5041: while (my ($name,$value) = each %returnhash) {
1.53 www 5042: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5043: }
1.270 www 5044: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5045: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5046: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5047: $envhash{'course.'.$normalid.'.home'}=$chome;
5048: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5049: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5050: }
5051: }
1.731 albertel 5052: if (!$args->{'one_time'}) {
1.949 raeburn 5053: &appenv(\%envhash);
1.731 albertel 5054: }
1.302 albertel 5055: return %returnhash;
1.461 www 5056: }
5057:
1.1080 raeburn 5058: sub update_released_required {
5059: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5060: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5061: $cid = $env{'request.course.id'};
5062: $cdom = $env{'course.'.$cid.'.domain'};
5063: $cnum = $env{'course.'.$cid.'.num'};
5064: $chome = $env{'course.'.$cid.'.home'};
5065: }
5066: if ($needsrelease) {
5067: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5068: my $needsupdate;
5069: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5070: $needsupdate = 1;
5071: } else {
5072: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5073: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5074: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5075: $needsupdate = 1;
5076: }
5077: }
5078: if ($needsupdate) {
5079: my %needshash = (
5080: 'internal.releaserequired' => $needsrelease,
5081: );
5082: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5083: if ($putresult eq 'ok') {
5084: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5085: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5086: if (ref($crsinfo{$cid}) eq 'HASH') {
5087: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5088: &courseidput($cdom,\%crsinfo,$chome,'notime');
5089: }
5090: }
5091: }
5092: }
5093: return;
5094: }
5095:
1.461 www 5096: # -------------------------------------------------See if a user is privileged
5097:
5098: sub privileged {
1.1219 raeburn 5099: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5100: my $now = time;
1.1219 raeburn 5101: my $roles;
5102: if (ref($possroles) eq 'ARRAY') {
5103: $roles = $possroles;
5104: } else {
5105: $roles = ['dc','su'];
5106: }
5107: if (ref($possdomains) eq 'ARRAY') {
5108: my %privileged = &privileged_by_domain($possdomains,$roles);
5109: foreach my $dom (@{$possdomains}) {
5110: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5111: (ref($privileged{$dom}) eq 'HASH')) {
5112: foreach my $role (@{$roles}) {
5113: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5114: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5115: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5116: return 1 unless (($end && $end < $now) ||
5117: ($start && $start > $now));
5118: }
5119: }
5120: }
5121: }
5122: }
5123: } else {
5124: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5125: my $now = time;
1.1170 droeschl 5126:
1.1275 musolffc 5127: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5128: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5129: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5130: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5131: or ($tstart && $tstart > $now);
1.1170 droeschl 5132: }
1.1219 raeburn 5133: }
5134: }
5135: return 0;
5136: }
1.1170 droeschl 5137:
1.1219 raeburn 5138: sub privileged_by_domain {
5139: my ($domains,$roles) = @_;
5140: my %privileged = ();
5141: my $cachetime = 60*60*24;
5142: my $now = time;
5143: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5144: return %privileged;
5145: }
5146: foreach my $dom (@{$domains}) {
5147: next if (ref($privileged{$dom}) eq 'HASH');
5148: my $needroles;
5149: foreach my $role (@{$roles}) {
5150: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5151: if (defined($cached)) {
5152: if (ref($result) eq 'HASH') {
5153: $privileged{$dom}{$role} = $result;
5154: }
5155: } else {
5156: $needroles = 1;
5157: }
5158: }
5159: if ($needroles) {
5160: my %dompersonnel = &get_domain_roles($dom,$roles);
5161: $privileged{$dom} = {};
5162: foreach my $server (keys(%dompersonnel)) {
5163: if (ref($dompersonnel{$server}) eq 'HASH') {
5164: foreach my $item (keys(%{$dompersonnel{$server}})) {
5165: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5166: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5167: next if ($end && $end < $now);
5168: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5169: $dompersonnel{$server}{$item};
5170: }
5171: }
5172: }
5173: if (ref($privileged{$dom}) eq 'HASH') {
5174: foreach my $role (@{$roles}) {
5175: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5176: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5177: } else {
5178: my %hash = ();
5179: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5180: }
5181: }
5182: }
5183: }
5184: }
5185: return %privileged;
1.9 www 5186: }
1.1 albertel 5187:
1.103 harris41 5188: # -------------------------------------------------------- Get user privileges
1.11 www 5189:
5190: sub rolesinit {
1.1169 droeschl 5191: my ($domain, $username) = @_;
5192: my %userroles = ('user.login.time' => time);
5193: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5194:
5195: # firstaccess and timerinterval are related to timed maps/resources.
5196: # also, blocking can be triggered by an activating timer
5197: # it's saved in the user's %env.
5198: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5199: my %timerinterval = &dump('timerinterval', $domain, $username);
5200: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5201: %timerintchk, %timerintenv);
5202:
1.1162 raeburn 5203: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5204: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5205: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5206: }
1.1169 droeschl 5207:
1.1162 raeburn 5208: foreach my $key (keys(%timerinterval)) {
5209: my ($cid,$rest) = split(/\0/,$key);
5210: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5211: }
1.1169 droeschl 5212:
1.11 www 5213: my %allroles=();
1.1162 raeburn 5214: my %allgroups=();
1.11 www 5215:
1.1274 raeburn 5216: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5217: my $role = $rolesdump{$area};
5218: $area =~ s/\_\w\w$//;
5219:
5220: my ($trole, $tend, $tstart, $group_privs);
5221:
5222: if ($role =~ /^cr/) {
5223: # Custom role, defined by a user
5224: # e.g., user.role.cr/msu/smith/mynewrole
5225: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5226: $trole = $1;
5227: ($tend, $tstart) = split('_', $2);
5228: } else {
5229: $trole = $role;
5230: }
5231: } elsif ($role =~ m|^gr/|) {
5232: # Role of member in a group, defined within a course/community
5233: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5234: ($trole, $tend, $tstart) = split(/_/, $role);
5235: next if $tstart eq '-1';
5236: ($trole, $group_privs) = split(/\//, $trole);
5237: $group_privs = &unescape($group_privs);
5238: } else {
5239: # Just a normal role, defined in roles.tab
5240: ($trole, $tend, $tstart) = split(/_/,$role);
5241: }
5242:
5243: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5244: $username);
5245: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5246:
5247: # role expired or not available yet?
5248: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5249: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5250:
5251: next if $area eq '' or $trole eq '';
5252:
5253: my $spec = "$trole.$area";
5254: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5255:
5256: if ($trole =~ /^cr\//) {
5257: # Custom role, defined by a user
5258: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5259: } elsif ($trole eq 'gr') {
5260: # Role of a member in a group, defined within a course/community
5261: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5262: next;
5263: } else {
5264: # Normal role, defined in roles.tab
5265: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5266: }
5267:
5268: my $cid = $tdomain.'_'.$trest;
5269: unless ($firstaccchk{$cid}) {
5270: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5271: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5272: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5273: $coursetimerstarts{$cid}{$item};
5274: }
5275: }
5276: $firstaccchk{$cid} = 1;
5277: }
5278: unless ($timerintchk{$cid}) {
5279: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5280: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5281: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5282: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5283: }
1.12 www 5284: }
1.1169 droeschl 5285: $timerintchk{$cid} = 1;
1.191 harris41 5286: }
1.11 www 5287: }
1.1169 droeschl 5288:
5289: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5290: \%allroles, \%allgroups);
5291: $env{'user.adv'} = $userroles{'user.adv'};
5292:
1.1162 raeburn 5293: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5294: }
5295:
1.567 raeburn 5296: sub set_arearole {
1.1215 raeburn 5297: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5298: unless ($nolog) {
1.567 raeburn 5299: # log the associated role with the area
1.1215 raeburn 5300: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5301: }
1.743 albertel 5302: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5303: }
5304:
5305: sub custom_roleprivs {
5306: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5307: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5308: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5309: if (&hostname($homsvr) ne '') {
1.567 raeburn 5310: my ($rdummy,$roledef)=
5311: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5312: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5313: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5314: if (defined($syspriv)) {
1.1043 raeburn 5315: if ($trest =~ /^$match_community$/) {
5316: $syspriv =~ s/bre\&S//;
5317: }
1.567 raeburn 5318: $$allroles{'cm./'}.=':'.$syspriv;
5319: $$allroles{$spec.'./'}.=':'.$syspriv;
5320: }
5321: if ($tdomain ne '') {
5322: if (defined($dompriv)) {
5323: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5324: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5325: }
5326: if (($trest ne '') && (defined($coursepriv))) {
5327: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5328: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5329: }
5330: }
5331: }
5332: }
5333: }
5334:
1.678 raeburn 5335: sub group_roleprivs {
5336: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5337: my $access = 1;
5338: my $now = time;
5339: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5340: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5341: if ($access) {
1.811 albertel 5342: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5343: $$allgroups{$course}{$group} .=':'.$group_privs;
5344: }
5345: }
1.567 raeburn 5346:
5347: sub standard_roleprivs {
5348: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5349: if (defined($pr{$trole.':s'})) {
5350: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5351: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5352: }
5353: if ($tdomain ne '') {
5354: if (defined($pr{$trole.':d'})) {
5355: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5356: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5357: }
5358: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5359: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5360: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5361: }
5362: }
5363: }
5364:
5365: sub set_userprivs {
1.1064 raeburn 5366: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5367: my $author=0;
5368: my $adv=0;
1.678 raeburn 5369: my %grouproles = ();
5370: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5371: my @groupkeys;
1.1000 raeburn 5372: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5373: push(@groupkeys,$role);
5374: }
5375: if (ref($groups_roles) eq 'HASH') {
5376: foreach my $key (keys(%{$groups_roles})) {
5377: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5378: push(@groupkeys,$key);
5379: }
5380: }
5381: }
5382: if (@groupkeys > 0) {
5383: foreach my $role (@groupkeys) {
5384: my ($trole,$area,$sec,$extendedarea);
5385: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5386: $trole = $1;
5387: $area = $2;
5388: $sec = $3;
5389: $extendedarea = $area.$sec;
5390: if (exists($$allgroups{$area})) {
5391: foreach my $group (keys(%{$$allgroups{$area}})) {
5392: my $spec = $trole.'.'.$extendedarea;
5393: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5394: $$allgroups{$area}{$group};
1.1064 raeburn 5395: }
1.678 raeburn 5396: }
5397: }
5398: }
5399: }
5400: }
1.800 albertel 5401: foreach my $group (keys(%grouproles)) {
5402: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5403: }
1.800 albertel 5404: foreach my $role (keys(%{$allroles})) {
5405: my %thesepriv;
1.941 raeburn 5406: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5407: foreach my $item (split(/:/,$$allroles{$role})) {
5408: if ($item ne '') {
5409: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5410: if ($restrictions eq '') {
5411: $thesepriv{$privilege}='F';
5412: } elsif ($thesepriv{$privilege} ne 'F') {
5413: $thesepriv{$privilege}.=$restrictions;
5414: }
5415: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5416: }
5417: }
5418: my $thesestr='';
1.1104 raeburn 5419: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5420: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5421: }
5422: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5423: }
5424: return ($author,$adv);
5425: }
5426:
1.994 raeburn 5427: sub role_status {
1.1104 raeburn 5428: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5429: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5430: my ($one,$two) = split(m{\./},$rolekey,2);
5431: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5432: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5433: $$where = '/'.$two;
1.994 raeburn 5434: $$trolecode=$$role.'.'.$$where;
5435: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5436: $$tstatus='is';
1.1104 raeburn 5437: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5438: $$tstatus='future';
1.1034 raeburn 5439: if ($$tstart<$now) {
5440: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5441: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5442: my (%allroles,%allgroups,$group_privs,
5443: %groups_roles,@rolecodes);
1.1002 raeburn 5444: my %userroles = (
5445: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5446: );
1.1064 raeburn 5447: @rolecodes = ('cm');
1.1002 raeburn 5448: my $spec=$$role.'.'.$$where;
5449: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5450: if ($$role =~ /^cr\//) {
5451: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5452: push(@rolecodes,'cr');
1.1002 raeburn 5453: } elsif ($$role eq 'gr') {
1.1064 raeburn 5454: push(@rolecodes,$$role);
1.1002 raeburn 5455: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5456: $env{'user.name'});
1.1064 raeburn 5457: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5458: (undef,my $group_privs) = split(/\//,$trole);
5459: $group_privs = &unescape($group_privs);
5460: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5461: 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 5462: &get_groups_roles($tdomain,$trest,
5463: \%course_roles,\@rolecodes,
5464: \%groups_roles);
1.1002 raeburn 5465: } else {
1.1064 raeburn 5466: push(@rolecodes,$$role);
1.1002 raeburn 5467: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5468: }
1.1064 raeburn 5469: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5470: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5471: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5472: }
5473: }
1.1034 raeburn 5474: $$tstatus = 'is';
1.1002 raeburn 5475: }
1.994 raeburn 5476: }
5477: if ($$tend) {
1.1104 raeburn 5478: if ($$tend<$update) {
1.994 raeburn 5479: $$tstatus='expired';
5480: } elsif ($$tend<$now) {
5481: $$tstatus='will_not';
5482: }
5483: }
5484: }
5485: }
5486: }
5487:
1.1104 raeburn 5488: sub get_groups_roles {
5489: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5490: return unless((ref($cdom_courseroles) eq 'HASH') &&
5491: (ref($rolecodes) eq 'ARRAY') &&
5492: (ref($groups_roles) eq 'HASH'));
5493: if (keys(%{$cdom_courseroles}) > 0) {
5494: my ($cnum) = ($rest =~ /^($match_courseid)/);
5495: if ($cdom ne '' && $cnum ne '') {
5496: foreach my $key (keys(%{$cdom_courseroles})) {
5497: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5498: my $crsrole = $1;
5499: my $crssec = $2;
5500: if ($crsrole =~ /^cr/) {
5501: unless (grep(/^cr$/,@{$rolecodes})) {
5502: push(@{$rolecodes},'cr');
5503: }
5504: } else {
5505: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5506: push(@{$rolecodes},$crsrole);
5507: }
5508: }
5509: my $rolekey = "$crsrole./$cdom/$cnum";
5510: if ($crssec ne '') {
5511: $rolekey .= "/$crssec";
5512: }
5513: $rolekey .= './';
5514: $groups_roles->{$rolekey} = $rolecodes;
5515: }
5516: }
5517: }
5518: }
5519: return;
5520: }
5521:
5522: sub delete_env_groupprivs {
5523: my ($where,$courseroles,$possroles) = @_;
5524: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5525: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5526: unless (ref($courseroles->{$udom}) eq 'HASH') {
5527: %{$courseroles->{$udom}} =
5528: &get_my_roles('','','userroles',['active'],
5529: $possroles,[$udom],1);
5530: }
5531: if (ref($courseroles->{$udom}) eq 'HASH') {
5532: foreach my $item (keys(%{$courseroles->{$udom}})) {
5533: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5534: my $area = '/'.$cdom.'/'.$cnum;
5535: my $privkey = "user.priv.$crsrole.$area";
5536: if ($crssec ne '') {
5537: $privkey .= '/'.$crssec;
5538: }
5539: $privkey .= ".$area/$group";
5540: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5541: }
5542: }
5543: return;
5544: }
5545:
1.994 raeburn 5546: sub check_adhoc_privs {
1.1104 raeburn 5547: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5548: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5549: my $setprivs;
1.994 raeburn 5550: if ($env{$cckey}) {
5551: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5552: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5553: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5554: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5555: $setprivs = 1;
1.994 raeburn 5556: }
5557: } else {
1.1088 raeburn 5558: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5559: $setprivs = 1;
1.994 raeburn 5560: }
1.1185 raeburn 5561: return $setprivs;
1.994 raeburn 5562: }
5563:
5564: sub set_adhoc_privileges {
5565: # role can be cc or ca
1.1088 raeburn 5566: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5567: my $area = '/'.$dcdom.'/'.$pickedcourse;
5568: my $spec = $role.'.'.$area;
5569: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5570: $env{'user.name'},1);
1.994 raeburn 5571: my %ccrole = ();
5572: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5573: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5574: &appenv(\%userroles,[$role,'cm']);
5575: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5576: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5577: &appenv( {'request.role' => $spec,
5578: 'request.role.domain' => $dcdom,
5579: 'request.course.sec' => ''
5580: }
5581: );
5582: my $tadv=0;
5583: if (&allowed('adv') eq 'F') { $tadv=1; }
5584: &appenv({'request.role.adv' => $tadv});
5585: }
1.994 raeburn 5586: }
5587:
1.12 www 5588: # --------------------------------------------------------------- get interface
5589:
5590: sub get {
1.131 albertel 5591: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5592: my $items='';
1.800 albertel 5593: foreach my $item (@$storearr) {
5594: $items.=&escape($item).'&';
1.191 harris41 5595: }
1.12 www 5596: $items=~s/\&$//;
1.620 albertel 5597: if (!$udomain) { $udomain=$env{'user.domain'}; }
5598: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5599: my $uhome=&homeserver($uname,$udomain);
5600:
1.133 albertel 5601: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5602: my @pairs=split(/\&/,$rep);
1.273 albertel 5603: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5604: return @pairs;
5605: }
1.15 www 5606: my %returnhash=();
1.42 www 5607: my $i=0;
1.800 albertel 5608: foreach my $item (@$storearr) {
5609: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5610: $i++;
1.191 harris41 5611: }
1.15 www 5612: return %returnhash;
1.27 www 5613: }
5614:
5615: # --------------------------------------------------------------- del interface
5616:
5617: sub del {
1.133 albertel 5618: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5619: my $items='';
1.800 albertel 5620: foreach my $item (@$storearr) {
5621: $items.=&escape($item).'&';
1.191 harris41 5622: }
1.984 neumanie 5623:
1.27 www 5624: $items=~s/\&$//;
1.620 albertel 5625: if (!$udomain) { $udomain=$env{'user.domain'}; }
5626: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5627: my $uhome=&homeserver($uname,$udomain);
5628: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5629: }
5630:
5631: # -------------------------------------------------------------- dump interface
5632:
1.1180 droeschl 5633: sub unserialize {
5634: my ($rep, $escapedkeys) = @_;
5635:
5636: return {} if $rep =~ /^error/;
5637:
5638: my %returnhash=();
1.1252 raeburn 5639: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5640: my ($key, $value) = split(/=/, $item, 2);
5641: $key = unescape($key) unless $escapedkeys;
5642: next if $key =~ /^error: 2 /;
1.1252 raeburn 5643: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5644: }
5645: #return %returnhash;
5646: return \%returnhash;
5647: }
5648:
5649: # see Lond::dump_with_regexp
5650: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5651: sub dump {
1.1180 droeschl 5652: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5653: if (!$udomain) { $udomain=$env{'user.domain'}; }
5654: if (!$uname) { $uname=$env{'user.name'}; }
5655: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5656:
1.1266 raeburn 5657: if ($regexp) {
5658: $regexp=&escape($regexp);
5659: } else {
5660: $regexp='.';
5661: }
1.1180 droeschl 5662: if (grep { $_ eq $uhome } current_machine_ids()) {
5663: # user is hosted on this machine
1.1266 raeburn 5664: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5665: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5666: return %{unserialize($reply, $escapedkeys)};
5667: }
1.1166 raeburn 5668: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5669: my @pairs=split(/\&/,$rep);
5670: my %returnhash=();
1.1098 foxr 5671: if (!($rep =~ /^error/ )) {
5672: foreach my $item (@pairs) {
5673: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5674: $key = unescape($key) unless $escapedkeys;
5675: #$key = &unescape($key);
1.1098 foxr 5676: next if ($key =~ /^error: 2 /);
5677: $returnhash{$key}=&thaw_unescape($value);
5678: }
1.755 albertel 5679: }
5680: return %returnhash;
1.407 www 5681: }
5682:
1.1098 foxr 5683:
1.717 albertel 5684: # --------------------------------------------------------- dumpstore interface
5685:
5686: sub dumpstore {
5687: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5688: # same as dump but keys must be escaped. They may contain colon separated
5689: # lists of values that may themself contain colons (e.g. symbs).
5690: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5691: }
5692:
1.407 www 5693: # -------------------------------------------------------------- keys interface
5694:
5695: sub getkeys {
5696: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5697: if (!$udomain) { $udomain=$env{'user.domain'}; }
5698: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5699: my $uhome=&homeserver($uname,$udomain);
5700: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5701: my @keyarray=();
1.800 albertel 5702: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5703: next if ($key =~ /^error: 2 /);
1.800 albertel 5704: push(@keyarray,&unescape($key));
1.407 www 5705: }
5706: return @keyarray;
1.318 matthew 5707: }
5708:
1.319 matthew 5709: # --------------------------------------------------------------- currentdump
5710: sub currentdump {
1.328 matthew 5711: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5712: $courseid = $env{'request.course.id'} if (! defined($courseid));
5713: $sdom = $env{'user.domain'} if (! defined($sdom));
5714: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5715: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5716: my $rep;
5717:
5718: if (grep { $_ eq $uhome } current_machine_ids()) {
5719: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5720: $courseid)));
5721: } else {
5722: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5723: }
5724:
1.318 matthew 5725: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5726: #
1.318 matthew 5727: my %returnhash=();
1.319 matthew 5728: #
5729: if ($rep eq "unknown_cmd") {
5730: # an old lond will not know currentdump
5731: # Do a dump and make it look like a currentdump
1.822 albertel 5732: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5733: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5734: my %hash = @tmp;
5735: @tmp=();
1.424 matthew 5736: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5737: } else {
5738: my @pairs=split(/\&/,$rep);
1.800 albertel 5739: foreach my $pair (@pairs) {
5740: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5741: my ($symb,$param) = split(/:/,$key);
5742: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5743: &thaw_unescape($value);
1.319 matthew 5744: }
1.191 harris41 5745: }
1.12 www 5746: return %returnhash;
1.424 matthew 5747: }
5748:
5749: sub convert_dump_to_currentdump{
5750: my %hash = %{shift()};
5751: my %returnhash;
5752: # Code ripped from lond, essentially. The only difference
5753: # here is the unescaping done by lonnet::dump(). Conceivably
5754: # we might run in to problems with parameter names =~ /^v\./
5755: while (my ($key,$value) = each(%hash)) {
5756: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5757: $symb = &unescape($symb);
5758: $param = &unescape($param);
1.424 matthew 5759: next if ($v eq 'version' || $symb eq 'keys');
5760: next if (exists($returnhash{$symb}) &&
5761: exists($returnhash{$symb}->{$param}) &&
5762: $returnhash{$symb}->{'v.'.$param} > $v);
5763: $returnhash{$symb}->{$param}=$value;
5764: $returnhash{$symb}->{'v.'.$param}=$v;
5765: }
5766: #
5767: # Remove all of the keys in the hashes which keep track of
5768: # the version of the parameter.
5769: while (my ($symb,$param_hash) = each(%returnhash)) {
5770: # use a foreach because we are going to delete from the hash.
5771: foreach my $key (keys(%$param_hash)) {
5772: delete($param_hash->{$key}) if ($key =~ /^v\./);
5773: }
5774: }
5775: return \%returnhash;
1.12 www 5776: }
5777:
1.627 albertel 5778: # ------------------------------------------------------ critical inc interface
5779:
5780: sub cinc {
5781: return &inc(@_,'critical');
5782: }
5783:
1.449 matthew 5784: # --------------------------------------------------------------- inc interface
5785:
5786: sub inc {
1.627 albertel 5787: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5788: if (!$udomain) { $udomain=$env{'user.domain'}; }
5789: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5790: my $uhome=&homeserver($uname,$udomain);
5791: my $items='';
5792: if (! ref($store)) {
5793: # got a single value, so use that instead
5794: $items = &escape($store).'=&';
5795: } elsif (ref($store) eq 'SCALAR') {
5796: $items = &escape($$store).'=&';
5797: } elsif (ref($store) eq 'ARRAY') {
5798: $items = join('=&',map {&escape($_);} @{$store});
5799: } elsif (ref($store) eq 'HASH') {
5800: while (my($key,$value) = each(%{$store})) {
5801: $items.= &escape($key).'='.&escape($value).'&';
5802: }
5803: }
5804: $items=~s/\&$//;
1.627 albertel 5805: if ($critical) {
5806: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5807: } else {
5808: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5809: }
1.449 matthew 5810: }
5811:
1.12 www 5812: # --------------------------------------------------------------- put interface
5813:
5814: sub put {
1.134 albertel 5815: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5816: if (!$udomain) { $udomain=$env{'user.domain'}; }
5817: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5818: my $uhome=&homeserver($uname,$udomain);
1.12 www 5819: my $items='';
1.800 albertel 5820: foreach my $item (keys(%$storehash)) {
5821: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5822: }
1.12 www 5823: $items=~s/\&$//;
1.134 albertel 5824: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5825: }
5826:
1.631 albertel 5827: # ------------------------------------------------------------ newput interface
5828:
5829: sub newput {
5830: my ($namespace,$storehash,$udomain,$uname)=@_;
5831: if (!$udomain) { $udomain=$env{'user.domain'}; }
5832: if (!$uname) { $uname=$env{'user.name'}; }
5833: my $uhome=&homeserver($uname,$udomain);
5834: my $items='';
5835: foreach my $key (keys(%$storehash)) {
5836: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5837: }
5838: $items=~s/\&$//;
5839: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5840: }
5841:
5842: # --------------------------------------------------------- putstore interface
5843:
1.524 raeburn 5844: sub putstore {
1.1269 raeburn 5845: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 5846: if (!$udomain) { $udomain=$env{'user.domain'}; }
5847: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5848: my $uhome=&homeserver($uname,$udomain);
5849: my $items='';
1.715 albertel 5850: foreach my $key (keys(%$storehash)) {
5851: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5852: }
1.715 albertel 5853: $items=~s/\&$//;
1.716 albertel 5854: my $esc_symb=&escape($symb);
5855: my $esc_v=&escape($version);
1.715 albertel 5856: my $reply =
1.716 albertel 5857: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5858: $uhome);
1.1269 raeburn 5859: if (($tolog) && ($reply eq 'ok')) {
5860: my $namevalue='';
5861: foreach my $key (keys(%{$storehash})) {
5862: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5863: }
5864: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
5865: '&host='.&escape($perlvar{'lonHostID'}).
5866: '&version='.$esc_v.
5867: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
5868: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
5869: }
1.715 albertel 5870: if ($reply eq 'unknown_cmd') {
1.716 albertel 5871: # gfall back to way things use to be done
1.715 albertel 5872: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5873: $uname);
1.524 raeburn 5874: }
1.715 albertel 5875: return $reply;
5876: }
5877:
5878: sub old_putstore {
1.716 albertel 5879: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5880: if (!$udomain) { $udomain=$env{'user.domain'}; }
5881: if (!$uname) { $uname=$env{'user.name'}; }
5882: my $uhome=&homeserver($uname,$udomain);
5883: my %newstorehash;
1.800 albertel 5884: foreach my $item (keys(%$storehash)) {
5885: my $key = $version.':'.&escape($symb).':'.$item;
5886: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5887: }
5888: my $items='';
5889: my %allitems = ();
1.800 albertel 5890: foreach my $item (keys(%newstorehash)) {
5891: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5892: my $key = $1.':keys:'.$2;
5893: $allitems{$key} .= $3.':';
5894: }
1.800 albertel 5895: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5896: }
1.800 albertel 5897: foreach my $item (keys(%allitems)) {
5898: $allitems{$item} =~ s/\:$//;
5899: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5900: }
5901: $items=~s/\&$//;
5902: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5903: }
5904:
1.47 www 5905: # ------------------------------------------------------ critical put interface
5906:
5907: sub cput {
1.134 albertel 5908: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5909: if (!$udomain) { $udomain=$env{'user.domain'}; }
5910: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5911: my $uhome=&homeserver($uname,$udomain);
1.47 www 5912: my $items='';
1.800 albertel 5913: foreach my $item (keys(%$storehash)) {
5914: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5915: }
1.47 www 5916: $items=~s/\&$//;
1.134 albertel 5917: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5918: }
5919:
5920: # -------------------------------------------------------------- eget interface
5921:
5922: sub eget {
1.133 albertel 5923: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5924: my $items='';
1.800 albertel 5925: foreach my $item (@$storearr) {
5926: $items.=&escape($item).'&';
1.191 harris41 5927: }
1.12 www 5928: $items=~s/\&$//;
1.620 albertel 5929: if (!$udomain) { $udomain=$env{'user.domain'}; }
5930: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5931: my $uhome=&homeserver($uname,$udomain);
5932: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5933: my @pairs=split(/\&/,$rep);
5934: my %returnhash=();
1.42 www 5935: my $i=0;
1.800 albertel 5936: foreach my $item (@$storearr) {
5937: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5938: $i++;
1.191 harris41 5939: }
1.12 www 5940: return %returnhash;
5941: }
5942:
1.667 albertel 5943: # ------------------------------------------------------------ tmpput interface
5944: sub tmpput {
1.802 raeburn 5945: my ($storehash,$server,$context)=@_;
1.667 albertel 5946: my $items='';
1.800 albertel 5947: foreach my $item (keys(%$storehash)) {
5948: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5949: }
5950: $items=~s/\&$//;
1.802 raeburn 5951: if (defined($context)) {
5952: $items .= ':'.&escape($context);
5953: }
1.667 albertel 5954: return &reply("tmpput:$items",$server);
5955: }
5956:
5957: # ------------------------------------------------------------ tmpget interface
5958: sub tmpget {
1.688 albertel 5959: my ($token,$server)=@_;
5960: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5961: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5962: my %returnhash;
5963: foreach my $item (split(/\&/,$rep)) {
5964: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5965: next if ($key =~ /^error: 2 /);
1.667 albertel 5966: $returnhash{&unescape($key)}=&thaw_unescape($value);
5967: }
5968: return %returnhash;
5969: }
5970:
1.1113 raeburn 5971: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5972: sub tmpdel {
5973: my ($token,$server)=@_;
5974: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5975: return &reply("tmpdel:$token",$server);
5976: }
5977:
1.1198 raeburn 5978: # ------------------------------------------------------------ get_timebased_id
5979:
5980: sub get_timebased_id {
5981: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5982: $maxtries) = @_;
5983: my ($newid,$error,$dellock);
5984: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5985: return ('','ok','invalid call to get suffix');
5986: }
5987:
5988: # set defaults for any optional args for which values were not supplied
5989: if ($who eq '') {
5990: $who = $env{'user.name'}.':'.$env{'user.domain'};
5991: }
5992: if (!$locktries) {
5993: $locktries = 3;
5994: }
5995: if (!$maxtries) {
5996: $maxtries = 10;
5997: }
5998:
5999: if (($cdom eq '') || ($cnum eq '')) {
6000: if ($env{'request.course.id'}) {
6001: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6002: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6003: }
6004: if (($cdom eq '') || ($cnum eq '')) {
6005: return ('','ok','call to get suffix not in course context');
6006: }
6007: }
6008:
6009: # construct locking item
6010: my $lockhash = {
6011: $prefix."\0".'locked_'.$keyid => $who,
6012: };
6013: my $tries = 0;
6014:
6015: # attempt to get lock on nohist_$namespace file
6016: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6017: while (($gotlock ne 'ok') && $tries <$locktries) {
6018: $tries ++;
6019: sleep 1;
6020: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6021: }
6022:
6023: # attempt to get unique identifier, based on current timestamp
6024: if ($gotlock eq 'ok') {
6025: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6026: my $id = time;
6027: $newid = $id;
1.1268 raeburn 6028: if ($idtype eq 'addcode') {
6029: $newid .= &sixnum_code();
6030: }
1.1198 raeburn 6031: my $idtries = 0;
6032: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6033: if ($idtype eq 'concat') {
6034: $newid = $id.$idtries;
1.1268 raeburn 6035: } elsif ($idtype eq 'addcode') {
6036: $newid = $newid.&sixnum_code();
1.1198 raeburn 6037: } else {
6038: $newid ++;
6039: }
6040: $idtries ++;
6041: }
6042: if (!exists($inuse{$prefix."\0".$newid})) {
6043: my %new_item = (
6044: $prefix."\0".$newid => $who,
6045: );
6046: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6047: $cdom,$cnum);
6048: if ($putresult ne 'ok') {
6049: undef($newid);
6050: $error = 'error saving new item: '.$putresult;
6051: }
6052: } else {
1.1268 raeburn 6053: undef($newid);
1.1198 raeburn 6054: $error = ('error: no unique suffix available for the new item ');
6055: }
6056: # remove lock
6057: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6058: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6059: } else {
6060: $error = "error: could not obtain lockfile\n";
6061: $dellock = 'ok';
1.1276 raeburn 6062: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6063: $dellock = 'nolock';
6064: }
1.1198 raeburn 6065: }
6066: return ($newid,$dellock,$error);
6067: }
6068:
1.1268 raeburn 6069: sub sixnum_code {
6070: my $code;
6071: for (0..6) {
6072: $code .= int( rand(9) );
6073: }
6074: return $code;
6075: }
6076:
1.765 albertel 6077: # -------------------------------------------------- portfolio access checking
6078:
6079: sub portfolio_access {
1.1270 raeburn 6080: my ($requrl,$clientip) = @_;
1.765 albertel 6081: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6082: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6083: if ($result) {
6084: my %setters;
6085: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6086: my ($startblock,$endblock) =
6087: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6088: if ($startblock && $endblock) {
6089: return 'B';
6090: }
6091: } else {
6092: my ($startblock,$endblock) =
6093: &Apache::loncommon::blockcheck(\%setters,'port');
6094: if ($startblock && $endblock) {
6095: return 'B';
6096: }
6097: }
6098: }
1.765 albertel 6099: if ($result eq 'ok') {
1.766 albertel 6100: return 'F';
1.765 albertel 6101: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6102: return 'A';
1.765 albertel 6103: }
1.766 albertel 6104: return '';
1.765 albertel 6105: }
6106:
6107: sub get_portfolio_access {
1.1270 raeburn 6108: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6109:
6110: if (!ref($access_hash)) {
6111: my $current_perms = &get_portfile_permissions($udom,$unum);
6112: my %access_controls = &get_access_controls($current_perms,$group,
6113: $file_name);
6114: $access_hash = $access_controls{$file_name};
6115: }
6116:
1.1270 raeburn 6117: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6118: my $now = time;
6119: if (ref($access_hash) eq 'HASH') {
6120: foreach my $key (keys(%{$access_hash})) {
6121: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6122: if ($start > $now) {
6123: next;
6124: }
6125: if ($end && $end<$now) {
6126: next;
6127: }
6128: if ($scope eq 'public') {
6129: $public = $key;
6130: last;
6131: } elsif ($scope eq 'guest') {
6132: $guest = $key;
6133: } elsif ($scope eq 'domains') {
6134: push(@domains,$key);
6135: } elsif ($scope eq 'users') {
6136: push(@users,$key);
6137: } elsif ($scope eq 'course') {
6138: push(@courses,$key);
6139: } elsif ($scope eq 'group') {
6140: push(@groups,$key);
1.1270 raeburn 6141: } elsif ($scope eq 'ip') {
6142: push(@ips,$key);
1.765 albertel 6143: }
6144: }
6145: if ($public) {
6146: return 'ok';
1.1270 raeburn 6147: } elsif (@ips > 0) {
6148: my $allowed;
6149: foreach my $ipkey (@ips) {
6150: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6151: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6152: $allowed = 1;
6153: last;
6154: }
6155: }
6156: }
6157: if ($allowed) {
6158: return 'ok';
6159: }
1.765 albertel 6160: }
6161: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6162: if ($guest) {
6163: return $guest;
6164: }
6165: } else {
6166: if (@domains > 0) {
6167: foreach my $domkey (@domains) {
6168: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6169: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6170: return 'ok';
6171: }
6172: }
6173: }
6174: }
6175: if (@users > 0) {
6176: foreach my $userkey (@users) {
1.865 raeburn 6177: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6178: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6179: if (ref($item) eq 'HASH') {
6180: if (($item->{'uname'} eq $env{'user.name'}) &&
6181: ($item->{'udom'} eq $env{'user.domain'})) {
6182: return 'ok';
6183: }
6184: }
6185: }
6186: }
1.765 albertel 6187: }
6188: }
6189: my %roleshash;
6190: my @courses_and_groups = @courses;
6191: push(@courses_and_groups,@groups);
6192: if (@courses_and_groups > 0) {
6193: my (%allgroups,%allroles);
6194: my ($start,$end,$role,$sec,$group);
6195: foreach my $envkey (%env) {
1.1060 raeburn 6196: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6197: my $cid = $2.'_'.$3;
6198: if ($1 eq 'gr') {
6199: $group = $4;
6200: $allgroups{$cid}{$group} = $env{$envkey};
6201: } else {
6202: if ($4 eq '') {
6203: $sec = 'none';
6204: } else {
6205: $sec = $4;
6206: }
6207: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6208: }
1.811 albertel 6209: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6210: my $cid = $2.'_'.$3;
6211: if ($4 eq '') {
6212: $sec = 'none';
6213: } else {
6214: $sec = $4;
6215: }
6216: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6217: }
6218: }
6219: if (keys(%allroles) == 0) {
6220: return;
6221: }
6222: foreach my $key (@courses_and_groups) {
6223: my %content = %{$$access_hash{$key}};
6224: my $cnum = $content{'number'};
6225: my $cdom = $content{'domain'};
6226: my $cid = $cdom.'_'.$cnum;
6227: if (!exists($allroles{$cid})) {
6228: next;
6229: }
6230: foreach my $role_id (keys(%{$content{'roles'}})) {
6231: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6232: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6233: my @status = @{$content{'roles'}{$role_id}{'access'}};
6234: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6235: foreach my $role (keys(%{$allroles{$cid}})) {
6236: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6237: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6238: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6239: if (grep/^all$/,@sections) {
6240: return 'ok';
6241: } else {
6242: if (grep/^$sec$/,@sections) {
6243: return 'ok';
6244: }
6245: }
6246: }
6247: }
6248: if (keys(%{$allgroups{$cid}}) == 0) {
6249: if (grep/^none$/,@groups) {
6250: return 'ok';
6251: }
6252: } else {
6253: if (grep/^all$/,@groups) {
6254: return 'ok';
6255: }
6256: foreach my $group (keys(%{$allgroups{$cid}})) {
6257: if (grep/^$group$/,@groups) {
6258: return 'ok';
6259: }
6260: }
6261: }
6262: }
6263: }
6264: }
6265: }
6266: }
6267: if ($guest) {
6268: return $guest;
6269: }
6270: }
6271: }
6272: return;
6273: }
6274:
6275: sub course_group_datechecker {
6276: my ($dates,$now,$status) = @_;
6277: my ($start,$end) = split(/\./,$dates);
6278: if (!$start && !$end) {
6279: return 'ok';
6280: }
6281: if (grep/^active$/,@{$status}) {
6282: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6283: return 'ok';
6284: }
6285: }
6286: if (grep/^previous$/,@{$status}) {
6287: if ($end > $now ) {
6288: return 'ok';
6289: }
6290: }
6291: if (grep/^future$/,@{$status}) {
6292: if ($start > $now) {
6293: return 'ok';
6294: }
6295: }
6296: return;
6297: }
6298:
6299: sub parse_portfolio_url {
6300: my ($url) = @_;
6301:
6302: my ($type,$udom,$unum,$group,$file_name);
6303:
1.823 albertel 6304: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6305: $type = 1;
6306: $udom = $1;
6307: $unum = $2;
6308: $file_name = $3;
1.823 albertel 6309: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6310: $type = 2;
6311: $udom = $1;
6312: $unum = $2;
6313: $group = $3;
6314: $file_name = $3.'/'.$4;
6315: }
6316: if (wantarray) {
6317: return ($type,$udom,$unum,$file_name,$group);
6318: }
6319: return $type;
6320: }
6321:
6322: sub is_portfolio_url {
6323: my ($url) = @_;
6324: return scalar(&parse_portfolio_url($url));
6325: }
6326:
1.798 raeburn 6327: sub is_portfolio_file {
6328: my ($file) = @_;
1.820 raeburn 6329: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6330: return 1;
6331: }
6332: return;
6333: }
6334:
1.976 raeburn 6335: sub usertools_access {
1.1084 raeburn 6336: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6337: my ($access,%tools);
6338: if ($context eq '') {
6339: $context = 'tools';
6340: }
6341: if ($context eq 'requestcourses') {
6342: %tools = (
6343: official => 1,
6344: unofficial => 1,
1.1006 raeburn 6345: community => 1,
1.1246 raeburn 6346: textbook => 1,
1.985 raeburn 6347: );
1.1183 raeburn 6348: } elsif ($context eq 'requestauthor') {
6349: %tools = (
6350: requestauthor => 1,
6351: );
1.985 raeburn 6352: } else {
6353: %tools = (
6354: aboutme => 1,
6355: blog => 1,
1.1177 raeburn 6356: webdav => 1,
1.985 raeburn 6357: portfolio => 1,
6358: );
6359: }
1.976 raeburn 6360: return if (!defined($tools{$tool}));
6361:
1.1242 raeburn 6362: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6363: $udom = $env{'user.domain'};
6364: $uname = $env{'user.name'};
6365: }
6366:
1.978 raeburn 6367: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6368: if ($action ne 'reload') {
1.985 raeburn 6369: if ($context eq 'requestcourses') {
6370: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6371: } elsif ($context eq 'requestauthor') {
6372: return $env{'environment.canrequest.author'};
1.985 raeburn 6373: } else {
6374: return $env{'environment.availabletools.'.$tool};
6375: }
6376: }
1.976 raeburn 6377: }
6378:
1.1183 raeburn 6379: my ($toolstatus,$inststatus,$envkey);
6380: if ($context eq 'requestauthor') {
6381: $envkey = $context;
6382: } else {
6383: $envkey = $context.'.'.$tool;
6384: }
1.976 raeburn 6385:
1.985 raeburn 6386: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6387: ($action ne 'reload')) {
1.1183 raeburn 6388: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6389: $inststatus = $env{'environment.inststatus'};
6390: } else {
1.1084 raeburn 6391: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6392: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6393: $inststatus = $userenvref->{'inststatus'};
6394: } else {
1.1183 raeburn 6395: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6396: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6397: $inststatus = $userenv{'inststatus'};
6398: }
1.976 raeburn 6399: }
6400:
6401: if ($toolstatus ne '') {
6402: if ($toolstatus) {
6403: $access = 1;
6404: } else {
6405: $access = 0;
6406: }
6407: return $access;
6408: }
6409:
1.1084 raeburn 6410: my ($is_adv,%domdef);
6411: if (ref($is_advref) eq 'HASH') {
6412: $is_adv = $is_advref->{'is_adv'};
6413: } else {
6414: $is_adv = &is_advanced_user($udom,$uname);
6415: }
6416: if (ref($domdefref) eq 'HASH') {
6417: %domdef = %{$domdefref};
6418: } else {
6419: %domdef = &get_domain_defaults($udom);
6420: }
1.976 raeburn 6421: if (ref($domdef{$tool}) eq 'HASH') {
6422: if ($is_adv) {
6423: if ($domdef{$tool}{'_LC_adv'} ne '') {
6424: if ($domdef{$tool}{'_LC_adv'}) {
6425: $access = 1;
6426: } else {
6427: $access = 0;
6428: }
6429: return $access;
6430: }
6431: }
6432: if ($inststatus ne '') {
6433: my ($hasaccess,$hasnoaccess);
6434: foreach my $affiliation (split(/:/,$inststatus)) {
6435: if ($domdef{$tool}{$affiliation} ne '') {
6436: if ($domdef{$tool}{$affiliation}) {
6437: $hasaccess = 1;
6438: } else {
6439: $hasnoaccess = 1;
6440: }
6441: }
6442: }
6443: if ($hasaccess || $hasnoaccess) {
6444: if ($hasaccess) {
6445: $access = 1;
6446: } elsif ($hasnoaccess) {
6447: $access = 0;
6448: }
6449: return $access;
6450: }
6451: } else {
6452: if ($domdef{$tool}{'default'} ne '') {
6453: if ($domdef{$tool}{'default'}) {
6454: $access = 1;
6455: } elsif ($domdef{$tool}{'default'} == 0) {
6456: $access = 0;
6457: }
6458: return $access;
6459: }
6460: }
6461: } else {
1.1177 raeburn 6462: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6463: $access = 1;
6464: } else {
6465: $access = 0;
6466: }
1.976 raeburn 6467: return $access;
6468: }
6469: }
6470:
1.1050 raeburn 6471: sub is_course_owner {
6472: my ($cdom,$cnum,$udom,$uname) = @_;
6473: if (($udom eq '') || ($uname eq '')) {
6474: $udom = $env{'user.domain'};
6475: $uname = $env{'user.name'};
6476: }
6477: unless (($udom eq '') || ($uname eq '')) {
6478: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6479: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6480: return 1;
6481: } else {
6482: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6483: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6484: return 1;
6485: }
6486: }
6487: }
6488: }
6489: return;
6490: }
6491:
1.976 raeburn 6492: sub is_advanced_user {
6493: my ($udom,$uname) = @_;
1.1085 raeburn 6494: if ($udom ne '' && $uname ne '') {
6495: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6496: if (wantarray) {
6497: return ($env{'user.adv'},$env{'user.author'});
6498: } else {
6499: return $env{'user.adv'};
6500: }
1.1085 raeburn 6501: }
6502: }
1.976 raeburn 6503: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6504: my %allroles;
1.1128 raeburn 6505: my ($is_adv,$is_author);
1.976 raeburn 6506: foreach my $role (keys(%roleshash)) {
6507: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6508: my $area = '/'.$tdomain.'/'.$trest;
6509: if ($sec ne '') {
6510: $area .= '/'.$sec;
6511: }
6512: if (($area ne '') && ($trole ne '')) {
6513: my $spec=$trole.'.'.$area;
6514: if ($trole =~ /^cr\//) {
6515: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6516: } elsif ($trole ne 'gr') {
6517: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6518: }
1.1128 raeburn 6519: if ($trole eq 'au') {
6520: $is_author = 1;
6521: }
1.976 raeburn 6522: }
6523: }
6524: foreach my $role (keys(%allroles)) {
6525: last if ($is_adv);
6526: foreach my $item (split(/:/,$allroles{$role})) {
6527: if ($item ne '') {
6528: my ($privilege,$restrictions)=split(/&/,$item);
6529: if ($privilege eq 'adv') {
6530: $is_adv = 1;
6531: last;
6532: }
6533: }
6534: }
6535: }
1.1128 raeburn 6536: if (wantarray) {
6537: return ($is_adv,$is_author);
6538: }
1.976 raeburn 6539: return $is_adv;
6540: }
1.798 raeburn 6541:
1.1035 raeburn 6542: sub check_can_request {
1.1036 raeburn 6543: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6544: my $canreq = 0;
6545: my ($types,$typename) = &Apache::loncommon::course_types();
6546: my @options = ('approval','validate','autolimit');
6547: my $optregex = join('|',@options);
6548: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6549: foreach my $type (@{$types}) {
6550: if (&usertools_access($env{'user.name'},
6551: $env{'user.domain'},
6552: $type,undef,'requestcourses')) {
6553: $canreq ++;
1.1036 raeburn 6554: if (ref($request_domains) eq 'HASH') {
6555: push(@{$request_domains->{$type}},$env{'user.domain'});
6556: }
1.1035 raeburn 6557: if ($dom eq $env{'user.domain'}) {
6558: $can_request->{$type} = 1;
6559: }
6560: }
6561: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6562: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6563: if (@curr > 0) {
1.1036 raeburn 6564: foreach my $item (@curr) {
6565: if (ref($request_domains) eq 'HASH') {
6566: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6567: if ($otherdom ne '') {
6568: if (ref($request_domains->{$type}) eq 'ARRAY') {
6569: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6570: push(@{$request_domains->{$type}},$otherdom);
6571: }
6572: } else {
6573: push(@{$request_domains->{$type}},$otherdom);
6574: }
6575: }
6576: }
6577: }
6578: unless($dom eq $env{'user.domain'}) {
6579: $canreq ++;
1.1035 raeburn 6580: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6581: $can_request->{$type} = 1;
6582: }
6583: }
6584: }
6585: }
6586: }
6587: }
6588: return $canreq;
6589: }
6590:
1.341 www 6591: # ---------------------------------------------- Custom access rule evaluation
6592:
6593: sub customaccess {
6594: my ($priv,$uri)=@_;
1.807 albertel 6595: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6596: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6597: $udom = &LONCAPA::clean_domain($udom);
6598: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6599: my $access=0;
1.800 albertel 6600: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6601: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6602: if ($type eq 'user') {
6603: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6604: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6605: if ($tdom) {
6606: if ($tdom ne $env{'user.domain'}) { next; }
6607: }
1.896 albertel 6608: if ($tuname) {
6609: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6610: }
6611: $access=($effect eq 'allow');
6612: last;
6613: }
6614: } else {
6615: if ($role) {
6616: if ($role ne $urole) { next; }
6617: }
6618: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6619: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6620: if ($tdom) {
6621: if ($tdom ne $udom) { next; }
6622: }
6623: if ($tcrs) {
6624: if ($tcrs ne $ucrs) { next; }
6625: }
6626: if ($tsec) {
6627: if ($tsec ne $usec) { next; }
6628: }
6629: $access=($effect eq 'allow');
6630: last;
6631: }
6632: if ($realm eq '' && $role eq '') {
6633: $access=($effect eq 'allow');
6634: }
1.402 bowersj2 6635: }
1.341 www 6636: }
6637: return $access;
6638: }
6639:
1.103 harris41 6640: # ------------------------------------------------- Check for a user privilege
1.12 www 6641:
6642: sub allowed {
1.1281 raeburn 6643: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6644: my $ver_orguri=$uri;
1.439 www 6645: $uri=&deversion($uri);
1.152 www 6646: my $orguri=$uri;
1.52 www 6647: $uri=&declutter($uri);
1.809 raeburn 6648:
1.810 raeburn 6649: if ($priv eq 'evb') {
6650: # Evade communication block restrictions for specified role in a course
6651: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6652: return $1;
6653: } else {
6654: return;
6655: }
6656: }
6657:
1.620 albertel 6658: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6659: # Free bre access to adm and meta resources
1.775 albertel 6660: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6661: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6662: && ($priv eq 'bre')) {
1.14 www 6663: return 'F';
1.159 www 6664: }
6665:
1.545 banghart 6666: # Free bre access to user's own portfolio contents
1.714 raeburn 6667: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6668: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6669: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6670: my %setters;
6671: my ($startblock,$endblock) =
6672: &Apache::loncommon::blockcheck(\%setters,'port');
6673: if ($startblock && $endblock) {
6674: return 'B';
6675: } else {
6676: return 'F';
6677: }
1.545 banghart 6678: }
6679:
1.762 raeburn 6680: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6681: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6682: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6683: if (exists($env{'request.course.id'})) {
6684: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6685: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6686: if (($domain eq $cdom) && ($name eq $cnum)) {
6687: my $courseprivid=$env{'request.course.id'};
6688: $courseprivid=~s/\_/\//;
6689: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6690: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6691: return $1;
1.762 raeburn 6692: } else {
6693: if ($env{'request.course.sec'}) {
6694: $courseprivid.='/'.$env{'request.course.sec'};
6695: }
6696: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6697: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6698: return $2;
6699: }
1.714 raeburn 6700: }
6701: }
6702: }
6703: }
6704:
1.159 www 6705: # Free bre to public access
6706:
6707: if ($priv eq 'bre') {
1.238 www 6708: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6709: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6710: return 'F';
6711: }
1.238 www 6712: if ($copyright eq 'priv') {
6713: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6714: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6715: return '';
6716: }
6717: }
6718: if ($copyright eq 'domain') {
6719: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6720: unless (($env{'user.domain'} eq $1) ||
6721: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6722: return '';
6723: }
1.262 matthew 6724: }
1.620 albertel 6725: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6726: # Library role, so allow browsing of resources in this domain.
6727: return 'F';
1.238 www 6728: }
1.341 www 6729: if ($copyright eq 'custom') {
6730: unless (&customaccess($priv,$uri)) { return ''; }
6731: }
1.14 www 6732: }
1.264 matthew 6733: # Domain coordinator is trying to create a course
1.620 albertel 6734: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6735: # uri is the requested domain in this case.
6736: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6737: # a role of dc for the domain in question.
1.620 albertel 6738: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6739: }
1.29 www 6740:
1.52 www 6741: my $thisallowed='';
6742: my $statecond=0;
6743: my $courseprivid='';
6744:
1.1039 raeburn 6745: my $ownaccess;
1.1043 raeburn 6746: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6747: if (($priv eq 'bro') && ($env{'user.author'})) {
6748: if ($uri eq '') {
6749: $ownaccess = 1;
6750: } else {
6751: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6752: my $udom = $env{'user.domain'};
6753: my $uname = $env{'user.name'};
6754: if ($uri =~ m{^\Q$udom\E/?$}) {
6755: $ownaccess = 1;
1.1040 raeburn 6756: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6757: unless ($uri =~ m{\.\./}) {
6758: $ownaccess = 1;
6759: }
6760: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6761: my $now = time;
6762: if ($uri =~ m{^([^/]+)/?$}) {
6763: my $adom = $1;
6764: foreach my $key (keys(%env)) {
1.1042 raeburn 6765: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6766: my ($start,$end) = split('.',$env{$key});
6767: if (($now >= $start) && (!$end || $end < $now)) {
6768: $ownaccess = 1;
6769: last;
6770: }
6771: }
6772: }
6773: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6774: my $adom = $1;
6775: my $aname = $2;
1.1042 raeburn 6776: foreach my $role ('ca','aa') {
6777: if ($env{"user.role.$role./$adom/$aname"}) {
6778: my ($start,$end) =
6779: split('.',$env{"user.role.$role./$adom/$aname"});
6780: if (($now >= $start) && (!$end || $end < $now)) {
6781: $ownaccess = 1;
6782: last;
6783: }
1.1039 raeburn 6784: }
6785: }
6786: }
6787: }
6788: }
6789: }
6790: }
6791:
1.52 www 6792: # Course
6793:
1.620 albertel 6794: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6795: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6796: $thisallowed.=$1;
6797: }
1.52 www 6798: }
1.29 www 6799:
1.52 www 6800: # Domain
6801:
1.620 albertel 6802: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6803: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6804: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6805: $thisallowed.=$1;
6806: }
1.12 www 6807: }
1.52 www 6808:
1.1141 raeburn 6809: # User who is not author or co-author might still be able to edit
6810: # resource of an author in the domain (e.g., if Domain Coordinator).
6811: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6812: (&allowed('mdc',$env{'request.course.id'}))) {
6813: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6814: $thisallowed.=$1;
6815: }
6816: }
6817:
1.52 www 6818: # Course: uri itself is a course
1.66 www 6819: my $courseuri=$uri;
6820: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6821: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6822:
1.620 albertel 6823: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6824: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6825: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6826: $thisallowed.=$1;
6827: }
1.12 www 6828: }
1.29 www 6829:
1.665 albertel 6830: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6831: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6832: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6833: $thisallowed='';
1.671 raeburn 6834: my ($match)=&is_on_map($uri);
6835: if ($match) {
6836: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6837: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 6838: my $value = $1;
6839: if ($noblockcheck) {
6840: $thisallowed.=$value;
1.1162 raeburn 6841: } else {
1.1281 raeburn 6842: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6843: if (@blockers > 0) {
6844: $thisallowed = 'B';
6845: } else {
6846: $thisallowed.=$value;
6847: }
1.1162 raeburn 6848: }
1.671 raeburn 6849: }
6850: } else {
1.705 albertel 6851: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6852: if ($refuri) {
6853: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6854: $thisallowed='F';
1.671 raeburn 6855: } else {
6856: $refuri=&declutter($refuri);
6857: my ($match) = &is_on_map($refuri);
6858: if ($match) {
1.1281 raeburn 6859: if ($noblockcheck) {
6860: $thisallowed='F';
1.1162 raeburn 6861: } else {
1.1281 raeburn 6862: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6863: if (@blockers > 0) {
6864: $thisallowed = 'B';
6865: } else {
6866: $thisallowed='F';
6867: }
1.1162 raeburn 6868: }
1.671 raeburn 6869: }
1.669 raeburn 6870: }
1.671 raeburn 6871: }
6872: }
1.314 www 6873: }
1.492 albertel 6874:
1.766 albertel 6875: if ($priv eq 'bre'
6876: && $thisallowed ne 'F'
6877: && $thisallowed ne '2'
6878: && &is_portfolio_url($uri)) {
1.1270 raeburn 6879: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 6880: }
1.1250 raeburn 6881:
1.52 www 6882: # Full access at system, domain or course-wide level? Exit.
1.29 www 6883: if ($thisallowed=~/F/) {
6884: return 'F';
6885: }
6886:
1.52 www 6887: # If this is generating or modifying users, exit with special codes
1.29 www 6888:
1.643 www 6889: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6890: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6891: my ($audom,$auname)=split('/',$uri);
1.643 www 6892: # no author name given, so this just checks on the general right to make a co-author in this domain
6893: unless ($auname) { return $thisallowed; }
6894: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6895: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6896: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6897: ($audom ne $env{'request.role.domain'}))) { return ''; }
6898: }
1.52 www 6899: return $thisallowed;
6900: }
6901: #
1.103 harris41 6902: # Gathered so far: system, domain and course wide privileges
1.52 www 6903: #
6904: # Course: See if uri or referer is an individual resource that is part of
6905: # the course
6906:
1.620 albertel 6907: if ($env{'request.course.id'}) {
1.232 www 6908:
1.620 albertel 6909: $courseprivid=$env{'request.course.id'};
6910: if ($env{'request.course.sec'}) {
6911: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6912: }
6913: $courseprivid=~s/\_/\//;
6914: my $checkreferer=1;
1.232 www 6915: my ($match,$cond)=&is_on_map($uri);
6916: if ($match) {
6917: $statecond=$cond;
1.620 albertel 6918: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6919: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6920: my $value = $1;
6921: if ($priv eq 'bre') {
1.1281 raeburn 6922: if ($noblockcheck) {
6923: $thisallowed.=$value;
1.1162 raeburn 6924: } else {
1.1281 raeburn 6925: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6926: if (@blockers > 0) {
6927: $thisallowed = 'B';
6928: } else {
6929: $thisallowed.=$value;
6930: }
1.1162 raeburn 6931: }
6932: } else {
6933: $thisallowed.=$value;
6934: }
1.52 www 6935: $checkreferer=0;
6936: }
1.29 www 6937: }
1.83 www 6938:
1.148 www 6939: if ($checkreferer) {
1.620 albertel 6940: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6941: unless ($refuri) {
1.800 albertel 6942: foreach my $key (keys(%env)) {
6943: if ($key=~/^httpref\..*\*/) {
6944: my $pattern=$key;
1.156 www 6945: $pattern=~s/^httpref\.\/res\///;
1.148 www 6946: $pattern=~s/\*/\[\^\/\]\+/g;
6947: $pattern=~s/\//\\\//g;
1.152 www 6948: if ($orguri=~/$pattern/) {
1.800 albertel 6949: $refuri=$env{$key};
1.148 www 6950: }
6951: }
1.191 harris41 6952: }
1.148 www 6953: }
1.232 www 6954:
1.148 www 6955: if ($refuri) {
1.152 www 6956: $refuri=&declutter($refuri);
1.232 www 6957: my ($match,$cond)=&is_on_map($refuri);
6958: if ($match) {
6959: my $refstatecond=$cond;
1.620 albertel 6960: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6961: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6962: my $value = $1;
6963: if ($priv eq 'bre') {
1.1281 raeburn 6964: if ($noblockcheck) {
6965: $thisallowed.=$value;
1.1162 raeburn 6966: } else {
1.1281 raeburn 6967: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6968: if (@blockers > 0) {
6969: $thisallowed = 'B';
6970: } else {
6971: $thisallowed.=$value;
6972: }
1.1162 raeburn 6973: }
6974: } else {
6975: $thisallowed.=$value;
6976: }
1.53 www 6977: $uri=$refuri;
6978: $statecond=$refstatecond;
1.52 www 6979: }
6980: }
1.148 www 6981: }
1.29 www 6982: }
1.52 www 6983: }
1.29 www 6984:
1.52 www 6985: #
1.103 harris41 6986: # Gathered now: all privileges that could apply, and condition number
1.52 www 6987: #
6988: #
6989: # Full or no access?
6990: #
1.29 www 6991:
1.52 www 6992: if ($thisallowed=~/F/) {
6993: return 'F';
6994: }
1.29 www 6995:
1.52 www 6996: unless ($thisallowed) {
6997: return '';
6998: }
1.29 www 6999:
1.52 www 7000: # Restrictions exist, deal with them
7001: #
7002: # C:according to course preferences
7003: # R:according to resource settings
7004: # L:unless locked
7005: # X:according to user session state
7006: #
7007:
7008: # Possibly locked functionality, check all courses
1.54 www 7009: # Locks might take effect only after 10 minutes cache expiration for other
7010: # courses, and 2 minutes for current course
1.52 www 7011:
7012: my $envkey;
7013: if ($thisallowed=~/L/) {
1.1000 raeburn 7014: foreach $envkey (keys(%env)) {
1.54 www 7015: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7016: my $courseid=$2;
7017: my $roleid=$1.'.'.$2;
1.92 www 7018: $courseid=~s/^\///;
1.54 www 7019: my $expiretime=600;
1.620 albertel 7020: if ($env{'request.role'} eq $roleid) {
1.54 www 7021: $expiretime=120;
7022: }
7023: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7024: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7025: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7026: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7027: }
1.620 albertel 7028: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7029: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7030: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7031: &log($env{'user.domain'},$env{'user.name'},
7032: $env{'user.home'},
1.57 www 7033: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7034: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7035: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7036: return '';
7037: }
7038: }
1.620 albertel 7039: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7040: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7041: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7042: &log($env{'user.domain'},$env{'user.name'},
7043: $env{'user.home'},
1.57 www 7044: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7045: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7046: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7047: return '';
7048: }
7049: }
7050: }
1.29 www 7051: }
1.52 www 7052: }
7053:
7054: #
7055: # Rest of the restrictions depend on selected course
7056: #
7057:
1.620 albertel 7058: unless ($env{'request.course.id'}) {
1.766 albertel 7059: if ($thisallowed eq 'A') {
7060: return 'A';
1.814 raeburn 7061: } elsif ($thisallowed eq 'B') {
7062: return 'B';
1.766 albertel 7063: } else {
7064: return '1';
7065: }
1.52 www 7066: }
1.29 www 7067:
1.52 www 7068: #
7069: # Now user is definitely in a course
7070: #
1.53 www 7071:
7072:
7073: # Course preferences
7074:
7075: if ($thisallowed=~/C/) {
1.620 albertel 7076: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7077: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7078: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7079: =~/\Q$rolecode\E/) {
1.1103 raeburn 7080: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7081: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7082: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7083: $env{'request.course.id'});
7084: }
1.237 www 7085: return '';
7086: }
7087:
1.620 albertel 7088: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7089: =~/\Q$unamedom\E/) {
1.1103 raeburn 7090: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7091: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7092: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7093: $env{'request.course.id'});
7094: }
1.54 www 7095: return '';
7096: }
1.53 www 7097: }
7098:
7099: # Resource preferences
7100:
7101: if ($thisallowed=~/R/) {
1.620 albertel 7102: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7103: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7104: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7105: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7106: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7107: }
7108: return '';
1.54 www 7109: }
1.53 www 7110: }
1.30 www 7111:
1.246 www 7112: # Restricted by state or randomout?
1.30 www 7113:
1.52 www 7114: if ($thisallowed=~/X/) {
1.620 albertel 7115: if ($env{'acc.randomout'}) {
1.579 albertel 7116: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7117: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7118: return '';
7119: }
1.247 www 7120: }
7121: if (&condval($statecond)) {
1.52 www 7122: return '2';
7123: } else {
7124: return '';
7125: }
7126: }
1.30 www 7127:
1.766 albertel 7128: if ($thisallowed eq 'A') {
7129: return 'A';
1.814 raeburn 7130: } elsif ($thisallowed eq 'B') {
7131: return 'B';
1.766 albertel 7132: }
1.52 www 7133: return 'F';
1.232 www 7134: }
1.1162 raeburn 7135:
1.1192 raeburn 7136: # ------------------------------------------- Check construction space access
7137:
7138: sub constructaccess {
7139: my ($url,$setpriv)=@_;
7140:
7141: # We do not allow editing of previous versions of files
7142: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7143:
7144: # Get username and domain from URL
7145: my ($ownername,$ownerdomain,$ownerhome);
7146:
7147: ($ownerdomain,$ownername) =
7148: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7149:
7150: # The URL does not really point to any authorspace, forget it
7151: unless (($ownername) && ($ownerdomain)) { return ''; }
7152:
7153: # Now we need to see if the user has access to the authorspace of
7154: # $ownername at $ownerdomain
7155:
7156: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7157: # Real author for this?
7158: $ownerhome = $env{'user.home'};
7159: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7160: return ($ownername,$ownerdomain,$ownerhome);
7161: }
7162: } else {
7163: # Co-author for this?
7164: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7165: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7166: $ownerhome = &homeserver($ownername,$ownerdomain);
7167: return ($ownername,$ownerdomain,$ownerhome);
7168: }
7169: }
7170:
7171: # We don't have any access right now. If we are not possibly going to do anything about this,
7172: # we might as well leave
7173: unless ($setpriv) { return ''; }
7174:
7175: # Backdoor access?
7176: my $allowed=&allowed('eco',$ownerdomain);
7177: # Nope
7178: unless ($allowed) { return ''; }
7179: # Looks like we may have access, but could be locked by the owner of the construction space
7180: if ($allowed eq 'U') {
7181: my %blocked=&get('environment',['domcoord.author'],
7182: $ownerdomain,$ownername);
7183: # Is blocked by owner
7184: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7185: }
7186: if (($allowed eq 'F') || ($allowed eq 'U')) {
7187: # Grant temporary access
7188: my $then=$env{'user.login.time'};
1.1209 raeburn 7189: my $update=$env{'user.update.time'};
1.1192 raeburn 7190: if (!$update) { $update = $then; }
7191: my $refresh=$env{'user.refresh.time'};
7192: if (!$refresh) { $refresh = $update; }
7193: my $now = time;
7194: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7195: $now,'ca','constructaccess');
7196: $ownerhome = &homeserver($ownername,$ownerdomain);
7197: return($ownername,$ownerdomain,$ownerhome);
7198: }
7199: # No business here
7200: return '';
7201: }
7202:
1.1282 ! raeburn 7203: # ----------------------------------------------------------- Content Blocking
! 7204:
! 7205: {
! 7206: # Caches for faster Course Contents display where content blocking
! 7207: # is in operation (i.e., interval param set) for timed quiz.
! 7208: #
! 7209: # User for whom data are being temporarily cached.
! 7210: my $cacheduser='';
! 7211: # Cached blockers for this user (a hash of blocking items).
! 7212: my %cachedblockers=();
! 7213: # When the data were last cached.
! 7214: my $cachedlast='';
! 7215:
! 7216: sub load_all_blockers {
! 7217: my ($uname,$udom,$blocks)=@_;
! 7218: if (($uname ne '') && ($udom ne '')) {
! 7219: if (($cacheduser eq $uname.':'.$udom) &&
! 7220: (abs($cachedlast-time)<5)) {
! 7221: return;
! 7222: }
! 7223: }
! 7224: $cachedlast=time;
! 7225: $cacheduser=$uname.':'.$udom;
! 7226: %cachedblockers = &get_commblock_resources($blocks);
! 7227: }
! 7228:
1.1162 raeburn 7229: sub get_comm_blocks {
7230: my ($cdom,$cnum) = @_;
7231: if ($cdom eq '' || $cnum eq '') {
7232: return unless ($env{'request.course.id'});
7233: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7234: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7235: }
7236: my %commblocks;
7237: my $hashid=$cdom.'_'.$cnum;
7238: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7239: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7240: %commblocks = %{$blocksref};
7241: } else {
7242: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7243: my $cachetime = 600;
7244: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7245: }
7246: return %commblocks;
7247: }
7248:
1.1282 ! raeburn 7249: sub get_commblock_resources {
! 7250: my ($blocks) = @_;
! 7251: my %blockers = ();
! 7252: return %blockers unless ($env{'request.course.id'});
! 7253: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7254: my %commblocks;
7255: if (ref($blocks) eq 'HASH') {
7256: %commblocks = %{$blocks};
7257: } else {
7258: %commblocks = &get_comm_blocks();
7259: }
1.1282 ! raeburn 7260: return %blockers unless (keys(%commblocks) > 0);
! 7261: my $navmap = Apache::lonnavmaps::navmap->new();
! 7262: return %blockers unless (ref($navmap));
1.1162 raeburn 7263: my $now = time;
7264: foreach my $block (keys(%commblocks)) {
7265: if ($block =~ /^(\d+)____(\d+)$/) {
7266: my ($start,$end) = ($1,$2);
7267: if ($start <= $now && $end >= $now) {
7268: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7269: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7270: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 ! raeburn 7271: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
! 7272: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7273: }
7274: }
7275: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 ! raeburn 7276: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
! 7277: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7278: }
7279: }
7280: }
7281: }
7282: }
7283: } elsif ($block =~ /^firstaccess____(.+)$/) {
7284: my $item = $1;
1.1163 raeburn 7285: my @to_test;
1.1162 raeburn 7286: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7287: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 ! raeburn 7288: my @interval;
! 7289: my $type = 'map';
! 7290: if ($item eq 'course') {
! 7291: $type = 'course';
! 7292: @interval=&EXT("resource.0.interval");
! 7293: } else {
! 7294: if ($item =~ /___\d+___/) {
! 7295: $type = 'resource';
! 7296: @interval=&EXT("resource.0.interval",$item);
! 7297: if (ref($navmap)) {
! 7298: my $res = $navmap->getBySymb($item);
! 7299: push(@to_test,$res);
! 7300: }
1.1162 raeburn 7301: } else {
1.1282 ! raeburn 7302: my $mapsymb = &symbread($item,1);
! 7303: if ($mapsymb) {
! 7304: if (ref($navmap)) {
! 7305: my $mapres = $navmap->getBySymb($mapsymb);
! 7306: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
! 7307: foreach my $res (@to_test) {
! 7308: my $symb = $res->symb();
! 7309: next if ($symb eq $mapsymb);
! 7310: if ($symb ne '') {
! 7311: @interval=&EXT("resource.0.interval",$symb);
! 7312: if ($interval[1] eq 'map') {
! 7313: last;
1.1162 raeburn 7314: }
7315: }
7316: }
7317: }
7318: }
7319: }
1.1282 ! raeburn 7320: }
! 7321: if ($interval[0] =~ /^\d+$/) {
! 7322: my $first_access;
! 7323: if ($type eq 'resource') {
! 7324: $first_access=&get_first_access($interval[1],$item);
! 7325: } elsif ($type eq 'map') {
! 7326: $first_access=&get_first_access($interval[1],undef,$item);
! 7327: } else {
! 7328: $first_access=&get_first_access($interval[1]);
! 7329: }
! 7330: if ($first_access) {
! 7331: my $timesup = $first_access+$interval[0];
! 7332: if ($timesup > $now) {
! 7333: my $activeblock;
! 7334: foreach my $res (@to_test) {
! 7335: if ($res->completable()) {
! 7336: $activeblock = 1;
! 7337: last;
! 7338: }
! 7339: }
! 7340: if ($activeblock) {
! 7341: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
! 7342: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
! 7343: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
! 7344: }
! 7345: }
! 7346: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
! 7347: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
! 7348: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7349: }
1.1162 raeburn 7350: }
7351: }
7352: }
7353: }
7354: }
7355: }
7356: }
7357: }
7358: }
1.1282 ! raeburn 7359: return %blockers;
1.1162 raeburn 7360: }
7361:
1.1282 ! raeburn 7362: sub has_comm_blocking {
! 7363: my ($priv,$symb,$uri,$blocks) = @_;
! 7364: my @blockers;
! 7365: return unless ($env{'request.course.id'});
! 7366: return unless ($priv eq 'bre');
! 7367: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
! 7368: return if ($env{'request.state'} eq 'construct');
! 7369: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
! 7370: return unless (keys(%cachedblockers) > 0);
! 7371: my (%possibles,@symbs);
! 7372: if (!$symb) {
! 7373: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7374: }
1.1282 ! raeburn 7375: if ($symb) {
! 7376: @symbs = ($symb);
! 7377: } elsif (keys(%possibles)) {
! 7378: @symbs = keys(%possibles);
! 7379: }
! 7380: my $noblock;
! 7381: foreach my $symb (@symbs) {
! 7382: last if ($noblock);
! 7383: my ($map,$resid,$resurl)=&decode_symb($symb);
! 7384: foreach my $block (keys(%cachedblockers)) {
! 7385: if ($block =~ /^firstaccess____(.+)$/) {
! 7386: my $item = $1;
! 7387: if (($item eq $map) || ($item eq $symb)) {
! 7388: $noblock = 1;
! 7389: last;
! 7390: }
! 7391: }
! 7392: if (ref($cachedblockers{$block}) eq 'HASH') {
! 7393: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
! 7394: if ($cachedblockers{$block}{'resources'}{$symb}) {
! 7395: unless (grep(/^\Q$block\E$/,@blockers)) {
! 7396: push(@blockers,$block);
! 7397: }
! 7398: }
! 7399: }
1.1162 raeburn 7400: }
1.1282 ! raeburn 7401: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
! 7402: if ($cachedblockers{$block}{'maps'}{$map}) {
! 7403: unless (grep(/^\Q$block\E$/,@blockers)) {
! 7404: push(@blockers,$block);
! 7405: }
! 7406: }
1.1162 raeburn 7407: }
7408: }
7409: }
1.1282 ! raeburn 7410: return if ($noblock);
! 7411: return @blockers;
! 7412: }
1.1162 raeburn 7413: }
7414:
1.1282 ! raeburn 7415: # -------------------------------- Deversion and split uri into path an filename
! 7416:
1.1133 foxr 7417: #
1.1282 ! raeburn 7418: # Removes the version from a URI and
1.1133 foxr 7419: # splits it in to its filename and path to the filename.
7420: # Seems like File::Basename could have done this more clearly.
7421: # Parameters:
7422: # $uri - input URI
7423: # Returns:
7424: # Two element list consisting of
7425: # $pathname - the URI up to and excluding the trailing /
7426: # $filename - The part of the URI following the last /
7427: # NOTE:
7428: # Another realization of this is simply:
7429: # use File::Basename;
7430: # ...
7431: # $uri = shift;
7432: # $filename = basename($uri);
7433: # $path = dirname($uri);
7434: # return ($filename, $path);
7435: #
7436: # The implementation below is probably faster however.
7437: #
1.710 albertel 7438: sub split_uri_for_cond {
7439: my $uri=&deversion(&declutter(shift));
7440: my @uriparts=split(/\//,$uri);
7441: my $filename=pop(@uriparts);
7442: my $pathname=join('/',@uriparts);
7443: return ($pathname,$filename);
7444: }
1.232 www 7445: # --------------------------------------------------- Is a resource on the map?
7446:
7447: sub is_on_map {
1.710 albertel 7448: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7449: #Trying to find the conditional for the file
1.620 albertel 7450: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7451: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7452: if ($match) {
1.289 bowersj2 7453: return (1,$1);
7454: } else {
1.434 www 7455: return (0,0);
1.289 bowersj2 7456: }
1.12 www 7457: }
7458:
1.427 www 7459: # --------------------------------------------------------- Get symb from alias
7460:
7461: sub get_symb_from_alias {
7462: my $symb=shift;
7463: my ($map,$resid,$url)=&decode_symb($symb);
7464: # Already is a symb
7465: if ($url) { return $symb; }
7466: # Must be an alias
7467: my $aliassymb='';
7468: my %bighash;
1.620 albertel 7469: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7470: &GDBM_READER(),0640)) {
7471: my $rid=$bighash{'mapalias_'.$symb};
7472: if ($rid) {
7473: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7474: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7475: $resid,$bighash{'src_'.$rid});
1.427 www 7476: }
7477: untie %bighash;
7478: }
7479: return $aliassymb;
7480: }
7481:
1.12 www 7482: # ----------------------------------------------------------------- Define Role
7483:
7484: sub definerole {
7485: if (allowed('mcr','/')) {
7486: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7487: foreach my $role (split(':',$sysrole)) {
7488: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7489: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7490: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7491: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7492: return "refused:s:$crole&$cqual";
7493: }
7494: }
1.191 harris41 7495: }
1.800 albertel 7496: foreach my $role (split(':',$domrole)) {
7497: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7498: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7499: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7500: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7501: return "refused:d:$crole&$cqual";
7502: }
7503: }
1.191 harris41 7504: }
1.800 albertel 7505: foreach my $role (split(':',$courole)) {
7506: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7507: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7508: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7509: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7510: return "refused:c:$crole&$cqual";
7511: }
7512: }
1.191 harris41 7513: }
1.620 albertel 7514: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7515: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7516: "rolesdef_$rolename=".
7517: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7518: return reply($command,$env{'user.home'});
1.12 www 7519: } else {
7520: return 'refused';
7521: }
1.105 harris41 7522: }
7523:
7524: # ---------------- Make a metadata query against the network of library servers
7525:
7526: sub metadata_query {
1.1237 raeburn 7527: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7528: my %rhash;
1.845 albertel 7529: my %libserv = &all_library();
1.244 matthew 7530: my @server_list = (defined($server_array) ? @$server_array
7531: : keys(%libserv) );
7532: for my $server (@server_list) {
1.1237 raeburn 7533: my $domains = '';
7534: if (ref($domains_hash) eq 'HASH') {
7535: $domains = $domains_hash->{$server};
7536: }
1.118 harris41 7537: unless ($custom or $customshow) {
1.1237 raeburn 7538: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7539: $rhash{$server}=$reply;
7540: }
7541: else {
7542: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7543: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7544: $server);
7545: $rhash{$server}=$reply;
7546: }
1.112 harris41 7547: }
1.118 harris41 7548: return \%rhash;
1.240 www 7549: }
7550:
7551: # ----------------------------------------- Send log queries and wait for reply
7552:
7553: sub log_query {
7554: my ($uname,$udom,$query,%filters)=@_;
7555: my $uhome=&homeserver($uname,$udom);
7556: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7557: my $uhost=&hostname($uhome);
1.800 albertel 7558: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7559: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7560: $uhome);
1.479 albertel 7561: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7562: return get_query_reply($queryid);
7563: }
7564:
1.818 raeburn 7565: # -------------------------- Update MySQL table for portfolio file
7566:
7567: sub update_portfolio_table {
1.821 raeburn 7568: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7569: if ($group ne '') {
7570: $file_name =~s /^\Q$group\E//;
7571: }
1.818 raeburn 7572: my $homeserver = &homeserver($uname,$udom);
7573: my $queryid=
1.821 raeburn 7574: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7575: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7576: my $reply = &get_query_reply($queryid);
7577: return $reply;
7578: }
7579:
1.899 raeburn 7580: # -------------------------- Update MySQL allusers table
7581:
7582: sub update_allusers_table {
7583: my ($uname,$udom,$names) = @_;
7584: my $homeserver = &homeserver($uname,$udom);
7585: my $queryid=
7586: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7587: 'lastname='.&escape($names->{'lastname'}).'%%'.
7588: 'firstname='.&escape($names->{'firstname'}).'%%'.
7589: 'middlename='.&escape($names->{'middlename'}).'%%'.
7590: 'generation='.&escape($names->{'generation'}).'%%'.
7591: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7592: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7593: return;
1.899 raeburn 7594: }
7595:
1.508 raeburn 7596: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7597:
7598: sub fetch_enrollment_query {
1.511 raeburn 7599: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7600: my $homeserver;
1.547 raeburn 7601: my $maxtries = 1;
1.508 raeburn 7602: if ($context eq 'automated') {
7603: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7604: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7605: } else {
7606: $homeserver = &homeserver($cnum,$dom);
7607: }
1.838 albertel 7608: my $host=&hostname($homeserver);
1.506 raeburn 7609: my $cmd = '';
1.1000 raeburn 7610: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7611: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7612: }
7613: $cmd =~ s/%%$//;
7614: $cmd = &escape($cmd);
7615: my $query = 'fetchenrollment';
1.620 albertel 7616: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7617: unless ($queryid=~/^\Q$host\E\_/) {
7618: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7619: return 'error: '.$queryid;
7620: }
1.506 raeburn 7621: my $reply = &get_query_reply($queryid);
1.547 raeburn 7622: my $tries = 1;
7623: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7624: $reply = &get_query_reply($queryid);
7625: $tries ++;
7626: }
1.526 raeburn 7627: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7628: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7629: } else {
1.901 albertel 7630: my @responses = split(/:/,$reply);
1.515 raeburn 7631: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7632: foreach my $line (@responses) {
7633: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7634: $$replyref{$key} = $value;
7635: }
7636: } else {
1.1117 foxr 7637: my $pathname = LONCAPA::tempdir();
1.800 albertel 7638: foreach my $line (@responses) {
7639: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7640: $$replyref{$key} = $value;
7641: if ($value > 0) {
1.800 albertel 7642: foreach my $item (@{$$affiliatesref{$key}}) {
7643: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7644: my $destname = $pathname.'/'.$filename;
7645: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7646: if ($xml_classlist =~ /^error/) {
7647: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7648: } else {
1.506 raeburn 7649: if ( open(FILE,">$destname") ) {
7650: print FILE &unescape($xml_classlist);
7651: close(FILE);
1.526 raeburn 7652: } else {
7653: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7654: }
7655: }
7656: }
7657: }
7658: }
7659: }
7660: return 'ok';
7661: }
7662: return 'error';
7663: }
7664:
1.242 www 7665: sub get_query_reply {
7666: my $queryid=shift;
1.1117 foxr 7667: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7668: my $reply='';
7669: for (1..100) {
7670: sleep 2;
7671: if (-e $replyfile.'.end') {
1.448 albertel 7672: if (open(my $fh,$replyfile)) {
1.904 albertel 7673: $reply = join('',<$fh>);
7674: close($fh);
1.240 www 7675: } else { return 'error: reply_file_error'; }
1.242 www 7676: return &unescape($reply);
7677: }
1.240 www 7678: }
1.242 www 7679: return 'timeout:'.$queryid;
1.240 www 7680: }
7681:
7682: sub courselog_query {
1.241 www 7683: #
7684: # possible filters:
7685: # url: url or symb
7686: # username
7687: # domain
7688: # action: view, submit, grade
7689: # start: timestamp
7690: # end: timestamp
7691: #
1.240 www 7692: my (%filters)=@_;
1.620 albertel 7693: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7694: if ($filters{'url'}) {
7695: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7696: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7697: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7698: }
1.620 albertel 7699: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7700: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7701: return &log_query($cname,$cdom,'courselog',%filters);
7702: }
7703:
7704: sub userlog_query {
1.858 raeburn 7705: #
7706: # possible filters:
7707: # action: log check role
7708: # start: timestamp
7709: # end: timestamp
7710: #
1.240 www 7711: my ($uname,$udom,%filters)=@_;
7712: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7713: }
7714:
1.506 raeburn 7715: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7716:
7717: sub auto_run {
1.508 raeburn 7718: my ($cnum,$cdom) = @_;
1.876 raeburn 7719: my $response = 0;
7720: my $settings;
7721: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7722: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7723: $settings = $domconfig{'autoenroll'};
7724: if ($settings->{'run'} eq '1') {
7725: $response = 1;
7726: }
7727: } else {
1.934 raeburn 7728: my $homeserver;
7729: if (&is_course($cdom,$cnum)) {
7730: $homeserver = &homeserver($cnum,$cdom);
7731: } else {
7732: $homeserver = &domain($cdom,'primary');
7733: }
7734: if ($homeserver ne 'no_host') {
7735: $response = &reply('autorun:'.$cdom,$homeserver);
7736: }
1.876 raeburn 7737: }
1.506 raeburn 7738: return $response;
7739: }
1.776 albertel 7740:
1.506 raeburn 7741: sub auto_get_sections {
1.508 raeburn 7742: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7743: my $homeserver;
7744: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7745: $homeserver = &homeserver($cnum,$cdom);
7746: }
7747: if (!defined($homeserver)) {
7748: if ($cdom =~ /^$match_domain$/) {
7749: $homeserver = &domain($cdom,'primary');
7750: }
7751: }
7752: my @secs;
7753: if (defined($homeserver)) {
7754: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7755: unless ($response eq 'refused') {
7756: @secs = split(/:/,$response);
7757: }
1.506 raeburn 7758: }
7759: return @secs;
7760: }
1.776 albertel 7761:
1.506 raeburn 7762: sub auto_new_course {
1.1099 raeburn 7763: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7764: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7765: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7766: return $response;
7767: }
1.776 albertel 7768:
1.506 raeburn 7769: sub auto_validate_courseID {
1.508 raeburn 7770: my ($cnum,$cdom,$inst_course_id) = @_;
7771: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7772: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7773: return $response;
7774: }
1.776 albertel 7775:
1.1007 raeburn 7776: sub auto_validate_instcode {
1.1020 raeburn 7777: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7778: my ($homeserver,$response);
7779: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7780: $homeserver = &homeserver($cnum,$cdom);
7781: }
7782: if (!defined($homeserver)) {
7783: if ($cdom =~ /^$match_domain$/) {
7784: $homeserver = &domain($cdom,'primary');
7785: }
7786: }
1.1065 raeburn 7787: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7788: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7789: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7790: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7791: }
7792:
1.506 raeburn 7793: sub auto_create_password {
1.873 raeburn 7794: my ($cnum,$cdom,$authparam,$udom) = @_;
7795: my ($homeserver,$response);
1.506 raeburn 7796: my $create_passwd = 0;
7797: my $authchk = '';
1.873 raeburn 7798: if ($udom =~ /^$match_domain$/) {
7799: $homeserver = &domain($udom,'primary');
7800: }
7801: if ($homeserver eq '') {
7802: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7803: $homeserver = &homeserver($cnum,$cdom);
7804: }
7805: }
7806: if ($homeserver eq '') {
7807: $authchk = 'nodomain';
1.506 raeburn 7808: } else {
1.873 raeburn 7809: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7810: if ($response eq 'refused') {
7811: $authchk = 'refused';
7812: } else {
1.901 albertel 7813: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7814: }
1.506 raeburn 7815: }
7816: return ($authparam,$create_passwd,$authchk);
7817: }
7818:
1.706 raeburn 7819: sub auto_photo_permission {
7820: my ($cnum,$cdom,$students) = @_;
7821: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7822: my ($outcome,$perm_reqd,$conditions) =
7823: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7824: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7825: return (undef,undef);
7826: }
1.706 raeburn 7827: return ($outcome,$perm_reqd,$conditions);
7828: }
7829:
7830: sub auto_checkphotos {
7831: my ($uname,$udom,$pid) = @_;
7832: my $homeserver = &homeserver($uname,$udom);
7833: my ($result,$resulttype);
7834: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7835: &escape($uname).':'.&escape($pid),
7836: $homeserver));
1.709 albertel 7837: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7838: return (undef,undef);
7839: }
1.706 raeburn 7840: if ($outcome) {
7841: ($result,$resulttype) = split(/:/,$outcome);
7842: }
7843: return ($result,$resulttype);
7844: }
7845:
7846: sub auto_photochoice {
7847: my ($cnum,$cdom) = @_;
7848: my $homeserver = &homeserver($cnum,$cdom);
7849: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7850: &escape($cdom),
7851: $homeserver)));
1.709 albertel 7852: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7853: return (undef,undef);
7854: }
1.706 raeburn 7855: return ($update,$comment);
7856: }
7857:
7858: sub auto_photoupdate {
7859: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7860: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7861: my $host=&hostname($homeserver);
1.706 raeburn 7862: my $cmd = '';
7863: my $maxtries = 1;
1.800 albertel 7864: foreach my $affiliate (keys(%{$affiliatesref})) {
7865: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7866: }
7867: $cmd =~ s/%%$//;
7868: $cmd = &escape($cmd);
7869: my $query = 'institutionalphotos';
7870: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7871: unless ($queryid=~/^\Q$host\E\_/) {
7872: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7873: return 'error: '.$queryid;
7874: }
7875: my $reply = &get_query_reply($queryid);
7876: my $tries = 1;
7877: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7878: $reply = &get_query_reply($queryid);
7879: $tries ++;
7880: }
7881: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7882: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7883: } else {
7884: my @responses = split(/:/,$reply);
7885: my $outcome = shift(@responses);
7886: foreach my $item (@responses) {
7887: my ($key,$value) = split(/=/,$item);
7888: $$photo{$key} = $value;
7889: }
7890: return $outcome;
7891: }
7892: return 'error';
7893: }
7894:
1.521 raeburn 7895: sub auto_instcode_format {
1.793 albertel 7896: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7897: $cat_order) = @_;
1.521 raeburn 7898: my $courses = '';
1.772 raeburn 7899: my @homeservers;
1.521 raeburn 7900: if ($caller eq 'global') {
1.841 albertel 7901: my %servers = &get_servers($codedom,'library');
7902: foreach my $tryserver (keys(%servers)) {
7903: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7904: push(@homeservers,$tryserver);
7905: }
1.584 raeburn 7906: }
1.1022 raeburn 7907: } elsif ($caller eq 'requests') {
7908: if ($codedom =~ /^$match_domain$/) {
7909: my $chome = &domain($codedom,'primary');
7910: unless ($chome eq 'no_host') {
7911: push(@homeservers,$chome);
7912: }
7913: }
1.521 raeburn 7914: } else {
1.772 raeburn 7915: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7916: }
1.793 albertel 7917: foreach my $code (keys(%{$instcodes})) {
7918: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7919: }
7920: chop($courses);
1.772 raeburn 7921: my $ok_response = 0;
7922: my $response;
7923: while (@homeservers > 0 && $ok_response == 0) {
7924: my $server = shift(@homeservers);
7925: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7926: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7927: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7928: split(/:/,$response);
1.772 raeburn 7929: %{$codes} = (%{$codes},&str2hash($codes_str));
7930: push(@{$codetitles},&str2array($codetitles_str));
7931: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7932: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7933: $ok_response = 1;
7934: }
7935: }
7936: if ($ok_response) {
1.521 raeburn 7937: return 'ok';
1.772 raeburn 7938: } else {
7939: return $response;
1.521 raeburn 7940: }
7941: }
7942:
1.792 raeburn 7943: sub auto_instcode_defaults {
7944: my ($domain,$returnhash,$code_order) = @_;
7945: my @homeservers;
1.841 albertel 7946:
7947: my %servers = &get_servers($domain,'library');
7948: foreach my $tryserver (keys(%servers)) {
7949: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7950: push(@homeservers,$tryserver);
7951: }
1.792 raeburn 7952: }
1.841 albertel 7953:
1.792 raeburn 7954: my $response;
1.841 albertel 7955: foreach my $server (@homeservers) {
1.792 raeburn 7956: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7957: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7958:
7959: foreach my $pair (split(/\&/,$response)) {
7960: my ($name,$value)=split(/\=/,$pair);
7961: if ($name eq 'code_order') {
7962: @{$code_order} = split(/\&/,&unescape($value));
7963: } else {
7964: $returnhash->{&unescape($name)}=&unescape($value);
7965: }
7966: }
7967: return 'ok';
1.792 raeburn 7968: }
1.841 albertel 7969:
7970: return $response;
1.1003 raeburn 7971: }
7972:
7973: sub auto_possible_instcodes {
1.1007 raeburn 7974: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7975: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7976: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7977: return;
7978: }
1.1003 raeburn 7979: my (@homeservers,$uhome);
7980: if (defined(&domain($domain,'primary'))) {
7981: $uhome=&domain($domain,'primary');
7982: push(@homeservers,&domain($domain,'primary'));
7983: } else {
7984: my %servers = &get_servers($domain,'library');
7985: foreach my $tryserver (keys(%servers)) {
7986: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7987: push(@homeservers,$tryserver);
7988: }
7989: }
7990: }
7991: my $response;
7992: foreach my $server (@homeservers) {
7993: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7994: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7995: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7996: split(':',$response);
7997: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7998: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7999: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8000: my ($name,$value)=split('=',$item);
8001: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8002: }
8003: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8004: my ($name,$value)=split('=',$item);
8005: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8006: }
8007: return 'ok';
8008: }
8009: return $response;
8010: }
1.792 raeburn 8011:
1.1010 raeburn 8012: sub auto_courserequest_checks {
8013: my ($dom) = @_;
1.1020 raeburn 8014: my ($homeserver,%validations);
8015: if ($dom =~ /^$match_domain$/) {
8016: $homeserver = &domain($dom,'primary');
8017: }
8018: unless ($homeserver eq 'no_host') {
8019: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8020: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8021: my @items = split(/&/,$response);
8022: foreach my $item (@items) {
8023: my ($key,$value) = split('=',$item);
8024: $validations{&unescape($key)} = &thaw_unescape($value);
8025: }
8026: }
8027: }
1.1010 raeburn 8028: return %validations;
8029: }
8030:
1.1020 raeburn 8031: sub auto_courserequest_validation {
1.1255 raeburn 8032: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8033: my ($homeserver,$response);
8034: if ($dom =~ /^$match_domain$/) {
8035: $homeserver = &domain($dom,'primary');
8036: }
1.1255 raeburn 8037: unless ($homeserver eq 'no_host') {
8038: my $customdata;
8039: if (ref($custominfo) eq 'HASH') {
8040: $customdata = &freeze_escape($custominfo);
8041: }
1.1020 raeburn 8042: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8043: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8044: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8045: $customdata,$homeserver));
1.1020 raeburn 8046: }
8047: return $response;
8048: }
8049:
1.777 albertel 8050: sub auto_validate_class_sec {
1.918 raeburn 8051: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8052: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8053: my $ownerlist;
8054: if (ref($owners) eq 'ARRAY') {
8055: $ownerlist = join(',',@{$owners});
8056: } else {
8057: $ownerlist = $owners;
8058: }
1.773 raeburn 8059: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8060: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8061: return $response;
8062: }
8063:
1.1248 raeburn 8064: sub auto_crsreq_update {
8065: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8066: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8067: my ($homeserver,%crsreqresponse);
8068: if ($cdom =~ /^$match_domain$/) {
8069: $homeserver = &domain($cdom,'primary');
8070: }
8071: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8072: my $info;
8073: if (ref($inbound) eq 'HASH') {
8074: $info = &freeze_escape($inbound);
8075: }
8076: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8077: ':'.&escape($action).':'.&escape($ownername).':'.
8078: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8079: &escape($title).':'.&escape($code).':'.
8080: &escape($accessstart).':'.&escape($accessend).':'.$info,
8081: $homeserver);
1.1248 raeburn 8082: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8083: my @items = split(/&/,$response);
8084: foreach my $item (@items) {
8085: my ($key,$value) = split('=',$item);
8086: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8087: }
8088: }
8089: }
8090: return \%crsreqresponse;
8091: }
8092:
1.679 raeburn 8093: # ------------------------------------------------------- Course Group routines
8094:
8095: sub get_coursegroups {
1.809 raeburn 8096: my ($cdom,$cnum,$group,$namespace) = @_;
8097: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8098: }
8099:
1.679 raeburn 8100: sub modify_coursegroup {
8101: my ($cdom,$cnum,$groupsettings) = @_;
8102: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8103: }
8104:
1.809 raeburn 8105: sub toggle_coursegroup_status {
8106: my ($cdom,$cnum,$group,$action) = @_;
8107: my ($from_namespace,$to_namespace);
8108: if ($action eq 'delete') {
8109: $from_namespace = 'coursegroups';
8110: $to_namespace = 'deleted_groups';
8111: } else {
8112: $from_namespace = 'deleted_groups';
8113: $to_namespace = 'coursegroups';
8114: }
8115: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8116: if (my $tmp = &error(%curr_group)) {
8117: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8118: return ('read error',$tmp);
8119: } else {
8120: my %savedsettings = %curr_group;
1.809 raeburn 8121: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8122: my $deloutcome;
8123: if ($result eq 'ok') {
1.809 raeburn 8124: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8125: } else {
8126: return ('write error',$result);
8127: }
8128: if ($deloutcome eq 'ok') {
8129: return 'ok';
8130: } else {
8131: return ('delete error',$deloutcome);
8132: }
8133: }
8134: }
8135:
1.679 raeburn 8136: sub modify_group_roles {
1.957 raeburn 8137: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8138: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8139: my $role = 'gr/'.&escape($userprivs);
8140: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8141: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8142: if ($result eq 'ok') {
8143: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8144: }
1.679 raeburn 8145: return $result;
8146: }
8147:
8148: sub modify_coursegroup_membership {
8149: my ($cdom,$cnum,$membership) = @_;
8150: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8151: return $result;
8152: }
8153:
1.682 raeburn 8154: sub get_active_groups {
8155: my ($udom,$uname,$cdom,$cnum) = @_;
8156: my $now = time;
8157: my %groups = ();
8158: foreach my $key (keys(%env)) {
1.811 albertel 8159: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8160: my ($start,$end) = split(/\./,$env{$key});
8161: if (($end!=0) && ($end<$now)) { next; }
8162: if (($start!=0) && ($start>$now)) { next; }
8163: if ($1 eq $cdom && $2 eq $cnum) {
8164: $groups{$3} = $env{$key} ;
8165: }
8166: }
8167: }
8168: return %groups;
8169: }
8170:
1.683 raeburn 8171: sub get_group_membership {
8172: my ($cdom,$cnum,$group) = @_;
8173: return(&dump('groupmembership',$cdom,$cnum,$group));
8174: }
8175:
8176: sub get_users_groups {
8177: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8178: my @usersgroups;
1.683 raeburn 8179: my $cachetime=1800;
8180:
8181: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8182: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8183: if (defined($cached)) {
1.734 albertel 8184: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8185: } else {
8186: $grouplist = '';
1.816 raeburn 8187: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8188: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8189: my $access_end = $env{'course.'.$courseid.
8190: '.default_enrollment_end_date'};
8191: my $now = time;
8192: foreach my $key (keys(%roleshash)) {
8193: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8194: my $group = $1;
8195: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8196: my $start = $2;
8197: my $end = $1;
8198: if ($start == -1) { next; } # deleted from group
8199: if (($start!=0) && ($start>$now)) { next; }
8200: if (($end!=0) && ($end<$now)) {
8201: if ($access_end && $access_end < $now) {
8202: if ($access_end - $end < 86400) {
8203: push(@usersgroups,$group);
1.733 raeburn 8204: }
8205: }
1.817 raeburn 8206: next;
1.733 raeburn 8207: }
1.817 raeburn 8208: push(@usersgroups,$group);
1.683 raeburn 8209: }
8210: }
8211: }
1.817 raeburn 8212: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8213: $grouplist = join(':',@usersgroups);
8214: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8215: }
1.733 raeburn 8216: return @usersgroups;
1.683 raeburn 8217: }
8218:
8219: sub devalidate_getgroups_cache {
8220: my ($udom,$uname,$cdom,$cnum)=@_;
8221: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8222:
1.683 raeburn 8223: my $hashid="$udom:$uname:$courseid";
8224: &devalidate_cache_new('getgroups',$hashid);
8225: }
8226:
1.12 www 8227: # ------------------------------------------------------------------ Plain Text
8228:
8229: sub plaintext {
1.988 raeburn 8230: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8231: if ($short =~ m{^cr/}) {
1.758 albertel 8232: return (split('/',$short))[-1];
8233: }
1.742 raeburn 8234: if (!defined($cid)) {
8235: $cid = $env{'request.course.id'};
8236: }
8237: my %rolenames = (
1.1008 raeburn 8238: Course => 'std',
8239: Community => 'alt1',
1.742 raeburn 8240: );
1.1037 raeburn 8241: if ($cid ne '') {
8242: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8243: unless ($forcedefault) {
8244: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8245: &Apache::lonlocal::mt_escape(\$roletext);
8246: return &Apache::lonlocal::mt($roletext);
8247: }
8248: }
8249: }
8250: if ((defined($type)) && (defined($rolenames{$type})) &&
8251: (defined($rolenames{$type})) &&
8252: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8253: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8254: } elsif ($cid ne '') {
8255: my $crstype = $env{'course.'.$cid.'.type'};
8256: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8257: (defined($prp{$short}{$rolenames{$crstype}}))) {
8258: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8259: }
1.742 raeburn 8260: }
1.1037 raeburn 8261: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8262: }
8263:
8264: # ----------------------------------------------------------------- Assign Role
8265:
8266: sub assignrole {
1.957 raeburn 8267: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8268: $context)=@_;
1.21 www 8269: my $mrole;
8270: if ($role =~ /^cr\//) {
1.393 www 8271: my $cwosec=$url;
1.811 albertel 8272: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8273: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8274: my $refused = 1;
8275: if ($context eq 'requestcourses') {
8276: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8277: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8278: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8279: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8280: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8281: if ($crsenv{'internal.courseowner'} eq
8282: $env{'user.name'}.':'.$env{'user.domain'}) {
8283: $refused = '';
8284: }
8285: }
8286: }
8287: }
8288: }
8289: if ($refused) {
8290: &logthis('Refused custom assignrole: '.
8291: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8292: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8293: return 'refused';
8294: }
1.104 www 8295: }
1.21 www 8296: $mrole='cr';
1.678 raeburn 8297: } elsif ($role =~ /^gr\//) {
8298: my $cwogrp=$url;
1.811 albertel 8299: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8300: unless (&allowed('mdg',$cwogrp)) {
8301: &logthis('Refused group assignrole: '.
8302: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8303: $env{'user.name'}.' at '.$env{'user.domain'});
8304: return 'refused';
8305: }
8306: $mrole='gr';
1.21 www 8307: } else {
1.82 www 8308: my $cwosec=$url;
1.811 albertel 8309: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8310: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8311: my $refused;
8312: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8313: if (!(&allowed('c'.$role,$url))) {
8314: $refused = 1;
8315: }
8316: } else {
8317: $refused = 1;
8318: }
1.947 raeburn 8319: if ($refused) {
1.1045 raeburn 8320: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8321: if (!$selfenroll && $context eq 'course') {
8322: my %crsenv;
8323: if ($role eq 'cc' || $role eq 'co') {
8324: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8325: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8326: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8327: if ($crsenv{'internal.courseowner'} eq
8328: $env{'user.name'}.':'.$env{'user.domain'}) {
8329: $refused = '';
8330: }
8331: }
8332: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8333: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8334: if ($crsenv{'internal.courseowner'} eq
8335: $env{'user.name'}.':'.$env{'user.domain'}) {
8336: $refused = '';
8337: }
8338: }
8339: }
8340: }
8341: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8342: $refused = '';
1.1017 raeburn 8343: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8344: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8345: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8346: my $wrongcc;
8347: if ($cnum =~ /^$match_community$/) {
8348: $wrongcc = 1 if ($role eq 'cc');
8349: } else {
8350: $wrongcc = 1 if ($role eq 'co');
8351: }
8352: unless ($wrongcc) {
8353: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8354: if ($crsenv{'internal.courseowner'} eq
8355: $env{'user.name'}.':'.$env{'user.domain'}) {
8356: $refused = '';
8357: }
1.1017 raeburn 8358: }
8359: }
1.1183 raeburn 8360: } elsif ($context eq 'requestauthor') {
8361: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8362: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8363: if ($env{'environment.requestauthor'} eq 'automatic') {
8364: $refused = '';
8365: } else {
8366: my %domdefaults = &get_domain_defaults($udom);
8367: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8368: my $checkbystatus;
8369: if ($env{'user.adv'}) {
8370: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8371: if ($disposition eq 'automatic') {
8372: $refused = '';
8373: } elsif ($disposition eq '') {
8374: $checkbystatus = 1;
8375: }
8376: } else {
8377: $checkbystatus = 1;
8378: }
8379: if ($checkbystatus) {
8380: if ($env{'environment.inststatus'}) {
8381: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8382: foreach my $type (@inststatuses) {
8383: if (($type ne '') &&
8384: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8385: $refused = '';
8386: }
8387: }
8388: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8389: $refused = '';
8390: }
8391: }
8392: }
8393: }
8394: }
1.1017 raeburn 8395: }
8396: if ($refused) {
1.947 raeburn 8397: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8398: ' '.$role.' '.$end.' '.$start.' by '.
8399: $env{'user.name'}.' at '.$env{'user.domain'});
8400: return 'refused';
8401: }
1.932 raeburn 8402: }
1.1131 raeburn 8403: } elsif ($role eq 'au') {
8404: if ($url ne '/'.$udom.'/') {
8405: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8406: ' to assign author role for '.$uname.':'.$udom.
8407: ' in domain: '.$url.' refused (wrong domain).');
8408: return 'refused';
8409: }
1.104 www 8410: }
1.21 www 8411: $mrole=$role;
8412: }
1.620 albertel 8413: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8414: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8415: if ($end) { $command.='_'.$end; }
1.21 www 8416: if ($start) {
8417: if ($end) {
1.81 www 8418: $command.='_'.$start;
1.21 www 8419: } else {
1.81 www 8420: $command.='_0_'.$start;
1.21 www 8421: }
8422: }
1.739 raeburn 8423: my $origstart = $start;
8424: my $origend = $end;
1.957 raeburn 8425: my $delflag;
1.357 www 8426: # actually delete
8427: if ($deleteflag) {
1.373 www 8428: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8429: # modify command to delete the role
1.620 albertel 8430: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8431: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8432: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8433: # set start and finish to negative values for userrolelog
8434: $start=-1;
8435: $end=-1;
1.957 raeburn 8436: $delflag = 1;
1.357 www 8437: }
8438: }
8439: # send command
1.349 www 8440: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8441: # log new user role if status is ok
1.349 www 8442: if ($answer eq 'ok') {
1.663 raeburn 8443: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8444: if (($role eq 'cc') || ($role eq 'in') ||
8445: ($role eq 'ep') || ($role eq 'ad') ||
8446: ($role eq 'ta') || ($role eq 'st') ||
8447: ($role=~/^cr/) || ($role eq 'gr') ||
8448: ($role eq 'co')) {
1.1200 raeburn 8449: # for course roles, perform group memberships changes triggered by role change.
8450: unless ($role =~ /^gr/) {
8451: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8452: $origstart,$selfenroll,$context);
8453: }
1.1184 raeburn 8454: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8455: $selfenroll,$context);
8456: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8457: ($role eq 'au') || ($role eq 'dc')) {
8458: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8459: $context);
8460: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8461: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8462: $context);
8463: }
1.1053 raeburn 8464: if ($role eq 'cc') {
8465: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8466: }
1.349 www 8467: }
8468: return $answer;
1.169 harris41 8469: }
8470:
1.1053 raeburn 8471: sub autoupdate_coowners {
8472: my ($url,$end,$start,$uname,$udom) = @_;
8473: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8474: if (($cdom ne '') && ($cnum ne '')) {
8475: my $now = time;
8476: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8477: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8478: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8479: my $instcode = $coursehash{'internal.coursecode'};
8480: if ($instcode ne '') {
1.1056 raeburn 8481: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8482: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8483: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8484: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8485: if ($result eq 'valid') {
8486: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8487: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8488: push(@newcoowners,$coowner);
8489: }
8490: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8491: push(@newcoowners,$uname.':'.$udom);
8492: }
8493: @newcoowners = sort(@newcoowners);
8494: } else {
8495: push(@newcoowners,$uname.':'.$udom);
8496: }
8497: } else {
8498: if ($coursehash{'internal.co-owners'}) {
8499: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8500: unless ($coowner eq $uname.':'.$udom) {
8501: push(@newcoowners,$coowner);
8502: }
8503: }
8504: unless (@newcoowners > 0) {
8505: $delcoowners = 1;
8506: $coowners = '';
8507: }
8508: }
8509: }
8510: if (@newcoowners || $delcoowners) {
8511: &store_coowners($cdom,$cnum,$coursehash{'home'},
8512: $delcoowners,@newcoowners);
8513: }
8514: }
8515: }
8516: }
8517: }
8518: }
8519: }
8520:
8521: sub store_coowners {
8522: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8523: my $cid = $cdom.'_'.$cnum;
8524: my ($coowners,$delresult,$putresult);
8525: if (@newcoowners) {
8526: $coowners = join(',',@newcoowners);
8527: my %coownershash = (
8528: 'internal.co-owners' => $coowners,
8529: );
8530: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8531: if ($putresult eq 'ok') {
8532: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8533: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8534: }
8535: }
8536: }
8537: if ($delcoowners) {
8538: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8539: if ($delresult eq 'ok') {
8540: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8541: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8542: }
8543: }
8544: }
8545: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8546: my %crsinfo =
8547: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8548: if (ref($crsinfo{$cid}) eq 'HASH') {
8549: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8550: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8551: }
8552: }
8553: }
8554:
1.169 harris41 8555: # -------------------------------------------------- Modify user authentication
1.197 www 8556: # Overrides without validation
8557:
1.169 harris41 8558: sub modifyuserauth {
8559: my ($udom,$uname,$umode,$upass)=@_;
8560: my $uhome=&homeserver($uname,$udom);
1.197 www 8561: unless (&allowed('mau',$udom)) { return 'refused'; }
8562: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8563: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8564: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8565: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8566: &escape($upass),$uhome);
1.620 albertel 8567: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8568: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8569: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8570: &log($udom,,$uname,$uhome,
1.620 albertel 8571: 'Authentication changed by '.$env{'user.domain'}.', '.
8572: $env{'user.name'}.', '.$umode.
1.197 www 8573: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8574: unless ($reply eq 'ok') {
1.197 www 8575: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8576: return 'error: '.$reply;
8577: }
1.170 harris41 8578: return 'ok';
1.80 www 8579: }
8580:
1.81 www 8581: # --------------------------------------------------------------- Modify a user
1.80 www 8582:
1.81 www 8583: sub modifyuser {
1.206 matthew 8584: my ($udom, $uname, $uid,
8585: $umode, $upass, $first,
8586: $middle, $last, $gene,
1.1058 raeburn 8587: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8588: $udom= &LONCAPA::clean_domain($udom);
8589: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8590: my $showcandelete = 'none';
8591: if (ref($candelete) eq 'ARRAY') {
8592: if (@{$candelete} > 0) {
8593: $showcandelete = join(', ',@{$candelete});
8594: }
8595: }
1.81 www 8596: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8597: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8598: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8599: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8600: ' desiredhome not specified').
1.620 albertel 8601: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8602: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8603: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8604: my $newuser;
8605: if ($uhome eq 'no_host') {
8606: $newuser = 1;
8607: }
1.80 www 8608: # ----------------------------------------------------------------- Create User
1.406 albertel 8609: if (($uhome eq 'no_host') &&
8610: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8611: my $unhome='';
1.844 albertel 8612: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8613: $unhome = $desiredhome;
1.620 albertel 8614: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8615: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8616: } else { # load balancing routine for determining $unhome
1.81 www 8617: my $loadm=10000000;
1.841 albertel 8618: my %servers = &get_servers($udom,'library');
8619: foreach my $tryserver (keys(%servers)) {
8620: my $answer=reply('load',$tryserver);
8621: if (($answer=~/\d+/) && ($answer<$loadm)) {
8622: $loadm=$answer;
8623: $unhome=$tryserver;
8624: }
1.80 www 8625: }
8626: }
8627: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8628: return 'error: unable to find a home server for '.$uname.
8629: ' in domain '.$udom;
1.80 www 8630: }
8631: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8632: &escape($upass),$unhome);
8633: unless ($reply eq 'ok') {
8634: return 'error: '.$reply;
8635: }
1.230 stredwic 8636: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8637: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8638: return 'error: unable verify users home machine.';
1.80 www 8639: }
1.209 matthew 8640: } # End of creation of new user
1.80 www 8641: # ---------------------------------------------------------------------- Add ID
8642: if ($uid) {
8643: $uid=~tr/A-Z/a-z/;
8644: my %uidhash=&idrget($udom,$uname);
1.196 www 8645: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8646: && (!$forceid)) {
1.80 www 8647: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8648: return 'error: user id "'.$uid.'" does not match '.
8649: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8650: }
8651: } else {
8652: &idput($udom,($uname => $uid));
8653: }
8654: }
8655: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8656: my @tmp=&get('environment',
1.899 raeburn 8657: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8658: 'permanentemail','inststatus'],
1.134 albertel 8659: $udom,$uname);
1.1075 raeburn 8660: my (%names,%oldnames);
1.313 matthew 8661: if ($tmp[0] =~ m/^error:.*/) {
8662: %names=();
8663: } else {
8664: %names = @tmp;
1.1075 raeburn 8665: %oldnames = %names;
1.313 matthew 8666: }
1.388 www 8667: #
1.1058 raeburn 8668: # If name, email and/or uid are blank (e.g., because an uploaded file
8669: # of users did not contain them), do not overwrite existing values
8670: # unless field is in $candelete array ref.
8671: #
8672:
8673: my @fields = ('firstname','middlename','lastname','generation',
8674: 'permanentemail','id');
8675: my %newvalues;
8676: if (ref($candelete) eq 'ARRAY') {
8677: foreach my $field (@fields) {
8678: if (grep(/^\Q$field\E$/,@{$candelete})) {
8679: if ($field eq 'firstname') {
8680: $names{$field} = $first;
8681: } elsif ($field eq 'middlename') {
8682: $names{$field} = $middle;
8683: } elsif ($field eq 'lastname') {
8684: $names{$field} = $last;
8685: } elsif ($field eq 'generation') {
8686: $names{$field} = $gene;
8687: } elsif ($field eq 'permanentemail') {
8688: $names{$field} = $email;
8689: } elsif ($field eq 'id') {
8690: $names{$field} = $uid;
8691: }
8692: }
8693: }
8694: }
1.388 www 8695: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8696: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8697: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8698: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8699: if ($email) {
8700: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8701: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8702: }
1.899 raeburn 8703: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8704: if (defined($inststatus)) {
8705: $names{'inststatus'} = '';
8706: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8707: if (ref($usertypes) eq 'HASH') {
8708: my @okstatuses;
8709: foreach my $item (split(/:/,$inststatus)) {
8710: if (defined($usertypes->{$item})) {
8711: push(@okstatuses,$item);
8712: }
8713: }
8714: if (@okstatuses) {
8715: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8716: }
8717: }
8718: }
1.1075 raeburn 8719: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8720: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8721: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8722: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8723: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8724: } else {
8725: $logmsg .= ' during self creation';
8726: }
1.1075 raeburn 8727: my $changed;
8728: if ($newuser) {
8729: $changed = 1;
8730: } else {
8731: foreach my $field (@fields) {
8732: if ($names{$field} ne $oldnames{$field}) {
8733: $changed = 1;
8734: last;
8735: }
8736: }
8737: }
8738: unless ($changed) {
8739: $logmsg = 'No changes in user information needed for: '.$logmsg;
8740: &logthis($logmsg);
8741: return 'ok';
8742: }
8743: my $reply = &put('environment', \%names, $udom,$uname);
8744: if ($reply ne 'ok') {
8745: return 'error: '.$reply;
8746: }
1.1087 raeburn 8747: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8748: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8749: }
1.1075 raeburn 8750: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8751: &devalidate_cache_new('namescache',$uname.':'.$udom);
8752: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8753: &logthis($logmsg);
1.134 albertel 8754: return 'ok';
1.80 www 8755: }
8756:
1.81 www 8757: # -------------------------------------------------------------- Modify student
1.80 www 8758:
1.81 www 8759: sub modifystudent {
8760: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8761: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8762: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8763: if (!$cid) {
1.620 albertel 8764: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8765: return 'not_in_class';
8766: }
1.80 www 8767: }
8768: # --------------------------------------------------------------- Make the user
1.81 www 8769: my $reply=&modifyuser
1.209 matthew 8770: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8771: $desiredhome,$email,$inststatus);
1.80 www 8772: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8773: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8774: # student's environment
1.297 matthew 8775: $uid = undef if (!$forceid);
1.455 albertel 8776: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8777: $gene,$usec,$end,$start,$type,$locktype,
8778: $cid,$selfenroll,$context,$credits);
1.297 matthew 8779: return $reply;
8780: }
8781:
8782: sub modify_student_enrollment {
1.1216 raeburn 8783: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8784: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8785: my ($cdom,$cnum,$chome);
8786: if (!$cid) {
1.620 albertel 8787: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8788: return 'not_in_class';
8789: }
1.620 albertel 8790: $cdom=$env{'course.'.$cid.'.domain'};
8791: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8792: } else {
8793: ($cdom,$cnum)=split(/_/,$cid);
8794: }
1.620 albertel 8795: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8796: if (!$chome) {
1.457 raeburn 8797: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8798: }
1.455 albertel 8799: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8800: # Make sure the user exists
1.81 www 8801: my $uhome=&homeserver($uname,$udom);
8802: if (($uhome eq '') || ($uhome eq 'no_host')) {
8803: return 'error: no such user';
8804: }
1.297 matthew 8805: # Get student data if we were not given enough information
8806: if (!defined($first) || $first eq '' ||
8807: !defined($last) || $last eq '' ||
8808: !defined($uid) || $uid eq '' ||
8809: !defined($middle) || $middle eq '' ||
8810: !defined($gene) || $gene eq '') {
1.294 matthew 8811: # They did not supply us with enough data to enroll the student, so
8812: # we need to pick up more information.
1.297 matthew 8813: my %tmp = &get('environment',
1.294 matthew 8814: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8815: ,$udom,$uname);
8816:
1.800 albertel 8817: #foreach my $key (keys(%tmp)) {
8818: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8819: #}
1.294 matthew 8820: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8821: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8822: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8823: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8824: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8825: }
1.556 albertel 8826: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8827: my $user = "$uname:$udom";
8828: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8829: my $reply=cput('classlist',
1.1148 raeburn 8830: {$user =>
1.1216 raeburn 8831: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8832: $cdom,$cnum);
1.1148 raeburn 8833: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8834: &devalidate_getsection_cache($udom,$uname,$cid);
8835: } else {
1.81 www 8836: return 'error: '.$reply;
8837: }
1.297 matthew 8838: # Add student role to user
1.83 www 8839: my $uurl='/'.$cid;
1.81 www 8840: $uurl=~s/\_/\//g;
8841: if ($usec) {
8842: $uurl.='/'.$usec;
8843: }
1.1148 raeburn 8844: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8845: $selfenroll,$context);
8846: if ($result ne 'ok') {
8847: if ($old_entry{$user} ne '') {
8848: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8849: } else {
8850: $reply = &del('classlist',[$user],$cdom,$cnum);
8851: }
8852: }
8853: return $result;
1.21 www 8854: }
8855:
1.556 albertel 8856: sub format_name {
8857: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8858: my $name;
8859: if ($first ne 'lastname') {
8860: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8861: } else {
8862: if ($lastname=~/\S/) {
8863: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8864: $name=~s/\s+,/,/;
8865: } else {
8866: $name.= $firstname.' '.$middlename.' '.$generation;
8867: }
8868: }
8869: $name=~s/^\s+//;
8870: $name=~s/\s+$//;
8871: $name=~s/\s+/ /g;
8872: return $name;
8873: }
8874:
1.84 www 8875: # ------------------------------------------------- Write to course preferences
8876:
8877: sub writecoursepref {
8878: my ($courseid,%prefs)=@_;
8879: $courseid=~s/^\///;
8880: $courseid=~s/\_/\//g;
8881: my ($cdomain,$cnum)=split(/\//,$courseid);
8882: my $chome=homeserver($cnum,$cdomain);
8883: if (($chome eq '') || ($chome eq 'no_host')) {
8884: return 'error: no such course';
8885: }
8886: my $cstring='';
1.800 albertel 8887: foreach my $pref (keys(%prefs)) {
8888: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8889: }
1.84 www 8890: $cstring=~s/\&$//;
8891: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8892: }
8893:
8894: # ---------------------------------------------------------- Make/modify course
8895:
8896: sub createcourse {
1.741 raeburn 8897: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8898: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8899: $url=&declutter($url);
8900: my $cid='';
1.1028 raeburn 8901: if ($context eq 'requestcourses') {
8902: my $can_create = 0;
8903: my ($ownername,$ownerdom) = split(':',$course_owner);
8904: if ($udom eq $ownerdom) {
8905: if (&usertools_access($ownername,$ownerdom,$category,undef,
8906: $context)) {
8907: $can_create = 1;
8908: }
8909: } else {
8910: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8911: $category);
8912: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8913: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8914: if (@curr > 0) {
8915: my @options = qw(approval validate autolimit);
8916: my $optregex = join('|',@options);
8917: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8918: $can_create = 1;
8919: }
8920: }
8921: }
8922: }
8923: if ($can_create) {
8924: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8925: unless (&allowed('ccc',$udom)) {
8926: return 'refused';
8927: }
1.1017 raeburn 8928: }
8929: } else {
8930: return 'refused';
8931: }
1.1028 raeburn 8932: } elsif (!&allowed('ccc',$udom)) {
8933: return 'refused';
1.84 www 8934: }
1.1011 raeburn 8935: # --------------------------------------------------------------- Get Unique ID
8936: my $uname;
8937: if ($cnum =~ /^$match_courseid$/) {
8938: my $chome=&homeserver($cnum,$udom,'true');
8939: if (($chome eq '') || ($chome eq 'no_host')) {
8940: $uname = $cnum;
8941: } else {
1.1038 raeburn 8942: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8943: }
8944: } else {
1.1038 raeburn 8945: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8946: }
8947: return $uname if ($uname =~ /^error/);
8948: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8949: if (!defined($course_server)) {
8950: if (defined(&domain($udom,'primary'))) {
8951: $course_server = &domain($udom,'primary');
8952: } else {
8953: $course_server = $env{'user.home'};
8954: }
8955: }
8956: my %host_servers =
8957: &Apache::lonnet::get_servers($udom,'library');
8958: unless ($host_servers{$course_server}) {
8959: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8960: }
1.84 www 8961: # ------------------------------------------------------------- Make the course
8962: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8963: $course_server);
1.84 www 8964: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8965: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8966: if (($uhome eq '') || ($uhome eq 'no_host')) {
8967: return 'error: no such course';
8968: }
1.271 www 8969: # ----------------------------------------------------------------- Course made
1.516 raeburn 8970: # log existence
1.1029 raeburn 8971: my $now = time;
1.918 raeburn 8972: my $newcourse = {
8973: $udom.'_'.$uname => {
1.921 raeburn 8974: description => $description,
8975: inst_code => $inst_code,
8976: owner => $course_owner,
8977: type => $crstype,
1.1029 raeburn 8978: creator => $env{'user.name'}.':'.
8979: $env{'user.domain'},
8980: created => $now,
8981: context => $context,
1.918 raeburn 8982: },
8983: };
1.921 raeburn 8984: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8985: # set toplevel url
1.271 www 8986: my $topurl=$url;
8987: unless ($nonstandard) {
8988: # ------------------------------------------ For standard courses, make top url
8989: my $mapurl=&clutter($url);
1.278 www 8990: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8991: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8992: <map>
8993: <resource id="1" type="start"></resource>
8994: <resource id="2" src="$mapurl"></resource>
8995: <resource id="3" type="finish"></resource>
8996: <link index="1" from="1" to="2"></link>
8997: <link index="2" from="2" to="3"></link>
8998: </map>
8999: ENDINITMAP
9000: $topurl=&declutter(
1.638 albertel 9001: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9002: );
9003: }
9004: # ----------------------------------------------------------- Write preferences
1.84 www 9005: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9006: ('description' => $description,
9007: 'url' => $topurl,
9008: 'internal.creator' => $env{'user.name'}.':'.
9009: $env{'user.domain'},
9010: 'internal.created' => $now,
9011: 'internal.creationcontext' => $context)
9012: );
1.84 www 9013: return '/'.$udom.'/'.$uname;
9014: }
9015:
1.1011 raeburn 9016: # ------------------------------------------------------------------- Create ID
9017: sub generate_coursenum {
1.1038 raeburn 9018: my ($udom,$crstype) = @_;
1.1011 raeburn 9019: my $domdesc = &domain($udom);
9020: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9021: my $first;
9022: if ($crstype eq 'Community') {
9023: $first = '0';
9024: } else {
9025: $first = int(1+rand(9));
9026: }
9027: my $uname=$first.
1.1011 raeburn 9028: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9029: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9030: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9031: # ----------------------------------------------- Make sure that does not exist
9032: my $uhome=&homeserver($uname,$udom,'true');
9033: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9034: if ($crstype eq 'Community') {
9035: $first = '0';
9036: } else {
9037: $first = int(1+rand(9));
9038: }
9039: $uname=$first.
1.1011 raeburn 9040: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9041: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9042: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9043: $uhome=&homeserver($uname,$udom,'true');
9044: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9045: return 'error: unable to generate unique course-ID';
9046: }
9047: }
9048: return $uname;
9049: }
9050:
1.813 albertel 9051: sub is_course {
1.1167 droeschl 9052: my ($cdom, $cnum) = scalar(@_) == 1 ?
9053: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9054:
9055: return unless $cdom and $cnum;
9056:
9057: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9058: '.');
9059:
1.1219 raeburn 9060: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9061: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9062: }
9063:
1.1015 raeburn 9064: sub store_userdata {
9065: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9066: my $result;
1.1016 raeburn 9067: if ($datakey ne '') {
1.1013 raeburn 9068: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9069: if ($udom eq '' || $uname eq '') {
9070: $udom = $env{'user.domain'};
9071: $uname = $env{'user.name'};
9072: }
9073: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9074: if (($uhome eq '') || ($uhome eq 'no_host')) {
9075: $result = 'error: no_host';
9076: } else {
9077: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9078: $storehash->{'host'} = $perlvar{'lonHostID'};
9079:
9080: my $namevalue='';
9081: foreach my $key (keys(%{$storehash})) {
9082: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9083: }
9084: $namevalue=~s/\&$//;
1.1224 raeburn 9085: unless ($namespace eq 'courserequests') {
9086: $datakey = &escape($datakey);
9087: }
1.1105 raeburn 9088: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9089: $namevalue,$uhome);
1.1013 raeburn 9090: }
9091: } else {
9092: $result = 'error: data to store was not a hash reference';
9093: }
9094: } else {
9095: $result= 'error: invalid requestkey';
9096: }
9097: return $result;
9098: }
9099:
1.21 www 9100: # ---------------------------------------------------------- Assign Custom Role
9101:
9102: sub assigncustomrole {
1.957 raeburn 9103: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9104: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9105: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9106: }
9107:
9108: # ----------------------------------------------------------------- Revoke Role
9109:
9110: sub revokerole {
1.957 raeburn 9111: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9112: my $now=time;
1.965 raeburn 9113: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9114: }
9115:
9116: # ---------------------------------------------------------- Revoke Custom Role
9117:
9118: sub revokecustomrole {
1.957 raeburn 9119: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9120: my $now=time;
1.357 www 9121: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9122: $deleteflag,$selfenroll,$context);
1.17 www 9123: }
9124:
1.533 banghart 9125: # ------------------------------------------------------------ Disk usage
1.535 albertel 9126: sub diskusage {
1.955 raeburn 9127: my ($udom,$uname,$directorypath,$getpropath)=@_;
9128: $directorypath =~ s/\/$//;
9129: my $listing=&reply('du2:'.&escape($directorypath).':'
9130: .&escape($getpropath).':'.&escape($uname).':'
9131: .&escape($udom),homeserver($uname,$udom));
9132: if ($listing eq 'unknown_cmd') {
9133: if ($getpropath) {
9134: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9135: }
9136: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9137: }
1.514 albertel 9138: return $listing;
1.512 banghart 9139: }
9140:
1.566 banghart 9141: sub is_locked {
1.1096 raeburn 9142: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9143: my @check;
9144: my $is_locked;
1.1093 raeburn 9145: push (@check,$file_name);
1.613 albertel 9146: my %locked = &get('file_permissions',\@check,
1.620 albertel 9147: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9148: my ($tmp)=keys(%locked);
9149: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9150:
1.566 banghart 9151: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9152: $is_locked = 'false';
9153: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9154: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9155: $is_locked = 'true';
1.1096 raeburn 9156: if (ref($which) eq 'ARRAY') {
9157: push(@{$which},$entry);
9158: } else {
9159: last;
9160: }
1.745 raeburn 9161: }
9162: }
1.566 banghart 9163: } else {
9164: $is_locked = 'false';
9165: }
1.1093 raeburn 9166: return $is_locked;
1.566 banghart 9167: }
9168:
1.759 albertel 9169: sub declutter_portfile {
9170: my ($file) = @_;
1.833 albertel 9171: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9172: return $file;
9173: }
9174:
1.559 banghart 9175: # ------------------------------------------------------------- Mark as Read Only
9176:
9177: sub mark_as_readonly {
9178: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9179: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9180: my ($tmp)=keys(%current_permissions);
9181: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9182: foreach my $file (@{$files}) {
1.759 albertel 9183: $file = &declutter_portfile($file);
1.561 banghart 9184: push(@{$current_permissions{$file}},$what);
1.559 banghart 9185: }
1.613 albertel 9186: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9187: return;
9188: }
9189:
1.572 banghart 9190: # ------------------------------------------------------------Save Selected Files
9191:
9192: sub save_selected_files {
9193: my ($user, $path, @files) = @_;
9194: my $filename = $user."savedfiles";
1.573 banghart 9195: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9196: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9197: foreach my $file (@files) {
1.620 albertel 9198: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9199: }
9200: foreach my $file (@other_files) {
1.574 banghart 9201: print (OUT $file."\n");
1.572 banghart 9202: }
1.574 banghart 9203: close (OUT);
1.572 banghart 9204: return 'ok';
9205: }
9206:
1.574 banghart 9207: sub clear_selected_files {
9208: my ($user) = @_;
9209: my $filename = $user."savedfiles";
1.1117 foxr 9210: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9211: print (OUT undef);
9212: close (OUT);
9213: return ("ok");
9214: }
9215:
1.572 banghart 9216: sub files_in_path {
9217: my ($user, $path) = @_;
9218: my $filename = $user."savedfiles";
9219: my %return_files;
1.1117 foxr 9220: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9221: while (my $line_in = <IN>) {
1.574 banghart 9222: chomp ($line_in);
9223: my @paths_and_file = split (m!/!, $line_in);
9224: my $file_part = pop (@paths_and_file);
9225: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9226: $path_part.='/';
9227: my $path_and_file = $path_part.$file_part;
9228: if ($path_part eq $path) {
9229: $return_files{$file_part}= 'selected';
9230: }
9231: }
1.574 banghart 9232: close (IN);
9233: return (\%return_files);
1.572 banghart 9234: }
9235:
9236: # called in portfolio select mode, to show files selected NOT in current directory
9237: sub files_not_in_path {
9238: my ($user, $path) = @_;
9239: my $filename = $user."savedfiles";
9240: my @return_files;
9241: my $path_part;
1.1117 foxr 9242: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9243: while (my $line = <IN>) {
1.572 banghart 9244: #ok, I know it's clunky, but I want it to work
1.800 albertel 9245: my @paths_and_file = split(m|/|, $line);
9246: my $file_part = pop(@paths_and_file);
9247: chomp($file_part);
9248: my $path_part = join('/', @paths_and_file);
1.572 banghart 9249: $path_part .= '/';
9250: my $path_and_file = $path_part.$file_part;
9251: if ($path_part ne $path) {
1.800 albertel 9252: push(@return_files, ($path_and_file));
1.572 banghart 9253: }
9254: }
1.800 albertel 9255: close(OUT);
1.574 banghart 9256: return (@return_files);
1.572 banghart 9257: }
9258:
1.1273 raeburn 9259: #------------------------------Submitted/Handedback Portfolio Files Versioning
9260:
9261: sub portfiles_versioning {
9262: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9263: my $portfolio_root = '/userfiles/portfolio';
9264: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9265: foreach my $file (@{$portfiles}) {
9266: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9267: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9268: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9269: my $getpropath = 1;
9270: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9271: $stu_name,$getpropath);
9272: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9273: my $new_answer =
9274: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9275: if ($new_answer ne 'problem getting file') {
9276: push(@{$versioned_portfiles}, $directory.$new_answer);
9277: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9278: [$symb,$env{'request.course.id'},'graded']);
9279: }
9280: }
9281: }
9282:
9283: sub get_next_version {
9284: my ($answer_name, $answer_ext, $dir_list) = @_;
9285: my $version;
9286: if (ref($dir_list) eq 'ARRAY') {
9287: foreach my $row (@{$dir_list}) {
9288: my ($file) = split(/\&/,$row,2);
9289: my ($file_name,$file_version,$file_ext) =
9290: &file_name_version_ext($file);
9291: if (($file_name eq $answer_name) &&
9292: ($file_ext eq $answer_ext)) {
9293: # gets here if filename and extension match,
9294: # regardless of version
9295: if ($file_version ne '') {
9296: # a versioned file is found so save it for later
9297: if ($file_version > $version) {
9298: $version = $file_version;
9299: }
9300: }
9301: }
9302: }
9303: }
9304: $version ++;
9305: return($version);
9306: }
9307:
9308: sub version_selected_portfile {
9309: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9310: my ($answer_name,$answer_ver,$answer_ext) =
9311: &file_name_version_ext($file_name);
9312: my $new_answer;
9313: $env{'form.copy'} =
9314: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9315: if($env{'form.copy'} eq '-1') {
9316: $new_answer = 'problem getting file';
9317: } else {
9318: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9319: my $copy_result =
9320: &finishuserfileupload($stu_name,$domain,'copy',
9321: '/portfolio'.$directory.$new_answer);
9322: }
9323: undef($env{'form.copy'});
9324: return ($new_answer);
9325: }
9326:
9327: sub file_name_version_ext {
9328: my ($file)=@_;
9329: my @file_parts = split(/\./, $file);
9330: my ($name,$version,$ext);
9331: if (@file_parts > 1) {
9332: $ext=pop(@file_parts);
9333: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9334: $version=pop(@file_parts);
9335: }
9336: $name=join('.',@file_parts);
9337: } else {
9338: $name=join('.',@file_parts);
9339: }
9340: return($name,$version,$ext);
9341: }
9342:
1.745 raeburn 9343: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9344:
1.745 raeburn 9345: sub get_portfile_permissions {
9346: my ($domain,$user) = @_;
1.613 albertel 9347: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9348: my ($tmp)=keys(%current_permissions);
9349: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9350: return \%current_permissions;
9351: }
9352:
9353: #---------------------------------------------Get portfolio file access controls
9354:
1.749 raeburn 9355: sub get_access_controls {
1.745 raeburn 9356: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9357: my %access;
9358: my $real_file = $file;
9359: $file =~ s/\.meta$//;
1.745 raeburn 9360: if (defined($file)) {
1.749 raeburn 9361: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9362: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9363: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9364: }
9365: }
1.745 raeburn 9366: } else {
1.749 raeburn 9367: foreach my $key (keys(%{$current_permissions})) {
9368: if ($key =~ /\0accesscontrol$/) {
9369: if (defined($group)) {
9370: if ($key !~ m-^\Q$group\E/-) {
9371: next;
9372: }
9373: }
9374: my ($fullpath) = split(/\0/,$key);
9375: if (ref($$current_permissions{$key}) eq 'HASH') {
9376: foreach my $control (keys(%{$$current_permissions{$key}})) {
9377: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9378: }
9379: }
9380: }
9381: }
9382: }
9383: return %access;
9384: }
9385:
9386: sub modify_access_controls {
9387: my ($file_name,$changes,$domain,$user)=@_;
9388: my ($outcome,$deloutcome);
9389: my %store_permissions;
9390: my %new_values;
9391: my %new_control;
9392: my %translation;
9393: my @deletions = ();
9394: my $now = time;
9395: if (exists($$changes{'activate'})) {
9396: if (ref($$changes{'activate'}) eq 'HASH') {
9397: my @newitems = sort(keys(%{$$changes{'activate'}}));
9398: my $numnew = scalar(@newitems);
9399: for (my $i=0; $i<$numnew; $i++) {
9400: my $newkey = $newitems[$i];
9401: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9402: if ($newkey =~ /^\d+:/) {
9403: $newkey =~ s/^(\d+)/$newid/;
9404: $translation{$1} = $newid;
9405: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9406: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9407: $translation{$1} = $newid;
9408: }
1.749 raeburn 9409: $new_values{$file_name."\0".$newkey} =
9410: $$changes{'activate'}{$newitems[$i]};
9411: $new_control{$newkey} = $now;
9412: }
9413: }
9414: }
9415: my %todelete;
9416: my %changed_items;
9417: foreach my $action ('delete','update') {
9418: if (exists($$changes{$action})) {
9419: if (ref($$changes{$action}) eq 'HASH') {
9420: foreach my $key (keys(%{$$changes{$action}})) {
9421: my ($itemnum) = ($key =~ /^([^:]+):/);
9422: if ($action eq 'delete') {
9423: $todelete{$itemnum} = 1;
9424: } else {
9425: $changed_items{$itemnum} = $key;
9426: }
9427: }
1.745 raeburn 9428: }
9429: }
1.749 raeburn 9430: }
9431: # get lock on access controls for file.
9432: my $lockhash = {
9433: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9434: ':'.$env{'user.domain'},
9435: };
9436: my $tries = 0;
9437: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9438:
9439: while (($gotlock ne 'ok') && $tries <3) {
9440: $tries ++;
9441: sleep 1;
9442: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9443: }
9444: if ($gotlock eq 'ok') {
9445: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9446: my ($tmp)=keys(%curr_permissions);
9447: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9448: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9449: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9450: if (ref($curr_controls) eq 'HASH') {
9451: foreach my $control_item (keys(%{$curr_controls})) {
9452: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9453: if (defined($todelete{$itemnum})) {
9454: push(@deletions,$file_name."\0".$control_item);
9455: } else {
9456: if (defined($changed_items{$itemnum})) {
9457: $new_control{$changed_items{$itemnum}} = $now;
9458: push(@deletions,$file_name."\0".$control_item);
9459: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9460: } else {
9461: $new_control{$control_item} = $$curr_controls{$control_item};
9462: }
9463: }
1.745 raeburn 9464: }
9465: }
9466: }
1.970 raeburn 9467: my ($group);
9468: if (&is_course($domain,$user)) {
9469: ($group,my $file) = split(/\//,$file_name,2);
9470: }
1.749 raeburn 9471: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9472: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9473: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9474: # remove lock
9475: my @del_lock = ($file_name."\0".'locked_access_records');
9476: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9477: my $sqlresult =
1.970 raeburn 9478: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9479: $group);
1.749 raeburn 9480: } else {
9481: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9482: }
1.749 raeburn 9483: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9484: }
9485:
1.827 raeburn 9486: sub make_public_indefinitely {
1.1271 raeburn 9487: my (@requrl) = @_;
9488: return &automated_portfile_access('public',\@requrl);
9489: }
9490:
9491: sub automated_portfile_access {
9492: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9493: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9494: return 'invalid';
9495: }
1.1271 raeburn 9496: my %urls;
9497: if (ref($addsref) eq 'ARRAY') {
9498: foreach my $requrl (@{$addsref}) {
9499: if (&is_portfolio_url($requrl)) {
9500: unless (exists($urls{$requrl})) {
9501: $urls{$requrl} = 'add';
9502: }
9503: }
9504: }
9505: }
9506: if (ref($delsref) eq 'ARRAY') {
9507: foreach my $requrl (@{$delsref}) {
9508: if (&is_portfolio_url($requrl)) {
9509: unless (exists($urls{$requrl})) {
9510: $urls{$requrl} = 'delete';
9511: }
9512: }
9513: }
9514: }
9515: unless (keys(%urls)) {
9516: return 'invalid';
9517: }
9518: my $ip;
9519: if ($accesstype eq 'ip') {
9520: if (ref($info) eq 'HASH') {
9521: if ($info->{'ip'} ne '') {
9522: $ip = $info->{'ip'};
9523: }
9524: }
9525: if ($ip eq '') {
9526: return 'invalid';
9527: }
9528: }
9529: my $errors;
1.827 raeburn 9530: my $now = time;
1.1271 raeburn 9531: my %current_perms;
9532: foreach my $requrl (sort(keys(%urls))) {
9533: my $action;
9534: if ($urls{$requrl} eq 'add') {
9535: $action = 'activate';
9536: } else {
9537: $action = 'none';
9538: }
9539: my $aclnum = 0;
1.827 raeburn 9540: my (undef,$udom,$unum,$file_name,$group) =
9541: &parse_portfolio_url($requrl);
1.1271 raeburn 9542: unless (exists($current_perms{$unum.':'.$udom})) {
9543: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9544: }
9545: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9546: $group,$file_name);
9547: foreach my $key (keys(%{$access_controls{$file_name}})) {
9548: my ($num,$scope,$end,$start) =
9549: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9550: if ($scope eq $accesstype) {
9551: if (($start <= $now) && ($end == 0)) {
9552: if ($accesstype eq 'ip') {
9553: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9554: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9555: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9556: if ($urls{$requrl} eq 'add') {
9557: $action = 'none';
9558: last;
9559: } else {
9560: $action = 'delete';
9561: $aclnum = $num;
9562: last;
9563: }
9564: }
9565: }
9566: }
9567: } elsif ($accesstype eq 'public') {
9568: if ($urls{$requrl} eq 'add') {
9569: $action = 'none';
9570: last;
9571: } else {
9572: $action = 'delete';
9573: $aclnum = $num;
9574: last;
9575: }
9576: }
9577: } elsif ($accesstype eq 'public') {
1.827 raeburn 9578: $action = 'update';
9579: $aclnum = $num;
1.1271 raeburn 9580: last;
1.827 raeburn 9581: }
9582: }
9583: }
9584: if ($action eq 'none') {
1.1271 raeburn 9585: next;
1.827 raeburn 9586: } else {
9587: my %changes;
9588: my $newend = 0;
9589: my $newstart = $now;
1.1271 raeburn 9590: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 9591: $changes{$action}{$newkey} = {
1.1271 raeburn 9592: type => $accesstype,
1.827 raeburn 9593: time => {
9594: start => $newstart,
9595: end => $newend,
9596: },
9597: };
1.1271 raeburn 9598: if ($accesstype eq 'ip') {
9599: $changes{$action}{$newkey}{'ip'} = [$ip];
9600: }
1.827 raeburn 9601: my ($outcome,$deloutcome,$new_values,$translation) =
9602: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 9603: unless ($outcome eq 'ok') {
9604: $errors .= $outcome.' ';
9605: }
1.827 raeburn 9606: }
1.1271 raeburn 9607: }
9608: if ($errors) {
9609: $errors =~ s/\s$//;
9610: return $errors;
1.827 raeburn 9611: } else {
1.1271 raeburn 9612: return 'ok';
1.827 raeburn 9613: }
9614: }
9615:
1.745 raeburn 9616: #------------------------------------------------------Get Marked as Read Only
9617:
9618: sub get_marked_as_readonly {
9619: my ($domain,$user,$what,$group) = @_;
9620: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9621: my @readonly_files;
1.629 banghart 9622: my $cmp1=$what;
9623: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9624: while (my ($file_name,$value) = each(%{$current_permissions})) {
9625: if (defined($group)) {
9626: if ($file_name !~ m-^\Q$group\E/-) {
9627: next;
9628: }
9629: }
1.561 banghart 9630: if (ref($value) eq "ARRAY"){
9631: foreach my $stored_what (@{$value}) {
1.629 banghart 9632: my $cmp2=$stored_what;
1.759 albertel 9633: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9634: $cmp2=join('',@{$stored_what});
1.745 raeburn 9635: }
1.629 banghart 9636: if ($cmp1 eq $cmp2) {
1.561 banghart 9637: push(@readonly_files, $file_name);
1.745 raeburn 9638: last;
1.563 banghart 9639: } elsif (!defined($what)) {
9640: push(@readonly_files, $file_name);
1.745 raeburn 9641: last;
1.561 banghart 9642: }
9643: }
1.745 raeburn 9644: }
1.561 banghart 9645: }
9646: return @readonly_files;
9647: }
1.577 banghart 9648: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9649:
1.577 banghart 9650: sub get_marked_as_readonly_hash {
1.745 raeburn 9651: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9652: my %readonly_files;
1.745 raeburn 9653: while (my ($file_name,$value) = each(%{$current_permissions})) {
9654: if (defined($group)) {
9655: if ($file_name !~ m-^\Q$group\E/-) {
9656: next;
9657: }
9658: }
1.577 banghart 9659: if (ref($value) eq "ARRAY"){
9660: foreach my $stored_what (@{$value}) {
1.745 raeburn 9661: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9662: foreach my $lock_descriptor(@{$stored_what}) {
9663: if ($lock_descriptor eq 'graded') {
9664: $readonly_files{$file_name} = 'graded';
9665: } elsif ($lock_descriptor eq 'handback') {
9666: $readonly_files{$file_name} = 'handback';
9667: } else {
9668: if (!exists($readonly_files{$file_name})) {
9669: $readonly_files{$file_name} = 'locked';
9670: }
9671: }
1.745 raeburn 9672: }
1.750 banghart 9673: }
1.577 banghart 9674: }
9675: }
9676: }
9677: return %readonly_files;
9678: }
1.559 banghart 9679: # ------------------------------------------------------------ Unmark as Read Only
9680:
9681: sub unmark_as_readonly {
1.629 banghart 9682: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9683: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9684: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9685: $file_name = &declutter_portfile($file_name);
1.634 albertel 9686: my $symb_crs = $what;
9687: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9688: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9689: my ($tmp)=keys(%current_permissions);
9690: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9691: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9692: foreach my $file (@readonly_files) {
1.759 albertel 9693: my $clean_file = &declutter_portfile($file);
9694: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9695: my $current_locks = $current_permissions{$file};
1.563 banghart 9696: my @new_locks;
9697: my @del_keys;
9698: if (ref($current_locks) eq "ARRAY"){
9699: foreach my $locker (@{$current_locks}) {
1.632 albertel 9700: my $compare=$locker;
1.749 raeburn 9701: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9702: $compare=join('',@{$locker});
1.746 raeburn 9703: if ($compare ne $symb_crs) {
9704: push(@new_locks, $locker);
9705: }
1.563 banghart 9706: }
9707: }
1.650 albertel 9708: if (scalar(@new_locks) > 0) {
1.563 banghart 9709: $current_permissions{$file} = \@new_locks;
9710: } else {
9711: push(@del_keys, $file);
1.613 albertel 9712: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9713: delete($current_permissions{$file});
1.563 banghart 9714: }
9715: }
1.561 banghart 9716: }
1.613 albertel 9717: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9718: return;
9719: }
1.512 banghart 9720:
1.17 www 9721: # ------------------------------------------------------------ Directory lister
9722:
9723: sub dirlist {
1.955 raeburn 9724: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9725: $uri=~s/^\///;
9726: $uri=~s/\/$//;
1.253 stredwic 9727: my ($udom, $uname);
1.955 raeburn 9728: if ($getuserdir) {
1.253 stredwic 9729: $udom = $userdomain;
9730: $uname = $username;
1.955 raeburn 9731: } else {
9732: (undef,$udom,$uname)=split(/\//,$uri);
9733: if(defined($userdomain)) {
9734: $udom = $userdomain;
9735: }
9736: if(defined($username)) {
9737: $uname = $username;
9738: }
1.253 stredwic 9739: }
1.955 raeburn 9740: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9741:
1.955 raeburn 9742: $dirRoot = $perlvar{'lonDocRoot'};
9743: if (defined($getpropath)) {
9744: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9745: $dirRoot =~ s/\/$//;
1.955 raeburn 9746: } elsif (defined($getuserdir)) {
9747: my $subdir=$uname.'__';
9748: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9749: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9750: ."/$udom/$subdir/$uname";
9751: } elsif (defined($alternateRoot)) {
9752: $dirRoot = $alternateRoot;
1.751 banghart 9753: }
1.253 stredwic 9754:
9755: if($udom) {
9756: if($uname) {
1.1135 raeburn 9757: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9758: if ($uhome eq 'no_host') {
9759: return ([],'no_host');
9760: }
1.955 raeburn 9761: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9762: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9763: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9764: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9765: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9766: } else {
9767: @listing_results = map { &unescape($_); } split(/:/,$listing);
9768: }
1.605 matthew 9769: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9770: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9771: @listing_results = split(/:/,$listing);
9772: } else {
9773: @listing_results = map { &unescape($_); } split(/:/,$listing);
9774: }
1.1135 raeburn 9775: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9776: ($listing eq 'rejected') || ($listing eq 'refused') ||
9777: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9778: return ([],$listing);
9779: } else {
9780: return (\@listing_results);
1.1135 raeburn 9781: }
1.955 raeburn 9782: } elsif(!$alternateRoot) {
1.1136 raeburn 9783: my (%allusers,%listerror);
1.841 albertel 9784: my %servers = &get_servers($udom,'library');
1.955 raeburn 9785: foreach my $tryserver (keys(%servers)) {
9786: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9787: &escape($udom),$tryserver);
9788: if ($listing eq 'unknown_cmd') {
9789: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9790: $udom, $tryserver);
9791: } else {
9792: @listing_results = map { &unescape($_); } split(/:/,$listing);
9793: }
1.841 albertel 9794: if ($listing eq 'unknown_cmd') {
9795: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9796: $udom, $tryserver);
9797: @listing_results = split(/:/,$listing);
9798: } else {
9799: @listing_results =
9800: map { &unescape($_); } split(/:/,$listing);
9801: }
1.1136 raeburn 9802: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9803: ($listing eq 'rejected') || ($listing eq 'refused') ||
9804: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9805: $listerror{$tryserver} = $listing;
9806: } else {
1.841 albertel 9807: foreach my $line (@listing_results) {
9808: my ($entry) = split(/&/,$line,2);
9809: $allusers{$entry} = 1;
9810: }
9811: }
1.253 stredwic 9812: }
1.1136 raeburn 9813: my @alluserslist=();
1.800 albertel 9814: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9815: push(@alluserslist,$user.'&user');
1.253 stredwic 9816: }
1.1136 raeburn 9817: return (\@alluserslist);
1.253 stredwic 9818: } else {
1.1136 raeburn 9819: return ([],'missing username');
1.253 stredwic 9820: }
1.955 raeburn 9821: } elsif(!defined($getpropath)) {
1.1136 raeburn 9822: my $path = $perlvar{'lonDocRoot'}.'/res/';
9823: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9824: return (\@all_domains);
1.955 raeburn 9825: } else {
1.1136 raeburn 9826: return ([],'missing domain');
1.275 stredwic 9827: }
9828: }
9829:
9830: # --------------------------------------------- GetFileTimestamp
9831: # This function utilizes dirlist and returns the date stamp for
9832: # when it was last modified. It will also return an error of -1
9833: # if an error occurs
9834:
9835: sub GetFileTimestamp {
1.955 raeburn 9836: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9837: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9838: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9839: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9840: undef,$getuserdir);
9841: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9842: return -1;
9843: }
9844: if (ref($fileref) eq 'ARRAY') {
9845: my @stats = split('&',$fileref->[0]);
1.375 matthew 9846: # @stats contains first the filename, then the stat output
9847: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9848: } else {
9849: return -1;
1.253 stredwic 9850: }
1.26 www 9851: }
9852:
1.712 albertel 9853: sub stat_file {
9854: my ($uri) = @_;
1.787 albertel 9855: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9856:
1.955 raeburn 9857: my ($udom,$uname,$file);
1.712 albertel 9858: if ($uri =~ m-^/(uploaded|editupload)/-) {
9859: ($udom,$uname,$file) =
1.811 albertel 9860: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9861: $file = 'userfiles/'.$file;
9862: }
9863: if ($uri =~ m-^/res/-) {
9864: ($udom,$uname) =
1.807 albertel 9865: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9866: $file = $uri;
9867: }
9868:
9869: if (!$udom || !$uname || !$file) {
9870: # unable to handle the uri
9871: return ();
9872: }
1.956 raeburn 9873: my $getpropath;
9874: if ($file =~ /^userfiles\//) {
9875: $getpropath = 1;
9876: }
1.1136 raeburn 9877: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9878: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9879: return ();
9880: } else {
9881: if (ref($listref) eq 'ARRAY') {
9882: my @stats = split('&',$listref->[0]);
9883: shift(@stats); #filename is first
9884: return @stats;
9885: }
1.712 albertel 9886: }
9887: return ();
9888: }
9889:
1.26 www 9890: # -------------------------------------------------------- Value of a Condition
9891:
1.713 albertel 9892: # gets the value of a specific preevaluated condition
9893: # stored in the string $env{user.state.<cid>}
9894: # or looks up a condition reference in the bighash and if if hasn't
9895: # already been evaluated recurses into docondval to get the value of
9896: # the condition, then memoizing it to
9897: # $env{user.state.<cid>.<condition>}
1.40 www 9898: sub directcondval {
9899: my $number=shift;
1.620 albertel 9900: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9901: &Apache::lonuserstate::evalstate();
9902: }
1.713 albertel 9903: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9904: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9905: } elsif ($number =~ /^_/) {
9906: my $sub_condition;
9907: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9908: &GDBM_READER(),0640)) {
9909: $sub_condition=$bighash{'conditions'.$number};
9910: untie(%bighash);
9911: }
9912: my $value = &docondval($sub_condition);
1.949 raeburn 9913: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9914: return $value;
9915: }
1.620 albertel 9916: if ($env{'user.state.'.$env{'request.course.id'}}) {
9917: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9918: } else {
9919: return 2;
9920: }
9921: }
9922:
1.713 albertel 9923: # get the collection of conditions for this resource
1.26 www 9924: sub condval {
9925: my $condidx=shift;
1.54 www 9926: my $allpathcond='';
1.713 albertel 9927: foreach my $cond (split(/\|/,$condidx)) {
9928: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9929: $allpathcond.=
9930: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9931: }
1.191 harris41 9932: }
1.54 www 9933: $allpathcond=~s/\|$//;
1.713 albertel 9934: return &docondval($allpathcond);
9935: }
9936:
9937: #evaluates an expression of conditions
9938: sub docondval {
9939: my ($allpathcond) = @_;
9940: my $result=0;
9941: if ($env{'request.course.id'}
9942: && defined($allpathcond)) {
9943: my $operand='|';
9944: my @stack;
9945: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9946: if ($chunk eq '(') {
9947: push @stack,($operand,$result);
9948: } elsif ($chunk eq ')') {
9949: my $before=pop @stack;
9950: if (pop @stack eq '&') {
9951: $result=$result>$before?$before:$result;
9952: } else {
9953: $result=$result>$before?$result:$before;
9954: }
9955: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9956: $operand=$chunk;
9957: } else {
9958: my $new=directcondval($chunk);
9959: if ($operand eq '&') {
9960: $result=$result>$new?$new:$result;
9961: } else {
9962: $result=$result>$new?$result:$new;
9963: }
9964: }
9965: }
1.26 www 9966: }
9967: return $result;
1.421 albertel 9968: }
9969:
9970: # ---------------------------------------------------- Devalidate courseresdata
9971:
9972: sub devalidatecourseresdata {
9973: my ($coursenum,$coursedomain)=@_;
9974: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9975: &devalidate_cache_new('courseres',$hashid);
1.28 www 9976: }
9977:
1.763 www 9978:
1.200 www 9979: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9980: #
9981: # Parameters:
9982: # $coursenum - Number of the course.
9983: # $coursedomain - Domain at which the course was created.
9984: # Returns:
9985: # A hash of the course parameters along (I think) with timestamps
9986: # and version info.
1.877 foxr 9987:
1.624 albertel 9988: sub get_courseresdata {
9989: my ($coursenum,$coursedomain)=@_;
1.200 www 9990: my $coursehom=&homeserver($coursenum,$coursedomain);
9991: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9992: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9993: my %dumpreply;
1.417 albertel 9994: unless (defined($cached)) {
1.624 albertel 9995: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9996: $result=\%dumpreply;
1.251 albertel 9997: my ($tmp) = keys(%dumpreply);
9998: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9999: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10000: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10001: return $tmp;
1.416 albertel 10002: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10003: $result=undef;
1.599 albertel 10004: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10005: }
10006: }
1.624 albertel 10007: return $result;
10008: }
10009:
1.633 albertel 10010: sub devalidateuserresdata {
10011: my ($uname,$udom)=@_;
10012: my $hashid="$udom:$uname";
10013: &devalidate_cache_new('userres',$hashid);
10014: }
10015:
1.624 albertel 10016: sub get_userresdata {
10017: my ($uname,$udom)=@_;
10018: #most student don\'t have any data set, check if there is some data
10019: if (&EXT_cache_status($udom,$uname)) { return undef; }
10020:
10021: my $hashid="$udom:$uname";
10022: my ($result,$cached)=&is_cached_new('userres',$hashid);
10023: if (!defined($cached)) {
10024: my %resourcedata=&dump('resourcedata',$udom,$uname);
10025: $result=\%resourcedata;
10026: &do_cache_new('userres',$hashid,$result,600);
10027: }
10028: my ($tmp)=keys(%$result);
10029: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10030: return $result;
10031: }
10032: #error 2 occurs when the .db doesn't exist
10033: if ($tmp!~/error: 2 /) {
1.672 albertel 10034: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 10035: " Trying to get resource data for ".
10036: $uname." at ".$udom.": ".
10037: $tmp."</font>");
10038: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10039: #&EXT_cache_set($udom,$uname);
10040: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10041: undef($tmp); # not really an error so don't send it back
1.624 albertel 10042: }
10043: return $tmp;
10044: }
1.879 foxr 10045: #----------------------------------------------- resdata - return resource data
10046: # Purpose:
10047: # Return resource data for either users or for a course.
10048: # Parameters:
10049: # $name - Course/user name.
10050: # $domain - Name of the domain the user/course is registered on.
10051: # $type - Type of thing $name is (must be 'course' or 'user'
10052: # @which - Array of names of resources desired.
10053: # Returns:
10054: # The value of the first reasource in @which that is found in the
10055: # resource hash.
10056: # Exceptional Conditions:
10057: # If the $type passed in is not valid (not the string 'course' or
10058: # 'user', an undefined reference is returned.
10059: # If none of the resources are found, an undef is returned
1.624 albertel 10060: sub resdata {
10061: my ($name,$domain,$type,@which)=@_;
10062: my $result;
10063: if ($type eq 'course') {
10064: $result=&get_courseresdata($name,$domain);
10065: } elsif ($type eq 'user') {
10066: $result=&get_userresdata($name,$domain);
10067: }
10068: if (!ref($result)) { return $result; }
1.251 albertel 10069: foreach my $item (@which) {
1.927 albertel 10070: if (defined($result->{$item->[0]})) {
10071: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10072: }
1.250 albertel 10073: }
1.291 albertel 10074: return undef;
1.200 www 10075: }
10076:
1.1236 raeburn 10077: sub get_numsuppfiles {
10078: my ($cnum,$cdom,$ignorecache)=@_;
10079: my $hashid=$cnum.':'.$cdom;
10080: my ($suppcount,$cached);
10081: unless ($ignorecache) {
10082: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10083: }
10084: unless (defined($cached)) {
10085: my $chome=&homeserver($cnum,$cdom);
10086: unless ($chome eq 'no_host') {
10087: ($suppcount,my $errors) = (0,0);
10088: my $suppmap = 'supplemental.sequence';
10089: ($suppcount,$errors) =
10090: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10091: }
10092: &do_cache_new('suppcount',$hashid,$suppcount,600);
10093: }
10094: return $suppcount;
10095: }
10096:
1.379 matthew 10097: #
10098: # EXT resource caching routines
10099: #
10100:
10101: sub clear_EXT_cache_status {
1.383 albertel 10102: &delenv('cache.EXT.');
1.379 matthew 10103: }
10104:
10105: sub EXT_cache_status {
10106: my ($target_domain,$target_user) = @_;
1.383 albertel 10107: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10108: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10109: # We know already the user has no data
10110: return 1;
10111: } else {
10112: return 0;
10113: }
10114: }
10115:
10116: sub EXT_cache_set {
10117: my ($target_domain,$target_user) = @_;
1.383 albertel 10118: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10119: #&appenv({$cachename => time});
1.379 matthew 10120: }
10121:
1.28 www 10122: # --------------------------------------------------------- Value of a Variable
1.58 www 10123: sub EXT {
1.715 albertel 10124:
1.1228 raeburn 10125: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10126: unless ($varname) { return ''; }
1.218 albertel 10127: #get real user name/domain, courseid and symb
10128: my $courseid;
1.359 albertel 10129: my $publicuser;
1.427 www 10130: if ($symbparm) {
10131: $symbparm=&get_symb_from_alias($symbparm);
10132: }
1.218 albertel 10133: if (!($uname && $udom)) {
1.790 albertel 10134: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10135: if (!$symbparm) { $symbparm=$cursymb; }
10136: } else {
1.620 albertel 10137: $courseid=$env{'request.course.id'};
1.218 albertel 10138: }
1.48 www 10139: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10140: my $rest;
1.320 albertel 10141: if (defined($therest[0])) {
1.48 www 10142: $rest=join('.',@therest);
10143: } else {
10144: $rest='';
10145: }
1.320 albertel 10146:
1.57 www 10147: my $qualifierrest=$qualifier;
10148: if ($rest) { $qualifierrest.='.'.$rest; }
10149: my $spacequalifierrest=$space;
10150: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10151: if ($realm eq 'user') {
1.48 www 10152: # --------------------------------------------------------------- user.resource
10153: if ($space eq 'resource') {
1.651 albertel 10154: if ( (defined($Apache::lonhomework::parsing_a_problem)
10155: || defined($Apache::lonhomework::parsing_a_task))
10156: &&
1.744 albertel 10157: ($symbparm eq &symbread()) ) {
10158: # if we are in the middle of processing the resource the
10159: # get the value we are planning on committing
10160: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10161: return $Apache::lonhomework::results{$qualifierrest};
10162: } else {
10163: return $Apache::lonhomework::history{$qualifierrest};
10164: }
1.335 albertel 10165: } else {
1.359 albertel 10166: my %restored;
1.620 albertel 10167: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10168: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10169: } else {
10170: %restored=&restore($symbparm,$courseid,$udom,$uname);
10171: }
1.335 albertel 10172: return $restored{$qualifierrest};
10173: }
1.48 www 10174: # ----------------------------------------------------------------- user.access
10175: } elsif ($space eq 'access') {
1.218 albertel 10176: # FIXME - not supporting calls for a specific user
1.48 www 10177: return &allowed($qualifier,$rest);
10178: # ------------------------------------------ user.preferences, user.environment
10179: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10180: if (($uname eq $env{'user.name'}) &&
10181: ($udom eq $env{'user.domain'})) {
10182: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10183: } else {
1.359 albertel 10184: my %returnhash;
10185: if (!$publicuser) {
10186: %returnhash=&userenvironment($udom,$uname,
10187: $qualifierrest);
10188: }
1.218 albertel 10189: return $returnhash{$qualifierrest};
10190: }
1.48 www 10191: # ----------------------------------------------------------------- user.course
10192: } elsif ($space eq 'course') {
1.218 albertel 10193: # FIXME - not supporting calls for a specific user
1.620 albertel 10194: return $env{join('.',('request.course',$qualifier))};
1.48 www 10195: # ------------------------------------------------------------------- user.role
10196: } elsif ($space eq 'role') {
1.218 albertel 10197: # FIXME - not supporting calls for a specific user
1.620 albertel 10198: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10199: if ($qualifier eq 'value') {
10200: return $role;
10201: } elsif ($qualifier eq 'extent') {
10202: return $where;
10203: }
10204: # ----------------------------------------------------------------- user.domain
10205: } elsif ($space eq 'domain') {
1.218 albertel 10206: return $udom;
1.48 www 10207: # ------------------------------------------------------------------- user.name
10208: } elsif ($space eq 'name') {
1.218 albertel 10209: return $uname;
1.48 www 10210: # ---------------------------------------------------- Any other user namespace
1.29 www 10211: } else {
1.359 albertel 10212: my %reply;
10213: if (!$publicuser) {
10214: %reply=&get($space,[$qualifierrest],$udom,$uname);
10215: }
10216: return $reply{$qualifierrest};
1.48 www 10217: }
1.236 www 10218: } elsif ($realm eq 'query') {
10219: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10220: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10221: [$spacequalifierrest]);
1.620 albertel 10222: return $env{'form.'.$spacequalifierrest};
1.236 www 10223: } elsif ($realm eq 'request') {
1.48 www 10224: # ------------------------------------------------------------- request.browser
10225: if ($space eq 'browser') {
1.1145 bisitz 10226: return $env{'browser.'.$qualifier};
1.57 www 10227: # ------------------------------------------------------------ request.filename
10228: } else {
1.620 albertel 10229: return $env{'request.'.$spacequalifierrest};
1.29 www 10230: }
1.28 www 10231: } elsif ($realm eq 'course') {
1.48 www 10232: # ---------------------------------------------------------- course.description
1.620 albertel 10233: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10234: } elsif ($realm eq 'resource') {
1.165 www 10235:
1.620 albertel 10236: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10237: if (!$symbparm) { $symbparm=&symbread(); }
10238: }
1.693 albertel 10239:
1.1232 raeburn 10240: if ($qualifier eq '') {
10241: if ($space eq 'title') {
10242: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10243: return &gettitle($symbparm);
10244: }
1.693 albertel 10245:
1.1232 raeburn 10246: if ($space eq 'map') {
10247: my ($map) = &decode_symb($symbparm);
10248: return &symbread($map);
10249: }
10250: if ($space eq 'maptitle') {
10251: my ($map) = &decode_symb($symbparm);
10252: return &gettitle($map);
10253: }
10254: if ($space eq 'filename') {
10255: if ($symbparm) {
10256: return &clutter((&decode_symb($symbparm))[2]);
10257: }
10258: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10259: }
1.1232 raeburn 10260:
1.1233 raeburn 10261: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10262: if ($space eq 'visibleparts') {
10263: my $navmap = Apache::lonnavmaps::navmap->new();
10264: my $item;
10265: if (ref($navmap)) {
10266: my $res = $navmap->getBySymb($symbparm);
10267: my $parts = $res->parts();
10268: if (ref($parts) eq 'ARRAY') {
10269: $item = join(',',@{$parts});
10270: }
10271: undef($navmap);
1.1232 raeburn 10272: }
1.1233 raeburn 10273: return $item;
1.1232 raeburn 10274: }
10275: }
10276: }
1.693 albertel 10277:
10278: my ($section, $group, @groups);
1.593 albertel 10279: my ($courselevelm,$courselevel);
1.1228 raeburn 10280: if (($courseid eq '') && ($cid)) {
10281: $courseid = $cid;
10282: }
10283: if (($symbparm && $courseid) &&
10284: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10285:
1.218 albertel 10286: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10287:
1.60 www 10288: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10289: my $symbp=$symbparm;
1.735 albertel 10290: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10291:
10292: my $symbparm=$symbp.'.'.$spacequalifierrest;
10293: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10294:
1.620 albertel 10295: if (($env{'user.name'} eq $uname) &&
10296: ($env{'user.domain'} eq $udom)) {
10297: $section=$env{'request.course.sec'};
1.733 raeburn 10298: @groups = split(/:/,$env{'request.course.groups'});
10299: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10300: } else {
1.539 albertel 10301: if (! defined($usection)) {
1.551 albertel 10302: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10303: } else {
10304: $section = $usection;
10305: }
1.733 raeburn 10306: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10307: }
10308:
10309: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10310: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10311: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10312:
1.593 albertel 10313: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10314: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10315: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10316:
1.60 www 10317: # ----------------------------------------------------------- first, check user
1.624 albertel 10318:
10319: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10320: ([$courselevelr,'resource'],
10321: [$courselevelm,'map' ],
10322: [$courselevel, 'course' ]));
1.931 albertel 10323: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10324:
1.594 albertel 10325: # ------------------------------------------------ second, check some of course
1.684 raeburn 10326: my $coursereply;
1.691 raeburn 10327: if (@groups > 0) {
10328: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10329: $mapparm,$spacequalifierrest);
1.927 albertel 10330: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10331: }
1.96 www 10332:
1.684 raeburn 10333: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10334: $env{'course.'.$courseid.'.domain'},
10335: 'course',
10336: ([$seclevelr, 'resource'],
10337: [$seclevelm, 'map' ],
10338: [$seclevel, 'course' ],
10339: [$courselevelr,'resource']));
10340: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10341:
1.60 www 10342: # ------------------------------------------------------ third, check map parms
1.218 albertel 10343: my %parmhash=();
10344: my $thisparm='';
10345: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10346: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10347: &GDBM_READER(),0640)) {
1.218 albertel 10348: $thisparm=$parmhash{$symbparm};
10349: untie(%parmhash);
10350: }
1.927 albertel 10351: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10352: }
1.594 albertel 10353: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10354:
1.218 albertel 10355: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10356: my $filename;
10357: if (!$symbparm) { $symbparm=&symbread(); }
10358: if ($symbparm) {
1.409 www 10359: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10360: } else {
1.620 albertel 10361: $filename=$env{'request.filename'};
1.282 albertel 10362: }
10363: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10364: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10365: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10366: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10367:
1.927 albertel 10368: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10369: if ($symbparm && defined($courseid) &&
1.620 albertel 10370: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10371: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10372: $env{'course.'.$courseid.'.domain'},
10373: 'course',
1.927 albertel 10374: ([$courselevelm,'map' ],
10375: [$courselevel, 'course']));
10376: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10377: }
1.145 www 10378: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10379: unless ($space eq '0') {
1.336 albertel 10380: my @parts=split(/_/,$space);
10381: my $id=pop(@parts);
10382: my $part=join('_',@parts);
10383: if ($part eq '') { $part='0'; }
1.927 albertel 10384: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10385: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10386: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10387: }
1.395 albertel 10388: if ($recurse) { return undef; }
10389: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10390: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10391: # ---------------------------------------------------- Any other user namespace
10392: } elsif ($realm eq 'environment') {
10393: # ----------------------------------------------------------------- environment
1.620 albertel 10394: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10395: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10396: } else {
1.770 albertel 10397: if ($uname eq 'anonymous' && $udom eq '') {
10398: return '';
10399: }
1.219 albertel 10400: my %returnhash=&userenvironment($udom,$uname,
10401: $spacequalifierrest);
10402: return $returnhash{$spacequalifierrest};
10403: }
1.28 www 10404: } elsif ($realm eq 'system') {
1.48 www 10405: # ----------------------------------------------------------------- system.time
10406: if ($space eq 'time') {
10407: return time;
10408: }
1.696 albertel 10409: } elsif ($realm eq 'server') {
10410: # ----------------------------------------------------------------- system.time
10411: if ($space eq 'name') {
10412: return $ENV{'SERVER_NAME'};
10413: }
1.28 www 10414: }
1.48 www 10415: return '';
1.61 www 10416: }
10417:
1.927 albertel 10418: sub get_reply {
10419: my ($reply_value) = @_;
1.940 raeburn 10420: if (ref($reply_value) eq 'ARRAY') {
10421: if (wantarray) {
10422: return @$reply_value;
10423: }
10424: return $reply_value->[0];
10425: } else {
10426: return $reply_value;
1.927 albertel 10427: }
10428: }
10429:
1.691 raeburn 10430: sub check_group_parms {
10431: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10432: my @groupitems = ();
10433: my $resultitem;
1.927 albertel 10434: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10435: foreach my $group (@{$groups}) {
10436: foreach my $level (@levels) {
1.927 albertel 10437: my $item = $courseid.'.['.$group.'].'.$level->[0];
10438: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10439: }
10440: }
10441: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10442: $env{'course.'.$courseid.'.domain'},
10443: 'course',@groupitems);
10444: return $coursereply;
10445: }
10446:
10447: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10448: my ($courseid,@groups) = @_;
10449: @groups = sort(@groups);
1.691 raeburn 10450: return @groups;
10451: }
10452:
1.395 albertel 10453: sub packages_tab_default {
10454: my ($uri,$varname)=@_;
10455: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10456:
10457: my (@extension,@specifics,$do_default);
10458: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10459: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10460: if ($pack_type eq 'default') {
10461: $do_default=1;
10462: } elsif ($pack_type eq 'extension') {
10463: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10464: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10465: # only look at packages defaults for packages that this id is
1.738 albertel 10466: push(@specifics,[$package,$pack_type,$pack_part]);
10467: }
10468: }
10469: # first look for a package that matches the requested part id
10470: foreach my $package (@specifics) {
10471: my (undef,$pack_type,$pack_part)=@{$package};
10472: next if ($pack_part ne $part);
10473: if (defined($packagetab{"$pack_type&$name&default"})) {
10474: return $packagetab{"$pack_type&$name&default"};
10475: }
10476: }
10477: # look for any possible matching non extension_ package
10478: foreach my $package (@specifics) {
10479: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10480: if (defined($packagetab{"$pack_type&$name&default"})) {
10481: return $packagetab{"$pack_type&$name&default"};
10482: }
1.585 albertel 10483: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10484: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10485: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10486: }
10487: }
1.738 albertel 10488: # look for any posible extension_ match
10489: foreach my $package (@extension) {
10490: my ($package,$pack_type)=@{$package};
10491: if (defined($packagetab{"$pack_type&$name&default"})) {
10492: return $packagetab{"$pack_type&$name&default"};
10493: }
10494: if (defined($packagetab{$package."&$name&default"})) {
10495: return $packagetab{$package."&$name&default"};
10496: }
10497: }
10498: # look for a global default setting
10499: if ($do_default && defined($packagetab{"default&$name&default"})) {
10500: return $packagetab{"default&$name&default"};
10501: }
1.395 albertel 10502: return undef;
10503: }
10504:
1.334 albertel 10505: sub add_prefix_and_part {
10506: my ($prefix,$part)=@_;
10507: my $keyroot;
10508: if (defined($prefix) && $prefix !~ /^__/) {
10509: # prefix that has a part already
10510: $keyroot=$prefix;
10511: } elsif (defined($prefix)) {
10512: # prefix that is missing a part
10513: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10514: } else {
10515: # no prefix at all
10516: if (defined($part)) { $keyroot='_'.$part; }
10517: }
10518: return $keyroot;
10519: }
10520:
1.71 www 10521: # ---------------------------------------------------------------- Get metadata
10522:
1.599 albertel 10523: my %metaentry;
1.1070 www 10524: my %importedpartids;
1.71 www 10525: sub metadata {
1.176 www 10526: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10527: $uri=&declutter($uri);
1.288 albertel 10528: # if it is a non metadata possible uri return quickly
1.529 albertel 10529: if (($uri eq '') ||
10530: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10531: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10532: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10533: return undef;
10534: }
1.1261 raeburn 10535: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10536: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10537: return undef;
1.288 albertel 10538: }
1.73 www 10539: my $filename=$uri;
10540: $uri=~s/\.meta$//;
1.172 www 10541: #
10542: # Is the metadata already cached?
1.177 www 10543: # Look at timestamp of caching
1.172 www 10544: # Everything is cached by the main uri, libraries are never directly cached
10545: #
1.428 albertel 10546: if (!defined($liburi)) {
1.599 albertel 10547: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10548: if (defined($cached)) { return $result->{':'.$what}; }
10549: }
10550: {
1.1069 www 10551: # Imported parts would go here
1.1070 www 10552: my %importedids=();
10553: my @origfileimportpartids=();
1.1069 www 10554: my $importedparts=0;
1.172 www 10555: #
10556: # Is this a recursive call for a library?
10557: #
1.599 albertel 10558: # if (! exists($metacache{$uri})) {
10559: # $metacache{$uri}={};
10560: # }
1.924 albertel 10561: my $cachetime = 60*60;
1.171 www 10562: if ($liburi) {
10563: $liburi=&declutter($liburi);
10564: $filename=$liburi;
1.401 bowersj2 10565: } else {
1.599 albertel 10566: &devalidate_cache_new('meta',$uri);
10567: undef(%metaentry);
1.401 bowersj2 10568: }
1.140 www 10569: my %metathesekeys=();
1.73 www 10570: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10571: my $metastring;
1.1140 www 10572: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10573: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10574: $metastring =
1.929 albertel 10575: &Apache::lonnet::ssi_body($which,
1.924 albertel 10576: ('grade_target' => 'meta'));
10577: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10578: } elsif (($uri !~ m -^(editupload)/-) &&
10579: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10580: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10581: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10582: $metastring=&getfile($file);
1.489 albertel 10583: }
1.208 albertel 10584: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10585: my $token;
1.140 www 10586: undef %metathesekeys;
1.71 www 10587: while ($token=$parser->get_token) {
1.339 albertel 10588: if ($token->[0] eq 'S') {
10589: if (defined($token->[2]->{'package'})) {
1.172 www 10590: #
10591: # This is a package - get package info
10592: #
1.339 albertel 10593: my $package=$token->[2]->{'package'};
10594: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10595: if (defined($token->[2]->{'id'})) {
10596: $keyroot.='_'.$token->[2]->{'id'};
10597: }
1.599 albertel 10598: if ($metaentry{':packages'}) {
10599: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10600: } else {
1.599 albertel 10601: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10602: }
1.736 albertel 10603: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10604: my $part=$keyroot;
10605: $part=~s/^\_//;
1.736 albertel 10606: if ($pack_entry=~/^\Q$package\E\&/ ||
10607: $pack_entry=~/^\Q$package\E_0\&/) {
10608: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10609: # ignore package.tab specified default values
10610: # here &package_tab_default() will fetch those
10611: if ($subp eq 'default') { next; }
1.736 albertel 10612: my $value=$packagetab{$pack_entry};
1.432 albertel 10613: my $unikey;
10614: if ($pack =~ /_0$/) {
10615: $unikey='parameter_0_'.$name;
10616: $part=0;
10617: } else {
10618: $unikey='parameter'.$keyroot.'_'.$name;
10619: }
1.339 albertel 10620: if ($subp eq 'display') {
10621: $value.=' [Part: '.$part.']';
10622: }
1.599 albertel 10623: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10624: $metathesekeys{$unikey}=1;
1.599 albertel 10625: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10626: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10627: }
1.599 albertel 10628: if (defined($metaentry{':'.$unikey.'.default'})) {
10629: $metaentry{':'.$unikey}=
10630: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10631: }
1.339 albertel 10632: }
10633: }
10634: } else {
1.172 www 10635: #
10636: # This is not a package - some other kind of start tag
1.339 albertel 10637: #
10638: my $entry=$token->[1];
1.1068 www 10639: my $unikey='';
1.175 www 10640:
1.339 albertel 10641: if ($entry eq 'import') {
1.175 www 10642: #
10643: # Importing a library here
1.339 albertel 10644: #
1.1067 www 10645: my $location=$parser->get_text('/import');
10646: my $dir=$filename;
10647: $dir=~s|[^/]*$||;
10648: $location=&filelocation($dir,$location);
1.1069 www 10649:
1.1068 www 10650: my $importmode=$token->[2]->{'importmode'};
10651: if ($importmode eq 'problem') {
1.1069 www 10652: # Import as problem/response
1.1068 www 10653: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10654: } elsif ($importmode eq 'part') {
10655: # Import as part(s)
1.1069 www 10656: $importedparts=1;
10657: # We need to get the original file and the imported file to get the part order correct
10658: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10659: # Load and inspect original file
1.1070 www 10660: if ($#origfileimportpartids<0) {
10661: undef(%importedpartids);
10662: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10663: my $origfile=&getfile($origfilelocation);
10664: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10665: }
10666:
1.1069 www 10667: # Load and inspect imported file
10668: my $impfile=&getfile($location);
10669: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10670: if ($#impfilepartids>=0) {
10671: # This problem had parts
1.1070 www 10672: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10673: } else {
10674: # Importing by turning a single problem into a problem part
10675: # It gets the import-tags ID as part-ID
10676: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10677: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10678: }
1.1068 www 10679: } else {
10680: # Normal import
10681: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10682: if (defined($token->[2]->{'id'})) {
10683: $unikey.='_'.$token->[2]->{'id'};
10684: }
1.1067 www 10685: }
10686:
1.339 albertel 10687: if ($depthcount<20) {
1.736 albertel 10688: my $metadata =
10689: &metadata($uri,'keys', $location,$unikey,
10690: $depthcount+1);
10691: foreach my $meta (split(',',$metadata)) {
10692: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10693: $metathesekeys{$meta}=1;
1.339 albertel 10694: }
1.1068 www 10695:
10696: }
1.1067 www 10697: } else {
10698: #
10699: # Not importing, some other kind of non-package, non-library start tag
10700: #
10701: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10702: if (defined($token->[2]->{'id'})) {
10703: $unikey.='_'.$token->[2]->{'id'};
10704: }
1.339 albertel 10705: if (defined($token->[2]->{'name'})) {
10706: $unikey.='_'.$token->[2]->{'name'};
10707: }
10708: $metathesekeys{$unikey}=1;
1.736 albertel 10709: foreach my $param (@{$token->[3]}) {
10710: $metaentry{':'.$unikey.'.'.$param} =
10711: $token->[2]->{$param};
1.339 albertel 10712: }
10713: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10714: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10715: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10716: # only ws inside the tag, and not in default, so use default
10717: # as value
1.599 albertel 10718: $metaentry{':'.$unikey}=$default;
1.908 albertel 10719: } elsif ( $internaltext =~ /\S/ ) {
10720: # something interesting inside the tag
10721: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10722: } else {
1.908 albertel 10723: # no interesting values, don't set a default
1.339 albertel 10724: }
1.172 www 10725: # end of not-a-package not-a-library import
1.339 albertel 10726: }
1.172 www 10727: # end of not-a-package start tag
1.339 albertel 10728: }
1.172 www 10729: # the next is the end of "start tag"
1.339 albertel 10730: }
10731: }
1.483 albertel 10732: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10733: $extension = lc($extension);
10734: if ($extension eq 'htm') { $extension='html'; }
10735:
1.737 albertel 10736: foreach my $key (keys(%packagetab)) {
1.483 albertel 10737: #no specific packages #how's our extension
10738: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10739: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10740: \%metathesekeys);
10741: }
1.883 albertel 10742:
10743: if (!exists($metaentry{':packages'})
10744: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10745: foreach my $key (keys(%packagetab)) {
1.483 albertel 10746: #no specific packages well let's get default then
10747: if ($key!~/^default&/) { next; }
1.488 albertel 10748: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10749: \%metathesekeys);
10750: }
10751: }
1.338 www 10752: # are there custom rights to evaluate
1.599 albertel 10753: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10754:
1.338 www 10755: #
10756: # Importing a rights file here
1.339 albertel 10757: #
10758: unless ($depthcount) {
1.599 albertel 10759: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10760: my $dir=$filename;
10761: $dir=~s|[^/]*$||;
10762: $location=&filelocation($dir,$location);
1.736 albertel 10763: my $rights_metadata =
10764: &metadata($uri,'keys',$location,'_rights',
10765: $depthcount+1);
10766: foreach my $rights (split(',',$rights_metadata)) {
10767: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10768: $metathesekeys{$rights}=1;
1.339 albertel 10769: }
10770: }
10771: }
1.737 albertel 10772: # uniqifiy package listing
10773: my %seen;
10774: my @uniq_packages =
10775: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10776: $metaentry{':packages'} = join(',',@uniq_packages);
10777:
1.1070 www 10778: if ($importedparts) {
10779: # We had imported parts and need to rebuild partorder
10780: $metaentry{':partorder'}='';
10781: $metathesekeys{'partorder'}=1;
10782: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10783: if ($origfileimportpartids[$index] eq 'part') {
10784: # original part, part of the problem
10785: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10786: } else {
10787: # we have imported parts at this position
10788: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10789: }
10790: }
10791: $metaentry{':partorder'}=~s/^\,//;
10792: }
10793:
1.737 albertel 10794: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10795: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 10796: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10797: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10798: # this is the end of "was not already recently cached
1.71 www 10799: }
1.599 albertel 10800: return $metaentry{':'.$what};
1.261 albertel 10801: }
10802:
1.488 albertel 10803: sub metadata_create_package_def {
1.483 albertel 10804: my ($uri,$key,$package,$metathesekeys)=@_;
10805: my ($pack,$name,$subp)=split(/\&/,$key);
10806: if ($subp eq 'default') { next; }
10807:
1.599 albertel 10808: if (defined($metaentry{':packages'})) {
10809: $metaentry{':packages'}.=','.$package;
1.483 albertel 10810: } else {
1.599 albertel 10811: $metaentry{':packages'}=$package;
1.483 albertel 10812: }
10813: my $value=$packagetab{$key};
10814: my $unikey;
10815: $unikey='parameter_0_'.$name;
1.599 albertel 10816: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10817: $$metathesekeys{$unikey}=1;
1.599 albertel 10818: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10819: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10820: }
1.599 albertel 10821: if (defined($metaentry{':'.$unikey.'.default'})) {
10822: $metaentry{':'.$unikey}=
10823: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10824: }
10825: }
10826:
1.261 albertel 10827: sub metadata_generate_part0 {
10828: my ($metadata,$metacache,$uri) = @_;
10829: my %allnames;
1.737 albertel 10830: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10831: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10832: my $part=$$metacache{':'.$metakey.'.part'};
10833: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10834: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10835: $allnames{$name}=$part;
10836: }
10837: }
10838: }
10839: foreach my $name (keys(%allnames)) {
10840: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10841: my $key=":parameter_0_$name";
1.261 albertel 10842: $$metacache{"$key.part"}='0';
10843: $$metacache{"$key.name"}=$name;
1.428 albertel 10844: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10845: $allnames{$name}.'_'.$name.
10846: '.type'};
1.428 albertel 10847: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10848: '.display'};
1.644 www 10849: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10850: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10851: $$metacache{"$key.display"}=$olddis;
10852: }
1.71 www 10853: }
10854:
1.764 albertel 10855: # ------------------------------------------------------ Devalidate title cache
10856:
10857: sub devalidate_title_cache {
10858: my ($url)=@_;
10859: if (!$env{'request.course.id'}) { return; }
10860: my $symb=&symbread($url);
10861: if (!$symb) { return; }
10862: my $key=$env{'request.course.id'}."\0".$symb;
10863: &devalidate_cache_new('title',$key);
10864: }
10865:
1.1014 droeschl 10866: # ------------------------------------------------- Get the title of a course
10867:
10868: sub current_course_title {
10869: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10870: }
1.301 www 10871: # ------------------------------------------------- Get the title of a resource
10872:
10873: sub gettitle {
10874: my $urlsymb=shift;
10875: my $symb=&symbread($urlsymb);
1.534 albertel 10876: if ($symb) {
1.620 albertel 10877: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10878: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10879: if (defined($cached)) {
10880: return $result;
10881: }
1.534 albertel 10882: my ($map,$resid,$url)=&decode_symb($symb);
10883: my $title='';
1.907 albertel 10884: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10885: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10886: } else {
10887: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10888: &GDBM_READER(),0640)) {
10889: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10890: $title=$bighash{'title_'.$mapid.'.'.$resid};
10891: untie(%bighash);
10892: }
1.534 albertel 10893: }
10894: $title=~s/\&colon\;/\:/gs;
10895: if ($title) {
1.1159 www 10896: # Remember both $symb and $title for dynamic metadata
10897: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10898: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10899: # Cache this title and then return it
1.599 albertel 10900: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10901: }
10902: $urlsymb=$url;
10903: }
10904: my $title=&metadata($urlsymb,'title');
10905: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10906: return $title;
1.301 www 10907: }
1.613 albertel 10908:
1.614 albertel 10909: sub get_slot {
10910: my ($which,$cnum,$cdom)=@_;
10911: if (!$cnum || !$cdom) {
1.790 albertel 10912: (undef,my $courseid)=&whichuser();
1.620 albertel 10913: $cdom=$env{'course.'.$courseid.'.domain'};
10914: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10915: }
1.703 albertel 10916: my $key=join("\0",'slots',$cdom,$cnum,$which);
10917: my %slotinfo;
10918: if (exists($remembered{$key})) {
10919: $slotinfo{$which} = $remembered{$key};
10920: } else {
10921: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10922: &Apache::lonhomework::showhash(%slotinfo);
10923: my ($tmp)=keys(%slotinfo);
10924: if ($tmp=~/^error:/) { return (); }
10925: $remembered{$key} = $slotinfo{$which};
10926: }
1.616 albertel 10927: if (ref($slotinfo{$which}) eq 'HASH') {
10928: return %{$slotinfo{$which}};
10929: }
10930: return $slotinfo{$which};
1.614 albertel 10931: }
1.1150 raeburn 10932:
10933: sub get_reservable_slots {
10934: my ($cnum,$cdom,$uname,$udom) = @_;
10935: my $now = time;
10936: my $reservable_info;
10937: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10938: if (exists($remembered{$key})) {
10939: $reservable_info = $remembered{$key};
10940: } else {
10941: my %resv;
10942: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10943: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10944: $reservable_info = \%resv;
10945: $remembered{$key} = $reservable_info;
10946: }
10947: return $reservable_info;
10948: }
10949:
10950: sub get_course_slots {
10951: my ($cnum,$cdom) = @_;
10952: my $hashid=$cnum.':'.$cdom;
10953: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10954: if (defined($cached)) {
10955: if (ref($result) eq 'HASH') {
10956: return %{$result};
10957: }
10958: } else {
10959: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10960: my ($tmp) = keys(%slots);
10961: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10962: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10963: return %slots;
10964: }
10965: }
10966: return;
10967: }
10968:
10969: sub devalidate_slots_cache {
10970: my ($cnum,$cdom)=@_;
10971: my $hashid=$cnum.':'.$cdom;
10972: &devalidate_cache_new('allslots',$hashid);
10973: }
10974:
1.1181 raeburn 10975: sub get_coursechange {
10976: my ($cdom,$cnum) = @_;
10977: if ($cdom eq '' || $cnum eq '') {
10978: return unless ($env{'request.course.id'});
10979: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10980: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10981: }
10982: my $hashid=$cdom.'_'.$cnum;
10983: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10984: if ((defined($cached)) && ($change ne '')) {
10985: return $change;
10986: } else {
10987: my %crshash;
10988: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10989: if ($crshash{'internal.contentchange'} eq '') {
10990: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10991: if ($change eq '') {
10992: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10993: $change = $crshash{'internal.created'};
10994: }
10995: } else {
10996: $change = $crshash{'internal.contentchange'};
10997: }
10998: my $cachetime = 600;
10999: &do_cache_new('crschange',$hashid,$change,$cachetime);
11000: }
11001: return $change;
11002: }
11003:
11004: sub devalidate_coursechange_cache {
11005: my ($cnum,$cdom)=@_;
11006: my $hashid=$cnum.':'.$cdom;
11007: &devalidate_cache_new('crschange',$hashid);
11008: }
11009:
1.31 www 11010: # ------------------------------------------------- Update symbolic store links
11011:
11012: sub symblist {
11013: my ($mapname,%newhash)=@_;
1.438 www 11014: $mapname=&deversion(&declutter($mapname));
1.31 www 11015: my %hash;
1.620 albertel 11016: if (($env{'request.course.fn'}) && (%newhash)) {
11017: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11018: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11019: foreach my $url (keys(%newhash)) {
1.711 albertel 11020: next if ($url eq 'last_known'
11021: && $env{'form.no_update_last_known'});
11022: $hash{declutter($url)}=&encode_symb($mapname,
11023: $newhash{$url}->[1],
11024: $newhash{$url}->[0]);
1.191 harris41 11025: }
1.31 www 11026: if (untie(%hash)) {
11027: return 'ok';
11028: }
11029: }
11030: }
11031: return 'error';
1.212 www 11032: }
11033:
11034: # --------------------------------------------------------------- Verify a symb
11035:
11036: sub symbverify {
1.1190 raeburn 11037: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11038: my $thisfn=$thisurl;
1.439 www 11039: $thisfn=&declutter($thisfn);
1.215 www 11040: # direct jump to resource in page or to a sequence - will construct own symbs
11041: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11042: # check URL part
1.409 www 11043: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11044:
1.431 www 11045: unless ($url eq $thisfn) { return 0; }
1.213 www 11046:
1.216 www 11047: $symb=&symbclean($symb);
1.510 www 11048: $thisurl=&deversion($thisurl);
1.439 www 11049: $thisfn=&deversion($thisfn);
1.213 www 11050:
11051: my %bighash;
11052: my $okay=0;
1.431 www 11053:
1.620 albertel 11054: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11055: &GDBM_READER(),0640)) {
1.1204 raeburn 11056: my $noclutter;
1.1032 raeburn 11057: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11058: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11059: if ($map =~ m{^uploaded/.+\.page$}) {
11060: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11061: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11062: $noclutter = 1;
11063: }
11064: }
11065: my $ids;
11066: if ($noclutter) {
11067: $ids=$bighash{'ids_'.$thisurl};
11068: } else {
11069: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11070: }
1.1102 raeburn 11071: unless ($ids) {
11072: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11073: $ids=$bighash{$idkey};
1.216 www 11074: }
11075: if ($ids) {
11076: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11077: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11078: $symb =~ s/\?.+$//;
1.1202 raeburn 11079: }
1.800 albertel 11080: foreach my $id (split(/\,/,$ids)) {
11081: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11082: if (
11083: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11084: eq $symb) {
11085: if (ref($encstate)) {
11086: $$encstate = $bighash{'encrypted_'.$id};
11087: }
1.620 albertel 11088: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11089: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11090: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11091: $okay=1;
1.1202 raeburn 11092: last;
1.582 albertel 11093: }
11094: }
1.216 www 11095: }
11096: }
1.213 www 11097: untie(%bighash);
11098: }
11099: return $okay;
1.31 www 11100: }
11101:
1.210 www 11102: # --------------------------------------------------------------- Clean-up symb
11103:
11104: sub symbclean {
11105: my $symb=shift;
1.568 albertel 11106: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11107: # remove version from map
11108: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11109:
1.210 www 11110: # remove version from URL
11111: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11112:
1.507 www 11113: # remove wrapper
11114:
1.510 www 11115: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11116: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11117: return $symb;
1.409 www 11118: }
11119:
11120: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11121:
11122: sub encode_symb {
11123: my ($map,$resid,$url)=@_;
11124: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11125: }
1.409 www 11126:
11127: sub decode_symb {
1.568 albertel 11128: my $symb=shift;
11129: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11130: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11131: return (&fixversion($map),$resid,&fixversion($url));
11132: }
11133:
11134: sub fixversion {
11135: my $fn=shift;
1.609 banghart 11136: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11137: my %bighash;
11138: my $uri=&clutter($fn);
1.620 albertel 11139: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11140: # is this cached?
1.599 albertel 11141: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11142: if (defined($cached)) { return $result; }
11143: # unfortunately not cached, or expired
1.620 albertel 11144: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11145: &GDBM_READER(),0640)) {
11146: if ($bighash{'version_'.$uri}) {
11147: my $version=$bighash{'version_'.$uri};
1.444 www 11148: unless (($version eq 'mostrecent') ||
11149: ($version==&getversion($uri))) {
1.440 www 11150: $uri=~s/\.(\w+)$/\.$version\.$1/;
11151: }
11152: }
11153: untie %bighash;
1.413 www 11154: }
1.599 albertel 11155: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11156: }
11157:
11158: sub deversion {
11159: my $url=shift;
11160: $url=~s/\.\d+\.(\w+)$/\.$1/;
11161: return $url;
1.210 www 11162: }
11163:
1.31 www 11164: # ------------------------------------------------------ Return symb list entry
11165:
11166: sub symbread {
1.1282 ! raeburn 11167: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 11168: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 ! raeburn 11169: if (defined($env{$cache_str})) {
! 11170: if ($ignorecachednull) {
! 11171: return $env{$cache_str} unless ($env{$cache_str} eq '');
! 11172: } else {
! 11173: return $env{$cache_str};
! 11174: }
! 11175: }
1.242 www 11176: # no filename provided? try from environment
1.1265 raeburn 11177: unless ($thisfn) {
1.620 albertel 11178: if ($env{'request.symb'}) {
11179: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11180: }
1.620 albertel 11181: $thisfn=$env{'request.filename'};
1.44 www 11182: }
1.569 albertel 11183: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11184: # is that filename actually a symb? Verify, clean, and return
11185: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11186: if (&symbverify($thisfn,$1)) {
1.620 albertel 11187: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11188: }
1.242 www 11189: }
1.44 www 11190: $thisfn=declutter($thisfn);
1.31 www 11191: my %hash;
1.37 www 11192: my %bighash;
11193: my $syval='';
1.620 albertel 11194: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11195: my $targetfn = $thisfn;
1.609 banghart 11196: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11197: $targetfn = 'adm/wrapper/'.$thisfn;
11198: }
1.687 albertel 11199: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11200: $targetfn=$1;
11201: }
1.620 albertel 11202: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11203: &GDBM_READER(),0640)) {
1.481 raeburn 11204: $syval=$hash{$targetfn};
1.37 www 11205: untie(%hash);
11206: }
11207: # ---------------------------------------------------------- There was an entry
11208: if ($syval) {
1.601 albertel 11209: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11210: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11211: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11212: #return $env{$cache_str}='';
1.601 albertel 11213: #}
11214: #$syval.=$1;
11215: #}
1.37 www 11216: } else {
11217: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11218: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11219: &GDBM_READER(),0640)) {
1.37 www 11220: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11221: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11222: unless ($ids) {
11223: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11224: }
11225: unless ($ids) {
11226: # alias?
11227: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11228: }
1.37 www 11229: if ($ids) {
11230: # ------------------------------------------------------------------- Has ID(s)
11231: my @possibilities=split(/\,/,$ids);
1.39 www 11232: if ($#possibilities==0) {
11233: # ----------------------------------------------- There is only one possibility
1.37 www 11234: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11235: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11236: $resid,$thisfn);
1.1282 ! raeburn 11237: if (ref($possibles) eq 'HASH') {
! 11238: $possibles->{$syval} = 1;
! 11239: }
! 11240: if ($checkforblock) {
! 11241: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
! 11242: if (@blockers) {
! 11243: $syval = '';
! 11244: return;
! 11245: }
! 11246: }
! 11247: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11248: # ------------------------------------------ There is more than one possibility
11249: my $realpossible=0;
1.800 albertel 11250: foreach my $id (@possibilities) {
11251: my $file=$bighash{'src_'.$id};
1.1282 ! raeburn 11252: my $canaccess;
! 11253: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
! 11254: $canaccess = 1;
! 11255: } else {
! 11256: $canaccess = &allowed('bre',$file);
! 11257: }
! 11258: if ($canaccess) {
! 11259: my ($mapid,$resid)=split(/\./,$id);
! 11260: if ($bighash{'map_type_'.$mapid} ne 'page') {
! 11261: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
! 11262: $resid,$thisfn);
! 11263: if (ref($possibles) eq 'HASH') {
! 11264: $possibles->{$syval} = 1;
! 11265: }
! 11266: if ($checkforblock) {
! 11267: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
! 11268: unless (@blockers > 0) {
! 11269: $syval = $poss_syval;
! 11270: $realpossible++;
! 11271: }
! 11272: } else {
! 11273: $syval = $poss_syval;
! 11274: $realpossible++;
! 11275: }
! 11276: }
1.39 www 11277: }
1.191 harris41 11278: }
1.39 www 11279: if ($realpossible!=1) { $syval=''; }
1.249 www 11280: } else {
11281: $syval='';
1.37 www 11282: }
11283: }
1.1282 ! raeburn 11284: untie(%bighash);
1.481 raeburn 11285: }
1.31 www 11286: }
1.62 www 11287: if ($syval) {
1.620 albertel 11288: return $env{$cache_str}=$syval;
1.62 www 11289: }
1.31 www 11290: }
1.949 raeburn 11291: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11292: return $env{$cache_str}='';
1.31 www 11293: }
11294:
11295: # ---------------------------------------------------------- Return random seed
11296:
1.32 www 11297: sub numval {
11298: my $txt=shift;
11299: $txt=~tr/A-J/0-9/;
11300: $txt=~tr/a-j/0-9/;
11301: $txt=~tr/K-T/0-9/;
11302: $txt=~tr/k-t/0-9/;
11303: $txt=~tr/U-Z/0-5/;
11304: $txt=~tr/u-z/0-5/;
11305: $txt=~s/\D//g;
1.564 albertel 11306: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11307: return int($txt);
1.368 albertel 11308: }
11309:
1.484 albertel 11310: sub numval2 {
11311: my $txt=shift;
11312: $txt=~tr/A-J/0-9/;
11313: $txt=~tr/a-j/0-9/;
11314: $txt=~tr/K-T/0-9/;
11315: $txt=~tr/k-t/0-9/;
11316: $txt=~tr/U-Z/0-5/;
11317: $txt=~tr/u-z/0-5/;
11318: $txt=~s/\D//g;
11319: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11320: my $total;
11321: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11322: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11323: return int($total);
11324: }
11325:
1.575 albertel 11326: sub numval3 {
11327: use integer;
11328: my $txt=shift;
11329: $txt=~tr/A-J/0-9/;
11330: $txt=~tr/a-j/0-9/;
11331: $txt=~tr/K-T/0-9/;
11332: $txt=~tr/k-t/0-9/;
11333: $txt=~tr/U-Z/0-5/;
11334: $txt=~tr/u-z/0-5/;
11335: $txt=~s/\D//g;
11336: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11337: my $total;
11338: foreach my $val (@txts) { $total+=$val; }
11339: if ($_64bit) { $total=(($total<<32)>>32); }
11340: return $total;
11341: }
11342:
1.675 albertel 11343: sub digest {
11344: my ($data)=@_;
11345: my $digest=&Digest::MD5::md5($data);
11346: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11347: my ($e,$f);
11348: {
11349: use integer;
11350: $e=($a+$b);
11351: $f=($c+$d);
11352: if ($_64bit) {
11353: $e=(($e<<32)>>32);
11354: $f=(($f<<32)>>32);
11355: }
11356: }
11357: if (wantarray) {
11358: return ($e,$f);
11359: } else {
11360: my $g;
11361: {
11362: use integer;
11363: $g=($e+$f);
11364: if ($_64bit) {
11365: $g=(($g<<32)>>32);
11366: }
11367: }
11368: return $g;
11369: }
11370: }
11371:
1.368 albertel 11372: sub latest_rnd_algorithm_id {
1.675 albertel 11373: return '64bit5';
1.366 albertel 11374: }
1.32 www 11375:
1.503 albertel 11376: sub get_rand_alg {
11377: my ($courseid)=@_;
1.790 albertel 11378: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11379: if ($courseid) {
1.620 albertel 11380: return $env{"course.$courseid.rndseed"};
1.503 albertel 11381: }
11382: return &latest_rnd_algorithm_id();
11383: }
11384:
1.562 albertel 11385: sub validCODE {
11386: my ($CODE)=@_;
11387: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11388: return 0;
11389: }
11390:
1.491 albertel 11391: sub getCODE {
1.620 albertel 11392: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11393: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11394: defined($Apache::lonhomework::parsing_a_task) ) &&
11395: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11396: return $Apache::lonhomework::history{'resource.CODE'};
11397: }
11398: return undef;
11399: }
1.1133 foxr 11400: #
11401: # Determines the random seed for a specific context:
11402: #
11403: # parameters:
11404: # symb - in course context the symb for the seed.
11405: # course_id - The course id of the form domain_coursenum.
11406: # domain - Domain for the user.
11407: # course - Course for the user.
11408: # cenv - environment of the course.
11409: #
11410: # NOTE:
11411: # All parameters are picked out of the environment if missing
11412: # or not defined.
11413: # If a symb cannot be determined the current time is used instead.
11414: #
11415: # For a given well defined symb, courside, domain, username,
11416: # and course environment, the seed is reproducible.
11417: #
1.31 www 11418: sub rndseed {
1.1133 foxr 11419: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11420: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11421: if (!defined($symb)) {
1.366 albertel 11422: unless ($symb=$wsymb) { return time; }
11423: }
1.1146 foxr 11424: if (!defined $courseid) {
11425: $courseid=$wcourseid;
11426: }
11427: if (!defined $domain) { $domain=$wdomain; }
11428: if (!defined $username) { $username=$wusername }
1.1133 foxr 11429:
11430: my $which;
11431: if (defined($cenv->{'rndseed'})) {
11432: $which = $cenv->{'rndseed'};
11433: } else {
11434: $which =&get_rand_alg($courseid);
11435: }
1.491 albertel 11436: if (defined(&getCODE())) {
1.1133 foxr 11437:
1.675 albertel 11438: if ($which eq '64bit5') {
11439: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11440: } elsif ($which eq '64bit4') {
1.575 albertel 11441: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11442: } else {
11443: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11444: }
1.675 albertel 11445: } elsif ($which eq '64bit5') {
11446: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11447: } elsif ($which eq '64bit4') {
11448: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11449: } elsif ($which eq '64bit3') {
11450: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11451: } elsif ($which eq '64bit2') {
11452: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11453: } elsif ($which eq '64bit') {
11454: return &rndseed_64bit($symb,$courseid,$domain,$username);
11455: }
11456: return &rndseed_32bit($symb,$courseid,$domain,$username);
11457: }
11458:
11459: sub rndseed_32bit {
11460: my ($symb,$courseid,$domain,$username)=@_;
11461: {
11462: use integer;
11463: my $symbchck=unpack("%32C*",$symb) << 27;
11464: my $symbseed=numval($symb) << 22;
11465: my $namechck=unpack("%32C*",$username) << 17;
11466: my $nameseed=numval($username) << 12;
11467: my $domainseed=unpack("%32C*",$domain) << 7;
11468: my $courseseed=unpack("%32C*",$courseid);
11469: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11470: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11471: #&logthis("rndseed :$num:$symb");
1.564 albertel 11472: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11473: return $num;
11474: }
11475: }
11476:
11477: sub rndseed_64bit {
11478: my ($symb,$courseid,$domain,$username)=@_;
11479: {
11480: use integer;
11481: my $symbchck=unpack("%32S*",$symb) << 21;
11482: my $symbseed=numval($symb) << 10;
11483: my $namechck=unpack("%32S*",$username);
11484:
11485: my $nameseed=numval($username) << 21;
11486: my $domainseed=unpack("%32S*",$domain) << 10;
11487: my $courseseed=unpack("%32S*",$courseid);
11488:
11489: my $num1=$symbchck+$symbseed+$namechck;
11490: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11491: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11492: #&logthis("rndseed :$num:$symb");
1.564 albertel 11493: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11494: return "$num1,$num2";
1.155 albertel 11495: }
1.366 albertel 11496: }
11497:
1.443 albertel 11498: sub rndseed_64bit2 {
11499: my ($symb,$courseid,$domain,$username)=@_;
11500: {
11501: use integer;
11502: # strings need to be an even # of cahracters long, it it is odd the
11503: # last characters gets thrown away
11504: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11505: my $symbseed=numval($symb) << 10;
11506: my $namechck=unpack("%32S*",$username.' ');
11507:
11508: my $nameseed=numval($username) << 21;
1.501 albertel 11509: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11510: my $courseseed=unpack("%32S*",$courseid.' ');
11511:
11512: my $num1=$symbchck+$symbseed+$namechck;
11513: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11514: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11515: #&logthis("rndseed :$num:$symb");
1.803 albertel 11516: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11517: return "$num1,$num2";
11518: }
11519: }
11520:
11521: sub rndseed_64bit3 {
11522: my ($symb,$courseid,$domain,$username)=@_;
11523: {
11524: use integer;
11525: # strings need to be an even # of cahracters long, it it is odd the
11526: # last characters gets thrown away
11527: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11528: my $symbseed=numval2($symb) << 10;
11529: my $namechck=unpack("%32S*",$username.' ');
11530:
11531: my $nameseed=numval2($username) << 21;
1.443 albertel 11532: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11533: my $courseseed=unpack("%32S*",$courseid.' ');
11534:
11535: my $num1=$symbchck+$symbseed+$namechck;
11536: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11537: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11538: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11539: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11540:
1.503 albertel 11541: return "$num1:$num2";
1.443 albertel 11542: }
11543: }
11544:
1.575 albertel 11545: sub rndseed_64bit4 {
11546: my ($symb,$courseid,$domain,$username)=@_;
11547: {
11548: use integer;
11549: # strings need to be an even # of cahracters long, it it is odd the
11550: # last characters gets thrown away
11551: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11552: my $symbseed=numval3($symb) << 10;
11553: my $namechck=unpack("%32S*",$username.' ');
11554:
11555: my $nameseed=numval3($username) << 21;
11556: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11557: my $courseseed=unpack("%32S*",$courseid.' ');
11558:
11559: my $num1=$symbchck+$symbseed+$namechck;
11560: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11561: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11562: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11563: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11564:
1.575 albertel 11565: return "$num1:$num2";
11566: }
11567: }
11568:
1.675 albertel 11569: sub rndseed_64bit5 {
11570: my ($symb,$courseid,$domain,$username)=@_;
11571: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11572: return "$num1:$num2";
11573: }
11574:
1.366 albertel 11575: sub rndseed_CODE_64bit {
11576: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11577: {
1.366 albertel 11578: use integer;
1.443 albertel 11579: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11580: my $symbseed=numval2($symb);
1.491 albertel 11581: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11582: my $CODEseed=numval(&getCODE());
1.443 albertel 11583: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11584: my $num1=$symbseed+$CODEchck;
11585: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11586: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11587: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11588: if ($_64bit) { $num1=(($num1<<32)>>32); }
11589: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11590: return "$num1:$num2";
1.366 albertel 11591: }
11592: }
11593:
1.575 albertel 11594: sub rndseed_CODE_64bit4 {
11595: my ($symb,$courseid,$domain,$username)=@_;
11596: {
11597: use integer;
11598: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11599: my $symbseed=numval3($symb);
11600: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11601: my $CODEseed=numval3(&getCODE());
11602: my $courseseed=unpack("%32S*",$courseid.' ');
11603: my $num1=$symbseed+$CODEchck;
11604: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11605: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11606: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11607: if ($_64bit) { $num1=(($num1<<32)>>32); }
11608: if ($_64bit) { $num2=(($num2<<32)>>32); }
11609: return "$num1:$num2";
11610: }
11611: }
11612:
1.675 albertel 11613: sub rndseed_CODE_64bit5 {
11614: my ($symb,$courseid,$domain,$username)=@_;
11615: my $code = &getCODE();
11616: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11617: return "$num1:$num2";
11618: }
11619:
1.366 albertel 11620: sub setup_random_from_rndseed {
11621: my ($rndseed)=@_;
1.503 albertel 11622: if ($rndseed =~/([,:])/) {
1.1262 raeburn 11623: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11624: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11625: &Math::Random::random_set_seed_from_phrase($rndseed);
11626: } else {
11627: &Math::Random::random_set_seed($num1,$num2);
11628: }
1.366 albertel 11629: } else {
11630: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11631: }
1.36 albertel 11632: }
11633:
1.474 albertel 11634: sub latest_receipt_algorithm_id {
1.835 albertel 11635: return 'receipt3';
1.474 albertel 11636: }
11637:
1.480 www 11638: sub recunique {
11639: my $fucourseid=shift;
11640: my $unique;
1.835 albertel 11641: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11642: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11643: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11644: } else {
11645: $unique=$perlvar{'lonReceipt'};
11646: }
11647: return unpack("%32C*",$unique);
11648: }
11649:
11650: sub recprefix {
11651: my $fucourseid=shift;
11652: my $prefix;
1.835 albertel 11653: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11654: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11655: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11656: } else {
11657: $prefix=$perlvar{'lonHostID'};
11658: }
11659: return unpack("%32C*",$prefix);
11660: }
11661:
1.76 www 11662: sub ireceipt {
1.474 albertel 11663: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11664:
11665: my $return =&recprefix($fucourseid).'-';
11666:
11667: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11668: $env{'request.state'} eq 'construct') {
11669: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11670: return $return;
11671: }
11672:
1.76 www 11673: my $cuname=unpack("%32C*",$funame);
11674: my $cudom=unpack("%32C*",$fudom);
11675: my $cucourseid=unpack("%32C*",$fucourseid);
11676: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11677: my $cunique=&recunique($fucourseid);
1.474 albertel 11678: my $cpart=unpack("%32S*",$part);
1.835 albertel 11679: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11680:
1.790 albertel 11681: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11682:
11683: $return.= ($cunique%$cuname+
11684: $cunique%$cudom+
11685: $cusymb%$cuname+
11686: $cusymb%$cudom+
11687: $cucourseid%$cuname+
11688: $cucourseid%$cudom+
11689: $cpart%$cuname+
11690: $cpart%$cudom);
11691: } else {
11692: $return.= ($cunique%$cuname+
11693: $cunique%$cudom+
11694: $cusymb%$cuname+
11695: $cusymb%$cudom+
11696: $cucourseid%$cuname+
11697: $cucourseid%$cudom);
11698: }
11699: return $return;
1.76 www 11700: }
11701:
11702: sub receipt {
1.474 albertel 11703: my ($part)=@_;
1.790 albertel 11704: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11705: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11706: }
1.260 ng 11707:
1.790 albertel 11708: sub whichuser {
11709: my ($passedsymb)=@_;
11710: my ($symb,$courseid,$domain,$name,$publicuser);
11711: if (defined($env{'form.grade_symb'})) {
11712: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11713: my $allowed=&allowed('vgr',$tmp_courseid);
11714: if (!$allowed &&
11715: exists($env{'request.course.sec'}) &&
11716: $env{'request.course.sec'} !~ /^\s*$/) {
11717: $allowed=&allowed('vgr',$tmp_courseid.
11718: '/'.$env{'request.course.sec'});
11719: }
11720: if ($allowed) {
11721: ($symb)=&get_env_multiple('form.grade_symb');
11722: $courseid=$tmp_courseid;
11723: ($domain)=&get_env_multiple('form.grade_domain');
11724: ($name)=&get_env_multiple('form.grade_username');
11725: return ($symb,$courseid,$domain,$name,$publicuser);
11726: }
11727: }
11728: if (!$passedsymb) {
11729: $symb=&symbread();
11730: } else {
11731: $symb=$passedsymb;
11732: }
11733: $courseid=$env{'request.course.id'};
11734: $domain=$env{'user.domain'};
11735: $name=$env{'user.name'};
11736: if ($name eq 'public' && $domain eq 'public') {
11737: if (!defined($env{'form.username'})) {
11738: $env{'form.username'}.=time.rand(10000000);
11739: }
11740: $name.=$env{'form.username'};
11741: }
11742: return ($symb,$courseid,$domain,$name,$publicuser);
11743:
11744: }
11745:
1.36 albertel 11746: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11747: # returns either the contents of the file or
11748: # -1 if the file doesn't exist
1.481 raeburn 11749: #
11750: # if the target is a file that was uploaded via DOCS,
11751: # a check will be made to see if a current copy exists on the local server,
11752: # if it does this will be served, otherwise a copy will be retrieved from
11753: # the home server for the course and stored in /home/httpd/html/userfiles on
11754: # the local server.
1.472 albertel 11755:
1.36 albertel 11756: sub getfile {
1.538 albertel 11757: my ($file) = @_;
1.609 banghart 11758: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11759: &repcopy($file);
11760: return &readfile($file);
11761: }
11762:
11763: sub repcopy_userfile {
11764: my ($file)=@_;
1.1142 raeburn 11765: my $londocroot = $perlvar{'lonDocRoot'};
11766: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11767: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11768: my ($cdom,$cnum,$filename) =
1.811 albertel 11769: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11770: my $uri="/uploaded/$cdom/$cnum/$filename";
11771: if (-e "$file") {
1.828 www 11772: # we already have a local copy, check it out
1.538 albertel 11773: my @fileinfo = stat($file);
1.828 www 11774: my $rtncode;
11775: my $info;
1.538 albertel 11776: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11777: if ($lwpresp ne 'ok') {
1.828 www 11778: # there is no such file anymore, even though we had a local copy
1.482 albertel 11779: if ($rtncode eq '404') {
1.538 albertel 11780: unlink($file);
1.482 albertel 11781: }
11782: return -1;
11783: }
11784: if ($info < $fileinfo[9]) {
1.828 www 11785: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11786: return 'ok';
1.828 www 11787: } else {
11788: # the file is outdated, get rid of it
11789: unlink($file);
1.482 albertel 11790: }
1.828 www 11791: }
11792: # one way or the other, at this point, we don't have the file
11793: # construct the correct path for the file
11794: my @parts = ($cdom,$cnum);
11795: if ($filename =~ m|^(.+)/[^/]+$|) {
11796: push @parts, split(/\//,$1);
11797: }
11798: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11799: foreach my $part (@parts) {
11800: $path .= '/'.$part;
11801: if (!-e $path) {
11802: mkdir($path,0770);
1.482 albertel 11803: }
11804: }
1.828 www 11805: # now the path exists for sure
11806: # get a user agent
11807: my $ua=new LWP::UserAgent;
11808: my $transferfile=$file.'.in.transfer';
11809: # FIXME: this should flock
11810: if (-e $transferfile) { return 'ok'; }
11811: my $request;
11812: $uri=~s/^\///;
1.980 raeburn 11813: my $homeserver = &homeserver($cnum,$cdom);
11814: my $protocol = $protocol{$homeserver};
11815: $protocol = 'http' if ($protocol ne 'https');
11816: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11817: my $response=$ua->request($request,$transferfile);
11818: # did it work?
11819: if ($response->is_error()) {
11820: unlink($transferfile);
11821: &logthis("Userfile repcopy failed for $uri");
11822: return -1;
11823: }
11824: # worked, rename the transfer file
11825: rename($transferfile,$file);
1.607 raeburn 11826: return 'ok';
1.481 raeburn 11827: }
11828:
1.517 albertel 11829: sub tokenwrapper {
11830: my $uri=shift;
1.980 raeburn 11831: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11832: $uri=~s|^/||;
1.620 albertel 11833: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11834: my $token=$1;
1.552 albertel 11835: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11836: if ($udom && $uname && $file) {
11837: $file=~s|(\?\.*)*$||;
1.949 raeburn 11838: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11839: my $homeserver = &homeserver($uname,$udom);
11840: my $protocol = $protocol{$homeserver};
11841: $protocol = 'http' if ($protocol ne 'https');
11842: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11843: (($uri=~/\?/)?'&':'?').'token='.$token.
11844: '&tokenissued='.$perlvar{'lonHostID'};
11845: } else {
11846: return '/adm/notfound.html';
11847: }
11848: }
11849:
1.828 www 11850: # call with reqtype HEAD: get last modification time
11851: # call with reqtype GET: get the file contents
11852: # Do not call this with reqtype GET for large files! It loads everything into memory
11853: #
1.481 raeburn 11854: sub getuploaded {
11855: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11856: $uri=~s/^\///;
1.980 raeburn 11857: my $homeserver = &homeserver($cnum,$cdom);
11858: my $protocol = $protocol{$homeserver};
11859: $protocol = 'http' if ($protocol ne 'https');
11860: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11861: my $ua=new LWP::UserAgent;
11862: my $request=new HTTP::Request($reqtype,$uri);
11863: my $response=$ua->request($request);
11864: $$rtncode = $response->code;
1.482 albertel 11865: if (! $response->is_success()) {
11866: return 'failed';
11867: }
11868: if ($reqtype eq 'HEAD') {
1.486 www 11869: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11870: } elsif ($reqtype eq 'GET') {
11871: $$info = $response->content;
1.472 albertel 11872: }
1.482 albertel 11873: return 'ok';
1.36 albertel 11874: }
11875:
1.481 raeburn 11876: sub readfile {
11877: my $file = shift;
11878: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11879: my $fh;
11880: open($fh,"<$file");
11881: my $a='';
1.800 albertel 11882: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11883: return $a;
11884: }
11885:
1.36 albertel 11886: sub filelocation {
1.590 banghart 11887: my ($dir,$file) = @_;
11888: my $location;
11889: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11890:
11891: if ($file =~ m-^/adm/-) {
11892: $file=~s-^/adm/wrapper/-/-;
11893: $file=~s-^/adm/coursedocs/showdoc/-/-;
11894: }
1.882 albertel 11895:
1.1139 www 11896: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11897: $location = $file;
1.609 banghart 11898: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11899: my ($udom,$uname,$filename)=
1.811 albertel 11900: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11901: my $home=&homeserver($uname,$udom);
11902: my $is_me=0;
11903: my @ids=¤t_machine_ids();
11904: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11905: if ($is_me) {
1.1117 foxr 11906: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11907: } else {
11908: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11909: $udom.'/'.$uname.'/'.$filename;
11910: }
1.882 albertel 11911: } elsif ($file =~ m-^/adm/-) {
11912: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11913: } else {
11914: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11915: $file=~s:^/(res|priv)/:/:;
11916: my $space=$1;
1.590 banghart 11917: if ( !( $file =~ m:^/:) ) {
11918: $location = $dir. '/'.$file;
11919: } else {
1.1142 raeburn 11920: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11921: }
1.59 albertel 11922: }
1.590 banghart 11923: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11924: while ($location=~m{/\.\./}) {
11925: if ($location =~ m{/[^/]+/\.\./}) {
11926: $location=~ s{/[^/]+/\.\./}{/}g;
11927: } else {
11928: $location=~ s{/\.\./}{/}g;
11929: }
11930: } #remove dir/..
1.590 banghart 11931: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11932: return $location;
1.46 www 11933: }
1.36 albertel 11934:
1.46 www 11935: sub hreflocation {
11936: my ($dir,$file)=@_;
1.980 raeburn 11937: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11938: $file=filelocation($dir,$file);
1.700 albertel 11939: } elsif ($file=~m-^/adm/-) {
11940: $file=~s-^/adm/wrapper/-/-;
11941: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11942: }
11943: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11944: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11945: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11946: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11947: {/uploaded/$1/$2/}x;
1.46 www 11948: }
1.913 albertel 11949: if ($file=~ m{^/userfiles/}) {
11950: $file =~ s{^/userfiles/}{/uploaded/};
11951: }
1.462 albertel 11952: return $file;
1.465 albertel 11953: }
11954:
1.1139 www 11955:
11956:
11957:
11958:
1.465 albertel 11959: sub current_machine_domains {
1.853 albertel 11960: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11961: }
11962:
11963: sub machine_domains {
11964: my ($hostname) = @_;
1.465 albertel 11965: my @domains;
1.838 albertel 11966: my %hostname = &all_hostnames();
1.465 albertel 11967: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11968: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11969: if ($hostname eq $name) {
1.844 albertel 11970: push(@domains,&host_domain($id));
1.465 albertel 11971: }
11972: }
11973: return @domains;
11974: }
11975:
11976: sub current_machine_ids {
1.853 albertel 11977: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11978: }
11979:
11980: sub machine_ids {
11981: my ($hostname) = @_;
11982: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11983: my @ids;
1.888 albertel 11984: my %name_to_host = &all_names();
1.889 albertel 11985: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11986: return @{ $name_to_host{$hostname} };
11987: }
11988: return;
1.31 www 11989: }
11990:
1.824 raeburn 11991: sub additional_machine_domains {
11992: my @domains;
11993: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11994: while( my $line = <$fh>) {
11995: $line =~ s/\s//g;
11996: push(@domains,$line);
11997: }
11998: return @domains;
11999: }
12000:
12001: sub default_login_domain {
12002: my $domain = $perlvar{'lonDefDomain'};
12003: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12004: foreach my $posdom (¤t_machine_domains(),
12005: &additional_machine_domains()) {
12006: if (lc($posdom) eq lc($testdomain)) {
12007: $domain=$posdom;
12008: last;
12009: }
12010: }
12011: return $domain;
12012: }
12013:
1.31 www 12014: # ------------------------------------------------------------- Declutters URLs
12015:
12016: sub declutter {
12017: my $thisfn=shift;
1.569 albertel 12018: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12019: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12020: $thisfn=~s{^/home/httpd/html}{};
12021: }
1.31 www 12022: $thisfn=~s/^\///;
1.697 albertel 12023: $thisfn=~s|^adm/wrapper/||;
12024: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12025: $thisfn=~s/^res\///;
1.1172 bisitz 12026: $thisfn=~s/^priv\///;
1.1032 raeburn 12027: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12028: $thisfn=~s/\?.+$//;
12029: }
1.268 www 12030: return $thisfn;
12031: }
12032:
12033: # ------------------------------------------------------------- Clutter up URLs
12034:
12035: sub clutter {
12036: my $thisfn='/'.&declutter(shift);
1.887 albertel 12037: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12038: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12039: $thisfn='/res'.$thisfn;
12040: }
1.1031 raeburn 12041: if ($thisfn !~m|^/adm|) {
12042: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12043: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12044: } else {
12045: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12046: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12047: if ($embstyle eq 'ssi'
12048: || ($embstyle eq 'hdn')
12049: || ($embstyle eq 'rat')
12050: || ($embstyle eq 'prv')
12051: || ($embstyle eq 'ign')) {
12052: #do nothing with these
12053: } elsif (($embstyle eq 'img')
1.695 albertel 12054: || ($embstyle eq 'emb')
12055: || ($embstyle eq 'wrp')) {
12056: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12057: } elsif ($embstyle eq 'unk'
12058: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12059: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12060: } else {
1.718 www 12061: # &logthis("Got a blank emb style");
1.695 albertel 12062: }
1.694 albertel 12063: }
12064: }
1.31 www 12065: return $thisfn;
1.12 www 12066: }
12067:
1.787 albertel 12068: sub clutter_with_no_wrapper {
12069: my $uri = &clutter(shift);
12070: if ($uri =~ m-^/adm/-) {
12071: $uri =~ s-^/adm/wrapper/-/-;
12072: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12073: }
12074: return $uri;
12075: }
12076:
1.557 albertel 12077: sub freeze_escape {
12078: my ($value)=@_;
12079: if (ref($value)) {
12080: $value=&nfreeze($value);
12081: return '__FROZEN__'.&escape($value);
12082: }
12083: return &escape($value);
12084: }
12085:
1.11 www 12086:
1.557 albertel 12087: sub thaw_unescape {
12088: my ($value)=@_;
12089: if ($value =~ /^__FROZEN__/) {
12090: substr($value,0,10,undef);
12091: $value=&unescape($value);
12092: return &thaw($value);
12093: }
12094: return &unescape($value);
12095: }
12096:
1.436 albertel 12097: sub correct_line_ends {
12098: my ($result)=@_;
12099: $$result =~s/\r\n/\n/mg;
12100: $$result =~s/\r/\n/mg;
1.415 albertel 12101: }
1.1 albertel 12102: # ================================================================ Main Program
12103:
1.184 www 12104: sub goodbye {
1.204 albertel 12105: &logthis("Starting Shut down");
1.443 albertel 12106: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12107: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12108: #converted
1.599 albertel 12109: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12110: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12111: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12112: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12113: #1.1 only
1.870 albertel 12114: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12115: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12116: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12117: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12118: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12119: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12120: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12121: &flushcourselogs();
12122: &logthis("Shutting down");
12123: }
12124:
1.852 albertel 12125: sub get_dns {
1.1210 raeburn 12126: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12127: if (!$ignore_cache) {
12128: my ($content,$cached)=
12129: &Apache::lonnet::is_cached_new('dns',$url);
12130: if ($cached) {
1.1210 raeburn 12131: &$func($content,$hashref);
1.869 albertel 12132: return;
12133: }
12134: }
12135:
12136: my %alldns;
1.852 albertel 12137: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12138: foreach my $dns (<$config>) {
12139: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12140: my $line = $1;
12141: my ($host,$protocol) = split(/:/,$line);
12142: if ($protocol ne 'https') {
12143: $protocol = 'http';
12144: }
12145: $alldns{$host} = $protocol;
1.869 albertel 12146: }
12147: while (%alldns) {
1.1263 raeburn 12148: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12149: my $ua=new LWP::UserAgent;
1.1134 raeburn 12150: $ua->timeout(30);
1.979 raeburn 12151: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12152: my $response=$ua->request($request);
1.979 raeburn 12153: delete($alldns{$dns});
1.852 albertel 12154: next if ($response->is_error());
12155: my @content = split("\n",$response->content);
1.1210 raeburn 12156: unless ($nocache) {
1.1219 raeburn 12157: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12158: }
12159: &$func(\@content,$hashref);
1.869 albertel 12160: return;
1.852 albertel 12161: }
12162: close($config);
1.871 albertel 12163: my $which = (split('/',$url))[3];
12164: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12165: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12166: my @content = <$config>;
1.1210 raeburn 12167: &$func(\@content,$hashref);
12168: return;
12169: }
12170:
12171: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12172: sub parse_dns_checksums_tab {
1.1210 raeburn 12173: my ($lines,$hashref) = @_;
1.1264 raeburn 12174: my $lonhost = $perlvar{'lonHostID'};
12175: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12176: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12177: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12178: my $webconfdir = '/etc/httpd/conf';
12179: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12180: $webconfdir = '/etc/apache2';
12181: } elsif ($distro =~ /^sles(\d+)$/) {
12182: if ($1 >= 10) {
12183: $webconfdir = '/etc/apache2';
12184: }
12185: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12186: if ($1 >= 10.0) {
12187: $webconfdir = '/etc/apache2';
12188: }
12189: }
1.1210 raeburn 12190: my ($release,$timestamp) = split(/\-/,$loncaparev);
12191: my (%chksum,%revnum);
12192: if (ref($lines) eq 'ARRAY') {
12193: chomp(@{$lines});
1.1238 raeburn 12194: my $version = shift(@{$lines});
12195: if ($version eq $release) {
1.1210 raeburn 12196: foreach my $line (@{$lines}) {
1.1238 raeburn 12197: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12198: if ($file =~ m{^/etc/httpd/conf}) {
12199: if ($webconfdir eq '/etc/apache2') {
12200: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12201: }
12202: }
1.1238 raeburn 12203: $chksum{$file} = $shasum;
12204: $revnum{$file} = $version;
1.1210 raeburn 12205: }
12206: if (ref($hashref) eq 'HASH') {
12207: %{$hashref} = (
12208: sums => \%chksum,
12209: versions => \%revnum,
12210: );
12211: }
12212: }
12213: }
1.869 albertel 12214: return;
1.852 albertel 12215: }
1.1210 raeburn 12216:
12217: sub fetch_dns_checksums {
1.1238 raeburn 12218: my %checksums;
12219: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12220: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12221: my ($release,$timestamp) = split(/\-/,$loncaparev);
12222: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12223: \%checksums);
1.1210 raeburn 12224: return \%checksums;
12225: }
12226:
1.327 albertel 12227: # ------------------------------------------------------------ Read domain file
12228: {
1.852 albertel 12229: my $loaded;
1.846 albertel 12230: my %domain;
12231:
1.852 albertel 12232: sub parse_domain_tab {
12233: my ($lines) = @_;
12234: foreach my $line (@$lines) {
12235: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12236:
1.846 albertel 12237: chomp($line);
1.852 albertel 12238: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12239: my %this_domain;
12240: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12241: 'lang_def', 'city', 'longi', 'lati',
12242: 'primary') {
12243: $this_domain{$field} = shift(@elements);
12244: }
12245: $domain{$name} = \%this_domain;
1.852 albertel 12246: }
12247: }
1.864 albertel 12248:
12249: sub reset_domain_info {
12250: undef($loaded);
12251: undef(%domain);
12252: }
12253:
1.852 albertel 12254: sub load_domain_tab {
1.869 albertel 12255: my ($ignore_cache) = @_;
12256: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 12257: my $fh;
12258: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12259: my @lines = <$fh>;
12260: &parse_domain_tab(\@lines);
1.448 albertel 12261: }
1.852 albertel 12262: close($fh);
12263: $loaded = 1;
1.327 albertel 12264: }
1.846 albertel 12265:
12266: sub domain {
1.852 albertel 12267: &load_domain_tab() if (!$loaded);
12268:
1.846 albertel 12269: my ($name,$what) = @_;
12270: return if ( !exists($domain{$name}) );
12271:
12272: if (!$what) {
12273: return $domain{$name}{'description'};
12274: }
12275: return $domain{$name}{$what};
12276: }
1.974 raeburn 12277:
12278: sub domain_info {
12279: &load_domain_tab() if (!$loaded);
12280: return %domain;
12281: }
12282:
1.327 albertel 12283: }
12284:
12285:
1.1 albertel 12286: # ------------------------------------------------------------- Read hosts file
12287: {
1.838 albertel 12288: my %hostname;
1.844 albertel 12289: my %hostdom;
1.845 albertel 12290: my %libserv;
1.852 albertel 12291: my $loaded;
1.888 albertel 12292: my %name_to_host;
1.1074 raeburn 12293: my %internetdom;
1.1107 raeburn 12294: my %LC_dns_serv;
1.852 albertel 12295:
12296: sub parse_hosts_tab {
12297: my ($file) = @_;
12298: foreach my $configline (@$file) {
12299: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12300: chomp($configline);
12301: if ($configline =~ /^\^/) {
12302: if ($configline =~ /^\^([\w.\-]+)/) {
12303: $LC_dns_serv{$1} = 1;
12304: }
12305: next;
12306: }
1.1074 raeburn 12307: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12308: $name=~s/\s//g;
12309: if ($id && $domain && $role && $name) {
12310: $hostname{$id}=$name;
1.888 albertel 12311: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12312: $hostdom{$id}=$domain;
12313: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12314: if (defined($protocol)) {
12315: if ($protocol eq 'https') {
12316: $protocol{$id} = $protocol;
12317: } else {
12318: $protocol{$id} = 'http';
12319: }
1.968 raeburn 12320: } else {
1.969 raeburn 12321: $protocol{$id} = 'http';
1.968 raeburn 12322: }
1.1074 raeburn 12323: if (defined($intdom)) {
12324: $internetdom{$id} = $intdom;
12325: }
1.852 albertel 12326: }
12327: }
12328: }
1.864 albertel 12329:
12330: sub reset_hosts_info {
1.897 albertel 12331: &purge_remembered();
1.864 albertel 12332: &reset_domain_info();
12333: &reset_hosts_ip_info();
1.892 albertel 12334: undef(%name_to_host);
1.864 albertel 12335: undef(%hostname);
12336: undef(%hostdom);
12337: undef(%libserv);
12338: undef($loaded);
12339: }
1.1 albertel 12340:
1.852 albertel 12341: sub load_hosts_tab {
1.869 albertel 12342: my ($ignore_cache) = @_;
12343: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12344: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12345: my @config = <$config>;
12346: &parse_hosts_tab(\@config);
12347: close($config);
12348: $loaded=1;
1.1 albertel 12349: }
1.852 albertel 12350:
1.838 albertel 12351: sub hostname {
1.852 albertel 12352: &load_hosts_tab() if (!$loaded);
12353:
1.838 albertel 12354: my ($lonid) = @_;
12355: return $hostname{$lonid};
12356: }
1.845 albertel 12357:
1.838 albertel 12358: sub all_hostnames {
1.852 albertel 12359: &load_hosts_tab() if (!$loaded);
12360:
1.838 albertel 12361: return %hostname;
12362: }
1.845 albertel 12363:
1.888 albertel 12364: sub all_names {
12365: &load_hosts_tab() if (!$loaded);
12366:
12367: return %name_to_host;
12368: }
12369:
1.974 raeburn 12370: sub all_host_domain {
12371: &load_hosts_tab() if (!$loaded);
12372: return %hostdom;
12373: }
12374:
1.845 albertel 12375: sub is_library {
1.852 albertel 12376: &load_hosts_tab() if (!$loaded);
12377:
1.845 albertel 12378: return exists($libserv{$_[0]});
12379: }
12380:
12381: sub all_library {
1.852 albertel 12382: &load_hosts_tab() if (!$loaded);
12383:
1.845 albertel 12384: return %libserv;
12385: }
12386:
1.1062 droeschl 12387: sub unique_library {
12388: #2x reverse removes all hostnames that appear more than once
12389: my %unique = reverse &all_library();
12390: return reverse %unique;
12391: }
12392:
1.841 albertel 12393: sub get_servers {
1.852 albertel 12394: &load_hosts_tab() if (!$loaded);
12395:
1.841 albertel 12396: my ($domain,$type) = @_;
12397: my %possible_hosts = ($type eq 'library') ? %libserv
12398: : %hostname;
12399: my %result;
1.842 albertel 12400: if (ref($domain) eq 'ARRAY') {
12401: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12402: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12403: $result{$host} = $hostname;
12404: }
12405: }
12406: } else {
12407: while ( my ($host,$hostname) = each(%possible_hosts)) {
12408: if ($hostdom{$host} eq $domain) {
12409: $result{$host} = $hostname;
12410: }
1.841 albertel 12411: }
12412: }
12413: return %result;
12414: }
1.845 albertel 12415:
1.1062 droeschl 12416: sub get_unique_servers {
12417: my %unique = reverse &get_servers(@_);
12418: return reverse %unique;
12419: }
12420:
1.844 albertel 12421: sub host_domain {
1.852 albertel 12422: &load_hosts_tab() if (!$loaded);
12423:
1.844 albertel 12424: my ($lonid) = @_;
12425: return $hostdom{$lonid};
12426: }
12427:
1.841 albertel 12428: sub all_domains {
1.852 albertel 12429: &load_hosts_tab() if (!$loaded);
12430:
1.841 albertel 12431: my %seen;
12432: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12433: return @uniq;
12434: }
1.1074 raeburn 12435:
12436: sub internet_dom {
12437: &load_hosts_tab() if (!$loaded);
12438:
12439: my ($lonid) = @_;
12440: return $internetdom{$lonid};
12441: }
1.1107 raeburn 12442:
12443: sub is_LC_dns {
12444: &load_hosts_tab() if (!$loaded);
12445:
12446: my ($hostname) = @_;
12447: return exists($LC_dns_serv{$hostname});
12448: }
12449:
1.1 albertel 12450: }
12451:
1.847 albertel 12452: {
12453: my %iphost;
1.856 albertel 12454: my %name_to_ip;
12455: my %lonid_to_ip;
1.869 albertel 12456:
1.847 albertel 12457: sub get_hosts_from_ip {
12458: my ($ip) = @_;
12459: my %iphosts = &get_iphost();
12460: if (ref($iphosts{$ip})) {
12461: return @{$iphosts{$ip}};
12462: }
12463: return;
1.839 albertel 12464: }
1.864 albertel 12465:
12466: sub reset_hosts_ip_info {
12467: undef(%iphost);
12468: undef(%name_to_ip);
12469: undef(%lonid_to_ip);
12470: }
1.856 albertel 12471:
12472: sub get_host_ip {
12473: my ($lonid) = @_;
12474: if (exists($lonid_to_ip{$lonid})) {
12475: return $lonid_to_ip{$lonid};
12476: }
12477: my $name=&hostname($lonid);
12478: my $ip = gethostbyname($name);
12479: return if (!$ip || length($ip) ne 4);
12480: $ip=inet_ntoa($ip);
12481: $name_to_ip{$name} = $ip;
12482: $lonid_to_ip{$lonid} = $ip;
12483: return $ip;
12484: }
1.847 albertel 12485:
12486: sub get_iphost {
1.869 albertel 12487: my ($ignore_cache) = @_;
1.894 albertel 12488:
1.869 albertel 12489: if (!$ignore_cache) {
12490: if (%iphost) {
12491: return %iphost;
12492: }
12493: my ($ip_info,$cached)=
12494: &Apache::lonnet::is_cached_new('iphost','iphost');
12495: if ($cached) {
12496: %iphost = %{$ip_info->[0]};
12497: %name_to_ip = %{$ip_info->[1]};
12498: %lonid_to_ip = %{$ip_info->[2]};
12499: return %iphost;
12500: }
12501: }
1.894 albertel 12502:
12503: # get yesterday's info for fallback
12504: my %old_name_to_ip;
12505: my ($ip_info,$cached)=
12506: &Apache::lonnet::is_cached_new('iphost','iphost');
12507: if ($cached) {
12508: %old_name_to_ip = %{$ip_info->[1]};
12509: }
12510:
1.888 albertel 12511: my %name_to_host = &all_names();
12512: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12513: my $ip;
12514: if (!exists($name_to_ip{$name})) {
12515: $ip = gethostbyname($name);
12516: if (!$ip || length($ip) ne 4) {
1.894 albertel 12517: if (defined($old_name_to_ip{$name})) {
12518: $ip = $old_name_to_ip{$name};
12519: &logthis("Can't find $name defaulting to old $ip");
12520: } else {
12521: &logthis("Name $name no IP found");
12522: next;
12523: }
12524: } else {
12525: $ip=inet_ntoa($ip);
1.847 albertel 12526: }
12527: $name_to_ip{$name} = $ip;
12528: } else {
12529: $ip = $name_to_ip{$name};
1.653 albertel 12530: }
1.888 albertel 12531: foreach my $id (@{ $name_to_host{$name} }) {
12532: $lonid_to_ip{$id} = $ip;
12533: }
12534: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12535: }
1.1219 raeburn 12536: &do_cache_new('iphost','iphost',
12537: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12538: 48*60*60);
1.869 albertel 12539:
1.847 albertel 12540: return %iphost;
1.598 albertel 12541: }
12542:
1.992 raeburn 12543: #
12544: # Given a DNS returns the loncapa host name for that DNS
12545: #
12546: sub host_from_dns {
12547: my ($dns) = @_;
12548: my @hosts;
12549: my $ip;
12550:
1.993 raeburn 12551: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12552: $ip = $name_to_ip{$dns};
12553: }
12554: if (!$ip) {
12555: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12556: if (length($ip) == 4) {
12557: $ip = &IO::Socket::inet_ntoa($ip);
12558: }
12559: }
12560: if ($ip) {
12561: @hosts = get_hosts_from_ip($ip);
12562: return $hosts[0];
12563: }
12564: return undef;
1.986 foxr 12565: }
1.992 raeburn 12566:
1.1074 raeburn 12567: sub get_internet_names {
12568: my ($lonid) = @_;
12569: return if ($lonid eq '');
12570: my ($idnref,$cached)=
12571: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12572: if ($cached) {
12573: return $idnref;
12574: }
12575: my $ip = &get_host_ip($lonid);
12576: my @hosts = &get_hosts_from_ip($ip);
12577: my %iphost = &get_iphost();
12578: my (@idns,%seen);
12579: foreach my $id (@hosts) {
12580: my $dom = &host_domain($id);
12581: my $prim_id = &domain($dom,'primary');
12582: my $prim_ip = &get_host_ip($prim_id);
12583: next if ($seen{$prim_ip});
12584: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12585: foreach my $id (@{$iphost{$prim_ip}}) {
12586: my $intdom = &internet_dom($id);
12587: unless (grep(/^\Q$intdom\E$/,@idns)) {
12588: push(@idns,$intdom);
12589: }
12590: }
12591: }
12592: $seen{$prim_ip} = 1;
12593: }
1.1219 raeburn 12594: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12595: }
12596:
1.986 foxr 12597: }
12598:
1.1079 raeburn 12599: sub all_loncaparevs {
1.1249 raeburn 12600: 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 12601: }
12602:
1.1227 raeburn 12603: # ---------------------------------------------------------- Read loncaparev table
12604: {
12605: sub load_loncaparevs {
12606: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12607: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12608: while (my $configline=<$config>) {
12609: chomp($configline);
12610: my ($hostid,$loncaparev)=split(/:/,$configline);
12611: $loncaparevs{$hostid}=$loncaparev;
12612: }
12613: close($config);
12614: }
12615: }
12616: }
12617: }
12618:
12619: # ---------------------------------------------------------- Read serverhostID table
12620: {
12621: sub load_serverhomeIDs {
12622: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12623: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12624: while (my $configline=<$config>) {
12625: chomp($configline);
12626: my ($name,$id)=split(/:/,$configline);
12627: $serverhomeIDs{$name}=$id;
12628: }
12629: close($config);
12630: }
12631: }
12632: }
12633: }
12634:
12635:
1.862 albertel 12636: BEGIN {
12637:
12638: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12639: unless ($readit) {
12640: {
12641: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12642: %perlvar = (%perlvar,%{$configvars});
12643: }
12644:
12645:
1.1 albertel 12646: # ------------------------------------------------------ Read spare server file
12647: {
1.448 albertel 12648: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12649:
12650: while (my $configline=<$config>) {
12651: chomp($configline);
1.284 matthew 12652: if ($configline) {
1.784 albertel 12653: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12654: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12655: push(@{ $spareid{$type} }, $host);
1.1 albertel 12656: }
12657: }
1.448 albertel 12658: close($config);
1.1 albertel 12659: }
1.11 www 12660: # ------------------------------------------------------------ Read permissions
12661: {
1.448 albertel 12662: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12663:
12664: while (my $configline=<$config>) {
1.448 albertel 12665: chomp($configline);
12666: if ($configline) {
12667: my ($role,$perm)=split(/ /,$configline);
12668: if ($perm ne '') { $pr{$role}=$perm; }
12669: }
1.11 www 12670: }
1.448 albertel 12671: close($config);
1.11 www 12672: }
12673:
12674: # -------------------------------------------- Read plain texts for permissions
12675: {
1.448 albertel 12676: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12677:
12678: while (my $configline=<$config>) {
1.448 albertel 12679: chomp($configline);
12680: if ($configline) {
1.742 raeburn 12681: my ($short,@plain)=split(/:/,$configline);
12682: %{$prp{$short}} = ();
12683: if (@plain > 0) {
12684: $prp{$short}{'std'} = $plain[0];
12685: for (my $i=1; $i<@plain; $i++) {
12686: $prp{$short}{'alt'.$i} = $plain[$i];
12687: }
12688: }
1.448 albertel 12689: }
1.135 www 12690: }
1.448 albertel 12691: close($config);
1.135 www 12692: }
12693:
12694: # ---------------------------------------------------------- Read package table
12695: {
1.448 albertel 12696: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12697:
12698: while (my $configline=<$config>) {
1.483 albertel 12699: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12700: chomp($configline);
12701: my ($short,$plain)=split(/:/,$configline);
12702: my ($pack,$name)=split(/\&/,$short);
12703: if ($plain ne '') {
12704: $packagetab{$pack.'&'.$name.'&name'}=$name;
12705: $packagetab{$short}=$plain;
12706: }
1.11 www 12707: }
1.448 albertel 12708: close($config);
1.329 matthew 12709: }
12710:
1.1073 raeburn 12711: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12712:
12713: &load_loncaparevs();
1.1073 raeburn 12714:
1.1074 raeburn 12715: # ---------------------------------------------------------- Read serverhostID table
12716:
1.1227 raeburn 12717: &load_serverhomeIDs();
12718:
12719: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12720: {
12721: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12722: if (-e $file) {
12723: my $parser = HTML::LCParser->new($file);
12724: while (my $token = $parser->get_token()) {
12725: if ($token->[0] eq 'S') {
12726: my $item = $token->[1];
12727: my $name = $token->[2]{'name'};
12728: my $value = $token->[2]{'value'};
12729: if ($item ne '' && $name ne '' && $value ne '') {
12730: my $release = $parser->get_text();
12731: $release =~ s/(^\s*|\s*$ )//gx;
12732: $needsrelease{$item.':'.$name.':'.$value} = $release;
12733: }
12734: }
12735: }
12736: }
1.1073 raeburn 12737: }
12738:
1.1138 raeburn 12739: # ---------------------------------------------------------- Read managers table
12740: {
12741: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12742: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12743: while (my $configline=<$config>) {
12744: chomp($configline);
12745: next if ($configline =~ /^\#/);
12746: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12747: $managerstab{$configline} = 1;
12748: }
12749: }
12750: close($config);
12751: }
12752: }
12753: }
12754:
1.329 matthew 12755: # ------------- set up temporary directory
12756: {
1.1117 foxr 12757: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12758:
1.11 www 12759: }
12760:
1.794 albertel 12761: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12762: 'compress_threshold'=> 20_000,
12763: });
1.185 www 12764:
1.281 www 12765: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12766: $dumpcount=0;
1.958 www 12767: $locknum=0;
1.22 www 12768:
1.163 harris41 12769: &logtouch();
1.672 albertel 12770: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12771: $readit=1;
1.564 albertel 12772: {
12773: use integer;
12774: my $test=(2**32)+1;
1.568 albertel 12775: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12776: &logthis(" Detected 64bit platform ($_64bit)");
12777: }
1.195 www 12778: }
1.1 albertel 12779: }
1.179 www 12780:
1.1 albertel 12781: 1;
1.191 harris41 12782: __END__
12783:
1.243 albertel 12784: =pod
12785:
1.191 harris41 12786: =head1 NAME
12787:
1.243 albertel 12788: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12789:
12790: =head1 SYNOPSIS
12791:
1.243 albertel 12792: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12793:
12794: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12795:
1.243 albertel 12796: Common parameters:
12797:
12798: =over 4
12799:
12800: =item *
12801:
12802: $uname : an internal username (if $cname expecting a course Id specifically)
12803:
12804: =item *
12805:
12806: $udom : a domain (if $cdom expecting a course's domain specifically)
12807:
12808: =item *
12809:
12810: $symb : a resource instance identifier
12811:
12812: =item *
12813:
12814: $namespace : the name of a .db file that contains the data needed or
12815: being set.
12816:
12817: =back
12818:
1.394 bowersj2 12819: =head1 OVERVIEW
1.191 harris41 12820:
1.394 bowersj2 12821: lonnet provides subroutines which interact with the
12822: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12823: about classes, users, and resources.
1.243 albertel 12824:
12825: For many of these objects you can also use this to store data about
12826: them or modify them in various ways.
1.191 harris41 12827:
1.394 bowersj2 12828: =head2 Symbs
1.191 harris41 12829:
1.394 bowersj2 12830: To identify a specific instance of a resource, LON-CAPA uses symbols
12831: or "symbs"X<symb>. These identifiers are built from the URL of the
12832: map, the resource number of the resource in the map, and the URL of
12833: the resource itself. The latter is somewhat redundant, but might help
12834: if maps change.
12835:
12836: An example is
12837:
12838: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12839:
12840: The respective map entry is
12841:
12842: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12843: title="Problem 2">
12844: </resource>
12845:
12846: Symbs are used by the random number generator, as well as to store and
12847: restore data specific to a certain instance of for example a problem.
12848:
12849: =head2 Storing And Retrieving Data
12850:
12851: X<store()>X<cstore()>X<restore()>Three of the most important functions
12852: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12853: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12854: is is the non-critical message twin of cstore. These functions are for
12855: handlers to store a perl hash to a user's permanent data space in an
12856: easy manner, and to retrieve it again on another call. It is expected
12857: that a handler would use this once at the beginning to retrieve data,
12858: and then again once at the end to send only the new data back.
12859:
12860: The data is stored in the user's data directory on the user's
12861: homeserver under the ID of the course.
12862:
12863: The hash that is returned by restore will have all of the previous
12864: value for all of the elements of the hash.
12865:
12866: Example:
12867:
12868: #creating a hash
12869: my %hash;
12870: $hash{'foo'}='bar';
12871:
12872: #storing it
12873: &Apache::lonnet::cstore(\%hash);
12874:
12875: #changing a value
12876: $hash{'foo'}='notbar';
12877:
12878: #adding a new value
12879: $hash{'bar'}='foo';
12880: &Apache::lonnet::cstore(\%hash);
12881:
12882: #retrieving the hash
12883: my %history=&Apache::lonnet::restore();
12884:
12885: #print the hash
12886: foreach my $key (sort(keys(%history))) {
12887: print("\%history{$key} = $history{$key}");
12888: }
12889:
12890: Will print out:
1.191 harris41 12891:
1.394 bowersj2 12892: %history{1:foo} = bar
12893: %history{1:keys} = foo:timestamp
12894: %history{1:timestamp} = 990455579
12895: %history{2:bar} = foo
12896: %history{2:foo} = notbar
12897: %history{2:keys} = foo:bar:timestamp
12898: %history{2:timestamp} = 990455580
12899: %history{bar} = foo
12900: %history{foo} = notbar
12901: %history{timestamp} = 990455580
12902: %history{version} = 2
12903:
12904: Note that the special hash entries C<keys>, C<version> and
12905: C<timestamp> were added to the hash. C<version> will be equal to the
12906: total number of versions of the data that have been stored. The
12907: C<timestamp> attribute will be the UNIX time the hash was
12908: stored. C<keys> is available in every historical section to list which
12909: keys were added or changed at a specific historical revision of a
12910: hash.
12911:
12912: B<Warning>: do not store the hash that restore returns directly. This
12913: will cause a mess since it will restore the historical keys as if the
12914: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12915:
1.394 bowersj2 12916: Calling convention:
1.191 harris41 12917:
1.1225 raeburn 12918: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 12919: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 12920:
1.394 bowersj2 12921: For more detailed information, see lonnet specific documentation.
1.191 harris41 12922:
1.394 bowersj2 12923: =head1 RETURN MESSAGES
1.191 harris41 12924:
1.394 bowersj2 12925: =over 4
1.191 harris41 12926:
1.394 bowersj2 12927: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12928:
1.394 bowersj2 12929: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12930: when the connection is brought back up
1.191 harris41 12931:
1.394 bowersj2 12932: =item * B<con_failed>: unable to contact remote host and unable to save message
12933: for later delivery
1.191 harris41 12934:
1.967 bisitz 12935: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12936:
1.394 bowersj2 12937: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12938: that was requested
1.191 harris41 12939:
1.243 albertel 12940: =back
1.191 harris41 12941:
1.243 albertel 12942: =head1 PUBLIC SUBROUTINES
1.191 harris41 12943:
1.243 albertel 12944: =head2 Session Environment Functions
1.191 harris41 12945:
1.243 albertel 12946: =over 4
1.191 harris41 12947:
1.394 bowersj2 12948: =item *
12949: X<appenv()>
1.949 raeburn 12950: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12951: the user envirnoment file, and will be restored for each access this
1.620 albertel 12952: user makes during this session, also modifies the %env for the current
1.949 raeburn 12953: process. Optional rolesarrayref - if defined contains a reference to an array
12954: of roles which are exempt from the restriction on modifying user.role entries
12955: in the user's environment.db and in %env.
1.191 harris41 12956:
12957: =item *
1.394 bowersj2 12958: X<delenv()>
1.987 raeburn 12959: B<delenv($delthis,$regexp)>: removes all items from the session
12960: environment file that begin with $delthis. If the
12961: optional second arg - $regexp - is true, $delthis is treated as a
12962: regular expression, otherwise \Q$delthis\E is used.
12963: The values are also deleted from the current processes %env.
1.191 harris41 12964:
1.795 albertel 12965: =item * get_env_multiple($name)
12966:
12967: gets $name from the %env hash, it seemlessly handles the cases where multiple
12968: values may be defined and end up as an array ref.
12969:
12970: returns an array of values
12971:
1.243 albertel 12972: =back
12973:
12974: =head2 User Information
1.191 harris41 12975:
1.243 albertel 12976: =over 4
1.191 harris41 12977:
12978: =item *
1.394 bowersj2 12979: X<queryauthenticate()>
12980: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12981: authentication scheme
12982:
12983: =item *
1.394 bowersj2 12984: X<authenticate()>
1.1073 raeburn 12985: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12986: authenticate user from domain's lib servers (first use the current
12987: one). C<$upass> should be the users password.
1.1073 raeburn 12988: $checkdefauth is optional (value is 1 if a check should be made to
12989: authenticate user using default authentication method, and allow
12990: account creation if username does not have account in the domain).
12991: $clientcancheckhost is optional (value is 1 if checking whether the
12992: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12993:
12994: =item *
1.394 bowersj2 12995: X<homeserver()>
12996: B<homeserver($uname,$udom)>: find the server which has
12997: the user's directory and files (there must be only one), this caches
12998: the answer, and also caches if there is a borken connection.
1.191 harris41 12999:
13000: =item *
1.394 bowersj2 13001: X<idget()>
13002: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13003: (IDs are a unique resource in a domain, there must be only 1 ID per
13004: username, and only 1 username per ID in a specific domain) (returns
13005: hash: id=>name,id=>name)
1.191 harris41 13006:
13007: =item *
1.394 bowersj2 13008: X<idrget()>
13009: B<idrget($udom,@unames)>: find the IDs behind a list of
13010: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13011:
13012: =item *
1.394 bowersj2 13013: X<idput()>
13014: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13015:
13016: =item *
1.394 bowersj2 13017: X<rolesinit()>
1.1169 droeschl 13018: B<rolesinit($udom,$username)>: get user privileges.
13019: returns user role, first access and timer interval hashes
1.243 albertel 13020:
13021: =item *
1.1171 droeschl 13022: X<privileged()>
13023: B<privileged($username,$domain)>: returns a true if user has a
13024: privileged and active role (i.e. su or dc), false otherwise.
13025:
13026: =item *
1.551 albertel 13027: X<getsection()>
13028: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13029: course $cname, return section name/number or '' for "not in course"
13030: and '-1' for "no section"
13031:
13032: =item *
1.394 bowersj2 13033: X<userenvironment()>
13034: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13035: passed in @what from the requested user's environment, returns a hash
13036:
1.858 raeburn 13037: =item *
13038: X<userlog_query()>
1.859 albertel 13039: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13040: activity.log file. %filters defines filters applied when parsing the
13041: log file. These can be start or end timestamps, or the type of action
13042: - log to look for Login or Logout events, check for Checkin or
13043: Checkout, role for role selection. The response is in the form
13044: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13045: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13046:
1.243 albertel 13047: =back
13048:
13049: =head2 User Roles
13050:
13051: =over 4
13052:
13053: =item *
13054:
1.1282 ! raeburn 13055: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 13056: F: full access
13057: U,I,K: authentication modes (cxx only)
13058: '': forbidden
13059: 1: user needs to choose course
13060: 2: browse allowed
1.766 albertel 13061: A: passphrase authentication needed
1.243 albertel 13062:
13063: =item *
13064:
1.1192 raeburn 13065: constructaccess($url,$setpriv) : check for access to construction space URL
13066:
13067: See if the owner domain and name in the URL match those in the
13068: expected environment. If so, return three element list
13069: ($ownername,$ownerdomain,$ownerhome).
13070:
13071: Otherwise return the null string.
13072:
13073: If second argument 'setpriv' is true, it assigns the privileges,
13074: and returns the same three element list, unless the owner has
13075: blocked "ad hoc" Domain Coordinator access to the Author Space,
13076: in which case the null string is returned.
13077:
13078: =item *
13079:
1.243 albertel 13080: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13081: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13082: and course level
13083:
13084: =item *
13085:
1.988 raeburn 13086: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13087: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13088: $type is Course (default) or Community.
1.988 raeburn 13089: If $forcedefault evaluates to true, text returned will be default
13090: text for $type. Otherwise, if this is a course, the text returned
13091: will be a custom name for the role (if defined in the course's
13092: environment). If no custom name is defined the default is returned.
13093:
1.832 raeburn 13094: =item *
13095:
1.1219 raeburn 13096: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13097: All arguments are optional. Returns a hash of a roles, either for
13098: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13099: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13100: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13101: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13102: For each key, value is set to colon-separated start and end times for
13103: the role. If no username and domain are specified, will default to
1.934 raeburn 13104: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13105: of role statuses (active, future or previous), roles
13106: (e.g., cc,in, st etc.) and domains of the roles which can be used
13107: to restrict the list of roles reported. If no array ref is
13108: provided for types, will default to return only active roles.
1.834 albertel 13109:
1.1195 raeburn 13110: =item *
13111:
13112: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 13113: user: $uname:$udom has a role in the course: $cdom_$cnum.
13114:
13115: Additional optional arguments are: $type (if role checking is to be restricted
13116: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13117: available roles) or future (roles available in the future), and
13118: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13119: have active Domain Coordinator role in course's domain or in additional
13120: domains (specified in 'Domains to check for privileged users' in course
13121: environment -- set via: Course Settings -> Classlists and staff listing).
13122:
13123: =item *
13124:
13125: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13126: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13127: $possdomains and $possroles are optional array refs -- to domains to check and
13128: roles to check. If $possdomains is not specified, a dump will be done of the
13129: users' roles.db to check for a dc or su role in any domain. This can be
13130: time consuming if &privileged is called repeatedly (e.g., when displaying a
13131: classlist), so in such cases, supplying a $possdomains array is preferred, as
13132: this then allows &privileged_by_domain() to be used, which caches the identity
13133: of privileged users, eliminating the need for repeated calls to &dump().
13134:
13135: =item *
13136:
13137: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13138: where the outer hash keys are domains specified in the $possdomains array ref,
13139: next inner hash keys are privileged roles specified in the $roles array ref,
13140: and the innermost hash contains key = value pairs for username:domain = end:start
13141: for active or future "privileged" users with that role in that domain. To avoid
13142: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13143: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13144:
1.243 albertel 13145: =back
13146:
13147: =head2 User Modification
13148:
13149: =over 4
13150:
13151: =item *
13152:
1.957 raeburn 13153: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13154: user for the level given by URL. Optional start and end dates (leave empty
13155: string or zero for "no date")
1.191 harris41 13156:
13157: =item *
13158:
1.243 albertel 13159: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13160: change a users, password, possible return values are: ok,
13161: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13162: refused
1.191 harris41 13163:
13164: =item *
13165:
1.243 albertel 13166: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13167:
13168: =item *
13169:
1.1058 raeburn 13170: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13171: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13172:
13173: will update user information (firstname,middlename,lastname,generation,
13174: permanentemail), and if forceid is true, student/employee ID also.
13175: A user's institutional affiliation(s) can also be updated.
13176: User information fields will not be overwritten with empty entries
13177: unless the field is included in the $candelete array reference.
13178: This array is included when a single user is modified via "Manage Users",
13179: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13180:
13181: =item *
13182:
1.286 matthew 13183: modifystudent
13184:
1.957 raeburn 13185: modify a student's enrollment and identification information.
1.1235 raeburn 13186: The course id is resolved based on the current user's environment.
13187: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13188: associated with a course.
13189:
1.297 matthew 13190: This call is essentially a wrapper for lonnet::modifyuser and
13191: lonnet::modify_student_enrollment
1.286 matthew 13192:
13193: Inputs:
13194:
13195: =over 4
13196:
1.957 raeburn 13197: =item B<$udom> Student's loncapa domain
1.286 matthew 13198:
1.957 raeburn 13199: =item B<$uname> Student's loncapa login name
1.286 matthew 13200:
1.964 bisitz 13201: =item B<$uid> Student/Employee ID
1.286 matthew 13202:
1.957 raeburn 13203: =item B<$umode> Student's authentication mode
1.286 matthew 13204:
1.957 raeburn 13205: =item B<$upass> Student's password
1.286 matthew 13206:
1.957 raeburn 13207: =item B<$first> Student's first name
1.286 matthew 13208:
1.957 raeburn 13209: =item B<$middle> Student's middle name
1.286 matthew 13210:
1.957 raeburn 13211: =item B<$last> Student's last name
1.286 matthew 13212:
1.957 raeburn 13213: =item B<$gene> Student's generation
1.286 matthew 13214:
1.957 raeburn 13215: =item B<$usec> Student's section in course
1.286 matthew 13216:
13217: =item B<$end> Unix time of the roles expiration
13218:
13219: =item B<$start> Unix time of the roles start date
13220:
13221: =item B<$forceid> If defined, allow $uid to be changed
13222:
13223: =item B<$desiredhome> server to use as home server for student
13224:
1.957 raeburn 13225: =item B<$email> Student's permanent e-mail address
13226:
13227: =item B<$type> Type of enrollment (auto or manual)
13228:
1.963 raeburn 13229: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13230:
13231: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13232:
1.963 raeburn 13233: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13234:
1.963 raeburn 13235: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13236:
1.1216 raeburn 13237: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13238:
13239: =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 13240:
1.286 matthew 13241: =back
1.297 matthew 13242:
13243: =item *
13244:
13245: modify_student_enrollment
13246:
1.1235 raeburn 13247: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13248: 'role.request.course' must be defined for this function to proceed.
13249:
13250: Inputs:
13251:
13252: =over 4
13253:
1.1235 raeburn 13254: =item $udom, student's domain
1.297 matthew 13255:
1.1235 raeburn 13256: =item $uname, student's name
1.297 matthew 13257:
1.1235 raeburn 13258: =item $uid, student's user id
1.297 matthew 13259:
1.1235 raeburn 13260: =item $first, student's first name
1.297 matthew 13261:
13262: =item $middle
13263:
13264: =item $last
13265:
13266: =item $gene
13267:
13268: =item $usec
13269:
13270: =item $end
13271:
13272: =item $start
13273:
1.957 raeburn 13274: =item $type
13275:
13276: =item $locktype
13277:
13278: =item $cid
13279:
13280: =item $selfenroll
13281:
13282: =item $context
13283:
1.1216 raeburn 13284: =item $credits, number of credits student will earn from this class
13285:
1.297 matthew 13286: =back
13287:
1.191 harris41 13288:
13289: =item *
13290:
1.243 albertel 13291: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13292: custom role; give a custom role to a user for the level given by URL. Specify
13293: name and domain of role author, and role name
1.191 harris41 13294:
13295: =item *
13296:
1.243 albertel 13297: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13298:
13299: =item *
13300:
1.243 albertel 13301: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13302:
13303: =back
13304:
13305: =head2 Course Infomation
13306:
13307: =over 4
1.191 harris41 13308:
13309: =item *
13310:
1.1118 foxr 13311: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13312: specified course id, including all environment settings for the
13313: course, the description of the course will be in the hash under the
13314: key 'description'
1.191 harris41 13315:
1.1118 foxr 13316: $options is an optional parameter that if supplied is a hash reference that controls
13317: what how this function works. It has the following key/values:
13318:
13319: =over 4
13320:
13321: =item freshen_cache
13322:
13323: If defined, and the environment cache for the course is valid, it is
13324: returned in the returned hash.
13325:
13326: =item one_time
13327:
13328: If defined, the last cache time is set to _now_
13329:
13330: =item user
13331:
13332: If defined, the supplied username is used instead of the current user.
13333:
13334:
13335: =back
13336:
1.191 harris41 13337: =item *
13338:
1.624 albertel 13339: resdata($name,$domain,$type,@which) : request for current parameter
13340: setting for a specific $type, where $type is either 'course' or 'user',
13341: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 13342: answers for 10 minutes.
1.243 albertel 13343:
1.877 foxr 13344: =item *
13345:
13346: get_courseresdata($courseid, $domain) : dump the entire course resource
13347: data base, returning a hash that is keyed by the resource name and has
13348: values that are the resource value. I believe that the timestamps and
13349: versions are also returned.
13350:
1.1236 raeburn 13351: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13352: supplemental content area. This routine caches the number of files for
13353: 10 minutes.
13354:
1.243 albertel 13355: =back
13356:
13357: =head2 Course Modification
13358:
13359: =over 4
1.191 harris41 13360:
13361: =item *
13362:
1.243 albertel 13363: writecoursepref($courseid,%prefs) : write preferences (environment
13364: database) for a course
1.191 harris41 13365:
13366: =item *
13367:
1.1011 raeburn 13368: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13369:
13370: =item *
13371:
1.1038 raeburn 13372: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13373:
1.1167 droeschl 13374: =item *
13375:
13376: is_course($courseid), is_course($cdom, $cnum)
13377:
13378: Accepts either a combined $courseid (in the form of domain_courseid) or the
13379: two component version $cdom, $cnum. It checks if the specified course exists.
13380:
13381: Returns:
13382: undef if the course doesn't exist, otherwise
13383: in scalar context the combined courseid.
13384: in list context the two components of the course identifier, domain and
13385: courseid.
13386:
1.243 albertel 13387: =back
13388:
13389: =head2 Resource Subroutines
13390:
13391: =over 4
1.191 harris41 13392:
13393: =item *
13394:
1.243 albertel 13395: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13396:
13397: =item *
13398:
1.243 albertel 13399: repcopy($filename) : subscribes to the requested file, and attempts to
13400: replicate from the owning library server, Might return
1.607 raeburn 13401: 'unavailable', 'not_found', 'forbidden', 'ok', or
13402: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13403: resource. Expects the local filesystem pathname
13404: (/home/httpd/html/res/....)
13405:
13406: =back
13407:
13408: =head2 Resource Information
13409:
13410: =over 4
1.191 harris41 13411:
13412: =item *
13413:
1.1228 raeburn 13414: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13415: and returns the value of a variety of different possible values,
13416: $varname should be a request string, and the other parameters can be
13417: used to specify who and what one is asking about. Ordinarily, $cid
13418: does not need to be specified, as it is retrived from
13419: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13420: within lonuserstate::loadmap() when initializing a course, before
13421: $env{'request.course.id'} has been set, so it needs to be provided
13422: in that one case.
1.243 albertel 13423:
13424: Possible values for $varname are environment.lastname (or other item
13425: from the envirnment hash), user.name (or someother aspect about the
13426: user), resource.0.maxtries (or some other part and parameter of a
13427: resource)
1.204 albertel 13428:
13429: =item *
13430:
1.243 albertel 13431: directcondval($number) : get current value of a condition; reads from a state
13432: string
1.204 albertel 13433:
13434: =item *
13435:
1.243 albertel 13436: condval($condidx) : value of condition index based on state
1.204 albertel 13437:
13438: =item *
13439:
1.243 albertel 13440: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13441: resource's metadata, $what should be either a specific key, or either
13442: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13443: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13444:
13445: this function automatically caches all requests
1.191 harris41 13446:
13447: =item *
13448:
1.243 albertel 13449: metadata_query($query,$custom,$customshow) : make a metadata query against the
13450: network of library servers; returns file handle of where SQL and regex results
13451: will be stored for query
1.191 harris41 13452:
13453: =item *
13454:
1.1282 ! raeburn 13455: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
! 13456: return symbolic list entry (all arguments optional).
! 13457:
! 13458: Args: filename is the filename (including path) for the file for which a symb
! 13459: is required; donotrecurse, if true will prevent calls to allowed() being made
! 13460: to check access status if more than one resource was found in the bighash
! 13461: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
! 13462: a randompick); ignorecachednull, if true will prevent a symb of '' being
! 13463: returned if $env{$cache_str} is defined as ''; checkforblock if true will
! 13464: cause possible symbs to be checked to determine if they are subject to content
! 13465: blocking, if so they will not be included as possible symbs; possibles is a
! 13466: ref to a hash, which, as a side effect, will be populated with all possible
! 13467: symbs (content blocking not tested).
! 13468:
1.243 albertel 13469: returns the data handle
1.191 harris41 13470:
13471: =item *
13472:
1.1190 raeburn 13473: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13474: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13475: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13476: on failure, user must be in a course, as it assumes the existence of
13477: the course initial hash, and uses $env('request.course.id'}. The third
13478: arg is an optional reference to a scalar. If this arg is passed in the
13479: call to symbverify, it will be set to 1 if the symb has been set to be
13480: encrypted; otherwise it will be null.
1.191 harris41 13481:
13482: =item *
13483:
1.243 albertel 13484: symbclean($symb) : removes versions numbers from a symb, returns the
13485: cleaned symb
1.191 harris41 13486:
13487: =item *
13488:
1.243 albertel 13489: is_on_map($uri) : checks if the $uri is somewhere on the current
13490: course map, user must be in a course for it to work.
1.191 harris41 13491:
13492: =item *
13493:
1.243 albertel 13494: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13495:
13496: =item *
13497:
1.243 albertel 13498: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13499: a random seed, all arguments are optional, if they aren't sent it uses the
13500: environment to derive them. Note: if symb isn't sent and it can't get one
13501: from &symbread it will use the current time as its return value
1.191 harris41 13502:
13503: =item *
13504:
1.243 albertel 13505: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13506: unfakeable, receipt
1.191 harris41 13507:
13508: =item *
13509:
1.620 albertel 13510: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13511:
13512: =item *
13513:
1.243 albertel 13514: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13515:
13516: =item *
13517:
1.243 albertel 13518: 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 13519:
13520: =item *
13521:
1.243 albertel 13522: 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 13523:
13524: =item *
13525:
1.243 albertel 13526: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13527:
13528: =item *
13529:
1.243 albertel 13530: devalidate($symb) : devalidate temporary spreadsheet calculations,
13531: forcing spreadsheet to reevaluate the resource scores next time.
13532:
1.1195 raeburn 13533: =item *
13534:
1.1196 raeburn 13535: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13536: when viewing in course context.
1.1195 raeburn 13537:
1.1196 raeburn 13538: input: six args -- filename (decluttered), course number, course domain,
13539: url, symb (if registered) and group (if this is a
13540: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13541:
1.1196 raeburn 13542: output: array of five scalars --
1.1195 raeburn 13543: $cfile -- url for file editing if editable on current server
13544: $home -- homeserver of resource (i.e., for author if published,
13545: or course if uploaded.).
13546: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13547: $forceedit -- 1 if icon/link should be to go to edit mode
13548: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13549:
13550: =item *
13551:
13552: is_course_upload($file,$cnum,$cdom)
13553:
13554: Used in course context to determine if current file was uploaded to
13555: the course (i.e., would be found in /userfiles/docs on the course's
13556: homeserver.
13557:
13558: input: 3 args -- filename (decluttered), course number and course domain.
13559: output: boolean -- 1 if file was uploaded.
13560:
1.243 albertel 13561: =back
13562:
13563: =head2 Storing/Retreiving Data
13564:
13565: =over 4
1.191 harris41 13566:
13567: =item *
13568:
1.1269 raeburn 13569: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13570: permanently for this url; hashref needs to be given and should be a \%hashname;
13571: the remaining args aren't required and if they aren't passed or are '' they will
13572: be derived from the env (with the exception of $laststore, which is an
13573: optional arg used when a user's submission is stored in grading).
13574: $laststore is $version=$timestamp, where $version is the most recent version
13575: number retrieved for the corresponding $symb in the $namespace db file, and
13576: $timestamp is the timestamp for that transaction (UNIX time).
13577: $laststore is currently only passed when cstore() is called by
13578: structuretags::finalize_storage().
1.191 harris41 13579:
13580: =item *
13581:
1.1269 raeburn 13582: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13583: but uses critical subroutine
1.191 harris41 13584:
13585: =item *
13586:
1.243 albertel 13587: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13588: all args are optional
1.191 harris41 13589:
13590: =item *
13591:
1.717 albertel 13592: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13593: dumps the complete (or key matching regexp) namespace into a hash
13594: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13595: normally &store()ed into
13596:
13597: $range should be either an integer '100' (give me the first 100
13598: matching records)
13599: or be two integers sperated by a - with no spaces
13600: '30-50' (give me the 30th through the 50th matching
13601: records)
13602:
13603:
13604: =item *
13605:
1.1269 raeburn 13606: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13607: replaces a &store() version of data with a replacement set of data
13608: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 13609: reference. If $tolog is true, the transaction is logged in the courselog
13610: with an action=PUTSTORE.
1.717 albertel 13611:
13612: =item *
13613:
1.243 albertel 13614: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13615: works very similar to store/cstore, but all data is stored in a
13616: temporary location and can be reset using tmpreset, $storehash should
13617: be a hash reference, returns nothing on success
1.191 harris41 13618:
13619: =item *
13620:
1.243 albertel 13621: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13622: similar to restore, but all data is stored in a temporary location and
13623: can be reset using tmpreset. Returns a hash of values on success,
13624: error string otherwise.
1.191 harris41 13625:
13626: =item *
13627:
1.243 albertel 13628: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13629: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13630:
13631: =item *
13632:
1.243 albertel 13633: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13634: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13635:
13636: =item *
13637:
1.243 albertel 13638: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13639: namesp ($udom and $uname are optional)
1.191 harris41 13640:
13641: =item *
13642:
1.702 albertel 13643: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13644: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13645: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13646:
1.702 albertel 13647: $range should be either an integer '100' (give me the first 100
13648: matching records)
13649: or be two integers sperated by a - with no spaces
13650: '30-50' (give me the 30th through the 50th matching
13651: records)
1.449 matthew 13652: =item *
13653:
13654: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13655: $store can be a scalar, an array reference, or if the amount to be
13656: incremented is > 1, a hash reference.
13657:
13658: ($udom and $uname are optional)
1.191 harris41 13659:
13660: =item *
13661:
1.243 albertel 13662: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13663: ($udom and $uname are optional)
1.191 harris41 13664:
13665: =item *
13666:
1.243 albertel 13667: cput($namespace,$storehash,$udom,$uname) : critical put
13668: ($udom and $uname are optional)
1.191 harris41 13669:
13670: =item *
13671:
1.748 albertel 13672: newput($namespace,$storehash,$udom,$uname) :
13673:
13674: Attempts to store the items in the $storehash, but only if they don't
13675: currently exist, if this succeeds you can be certain that you have
13676: successfully created a new key value pair in the $namespace db.
13677:
13678:
13679: Args:
13680: $namespace: name of database to store values to
13681: $storehash: hashref to store to the db
13682: $udom: (optional) domain of user containing the db
13683: $uname: (optional) name of user caontaining the db
13684:
13685: Returns:
13686: 'ok' -> succeeded in storing all keys of $storehash
13687: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13688: least <key> already existed in the db (other
13689: requested keys may also already exist)
1.967 bisitz 13690: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13691: 'con_lost' -> unable to contact request server
13692: 'refused' -> action was not allowed by remote machine
13693:
13694:
13695: =item *
13696:
1.243 albertel 13697: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13698: reference filled in from namesp (encrypts the return communication)
13699: ($udom and $uname are optional)
1.191 harris41 13700:
13701: =item *
13702:
1.243 albertel 13703: log($udom,$name,$home,$message) : write to permanent log for user; use
13704: critical subroutine
13705:
1.806 raeburn 13706: =item *
13707:
1.860 raeburn 13708: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13709: array reference filled in from namespace found in domain level on either
13710: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13711:
13712: =item *
13713:
1.860 raeburn 13714: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13715: domain level either on specified domain server ($uhome) or primary domain
13716: server ($udom and $uhome are optional)
1.806 raeburn 13717:
1.943 raeburn 13718: =item *
13719:
1.1240 raeburn 13720: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13721: for: authentication, language, quotas, timezone, date locale, and portal URL in
13722: the target domain.
13723:
13724: May also include additional key => value pairs for the following groups:
13725:
13726: =over
13727:
13728: =item
13729: disk quotas (MB allocated by default to portfolios and authoring spaces).
13730:
13731: =over
13732:
13733: =item defaultquota, authorquota
13734:
13735: =back
13736:
13737: =item
13738: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13739: portfolio for users).
13740:
13741: =over
13742:
13743: =item
13744: aboutme, blog, webdav, portfolio
13745:
13746: =back
13747:
13748: =item
13749: requestcourses: ability to request courses, and how requests are processed.
13750:
13751: =over
13752:
13753: =item
1.1246 raeburn 13754: official, unofficial, community, textbook
1.1240 raeburn 13755:
13756: =back
13757:
13758: =item
13759: inststatus: types of institutional affiliation, and order in which they are displayed.
13760:
13761: =over
13762:
13763: =item
1.1256 raeburn 13764: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 13765:
13766: =back
13767:
13768: =item
13769: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13770: for course's uploaded content.
13771:
13772: =over
13773:
13774: =item
1.1246 raeburn 13775: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13776: communityquota, textbookquota
1.1240 raeburn 13777:
13778: =back
13779:
13780: =item
13781: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13782: on your servers.
13783:
13784: =over
13785:
13786: =item
13787: remotesessions, hostedsessions
13788:
13789: =back
13790:
13791: =back
13792:
13793: In cases where a domain coordinator has never used the "Set Domain Configuration"
13794: utility to create a configuration.db file on a domain's primary library server
13795: only the following domain defaults: auth_def, auth_arg_def, lang_def
13796: -- corresponding values are authentication type (internal, krb4, krb5,
13797: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13798: will be available. Values are retrieved from cache (if current), unless the
13799: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13800: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13801:
13802: Typical usage:
1.943 raeburn 13803:
1.1240 raeburn 13804: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13805:
1.243 albertel 13806: =back
13807:
13808: =head2 Network Status Functions
13809:
13810: =over 4
1.191 harris41 13811:
13812: =item *
13813:
1.1137 raeburn 13814: dirlist() : return directory list based on URI (first arg).
13815:
13816: Inputs: 1 required, 5 optional.
13817:
13818: =over
13819:
13820: =item
13821: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13822:
13823: =item
13824: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13825:
13826: =item
13827: $username - username of user/course to be listed. Extracted from $uri if absent.
13828:
13829: =item
13830: $getpropath - boolean: 1 if prepend path using &propath().
13831:
13832: =item
13833: $getuserdir - boolean: 1 if prepend path for "userfiles".
13834:
13835: =item
13836: $alternateRoot - path to prepend in place of path from $uri.
13837:
13838: =back
13839:
13840: Returns: Array of up to two items.
13841:
13842: =over
13843:
13844: a reference to an array of files/subdirectories
13845:
13846: =over
13847:
13848: Each element in the array of files/subdirectories is a & separated list of
13849: item name and the result of running stat on the item. If dirlist was requested
13850: for a file instead of a directory, the item name will be ''. For a directory
13851: listing, if the item is a metadata file, the element will end &N&M
13852: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13853: default copyright set (1).
13854:
13855: =back
13856:
13857: a scalar containing error condition (if encountered).
13858:
13859: =over
13860:
13861: =item
13862: no_host (no homeserver identified for $username:$domain).
13863:
13864: =item
13865: no_such_host (server contacted for listing not identified as valid host).
13866:
13867: =item
13868: con_lost (connection to remote server failed).
13869:
13870: =item
13871: refused (invalid $username:$domain received on lond side).
13872:
13873: =item
13874: no_such_dir (directory at specified path on lond side does not exist).
13875:
13876: =item
13877: empty (directory at specified path on lond side is empty).
13878:
13879: =over
13880:
13881: This is currently not encountered because the &ls3, &ls2,
13882: &ls (_handler) routines on the lond side do not filter out
13883: . and .. from a directory listing.
13884:
13885: =back
13886:
13887: =back
13888:
13889: =back
1.191 harris41 13890:
13891: =item *
13892:
1.243 albertel 13893: spareserver() : find server with least workload from spare.tab
13894:
1.986 foxr 13895:
13896: =item *
13897:
13898: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13899: if there is no corresponding loncapa host.
13900:
1.243 albertel 13901: =back
13902:
1.986 foxr 13903:
1.243 albertel 13904: =head2 Apache Request
13905:
13906: =over 4
1.191 harris41 13907:
13908: =item *
13909:
1.243 albertel 13910: ssi($url,%hash) : server side include, does a complete request cycle on url to
13911: localhost, posts hash
13912:
13913: =back
13914:
13915: =head2 Data to String to Data
13916:
13917: =over 4
1.191 harris41 13918:
13919: =item *
13920:
1.243 albertel 13921: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13922: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13923:
13924: =item *
13925:
1.243 albertel 13926: hashref2str($hashref) : convert a hashref into a string complete with
13927: escaping and '=' and '&' separators, supports elements that are
13928: arrayrefs and hashrefs
1.191 harris41 13929:
13930: =item *
13931:
1.243 albertel 13932: arrayref2str($arrayref) : convert an arrayref into a string complete
13933: with escaping and '&' separators, supports elements that are arrayrefs
13934: and hashrefs
1.191 harris41 13935:
13936: =item *
13937:
1.243 albertel 13938: str2hash($string) : convert string to hash using unescaping and
13939: splitting on '=' and '&', supports elements that are arrayrefs and
13940: hashrefs
1.191 harris41 13941:
13942: =item *
13943:
1.243 albertel 13944: str2array($string) : convert string to hash using unescaping and
13945: splitting on '&', supports elements that are arrayrefs and hashrefs
13946:
13947: =back
13948:
13949: =head2 Logging Routines
13950:
13951:
13952: These routines allow one to make log messages in the lonnet.log and
13953: lonnet.perm logfiles.
1.191 harris41 13954:
1.1119 foxr 13955: =over 4
13956:
1.191 harris41 13957: =item *
13958:
1.243 albertel 13959: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13960:
13961: =item *
13962:
1.243 albertel 13963: logthis() : append message to the normal lonnet.log file, it gets
13964: preiodically rolled over and deleted.
1.191 harris41 13965:
13966: =item *
13967:
1.243 albertel 13968: logperm() : append a permanent message to lonnet.perm.log, this log
13969: file never gets deleted by any automated portion of the system, only
13970: messages of critical importance should go in here.
13971:
1.1119 foxr 13972:
1.243 albertel 13973: =back
13974:
13975: =head2 General File Helper Routines
13976:
13977: =over 4
1.191 harris41 13978:
13979: =item *
13980:
1.481 raeburn 13981: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13982: (a) files in /uploaded
13983: (i) If a local copy of the file exists -
13984: compares modification date of local copy with last-modified date for
13985: definitive version stored on home server for course. If local copy is
13986: stale, requests a new version from the home server and stores it.
13987: If the original has been removed from the home server, then local copy
13988: is unlinked.
13989: (ii) If local copy does not exist -
13990: requests the file from the home server and stores it.
13991:
13992: If $caller is 'uploadrep':
13993: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13994: for request for files originally uploaded via DOCS.
13995: - returns 'ok' if fresh local copy now available, -1 otherwise.
13996:
13997: Otherwise:
13998: This indicates a call from the content generation phase of the request.
13999: - returns the entire contents of the file or -1.
14000:
14001: (b) files in /res
14002: - returns the entire contents of a file or -1;
14003: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14004:
1.712 albertel 14005:
14006: =item *
14007:
14008: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14009: reference
14010:
14011: returns either a stat() list of data about the file or an empty list
14012: if the file doesn't exist or couldn't find out about it (connection
14013: problems or user unknown)
14014:
1.191 harris41 14015: =item *
14016:
1.243 albertel 14017: filelocation($dir,$file) : returns file system location of a file
14018: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14019: directory that relative $file lookups are to looked in ($dir of /a/dir
14020: and a file of ../bob will become /a/bob)
1.191 harris41 14021:
14022: =item *
14023:
14024: hreflocation($dir,$file) : returns file system location or a URL; same as
14025: filelocation except for hrefs
14026:
14027: =item *
14028:
1.1261 raeburn 14029: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14030: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14031:
1.243 albertel 14032: =back
14033:
1.608 albertel 14034: =head2 Usererfile file routines (/uploaded*)
14035:
14036: =over 4
14037:
14038: =item *
14039:
14040: userfileupload(): main rotine for putting a file in a user or course's
14041: filespace, arguments are,
14042:
1.620 albertel 14043: formname - required - this is the name of the element in $env where the
1.608 albertel 14044: filename, and the contents of the file to create/modifed exist
1.620 albertel 14045: the filename is in $env{'form.'.$formname.'.filename'} and the
14046: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14047: context - if coursedoc, store the file in the course of the active role
14048: of the current user;
14049: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14050: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14051: subdir - required - subdirectory to put the file in under ../userfiles/
14052: if undefined, it will be placed in "unknown"
14053:
14054: (This routine calls clean_filename() to remove any dangerous
14055: characters from the filename, and then calls finuserfileupload() to
14056: complete the transaction)
14057:
14058: returns either the url of the uploaded file (/uploaded/....) if successful
14059: and /adm/notfound.html if unsuccessful
14060:
14061: =item *
14062:
14063: clean_filename(): routine for cleaing a filename up for storage in
14064: userfile space, argument is:
14065:
14066: filename - proposed filename
14067:
14068: returns: the new clean filename
14069:
14070: =item *
14071:
1.1090 raeburn 14072: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14073: userspace, probably shouldn't be called directly
14074:
14075: docuname: username or courseid of destination for the file
14076: docudom: domain of user/course of destination for the file
14077: formname: same as for userfileupload()
1.1090 raeburn 14078: fname: filename (including subdirectories) for the file
14079: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14080: allfiles: reference to hash used to store objects found by parser
14081: codebase: reference to hash used for codebases of java objects found by parser
14082: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14083: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14084: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14085: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14086: context: if 'overwrite', will move the uploaded file from its temporary location to
14087: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14088: mimetype: reference to scalar to accommodate mime type determined
14089: from File::MMagic if $parser = parse.
1.608 albertel 14090:
14091: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14092: and /adm/notfound.html if unsuccessful (or an error message if context
14093: was 'overwrite').
14094:
1.608 albertel 14095:
14096: =item *
14097:
14098: renameuserfile(): renames an existing userfile to a new name
14099:
14100: Args:
14101: docuname: username or courseid of destination for the file
14102: docudom: domain of user/course of destination for the file
14103: old: current file name (including any subdirs under userfiles)
14104: new: desired file name (including any subdirs under userfiles)
14105:
14106: =item *
14107:
14108: mkdiruserfile(): creates a directory is a userfiles dir
14109:
14110: Args:
14111: docuname: username or courseid of destination for the file
14112: docudom: domain of user/course of destination for the file
14113: dir: dir to create (including any subdirs under userfiles)
14114:
14115: =item *
14116:
14117: removeuserfile(): removes a file that exists in userfiles
14118:
14119: Args:
14120: docuname: username or courseid of destination for the file
14121: docudom: domain of user/course of destination for the file
14122: fname: filname to delete (including any subdirs under userfiles)
14123:
14124: =item *
14125:
14126: removeuploadedurl(): convience function for removeuserfile()
14127:
14128: Args:
14129: url: a full /uploaded/... url to delete
14130:
1.747 albertel 14131: =item *
14132:
14133: get_portfile_permissions():
14134: Args:
14135: domain: domain of user or course contain the portfolio files
14136: user: name of user or num of course contain the portfolio files
14137: Returns:
14138: hashref of a dump of the proper file_permissions.db
14139:
14140:
14141: =item *
14142:
14143: get_access_controls():
14144:
14145: Args:
14146: current_permissions: the hash ref returned from get_portfile_permissions()
14147: group: (optional) the group you want the files associated with
14148: file: (optional) the file you want access info on
14149:
14150: Returns:
1.749 raeburn 14151: a hash (keys are file names) of hashes containing
14152: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14153: values are XML containing access control settings (see below)
1.747 albertel 14154:
14155: Internal notes:
14156:
1.749 raeburn 14157: access controls are stored in file_permissions.db as key=value pairs.
14158: key -> path to file/file_name\0uniqueID:scope_end_start
14159: where scope -> public,guest,course,group,domains or users.
14160: end -> UNIX time for end of access (0 -> no end date)
14161: start -> UNIX time for start of access
14162:
14163: value -> XML description of access control
14164: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14165: <start></start>
14166: <end></end>
14167:
14168: <password></password> for scope type = guest
14169:
14170: <domain></domain> for scope type = course or group
14171: <number></number>
14172: <roles id="">
14173: <role></role>
14174: <access></access>
14175: <section></section>
14176: <group></group>
14177: </roles>
14178:
14179: <dom></dom> for scope type = domains
14180:
14181: <users> for scope type = users
14182: <user>
14183: <uname></uname>
14184: <udom></udom>
14185: </user>
14186: </users>
14187: </scope>
14188:
14189: Access data is also aggregated for each file in an additional key=value pair:
14190: key -> path to file/file_name\0accesscontrol
14191: value -> reference to hash
14192: hash contains key = value pairs
14193: where key = uniqueID:scope_end_start
14194: value = UNIX time record was last updated
14195:
14196: Used to improve speed of look-ups of access controls for each file.
14197:
14198: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14199:
1.1198 raeburn 14200: =item *
14201:
1.749 raeburn 14202: modify_access_controls():
14203:
14204: Modifies access controls for a portfolio file
14205: Args
14206: 1. file name
14207: 2. reference to hash of required changes,
14208: 3. domain
14209: 4. username
14210: where domain,username are the domain of the portfolio owner
14211: (either a user or a course)
14212:
14213: Returns:
14214: 1. result of additions or updates ('ok' or 'error', with error message).
14215: 2. result of deletions ('ok' or 'error', with error message).
14216: 3. reference to hash of any new or updated access controls.
14217: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14218: key = integer (inbound ID)
1.1198 raeburn 14219: value = uniqueID
14220:
14221: =item *
14222:
14223: get_timebased_id():
14224:
14225: Attempts to get a unique timestamp-based suffix for use with items added to a
14226: course via the Course Editor (e.g., folders, composite pages,
14227: group bulletin boards).
14228:
14229: Args: (first three required; six others optional)
14230:
14231: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14232: docssequence, or name of group
14233:
14234: 2. keyid (alphanumeric): name of temporary locking key in hash,
14235: e.g., num, boardids
14236:
14237: 3. namespace: name of gdbm file used to store suffixes already assigned;
14238: file will be named nohist_namespace.db
14239:
14240: 4. cdom: domain of course; default is current course domain from %env
14241:
14242: 5. cnum: course number; default is current course number from %env
14243:
14244: 6. idtype: set to concat if an additional digit is to be appended to the
14245: unix timestamp to form the suffix, if the plain timestamp is already
14246: in use. Default is to not do this, but simply increment the unix
14247: timestamp by 1 until a unique key is obtained.
14248:
14249: 7. who: holder of locking key; defaults to user:domain for user.
14250:
14251: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14252: retrying); default is 3.
14253:
14254: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14255:
14256: Returns:
14257:
14258: 1. suffix obtained (numeric)
14259:
14260: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14261:
14262: 3. error: contains (localized) error message if an error occurred.
14263:
1.747 albertel 14264:
1.608 albertel 14265: =back
14266:
1.243 albertel 14267: =head2 HTTP Helper Routines
14268:
14269: =over 4
14270:
1.191 harris41 14271: =item *
14272:
14273: escape() : unpack non-word characters into CGI-compatible hex codes
14274:
14275: =item *
14276:
14277: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14278:
1.243 albertel 14279: =back
14280:
14281: =head1 PRIVATE SUBROUTINES
14282:
14283: =head2 Underlying communication routines (Shouldn't call)
14284:
14285: =over 4
14286:
14287: =item *
14288:
14289: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14290:
14291: =item *
14292:
14293: reply() : uses subreply to send a message to remote machine, logs all failures
14294:
14295: =item *
14296:
14297: critical() : passes a critical message to another server; if cannot
14298: get through then place message in connection buffer directory and
14299: returns con_delayed, if incapable of saving message, returns
14300: con_failed
14301:
14302: =item *
14303:
14304: reconlonc() : tries to reconnect lonc client processes.
14305:
14306: =back
14307:
14308: =head2 Resource Access Logging
14309:
14310: =over 4
14311:
14312: =item *
14313:
14314: flushcourselogs() : flush (save) buffer logs and access logs
14315:
14316: =item *
14317:
14318: courselog($what) : save message for course in hash
14319:
14320: =item *
14321:
14322: courseacclog($what) : save message for course using &courselog(). Perform
14323: special processing for specific resource types (problems, exams, quizzes, etc).
14324:
1.191 harris41 14325: =item *
14326:
14327: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14328: as a PerlChildExitHandler
1.243 albertel 14329:
14330: =back
14331:
14332: =head2 Other
14333:
14334: =over 4
14335:
14336: =item *
14337:
14338: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14339:
14340: =back
14341:
14342: =cut
1.877 foxr 14343:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>