Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1280
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1280 ! raeburn 4: # $Id: lonnet.pm,v 1.1279 2015/04/01 23:22:13 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
4447: my $cachedtime=();
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.110 www 4509: # --------------------------------------------- Set Expire Date for Spreadsheet
4510:
4511: sub expirespread {
4512: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4513: my $cid=$env{'request.course.id'};
1.110 www 4514: if ($cid) {
4515: my $now=time;
4516: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4517: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4518: $env{'course.'.$cid.'.num'}.
1.110 www 4519: ':nohist_expirationdates:'.
4520: &escape($key).'='.$now,
1.620 albertel 4521: $env{'course.'.$cid.'.home'})
1.110 www 4522: }
4523: return 'ok';
1.14 www 4524: }
4525:
1.109 www 4526: # ----------------------------------------------------- Devalidate Spreadsheets
4527:
4528: sub devalidate {
1.325 www 4529: my ($symb,$uname,$udom)=@_;
1.620 albertel 4530: my $cid=$env{'request.course.id'};
1.109 www 4531: if ($cid) {
1.391 matthew 4532: # delete the stored spreadsheets for
4533: # - the student level sheet of this user in course's homespace
4534: # - the assessment level sheet for this resource
4535: # for this user in user's homespace
1.553 albertel 4536: # - current conditional state info
1.325 www 4537: my $key=$uname.':'.$udom.':';
1.109 www 4538: my $status=
1.299 matthew 4539: &del('nohist_calculatedsheets',
1.391 matthew 4540: [$key.'studentcalc:'],
1.620 albertel 4541: $env{'course.'.$cid.'.domain'},
4542: $env{'course.'.$cid.'.num'})
1.133 albertel 4543: .' '.
4544: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4545: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4546: unless ($status eq 'ok ok') {
4547: &logthis('Could not devalidate spreadsheet '.
1.325 www 4548: $uname.' at '.$udom.' for '.
1.109 www 4549: $symb.': '.$status);
1.133 albertel 4550: }
1.553 albertel 4551: &delenv('user.state.'.$cid);
1.109 www 4552: }
4553: }
4554:
1.265 albertel 4555: sub get_scalar {
4556: my ($string,$end) = @_;
4557: my $value;
4558: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4559: $value = $1;
4560: } elsif ($$string =~ s/^([^&]*?)&//) {
4561: $value = $1;
4562: }
4563: return &unescape($value);
4564: }
4565:
4566: sub array2str {
4567: my (@array) = @_;
4568: my $result=&arrayref2str(\@array);
4569: $result=~s/^__ARRAY_REF__//;
4570: $result=~s/__END_ARRAY_REF__$//;
4571: return $result;
4572: }
4573:
1.204 albertel 4574: sub arrayref2str {
4575: my ($arrayref) = @_;
1.265 albertel 4576: my $result='__ARRAY_REF__';
1.204 albertel 4577: foreach my $elem (@$arrayref) {
1.265 albertel 4578: if(ref($elem) eq 'ARRAY') {
4579: $result.=&arrayref2str($elem).'&';
4580: } elsif(ref($elem) eq 'HASH') {
4581: $result.=&hashref2str($elem).'&';
4582: } elsif(ref($elem)) {
4583: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4584: } else {
4585: $result.=&escape($elem).'&';
4586: }
4587: }
4588: $result=~s/\&$//;
1.265 albertel 4589: $result .= '__END_ARRAY_REF__';
1.204 albertel 4590: return $result;
4591: }
4592:
1.168 albertel 4593: sub hash2str {
1.204 albertel 4594: my (%hash) = @_;
4595: my $result=&hashref2str(\%hash);
1.265 albertel 4596: $result=~s/^__HASH_REF__//;
4597: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4598: return $result;
4599: }
4600:
4601: sub hashref2str {
4602: my ($hashref)=@_;
1.265 albertel 4603: my $result='__HASH_REF__';
1.800 albertel 4604: foreach my $key (sort(keys(%$hashref))) {
4605: if (ref($key) eq 'ARRAY') {
4606: $result.=&arrayref2str($key).'=';
4607: } elsif (ref($key) eq 'HASH') {
4608: $result.=&hashref2str($key).'=';
4609: } elsif (ref($key)) {
1.265 albertel 4610: $result.='=';
1.800 albertel 4611: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4612: } else {
1.1132 raeburn 4613: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4614: }
4615:
1.800 albertel 4616: if(ref($hashref->{$key}) eq 'ARRAY') {
4617: $result.=&arrayref2str($hashref->{$key}).'&';
4618: } elsif(ref($hashref->{$key}) eq 'HASH') {
4619: $result.=&hashref2str($hashref->{$key}).'&';
4620: } elsif(ref($hashref->{$key})) {
1.265 albertel 4621: $result.='&';
1.800 albertel 4622: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4623: } else {
1.800 albertel 4624: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4625: }
4626: }
1.168 albertel 4627: $result=~s/\&$//;
1.265 albertel 4628: $result .= '__END_HASH_REF__';
1.168 albertel 4629: return $result;
4630: }
4631:
4632: sub str2hash {
1.265 albertel 4633: my ($string)=@_;
4634: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4635: return %$hash;
4636: }
4637:
4638: sub str2hashref {
1.168 albertel 4639: my ($string) = @_;
1.265 albertel 4640:
4641: my %hash;
4642:
4643: if($string !~ /^__HASH_REF__/) {
4644: if (! ($string eq '' || !defined($string))) {
4645: $hash{'error'}='Not hash reference';
4646: }
4647: return (\%hash, $string);
4648: }
4649:
4650: $string =~ s/^__HASH_REF__//;
4651:
4652: while($string !~ /^__END_HASH_REF__/) {
4653: #key
4654: my $key='';
4655: if($string =~ /^__HASH_REF__/) {
4656: ($key, $string)=&str2hashref($string);
4657: if(defined($key->{'error'})) {
4658: $hash{'error'}='Bad data';
4659: return (\%hash, $string);
4660: }
4661: } elsif($string =~ /^__ARRAY_REF__/) {
4662: ($key, $string)=&str2arrayref($string);
4663: if($key->[0] eq 'Array reference error') {
4664: $hash{'error'}='Bad data';
4665: return (\%hash, $string);
4666: }
4667: } else {
4668: $string =~ s/^(.*?)=//;
1.267 albertel 4669: $key=&unescape($1);
1.265 albertel 4670: }
4671: $string =~ s/^=//;
4672:
4673: #value
4674: my $value='';
4675: if($string =~ /^__HASH_REF__/) {
4676: ($value, $string)=&str2hashref($string);
4677: if(defined($value->{'error'})) {
4678: $hash{'error'}='Bad data';
4679: return (\%hash, $string);
4680: }
4681: } elsif($string =~ /^__ARRAY_REF__/) {
4682: ($value, $string)=&str2arrayref($string);
4683: if($value->[0] eq 'Array reference error') {
4684: $hash{'error'}='Bad data';
4685: return (\%hash, $string);
4686: }
4687: } else {
4688: $value=&get_scalar(\$string,'__END_HASH_REF__');
4689: }
4690: $string =~ s/^&//;
4691:
4692: $hash{$key}=$value;
1.204 albertel 4693: }
1.265 albertel 4694:
4695: $string =~ s/^__END_HASH_REF__//;
4696:
4697: return (\%hash, $string);
1.204 albertel 4698: }
4699:
4700: sub str2array {
1.265 albertel 4701: my ($string)=@_;
4702: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4703: return @$array;
4704: }
4705:
4706: sub str2arrayref {
1.204 albertel 4707: my ($string) = @_;
1.265 albertel 4708: my @array;
4709:
4710: if($string !~ /^__ARRAY_REF__/) {
4711: if (! ($string eq '' || !defined($string))) {
4712: $array[0]='Array reference error';
4713: }
4714: return (\@array, $string);
4715: }
4716:
4717: $string =~ s/^__ARRAY_REF__//;
4718:
4719: while($string !~ /^__END_ARRAY_REF__/) {
4720: my $value='';
4721: if($string =~ /^__HASH_REF__/) {
4722: ($value, $string)=&str2hashref($string);
4723: if(defined($value->{'error'})) {
4724: $array[0] ='Array reference error';
4725: return (\@array, $string);
4726: }
4727: } elsif($string =~ /^__ARRAY_REF__/) {
4728: ($value, $string)=&str2arrayref($string);
4729: if($value->[0] eq 'Array reference error') {
4730: $array[0] ='Array reference error';
4731: return (\@array, $string);
4732: }
4733: } else {
4734: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4735: }
4736: $string =~ s/^&//;
4737:
4738: push(@array, $value);
1.191 harris41 4739: }
1.265 albertel 4740:
4741: $string =~ s/^__END_ARRAY_REF__//;
4742:
4743: return (\@array, $string);
1.168 albertel 4744: }
4745:
1.167 albertel 4746: # -------------------------------------------------------------------Temp Store
4747:
1.168 albertel 4748: sub tmpreset {
4749: my ($symb,$namespace,$domain,$stuname) = @_;
4750: if (!$symb) {
4751: $symb=&symbread();
1.620 albertel 4752: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4753: }
4754: $symb=escape($symb);
4755:
1.620 albertel 4756: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4757: $namespace=~s/\//\_/g;
4758: $namespace=~s/\W//g;
4759:
1.620 albertel 4760: if (!$domain) { $domain=$env{'user.domain'}; }
4761: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4762: if ($domain eq 'public' && $stuname eq 'public') {
4763: $stuname=$ENV{'REMOTE_ADDR'};
4764: }
1.1117 foxr 4765: my $path=LONCAPA::tempdir();
1.168 albertel 4766: my %hash;
4767: if (tie(%hash,'GDBM_File',
4768: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4769: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4770: foreach my $key (keys(%hash)) {
1.180 albertel 4771: if ($key=~ /:$symb/) {
1.168 albertel 4772: delete($hash{$key});
4773: }
4774: }
4775: }
4776: }
4777:
1.167 albertel 4778: sub tmpstore {
1.168 albertel 4779: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4780:
4781: if (!$symb) {
4782: $symb=&symbread();
1.620 albertel 4783: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4784: }
4785: $symb=escape($symb);
4786:
4787: if (!$namespace) {
4788: # I don't think we would ever want to store this for a course.
4789: # it seems this will only be used if we don't have a course.
1.620 albertel 4790: #$namespace=$env{'request.course.id'};
1.168 albertel 4791: #if (!$namespace) {
1.620 albertel 4792: $namespace=$env{'request.state'};
1.168 albertel 4793: #}
4794: }
4795: $namespace=~s/\//\_/g;
4796: $namespace=~s/\W//g;
1.620 albertel 4797: if (!$domain) { $domain=$env{'user.domain'}; }
4798: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4799: if ($domain eq 'public' && $stuname eq 'public') {
4800: $stuname=$ENV{'REMOTE_ADDR'};
4801: }
1.168 albertel 4802: my $now=time;
4803: my %hash;
1.1117 foxr 4804: my $path=LONCAPA::tempdir();
1.168 albertel 4805: if (tie(%hash,'GDBM_File',
4806: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4807: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4808: $hash{"version:$symb"}++;
4809: my $version=$hash{"version:$symb"};
4810: my $allkeys='';
4811: foreach my $key (keys(%$storehash)) {
4812: $allkeys.=$key.':';
1.591 albertel 4813: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4814: }
4815: $hash{"$version:$symb:timestamp"}=$now;
4816: $allkeys.='timestamp';
4817: $hash{"$version:keys:$symb"}=$allkeys;
4818: if (untie(%hash)) {
4819: return 'ok';
4820: } else {
4821: return "error:$!";
4822: }
4823: } else {
4824: return "error:$!";
4825: }
4826: }
1.167 albertel 4827:
1.168 albertel 4828: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4829:
1.168 albertel 4830: sub tmprestore {
4831: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4832:
1.168 albertel 4833: if (!$symb) {
4834: $symb=&symbread();
1.620 albertel 4835: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4836: }
4837: $symb=escape($symb);
4838:
1.620 albertel 4839: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4840:
1.620 albertel 4841: if (!$domain) { $domain=$env{'user.domain'}; }
4842: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4843: if ($domain eq 'public' && $stuname eq 'public') {
4844: $stuname=$ENV{'REMOTE_ADDR'};
4845: }
1.168 albertel 4846: my %returnhash;
4847: $namespace=~s/\//\_/g;
4848: $namespace=~s/\W//g;
4849: my %hash;
1.1117 foxr 4850: my $path=LONCAPA::tempdir();
1.168 albertel 4851: if (tie(%hash,'GDBM_File',
4852: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4853: &GDBM_READER(),0640)) {
1.168 albertel 4854: my $version=$hash{"version:$symb"};
4855: $returnhash{'version'}=$version;
4856: my $scope;
4857: for ($scope=1;$scope<=$version;$scope++) {
4858: my $vkeys=$hash{"$scope:keys:$symb"};
4859: my @keys=split(/:/,$vkeys);
4860: my $key;
4861: $returnhash{"$scope:keys"}=$vkeys;
4862: foreach $key (@keys) {
1.591 albertel 4863: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4864: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4865: }
4866: }
1.168 albertel 4867: if (!(untie(%hash))) {
4868: return "error:$!";
4869: }
4870: } else {
4871: return "error:$!";
4872: }
4873: return %returnhash;
1.167 albertel 4874: }
4875:
1.9 www 4876: # ----------------------------------------------------------------------- Store
4877:
4878: sub store {
1.1269 raeburn 4879: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4880: my $home='';
4881:
1.168 albertel 4882: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4883:
1.213 www 4884: $symb=&symbclean($symb);
1.122 albertel 4885: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4886:
1.620 albertel 4887: if (!$domain) { $domain=$env{'user.domain'}; }
4888: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4889:
4890: &devalidate($symb,$stuname,$domain);
1.109 www 4891:
4892: $symb=escape($symb);
1.187 www 4893: if (!$namespace) {
1.620 albertel 4894: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4895: return '';
4896: }
4897: }
1.620 albertel 4898: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4899:
4900: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4901: $$storehash{'host'}=$perlvar{'lonHostID'};
4902:
1.12 www 4903: my $namevalue='';
1.800 albertel 4904: foreach my $key (keys(%$storehash)) {
4905: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4906: }
1.12 www 4907: $namevalue=~s/\&$//;
1.187 www 4908: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 4909: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 4910: }
4911:
1.47 www 4912: # -------------------------------------------------------------- Critical Store
4913:
4914: sub cstore {
1.1269 raeburn 4915: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4916: my $home='';
4917:
1.168 albertel 4918: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4919:
1.213 www 4920: $symb=&symbclean($symb);
1.122 albertel 4921: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4922:
1.620 albertel 4923: if (!$domain) { $domain=$env{'user.domain'}; }
4924: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4925:
4926: &devalidate($symb,$stuname,$domain);
1.109 www 4927:
4928: $symb=escape($symb);
1.187 www 4929: if (!$namespace) {
1.620 albertel 4930: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4931: return '';
4932: }
4933: }
1.620 albertel 4934: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4935:
4936: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4937: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4938:
1.47 www 4939: my $namevalue='';
1.800 albertel 4940: foreach my $key (keys(%$storehash)) {
4941: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4942: }
1.47 www 4943: $namevalue=~s/\&$//;
1.187 www 4944: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4945: return critical
1.1269 raeburn 4946: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 4947: }
4948:
1.9 www 4949: # --------------------------------------------------------------------- Restore
4950:
4951: sub restore {
1.124 www 4952: my ($symb,$namespace,$domain,$stuname) = @_;
4953: my $home='';
4954:
1.168 albertel 4955: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4956:
1.122 albertel 4957: if (!$symb) {
1.1224 raeburn 4958: return if ($namespace eq 'courserequests');
4959: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4960: } else {
1.1224 raeburn 4961: unless ($namespace eq 'courserequests') {
4962: $symb=&escape(&symbclean($symb));
4963: }
1.122 albertel 4964: }
1.188 www 4965: if (!$namespace) {
1.620 albertel 4966: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4967: return '';
4968: }
4969: }
1.620 albertel 4970: if (!$domain) { $domain=$env{'user.domain'}; }
4971: if (!$stuname) { $stuname=$env{'user.name'}; }
4972: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4973: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4974:
1.12 www 4975: my %returnhash=();
1.800 albertel 4976: foreach my $line (split(/\&/,$answer)) {
4977: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4978: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4979: }
1.75 www 4980: my $version;
4981: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4982: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4983: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4984: }
1.75 www 4985: }
1.13 www 4986: return %returnhash;
1.34 www 4987: }
4988:
4989: # ---------------------------------------------------------- Course Description
1.1118 foxr 4990: #
4991: #
1.34 www 4992:
4993: sub coursedescription {
1.731 albertel 4994: my ($courseid,$args)=@_;
1.34 www 4995: $courseid=~s/^\///;
1.49 www 4996: $courseid=~s/\_/\//g;
1.34 www 4997: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4998: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4999: my $normalid=$cdomain.'_'.$cnum;
5000: # need to always cache even if we get errors otherwise we keep
5001: # trying and trying and trying to get the course description.
5002: my %envhash=();
5003: my %returnhash=();
1.731 albertel 5004:
5005: my $expiretime=600;
5006: if ($env{'request.course.id'} eq $normalid) {
5007: $expiretime=120;
5008: }
5009:
5010: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5011: if (!$args->{'freshen_cache'}
5012: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5013: foreach my $key (keys(%env)) {
5014: next if ($key !~ /^\Q$prefix\E(.*)/);
5015: my ($setting) = $1;
5016: $returnhash{$setting} = $env{$key};
5017: }
5018: return %returnhash;
5019: }
5020:
1.1118 foxr 5021: # get the data again
5022:
1.731 albertel 5023: if (!$args->{'one_time'}) {
5024: $envhash{'course.'.$normalid.'.last_cache'}=time;
5025: }
1.811 albertel 5026:
1.34 www 5027: if ($chome ne 'no_host') {
1.302 albertel 5028: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5029: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5030: my $username = $env{'user.name'}; # Defult username
5031: if(defined $args->{'user'}) {
5032: $username = $args->{'user'};
5033: }
1.129 albertel 5034: $returnhash{'home'}= $chome;
5035: $returnhash{'domain'} = $cdomain;
5036: $returnhash{'num'} = $cnum;
1.741 raeburn 5037: if (!defined($returnhash{'type'})) {
5038: $returnhash{'type'} = 'Course';
5039: }
1.130 albertel 5040: while (my ($name,$value) = each %returnhash) {
1.53 www 5041: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5042: }
1.270 www 5043: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5044: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5045: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5046: $envhash{'course.'.$normalid.'.home'}=$chome;
5047: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5048: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5049: }
5050: }
1.731 albertel 5051: if (!$args->{'one_time'}) {
1.949 raeburn 5052: &appenv(\%envhash);
1.731 albertel 5053: }
1.302 albertel 5054: return %returnhash;
1.461 www 5055: }
5056:
1.1080 raeburn 5057: sub update_released_required {
5058: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5059: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5060: $cid = $env{'request.course.id'};
5061: $cdom = $env{'course.'.$cid.'.domain'};
5062: $cnum = $env{'course.'.$cid.'.num'};
5063: $chome = $env{'course.'.$cid.'.home'};
5064: }
5065: if ($needsrelease) {
5066: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5067: my $needsupdate;
5068: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5069: $needsupdate = 1;
5070: } else {
5071: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5072: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5073: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5074: $needsupdate = 1;
5075: }
5076: }
5077: if ($needsupdate) {
5078: my %needshash = (
5079: 'internal.releaserequired' => $needsrelease,
5080: );
5081: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5082: if ($putresult eq 'ok') {
5083: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5084: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5085: if (ref($crsinfo{$cid}) eq 'HASH') {
5086: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5087: &courseidput($cdom,\%crsinfo,$chome,'notime');
5088: }
5089: }
5090: }
5091: }
5092: return;
5093: }
5094:
1.461 www 5095: # -------------------------------------------------See if a user is privileged
5096:
5097: sub privileged {
1.1219 raeburn 5098: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5099: my $now = time;
1.1219 raeburn 5100: my $roles;
5101: if (ref($possroles) eq 'ARRAY') {
5102: $roles = $possroles;
5103: } else {
5104: $roles = ['dc','su'];
5105: }
5106: if (ref($possdomains) eq 'ARRAY') {
5107: my %privileged = &privileged_by_domain($possdomains,$roles);
5108: foreach my $dom (@{$possdomains}) {
5109: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5110: (ref($privileged{$dom}) eq 'HASH')) {
5111: foreach my $role (@{$roles}) {
5112: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5113: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5114: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5115: return 1 unless (($end && $end < $now) ||
5116: ($start && $start > $now));
5117: }
5118: }
5119: }
5120: }
5121: }
5122: } else {
5123: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5124: my $now = time;
1.1170 droeschl 5125:
1.1275 musolffc 5126: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5127: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5128: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5129: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5130: or ($tstart && $tstart > $now);
1.1170 droeschl 5131: }
1.1219 raeburn 5132: }
5133: }
5134: return 0;
5135: }
1.1170 droeschl 5136:
1.1219 raeburn 5137: sub privileged_by_domain {
5138: my ($domains,$roles) = @_;
5139: my %privileged = ();
5140: my $cachetime = 60*60*24;
5141: my $now = time;
5142: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5143: return %privileged;
5144: }
5145: foreach my $dom (@{$domains}) {
5146: next if (ref($privileged{$dom}) eq 'HASH');
5147: my $needroles;
5148: foreach my $role (@{$roles}) {
5149: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5150: if (defined($cached)) {
5151: if (ref($result) eq 'HASH') {
5152: $privileged{$dom}{$role} = $result;
5153: }
5154: } else {
5155: $needroles = 1;
5156: }
5157: }
5158: if ($needroles) {
5159: my %dompersonnel = &get_domain_roles($dom,$roles);
5160: $privileged{$dom} = {};
5161: foreach my $server (keys(%dompersonnel)) {
5162: if (ref($dompersonnel{$server}) eq 'HASH') {
5163: foreach my $item (keys(%{$dompersonnel{$server}})) {
5164: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5165: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5166: next if ($end && $end < $now);
5167: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5168: $dompersonnel{$server}{$item};
5169: }
5170: }
5171: }
5172: if (ref($privileged{$dom}) eq 'HASH') {
5173: foreach my $role (@{$roles}) {
5174: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5175: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5176: } else {
5177: my %hash = ();
5178: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5179: }
5180: }
5181: }
5182: }
5183: }
5184: return %privileged;
1.9 www 5185: }
1.1 albertel 5186:
1.103 harris41 5187: # -------------------------------------------------------- Get user privileges
1.11 www 5188:
5189: sub rolesinit {
1.1169 droeschl 5190: my ($domain, $username) = @_;
5191: my %userroles = ('user.login.time' => time);
5192: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5193:
5194: # firstaccess and timerinterval are related to timed maps/resources.
5195: # also, blocking can be triggered by an activating timer
5196: # it's saved in the user's %env.
5197: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5198: my %timerinterval = &dump('timerinterval', $domain, $username);
5199: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5200: %timerintchk, %timerintenv);
5201:
1.1162 raeburn 5202: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5203: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5204: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5205: }
1.1169 droeschl 5206:
1.1162 raeburn 5207: foreach my $key (keys(%timerinterval)) {
5208: my ($cid,$rest) = split(/\0/,$key);
5209: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5210: }
1.1169 droeschl 5211:
1.11 www 5212: my %allroles=();
1.1162 raeburn 5213: my %allgroups=();
1.11 www 5214:
1.1274 raeburn 5215: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5216: my $role = $rolesdump{$area};
5217: $area =~ s/\_\w\w$//;
5218:
5219: my ($trole, $tend, $tstart, $group_privs);
5220:
5221: if ($role =~ /^cr/) {
5222: # Custom role, defined by a user
5223: # e.g., user.role.cr/msu/smith/mynewrole
5224: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5225: $trole = $1;
5226: ($tend, $tstart) = split('_', $2);
5227: } else {
5228: $trole = $role;
5229: }
5230: } elsif ($role =~ m|^gr/|) {
5231: # Role of member in a group, defined within a course/community
5232: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5233: ($trole, $tend, $tstart) = split(/_/, $role);
5234: next if $tstart eq '-1';
5235: ($trole, $group_privs) = split(/\//, $trole);
5236: $group_privs = &unescape($group_privs);
5237: } else {
5238: # Just a normal role, defined in roles.tab
5239: ($trole, $tend, $tstart) = split(/_/,$role);
5240: }
5241:
5242: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5243: $username);
5244: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5245:
5246: # role expired or not available yet?
5247: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5248: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5249:
5250: next if $area eq '' or $trole eq '';
5251:
5252: my $spec = "$trole.$area";
5253: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5254:
5255: if ($trole =~ /^cr\//) {
5256: # Custom role, defined by a user
5257: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5258: } elsif ($trole eq 'gr') {
5259: # Role of a member in a group, defined within a course/community
5260: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5261: next;
5262: } else {
5263: # Normal role, defined in roles.tab
5264: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5265: }
5266:
5267: my $cid = $tdomain.'_'.$trest;
5268: unless ($firstaccchk{$cid}) {
5269: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5270: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5271: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5272: $coursetimerstarts{$cid}{$item};
5273: }
5274: }
5275: $firstaccchk{$cid} = 1;
5276: }
5277: unless ($timerintchk{$cid}) {
5278: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5279: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5280: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5281: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5282: }
1.12 www 5283: }
1.1169 droeschl 5284: $timerintchk{$cid} = 1;
1.191 harris41 5285: }
1.11 www 5286: }
1.1169 droeschl 5287:
5288: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5289: \%allroles, \%allgroups);
5290: $env{'user.adv'} = $userroles{'user.adv'};
5291:
1.1162 raeburn 5292: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5293: }
5294:
1.567 raeburn 5295: sub set_arearole {
1.1215 raeburn 5296: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5297: unless ($nolog) {
1.567 raeburn 5298: # log the associated role with the area
1.1215 raeburn 5299: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5300: }
1.743 albertel 5301: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5302: }
5303:
5304: sub custom_roleprivs {
5305: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5306: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5307: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5308: if (&hostname($homsvr) ne '') {
1.567 raeburn 5309: my ($rdummy,$roledef)=
5310: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5311: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5312: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5313: if (defined($syspriv)) {
1.1043 raeburn 5314: if ($trest =~ /^$match_community$/) {
5315: $syspriv =~ s/bre\&S//;
5316: }
1.567 raeburn 5317: $$allroles{'cm./'}.=':'.$syspriv;
5318: $$allroles{$spec.'./'}.=':'.$syspriv;
5319: }
5320: if ($tdomain ne '') {
5321: if (defined($dompriv)) {
5322: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5323: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5324: }
5325: if (($trest ne '') && (defined($coursepriv))) {
5326: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5327: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5328: }
5329: }
5330: }
5331: }
5332: }
5333:
1.678 raeburn 5334: sub group_roleprivs {
5335: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5336: my $access = 1;
5337: my $now = time;
5338: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5339: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5340: if ($access) {
1.811 albertel 5341: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5342: $$allgroups{$course}{$group} .=':'.$group_privs;
5343: }
5344: }
1.567 raeburn 5345:
5346: sub standard_roleprivs {
5347: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5348: if (defined($pr{$trole.':s'})) {
5349: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5350: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5351: }
5352: if ($tdomain ne '') {
5353: if (defined($pr{$trole.':d'})) {
5354: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5355: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5356: }
5357: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5358: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5359: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5360: }
5361: }
5362: }
5363:
5364: sub set_userprivs {
1.1064 raeburn 5365: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5366: my $author=0;
5367: my $adv=0;
1.678 raeburn 5368: my %grouproles = ();
5369: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5370: my @groupkeys;
1.1000 raeburn 5371: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5372: push(@groupkeys,$role);
5373: }
5374: if (ref($groups_roles) eq 'HASH') {
5375: foreach my $key (keys(%{$groups_roles})) {
5376: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5377: push(@groupkeys,$key);
5378: }
5379: }
5380: }
5381: if (@groupkeys > 0) {
5382: foreach my $role (@groupkeys) {
5383: my ($trole,$area,$sec,$extendedarea);
5384: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5385: $trole = $1;
5386: $area = $2;
5387: $sec = $3;
5388: $extendedarea = $area.$sec;
5389: if (exists($$allgroups{$area})) {
5390: foreach my $group (keys(%{$$allgroups{$area}})) {
5391: my $spec = $trole.'.'.$extendedarea;
5392: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5393: $$allgroups{$area}{$group};
1.1064 raeburn 5394: }
1.678 raeburn 5395: }
5396: }
5397: }
5398: }
5399: }
1.800 albertel 5400: foreach my $group (keys(%grouproles)) {
5401: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5402: }
1.800 albertel 5403: foreach my $role (keys(%{$allroles})) {
5404: my %thesepriv;
1.941 raeburn 5405: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5406: foreach my $item (split(/:/,$$allroles{$role})) {
5407: if ($item ne '') {
5408: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5409: if ($restrictions eq '') {
5410: $thesepriv{$privilege}='F';
5411: } elsif ($thesepriv{$privilege} ne 'F') {
5412: $thesepriv{$privilege}.=$restrictions;
5413: }
5414: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5415: }
5416: }
5417: my $thesestr='';
1.1104 raeburn 5418: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5419: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5420: }
5421: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5422: }
5423: return ($author,$adv);
5424: }
5425:
1.994 raeburn 5426: sub role_status {
1.1104 raeburn 5427: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5428: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5429: my ($one,$two) = split(m{\./},$rolekey,2);
5430: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5431: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5432: $$where = '/'.$two;
1.994 raeburn 5433: $$trolecode=$$role.'.'.$$where;
5434: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5435: $$tstatus='is';
1.1104 raeburn 5436: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5437: $$tstatus='future';
1.1034 raeburn 5438: if ($$tstart<$now) {
5439: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5440: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5441: my (%allroles,%allgroups,$group_privs,
5442: %groups_roles,@rolecodes);
1.1002 raeburn 5443: my %userroles = (
5444: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5445: );
1.1064 raeburn 5446: @rolecodes = ('cm');
1.1002 raeburn 5447: my $spec=$$role.'.'.$$where;
5448: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5449: if ($$role =~ /^cr\//) {
5450: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5451: push(@rolecodes,'cr');
1.1002 raeburn 5452: } elsif ($$role eq 'gr') {
1.1064 raeburn 5453: push(@rolecodes,$$role);
1.1002 raeburn 5454: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5455: $env{'user.name'});
1.1064 raeburn 5456: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5457: (undef,my $group_privs) = split(/\//,$trole);
5458: $group_privs = &unescape($group_privs);
5459: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5460: 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 5461: &get_groups_roles($tdomain,$trest,
5462: \%course_roles,\@rolecodes,
5463: \%groups_roles);
1.1002 raeburn 5464: } else {
1.1064 raeburn 5465: push(@rolecodes,$$role);
1.1002 raeburn 5466: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5467: }
1.1064 raeburn 5468: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5469: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5470: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5471: }
5472: }
1.1034 raeburn 5473: $$tstatus = 'is';
1.1002 raeburn 5474: }
1.994 raeburn 5475: }
5476: if ($$tend) {
1.1104 raeburn 5477: if ($$tend<$update) {
1.994 raeburn 5478: $$tstatus='expired';
5479: } elsif ($$tend<$now) {
5480: $$tstatus='will_not';
5481: }
5482: }
5483: }
5484: }
5485: }
5486:
1.1104 raeburn 5487: sub get_groups_roles {
5488: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5489: return unless((ref($cdom_courseroles) eq 'HASH') &&
5490: (ref($rolecodes) eq 'ARRAY') &&
5491: (ref($groups_roles) eq 'HASH'));
5492: if (keys(%{$cdom_courseroles}) > 0) {
5493: my ($cnum) = ($rest =~ /^($match_courseid)/);
5494: if ($cdom ne '' && $cnum ne '') {
5495: foreach my $key (keys(%{$cdom_courseroles})) {
5496: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5497: my $crsrole = $1;
5498: my $crssec = $2;
5499: if ($crsrole =~ /^cr/) {
5500: unless (grep(/^cr$/,@{$rolecodes})) {
5501: push(@{$rolecodes},'cr');
5502: }
5503: } else {
5504: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5505: push(@{$rolecodes},$crsrole);
5506: }
5507: }
5508: my $rolekey = "$crsrole./$cdom/$cnum";
5509: if ($crssec ne '') {
5510: $rolekey .= "/$crssec";
5511: }
5512: $rolekey .= './';
5513: $groups_roles->{$rolekey} = $rolecodes;
5514: }
5515: }
5516: }
5517: }
5518: return;
5519: }
5520:
5521: sub delete_env_groupprivs {
5522: my ($where,$courseroles,$possroles) = @_;
5523: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5524: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5525: unless (ref($courseroles->{$udom}) eq 'HASH') {
5526: %{$courseroles->{$udom}} =
5527: &get_my_roles('','','userroles',['active'],
5528: $possroles,[$udom],1);
5529: }
5530: if (ref($courseroles->{$udom}) eq 'HASH') {
5531: foreach my $item (keys(%{$courseroles->{$udom}})) {
5532: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5533: my $area = '/'.$cdom.'/'.$cnum;
5534: my $privkey = "user.priv.$crsrole.$area";
5535: if ($crssec ne '') {
5536: $privkey .= '/'.$crssec;
5537: }
5538: $privkey .= ".$area/$group";
5539: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5540: }
5541: }
5542: return;
5543: }
5544:
1.994 raeburn 5545: sub check_adhoc_privs {
1.1104 raeburn 5546: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5547: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5548: my $setprivs;
1.994 raeburn 5549: if ($env{$cckey}) {
5550: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5551: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5552: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5553: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5554: $setprivs = 1;
1.994 raeburn 5555: }
5556: } else {
1.1088 raeburn 5557: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5558: $setprivs = 1;
1.994 raeburn 5559: }
1.1185 raeburn 5560: return $setprivs;
1.994 raeburn 5561: }
5562:
5563: sub set_adhoc_privileges {
5564: # role can be cc or ca
1.1088 raeburn 5565: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5566: my $area = '/'.$dcdom.'/'.$pickedcourse;
5567: my $spec = $role.'.'.$area;
5568: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5569: $env{'user.name'},1);
1.994 raeburn 5570: my %ccrole = ();
5571: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5572: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5573: &appenv(\%userroles,[$role,'cm']);
5574: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5575: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5576: &appenv( {'request.role' => $spec,
5577: 'request.role.domain' => $dcdom,
5578: 'request.course.sec' => ''
5579: }
5580: );
5581: my $tadv=0;
5582: if (&allowed('adv') eq 'F') { $tadv=1; }
5583: &appenv({'request.role.adv' => $tadv});
5584: }
1.994 raeburn 5585: }
5586:
1.12 www 5587: # --------------------------------------------------------------- get interface
5588:
5589: sub get {
1.131 albertel 5590: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5591: my $items='';
1.800 albertel 5592: foreach my $item (@$storearr) {
5593: $items.=&escape($item).'&';
1.191 harris41 5594: }
1.12 www 5595: $items=~s/\&$//;
1.620 albertel 5596: if (!$udomain) { $udomain=$env{'user.domain'}; }
5597: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5598: my $uhome=&homeserver($uname,$udomain);
5599:
1.133 albertel 5600: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5601: my @pairs=split(/\&/,$rep);
1.273 albertel 5602: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5603: return @pairs;
5604: }
1.15 www 5605: my %returnhash=();
1.42 www 5606: my $i=0;
1.800 albertel 5607: foreach my $item (@$storearr) {
5608: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5609: $i++;
1.191 harris41 5610: }
1.15 www 5611: return %returnhash;
1.27 www 5612: }
5613:
5614: # --------------------------------------------------------------- del interface
5615:
5616: sub del {
1.133 albertel 5617: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5618: my $items='';
1.800 albertel 5619: foreach my $item (@$storearr) {
5620: $items.=&escape($item).'&';
1.191 harris41 5621: }
1.984 neumanie 5622:
1.27 www 5623: $items=~s/\&$//;
1.620 albertel 5624: if (!$udomain) { $udomain=$env{'user.domain'}; }
5625: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5626: my $uhome=&homeserver($uname,$udomain);
5627: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5628: }
5629:
5630: # -------------------------------------------------------------- dump interface
5631:
1.1180 droeschl 5632: sub unserialize {
5633: my ($rep, $escapedkeys) = @_;
5634:
5635: return {} if $rep =~ /^error/;
5636:
5637: my %returnhash=();
1.1252 raeburn 5638: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5639: my ($key, $value) = split(/=/, $item, 2);
5640: $key = unescape($key) unless $escapedkeys;
5641: next if $key =~ /^error: 2 /;
1.1252 raeburn 5642: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5643: }
5644: #return %returnhash;
5645: return \%returnhash;
5646: }
5647:
5648: # see Lond::dump_with_regexp
5649: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5650: sub dump {
1.1180 droeschl 5651: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5652: if (!$udomain) { $udomain=$env{'user.domain'}; }
5653: if (!$uname) { $uname=$env{'user.name'}; }
5654: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5655:
1.1266 raeburn 5656: if ($regexp) {
5657: $regexp=&escape($regexp);
5658: } else {
5659: $regexp='.';
5660: }
1.1180 droeschl 5661: if (grep { $_ eq $uhome } current_machine_ids()) {
5662: # user is hosted on this machine
1.1266 raeburn 5663: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5664: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5665: return %{unserialize($reply, $escapedkeys)};
5666: }
1.1166 raeburn 5667: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5668: my @pairs=split(/\&/,$rep);
5669: my %returnhash=();
1.1098 foxr 5670: if (!($rep =~ /^error/ )) {
5671: foreach my $item (@pairs) {
5672: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5673: $key = unescape($key) unless $escapedkeys;
5674: #$key = &unescape($key);
1.1098 foxr 5675: next if ($key =~ /^error: 2 /);
5676: $returnhash{$key}=&thaw_unescape($value);
5677: }
1.755 albertel 5678: }
5679: return %returnhash;
1.407 www 5680: }
5681:
1.1098 foxr 5682:
1.717 albertel 5683: # --------------------------------------------------------- dumpstore interface
5684:
5685: sub dumpstore {
5686: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5687: # same as dump but keys must be escaped. They may contain colon separated
5688: # lists of values that may themself contain colons (e.g. symbs).
5689: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5690: }
5691:
1.407 www 5692: # -------------------------------------------------------------- keys interface
5693:
5694: sub getkeys {
5695: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5696: if (!$udomain) { $udomain=$env{'user.domain'}; }
5697: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5698: my $uhome=&homeserver($uname,$udomain);
5699: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5700: my @keyarray=();
1.800 albertel 5701: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5702: next if ($key =~ /^error: 2 /);
1.800 albertel 5703: push(@keyarray,&unescape($key));
1.407 www 5704: }
5705: return @keyarray;
1.318 matthew 5706: }
5707:
1.319 matthew 5708: # --------------------------------------------------------------- currentdump
5709: sub currentdump {
1.328 matthew 5710: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5711: $courseid = $env{'request.course.id'} if (! defined($courseid));
5712: $sdom = $env{'user.domain'} if (! defined($sdom));
5713: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5714: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5715: my $rep;
5716:
5717: if (grep { $_ eq $uhome } current_machine_ids()) {
5718: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5719: $courseid)));
5720: } else {
5721: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5722: }
5723:
1.318 matthew 5724: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5725: #
1.318 matthew 5726: my %returnhash=();
1.319 matthew 5727: #
5728: if ($rep eq "unknown_cmd") {
5729: # an old lond will not know currentdump
5730: # Do a dump and make it look like a currentdump
1.822 albertel 5731: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5732: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5733: my %hash = @tmp;
5734: @tmp=();
1.424 matthew 5735: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5736: } else {
5737: my @pairs=split(/\&/,$rep);
1.800 albertel 5738: foreach my $pair (@pairs) {
5739: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5740: my ($symb,$param) = split(/:/,$key);
5741: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5742: &thaw_unescape($value);
1.319 matthew 5743: }
1.191 harris41 5744: }
1.12 www 5745: return %returnhash;
1.424 matthew 5746: }
5747:
5748: sub convert_dump_to_currentdump{
5749: my %hash = %{shift()};
5750: my %returnhash;
5751: # Code ripped from lond, essentially. The only difference
5752: # here is the unescaping done by lonnet::dump(). Conceivably
5753: # we might run in to problems with parameter names =~ /^v\./
5754: while (my ($key,$value) = each(%hash)) {
5755: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5756: $symb = &unescape($symb);
5757: $param = &unescape($param);
1.424 matthew 5758: next if ($v eq 'version' || $symb eq 'keys');
5759: next if (exists($returnhash{$symb}) &&
5760: exists($returnhash{$symb}->{$param}) &&
5761: $returnhash{$symb}->{'v.'.$param} > $v);
5762: $returnhash{$symb}->{$param}=$value;
5763: $returnhash{$symb}->{'v.'.$param}=$v;
5764: }
5765: #
5766: # Remove all of the keys in the hashes which keep track of
5767: # the version of the parameter.
5768: while (my ($symb,$param_hash) = each(%returnhash)) {
5769: # use a foreach because we are going to delete from the hash.
5770: foreach my $key (keys(%$param_hash)) {
5771: delete($param_hash->{$key}) if ($key =~ /^v\./);
5772: }
5773: }
5774: return \%returnhash;
1.12 www 5775: }
5776:
1.627 albertel 5777: # ------------------------------------------------------ critical inc interface
5778:
5779: sub cinc {
5780: return &inc(@_,'critical');
5781: }
5782:
1.449 matthew 5783: # --------------------------------------------------------------- inc interface
5784:
5785: sub inc {
1.627 albertel 5786: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5787: if (!$udomain) { $udomain=$env{'user.domain'}; }
5788: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5789: my $uhome=&homeserver($uname,$udomain);
5790: my $items='';
5791: if (! ref($store)) {
5792: # got a single value, so use that instead
5793: $items = &escape($store).'=&';
5794: } elsif (ref($store) eq 'SCALAR') {
5795: $items = &escape($$store).'=&';
5796: } elsif (ref($store) eq 'ARRAY') {
5797: $items = join('=&',map {&escape($_);} @{$store});
5798: } elsif (ref($store) eq 'HASH') {
5799: while (my($key,$value) = each(%{$store})) {
5800: $items.= &escape($key).'='.&escape($value).'&';
5801: }
5802: }
5803: $items=~s/\&$//;
1.627 albertel 5804: if ($critical) {
5805: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5806: } else {
5807: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5808: }
1.449 matthew 5809: }
5810:
1.12 www 5811: # --------------------------------------------------------------- put interface
5812:
5813: sub put {
1.134 albertel 5814: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5815: if (!$udomain) { $udomain=$env{'user.domain'}; }
5816: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5817: my $uhome=&homeserver($uname,$udomain);
1.12 www 5818: my $items='';
1.800 albertel 5819: foreach my $item (keys(%$storehash)) {
5820: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5821: }
1.12 www 5822: $items=~s/\&$//;
1.134 albertel 5823: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5824: }
5825:
1.631 albertel 5826: # ------------------------------------------------------------ newput interface
5827:
5828: sub newput {
5829: my ($namespace,$storehash,$udomain,$uname)=@_;
5830: if (!$udomain) { $udomain=$env{'user.domain'}; }
5831: if (!$uname) { $uname=$env{'user.name'}; }
5832: my $uhome=&homeserver($uname,$udomain);
5833: my $items='';
5834: foreach my $key (keys(%$storehash)) {
5835: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5836: }
5837: $items=~s/\&$//;
5838: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5839: }
5840:
5841: # --------------------------------------------------------- putstore interface
5842:
1.524 raeburn 5843: sub putstore {
1.1269 raeburn 5844: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 5845: if (!$udomain) { $udomain=$env{'user.domain'}; }
5846: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5847: my $uhome=&homeserver($uname,$udomain);
5848: my $items='';
1.715 albertel 5849: foreach my $key (keys(%$storehash)) {
5850: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5851: }
1.715 albertel 5852: $items=~s/\&$//;
1.716 albertel 5853: my $esc_symb=&escape($symb);
5854: my $esc_v=&escape($version);
1.715 albertel 5855: my $reply =
1.716 albertel 5856: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5857: $uhome);
1.1269 raeburn 5858: if (($tolog) && ($reply eq 'ok')) {
5859: my $namevalue='';
5860: foreach my $key (keys(%{$storehash})) {
5861: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5862: }
5863: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
5864: '&host='.&escape($perlvar{'lonHostID'}).
5865: '&version='.$esc_v.
5866: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
5867: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
5868: }
1.715 albertel 5869: if ($reply eq 'unknown_cmd') {
1.716 albertel 5870: # gfall back to way things use to be done
1.715 albertel 5871: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5872: $uname);
1.524 raeburn 5873: }
1.715 albertel 5874: return $reply;
5875: }
5876:
5877: sub old_putstore {
1.716 albertel 5878: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5879: if (!$udomain) { $udomain=$env{'user.domain'}; }
5880: if (!$uname) { $uname=$env{'user.name'}; }
5881: my $uhome=&homeserver($uname,$udomain);
5882: my %newstorehash;
1.800 albertel 5883: foreach my $item (keys(%$storehash)) {
5884: my $key = $version.':'.&escape($symb).':'.$item;
5885: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5886: }
5887: my $items='';
5888: my %allitems = ();
1.800 albertel 5889: foreach my $item (keys(%newstorehash)) {
5890: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5891: my $key = $1.':keys:'.$2;
5892: $allitems{$key} .= $3.':';
5893: }
1.800 albertel 5894: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5895: }
1.800 albertel 5896: foreach my $item (keys(%allitems)) {
5897: $allitems{$item} =~ s/\:$//;
5898: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5899: }
5900: $items=~s/\&$//;
5901: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5902: }
5903:
1.47 www 5904: # ------------------------------------------------------ critical put interface
5905:
5906: sub cput {
1.134 albertel 5907: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5908: if (!$udomain) { $udomain=$env{'user.domain'}; }
5909: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5910: my $uhome=&homeserver($uname,$udomain);
1.47 www 5911: my $items='';
1.800 albertel 5912: foreach my $item (keys(%$storehash)) {
5913: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5914: }
1.47 www 5915: $items=~s/\&$//;
1.134 albertel 5916: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5917: }
5918:
5919: # -------------------------------------------------------------- eget interface
5920:
5921: sub eget {
1.133 albertel 5922: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5923: my $items='';
1.800 albertel 5924: foreach my $item (@$storearr) {
5925: $items.=&escape($item).'&';
1.191 harris41 5926: }
1.12 www 5927: $items=~s/\&$//;
1.620 albertel 5928: if (!$udomain) { $udomain=$env{'user.domain'}; }
5929: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5930: my $uhome=&homeserver($uname,$udomain);
5931: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5932: my @pairs=split(/\&/,$rep);
5933: my %returnhash=();
1.42 www 5934: my $i=0;
1.800 albertel 5935: foreach my $item (@$storearr) {
5936: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5937: $i++;
1.191 harris41 5938: }
1.12 www 5939: return %returnhash;
5940: }
5941:
1.667 albertel 5942: # ------------------------------------------------------------ tmpput interface
5943: sub tmpput {
1.802 raeburn 5944: my ($storehash,$server,$context)=@_;
1.667 albertel 5945: my $items='';
1.800 albertel 5946: foreach my $item (keys(%$storehash)) {
5947: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5948: }
5949: $items=~s/\&$//;
1.802 raeburn 5950: if (defined($context)) {
5951: $items .= ':'.&escape($context);
5952: }
1.667 albertel 5953: return &reply("tmpput:$items",$server);
5954: }
5955:
5956: # ------------------------------------------------------------ tmpget interface
5957: sub tmpget {
1.688 albertel 5958: my ($token,$server)=@_;
5959: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5960: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5961: my %returnhash;
5962: foreach my $item (split(/\&/,$rep)) {
5963: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5964: next if ($key =~ /^error: 2 /);
1.667 albertel 5965: $returnhash{&unescape($key)}=&thaw_unescape($value);
5966: }
5967: return %returnhash;
5968: }
5969:
1.1113 raeburn 5970: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5971: sub tmpdel {
5972: my ($token,$server)=@_;
5973: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5974: return &reply("tmpdel:$token",$server);
5975: }
5976:
1.1198 raeburn 5977: # ------------------------------------------------------------ get_timebased_id
5978:
5979: sub get_timebased_id {
5980: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5981: $maxtries) = @_;
5982: my ($newid,$error,$dellock);
5983: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5984: return ('','ok','invalid call to get suffix');
5985: }
5986:
5987: # set defaults for any optional args for which values were not supplied
5988: if ($who eq '') {
5989: $who = $env{'user.name'}.':'.$env{'user.domain'};
5990: }
5991: if (!$locktries) {
5992: $locktries = 3;
5993: }
5994: if (!$maxtries) {
5995: $maxtries = 10;
5996: }
5997:
5998: if (($cdom eq '') || ($cnum eq '')) {
5999: if ($env{'request.course.id'}) {
6000: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6001: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6002: }
6003: if (($cdom eq '') || ($cnum eq '')) {
6004: return ('','ok','call to get suffix not in course context');
6005: }
6006: }
6007:
6008: # construct locking item
6009: my $lockhash = {
6010: $prefix."\0".'locked_'.$keyid => $who,
6011: };
6012: my $tries = 0;
6013:
6014: # attempt to get lock on nohist_$namespace file
6015: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6016: while (($gotlock ne 'ok') && $tries <$locktries) {
6017: $tries ++;
6018: sleep 1;
6019: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6020: }
6021:
6022: # attempt to get unique identifier, based on current timestamp
6023: if ($gotlock eq 'ok') {
6024: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6025: my $id = time;
6026: $newid = $id;
1.1268 raeburn 6027: if ($idtype eq 'addcode') {
6028: $newid .= &sixnum_code();
6029: }
1.1198 raeburn 6030: my $idtries = 0;
6031: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6032: if ($idtype eq 'concat') {
6033: $newid = $id.$idtries;
1.1268 raeburn 6034: } elsif ($idtype eq 'addcode') {
6035: $newid = $newid.&sixnum_code();
1.1198 raeburn 6036: } else {
6037: $newid ++;
6038: }
6039: $idtries ++;
6040: }
6041: if (!exists($inuse{$prefix."\0".$newid})) {
6042: my %new_item = (
6043: $prefix."\0".$newid => $who,
6044: );
6045: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6046: $cdom,$cnum);
6047: if ($putresult ne 'ok') {
6048: undef($newid);
6049: $error = 'error saving new item: '.$putresult;
6050: }
6051: } else {
1.1268 raeburn 6052: undef($newid);
1.1198 raeburn 6053: $error = ('error: no unique suffix available for the new item ');
6054: }
6055: # remove lock
6056: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6057: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6058: } else {
6059: $error = "error: could not obtain lockfile\n";
6060: $dellock = 'ok';
1.1276 raeburn 6061: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6062: $dellock = 'nolock';
6063: }
1.1198 raeburn 6064: }
6065: return ($newid,$dellock,$error);
6066: }
6067:
1.1268 raeburn 6068: sub sixnum_code {
6069: my $code;
6070: for (0..6) {
6071: $code .= int( rand(9) );
6072: }
6073: return $code;
6074: }
6075:
1.765 albertel 6076: # -------------------------------------------------- portfolio access checking
6077:
6078: sub portfolio_access {
1.1270 raeburn 6079: my ($requrl,$clientip) = @_;
1.765 albertel 6080: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6081: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6082: if ($result) {
6083: my %setters;
6084: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6085: my ($startblock,$endblock) =
6086: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6087: if ($startblock && $endblock) {
6088: return 'B';
6089: }
6090: } else {
6091: my ($startblock,$endblock) =
6092: &Apache::loncommon::blockcheck(\%setters,'port');
6093: if ($startblock && $endblock) {
6094: return 'B';
6095: }
6096: }
6097: }
1.765 albertel 6098: if ($result eq 'ok') {
1.766 albertel 6099: return 'F';
1.765 albertel 6100: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6101: return 'A';
1.765 albertel 6102: }
1.766 albertel 6103: return '';
1.765 albertel 6104: }
6105:
6106: sub get_portfolio_access {
1.1270 raeburn 6107: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6108:
6109: if (!ref($access_hash)) {
6110: my $current_perms = &get_portfile_permissions($udom,$unum);
6111: my %access_controls = &get_access_controls($current_perms,$group,
6112: $file_name);
6113: $access_hash = $access_controls{$file_name};
6114: }
6115:
1.1270 raeburn 6116: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6117: my $now = time;
6118: if (ref($access_hash) eq 'HASH') {
6119: foreach my $key (keys(%{$access_hash})) {
6120: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6121: if ($start > $now) {
6122: next;
6123: }
6124: if ($end && $end<$now) {
6125: next;
6126: }
6127: if ($scope eq 'public') {
6128: $public = $key;
6129: last;
6130: } elsif ($scope eq 'guest') {
6131: $guest = $key;
6132: } elsif ($scope eq 'domains') {
6133: push(@domains,$key);
6134: } elsif ($scope eq 'users') {
6135: push(@users,$key);
6136: } elsif ($scope eq 'course') {
6137: push(@courses,$key);
6138: } elsif ($scope eq 'group') {
6139: push(@groups,$key);
1.1270 raeburn 6140: } elsif ($scope eq 'ip') {
6141: push(@ips,$key);
1.765 albertel 6142: }
6143: }
6144: if ($public) {
6145: return 'ok';
1.1270 raeburn 6146: } elsif (@ips > 0) {
6147: my $allowed;
6148: foreach my $ipkey (@ips) {
6149: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6150: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6151: $allowed = 1;
6152: last;
6153: }
6154: }
6155: }
6156: if ($allowed) {
6157: return 'ok';
6158: }
1.765 albertel 6159: }
6160: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6161: if ($guest) {
6162: return $guest;
6163: }
6164: } else {
6165: if (@domains > 0) {
6166: foreach my $domkey (@domains) {
6167: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6168: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6169: return 'ok';
6170: }
6171: }
6172: }
6173: }
6174: if (@users > 0) {
6175: foreach my $userkey (@users) {
1.865 raeburn 6176: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6177: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6178: if (ref($item) eq 'HASH') {
6179: if (($item->{'uname'} eq $env{'user.name'}) &&
6180: ($item->{'udom'} eq $env{'user.domain'})) {
6181: return 'ok';
6182: }
6183: }
6184: }
6185: }
1.765 albertel 6186: }
6187: }
6188: my %roleshash;
6189: my @courses_and_groups = @courses;
6190: push(@courses_and_groups,@groups);
6191: if (@courses_and_groups > 0) {
6192: my (%allgroups,%allroles);
6193: my ($start,$end,$role,$sec,$group);
6194: foreach my $envkey (%env) {
1.1060 raeburn 6195: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6196: my $cid = $2.'_'.$3;
6197: if ($1 eq 'gr') {
6198: $group = $4;
6199: $allgroups{$cid}{$group} = $env{$envkey};
6200: } else {
6201: if ($4 eq '') {
6202: $sec = 'none';
6203: } else {
6204: $sec = $4;
6205: }
6206: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6207: }
1.811 albertel 6208: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6209: my $cid = $2.'_'.$3;
6210: if ($4 eq '') {
6211: $sec = 'none';
6212: } else {
6213: $sec = $4;
6214: }
6215: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6216: }
6217: }
6218: if (keys(%allroles) == 0) {
6219: return;
6220: }
6221: foreach my $key (@courses_and_groups) {
6222: my %content = %{$$access_hash{$key}};
6223: my $cnum = $content{'number'};
6224: my $cdom = $content{'domain'};
6225: my $cid = $cdom.'_'.$cnum;
6226: if (!exists($allroles{$cid})) {
6227: next;
6228: }
6229: foreach my $role_id (keys(%{$content{'roles'}})) {
6230: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6231: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6232: my @status = @{$content{'roles'}{$role_id}{'access'}};
6233: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6234: foreach my $role (keys(%{$allroles{$cid}})) {
6235: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6236: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6237: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6238: if (grep/^all$/,@sections) {
6239: return 'ok';
6240: } else {
6241: if (grep/^$sec$/,@sections) {
6242: return 'ok';
6243: }
6244: }
6245: }
6246: }
6247: if (keys(%{$allgroups{$cid}}) == 0) {
6248: if (grep/^none$/,@groups) {
6249: return 'ok';
6250: }
6251: } else {
6252: if (grep/^all$/,@groups) {
6253: return 'ok';
6254: }
6255: foreach my $group (keys(%{$allgroups{$cid}})) {
6256: if (grep/^$group$/,@groups) {
6257: return 'ok';
6258: }
6259: }
6260: }
6261: }
6262: }
6263: }
6264: }
6265: }
6266: if ($guest) {
6267: return $guest;
6268: }
6269: }
6270: }
6271: return;
6272: }
6273:
6274: sub course_group_datechecker {
6275: my ($dates,$now,$status) = @_;
6276: my ($start,$end) = split(/\./,$dates);
6277: if (!$start && !$end) {
6278: return 'ok';
6279: }
6280: if (grep/^active$/,@{$status}) {
6281: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6282: return 'ok';
6283: }
6284: }
6285: if (grep/^previous$/,@{$status}) {
6286: if ($end > $now ) {
6287: return 'ok';
6288: }
6289: }
6290: if (grep/^future$/,@{$status}) {
6291: if ($start > $now) {
6292: return 'ok';
6293: }
6294: }
6295: return;
6296: }
6297:
6298: sub parse_portfolio_url {
6299: my ($url) = @_;
6300:
6301: my ($type,$udom,$unum,$group,$file_name);
6302:
1.823 albertel 6303: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6304: $type = 1;
6305: $udom = $1;
6306: $unum = $2;
6307: $file_name = $3;
1.823 albertel 6308: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6309: $type = 2;
6310: $udom = $1;
6311: $unum = $2;
6312: $group = $3;
6313: $file_name = $3.'/'.$4;
6314: }
6315: if (wantarray) {
6316: return ($type,$udom,$unum,$file_name,$group);
6317: }
6318: return $type;
6319: }
6320:
6321: sub is_portfolio_url {
6322: my ($url) = @_;
6323: return scalar(&parse_portfolio_url($url));
6324: }
6325:
1.798 raeburn 6326: sub is_portfolio_file {
6327: my ($file) = @_;
1.820 raeburn 6328: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6329: return 1;
6330: }
6331: return;
6332: }
6333:
1.976 raeburn 6334: sub usertools_access {
1.1084 raeburn 6335: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6336: my ($access,%tools);
6337: if ($context eq '') {
6338: $context = 'tools';
6339: }
6340: if ($context eq 'requestcourses') {
6341: %tools = (
6342: official => 1,
6343: unofficial => 1,
1.1006 raeburn 6344: community => 1,
1.1246 raeburn 6345: textbook => 1,
1.985 raeburn 6346: );
1.1183 raeburn 6347: } elsif ($context eq 'requestauthor') {
6348: %tools = (
6349: requestauthor => 1,
6350: );
1.985 raeburn 6351: } else {
6352: %tools = (
6353: aboutme => 1,
6354: blog => 1,
1.1177 raeburn 6355: webdav => 1,
1.985 raeburn 6356: portfolio => 1,
6357: );
6358: }
1.976 raeburn 6359: return if (!defined($tools{$tool}));
6360:
1.1242 raeburn 6361: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6362: $udom = $env{'user.domain'};
6363: $uname = $env{'user.name'};
6364: }
6365:
1.978 raeburn 6366: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6367: if ($action ne 'reload') {
1.985 raeburn 6368: if ($context eq 'requestcourses') {
6369: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6370: } elsif ($context eq 'requestauthor') {
6371: return $env{'environment.canrequest.author'};
1.985 raeburn 6372: } else {
6373: return $env{'environment.availabletools.'.$tool};
6374: }
6375: }
1.976 raeburn 6376: }
6377:
1.1183 raeburn 6378: my ($toolstatus,$inststatus,$envkey);
6379: if ($context eq 'requestauthor') {
6380: $envkey = $context;
6381: } else {
6382: $envkey = $context.'.'.$tool;
6383: }
1.976 raeburn 6384:
1.985 raeburn 6385: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6386: ($action ne 'reload')) {
1.1183 raeburn 6387: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6388: $inststatus = $env{'environment.inststatus'};
6389: } else {
1.1084 raeburn 6390: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6391: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6392: $inststatus = $userenvref->{'inststatus'};
6393: } else {
1.1183 raeburn 6394: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6395: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6396: $inststatus = $userenv{'inststatus'};
6397: }
1.976 raeburn 6398: }
6399:
6400: if ($toolstatus ne '') {
6401: if ($toolstatus) {
6402: $access = 1;
6403: } else {
6404: $access = 0;
6405: }
6406: return $access;
6407: }
6408:
1.1084 raeburn 6409: my ($is_adv,%domdef);
6410: if (ref($is_advref) eq 'HASH') {
6411: $is_adv = $is_advref->{'is_adv'};
6412: } else {
6413: $is_adv = &is_advanced_user($udom,$uname);
6414: }
6415: if (ref($domdefref) eq 'HASH') {
6416: %domdef = %{$domdefref};
6417: } else {
6418: %domdef = &get_domain_defaults($udom);
6419: }
1.976 raeburn 6420: if (ref($domdef{$tool}) eq 'HASH') {
6421: if ($is_adv) {
6422: if ($domdef{$tool}{'_LC_adv'} ne '') {
6423: if ($domdef{$tool}{'_LC_adv'}) {
6424: $access = 1;
6425: } else {
6426: $access = 0;
6427: }
6428: return $access;
6429: }
6430: }
6431: if ($inststatus ne '') {
6432: my ($hasaccess,$hasnoaccess);
6433: foreach my $affiliation (split(/:/,$inststatus)) {
6434: if ($domdef{$tool}{$affiliation} ne '') {
6435: if ($domdef{$tool}{$affiliation}) {
6436: $hasaccess = 1;
6437: } else {
6438: $hasnoaccess = 1;
6439: }
6440: }
6441: }
6442: if ($hasaccess || $hasnoaccess) {
6443: if ($hasaccess) {
6444: $access = 1;
6445: } elsif ($hasnoaccess) {
6446: $access = 0;
6447: }
6448: return $access;
6449: }
6450: } else {
6451: if ($domdef{$tool}{'default'} ne '') {
6452: if ($domdef{$tool}{'default'}) {
6453: $access = 1;
6454: } elsif ($domdef{$tool}{'default'} == 0) {
6455: $access = 0;
6456: }
6457: return $access;
6458: }
6459: }
6460: } else {
1.1177 raeburn 6461: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6462: $access = 1;
6463: } else {
6464: $access = 0;
6465: }
1.976 raeburn 6466: return $access;
6467: }
6468: }
6469:
1.1050 raeburn 6470: sub is_course_owner {
6471: my ($cdom,$cnum,$udom,$uname) = @_;
6472: if (($udom eq '') || ($uname eq '')) {
6473: $udom = $env{'user.domain'};
6474: $uname = $env{'user.name'};
6475: }
6476: unless (($udom eq '') || ($uname eq '')) {
6477: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6478: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6479: return 1;
6480: } else {
6481: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6482: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6483: return 1;
6484: }
6485: }
6486: }
6487: }
6488: return;
6489: }
6490:
1.976 raeburn 6491: sub is_advanced_user {
6492: my ($udom,$uname) = @_;
1.1085 raeburn 6493: if ($udom ne '' && $uname ne '') {
6494: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6495: if (wantarray) {
6496: return ($env{'user.adv'},$env{'user.author'});
6497: } else {
6498: return $env{'user.adv'};
6499: }
1.1085 raeburn 6500: }
6501: }
1.976 raeburn 6502: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6503: my %allroles;
1.1128 raeburn 6504: my ($is_adv,$is_author);
1.976 raeburn 6505: foreach my $role (keys(%roleshash)) {
6506: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6507: my $area = '/'.$tdomain.'/'.$trest;
6508: if ($sec ne '') {
6509: $area .= '/'.$sec;
6510: }
6511: if (($area ne '') && ($trole ne '')) {
6512: my $spec=$trole.'.'.$area;
6513: if ($trole =~ /^cr\//) {
6514: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6515: } elsif ($trole ne 'gr') {
6516: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6517: }
1.1128 raeburn 6518: if ($trole eq 'au') {
6519: $is_author = 1;
6520: }
1.976 raeburn 6521: }
6522: }
6523: foreach my $role (keys(%allroles)) {
6524: last if ($is_adv);
6525: foreach my $item (split(/:/,$allroles{$role})) {
6526: if ($item ne '') {
6527: my ($privilege,$restrictions)=split(/&/,$item);
6528: if ($privilege eq 'adv') {
6529: $is_adv = 1;
6530: last;
6531: }
6532: }
6533: }
6534: }
1.1128 raeburn 6535: if (wantarray) {
6536: return ($is_adv,$is_author);
6537: }
1.976 raeburn 6538: return $is_adv;
6539: }
1.798 raeburn 6540:
1.1035 raeburn 6541: sub check_can_request {
1.1036 raeburn 6542: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6543: my $canreq = 0;
6544: my ($types,$typename) = &Apache::loncommon::course_types();
6545: my @options = ('approval','validate','autolimit');
6546: my $optregex = join('|',@options);
6547: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6548: foreach my $type (@{$types}) {
6549: if (&usertools_access($env{'user.name'},
6550: $env{'user.domain'},
6551: $type,undef,'requestcourses')) {
6552: $canreq ++;
1.1036 raeburn 6553: if (ref($request_domains) eq 'HASH') {
6554: push(@{$request_domains->{$type}},$env{'user.domain'});
6555: }
1.1035 raeburn 6556: if ($dom eq $env{'user.domain'}) {
6557: $can_request->{$type} = 1;
6558: }
6559: }
6560: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6561: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6562: if (@curr > 0) {
1.1036 raeburn 6563: foreach my $item (@curr) {
6564: if (ref($request_domains) eq 'HASH') {
6565: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6566: if ($otherdom ne '') {
6567: if (ref($request_domains->{$type}) eq 'ARRAY') {
6568: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6569: push(@{$request_domains->{$type}},$otherdom);
6570: }
6571: } else {
6572: push(@{$request_domains->{$type}},$otherdom);
6573: }
6574: }
6575: }
6576: }
6577: unless($dom eq $env{'user.domain'}) {
6578: $canreq ++;
1.1035 raeburn 6579: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6580: $can_request->{$type} = 1;
6581: }
6582: }
6583: }
6584: }
6585: }
6586: }
6587: return $canreq;
6588: }
6589:
1.341 www 6590: # ---------------------------------------------- Custom access rule evaluation
6591:
6592: sub customaccess {
6593: my ($priv,$uri)=@_;
1.807 albertel 6594: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6595: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6596: $udom = &LONCAPA::clean_domain($udom);
6597: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6598: my $access=0;
1.800 albertel 6599: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6600: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6601: if ($type eq 'user') {
6602: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6603: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6604: if ($tdom) {
6605: if ($tdom ne $env{'user.domain'}) { next; }
6606: }
1.896 albertel 6607: if ($tuname) {
6608: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6609: }
6610: $access=($effect eq 'allow');
6611: last;
6612: }
6613: } else {
6614: if ($role) {
6615: if ($role ne $urole) { next; }
6616: }
6617: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6618: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6619: if ($tdom) {
6620: if ($tdom ne $udom) { next; }
6621: }
6622: if ($tcrs) {
6623: if ($tcrs ne $ucrs) { next; }
6624: }
6625: if ($tsec) {
6626: if ($tsec ne $usec) { next; }
6627: }
6628: $access=($effect eq 'allow');
6629: last;
6630: }
6631: if ($realm eq '' && $role eq '') {
6632: $access=($effect eq 'allow');
6633: }
1.402 bowersj2 6634: }
1.341 www 6635: }
6636: return $access;
6637: }
6638:
1.103 harris41 6639: # ------------------------------------------------- Check for a user privilege
1.12 www 6640:
6641: sub allowed {
1.1270 raeburn 6642: my ($priv,$uri,$symb,$role,$clientip)=@_;
1.705 albertel 6643: my $ver_orguri=$uri;
1.439 www 6644: $uri=&deversion($uri);
1.152 www 6645: my $orguri=$uri;
1.52 www 6646: $uri=&declutter($uri);
1.809 raeburn 6647:
1.810 raeburn 6648: if ($priv eq 'evb') {
6649: # Evade communication block restrictions for specified role in a course
6650: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6651: return $1;
6652: } else {
6653: return;
6654: }
6655: }
6656:
1.620 albertel 6657: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6658: # Free bre access to adm and meta resources
1.775 albertel 6659: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6660: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6661: && ($priv eq 'bre')) {
1.14 www 6662: return 'F';
1.159 www 6663: }
6664:
1.545 banghart 6665: # Free bre access to user's own portfolio contents
1.714 raeburn 6666: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6667: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6668: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6669: my %setters;
6670: my ($startblock,$endblock) =
6671: &Apache::loncommon::blockcheck(\%setters,'port');
6672: if ($startblock && $endblock) {
6673: return 'B';
6674: } else {
6675: return 'F';
6676: }
1.545 banghart 6677: }
6678:
1.762 raeburn 6679: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6680: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6681: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6682: if (exists($env{'request.course.id'})) {
6683: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6684: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6685: if (($domain eq $cdom) && ($name eq $cnum)) {
6686: my $courseprivid=$env{'request.course.id'};
6687: $courseprivid=~s/\_/\//;
6688: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6689: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6690: return $1;
1.762 raeburn 6691: } else {
6692: if ($env{'request.course.sec'}) {
6693: $courseprivid.='/'.$env{'request.course.sec'};
6694: }
6695: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6696: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6697: return $2;
6698: }
1.714 raeburn 6699: }
6700: }
6701: }
6702: }
6703:
1.159 www 6704: # Free bre to public access
6705:
6706: if ($priv eq 'bre') {
1.238 www 6707: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6708: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6709: return 'F';
6710: }
1.238 www 6711: if ($copyright eq 'priv') {
6712: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6713: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6714: return '';
6715: }
6716: }
6717: if ($copyright eq 'domain') {
6718: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6719: unless (($env{'user.domain'} eq $1) ||
6720: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6721: return '';
6722: }
1.262 matthew 6723: }
1.620 albertel 6724: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6725: # Library role, so allow browsing of resources in this domain.
6726: return 'F';
1.238 www 6727: }
1.341 www 6728: if ($copyright eq 'custom') {
6729: unless (&customaccess($priv,$uri)) { return ''; }
6730: }
1.14 www 6731: }
1.264 matthew 6732: # Domain coordinator is trying to create a course
1.620 albertel 6733: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6734: # uri is the requested domain in this case.
6735: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6736: # a role of dc for the domain in question.
1.620 albertel 6737: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6738: }
1.29 www 6739:
1.52 www 6740: my $thisallowed='';
6741: my $statecond=0;
6742: my $courseprivid='';
6743:
1.1039 raeburn 6744: my $ownaccess;
1.1043 raeburn 6745: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6746: if (($priv eq 'bro') && ($env{'user.author'})) {
6747: if ($uri eq '') {
6748: $ownaccess = 1;
6749: } else {
6750: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6751: my $udom = $env{'user.domain'};
6752: my $uname = $env{'user.name'};
6753: if ($uri =~ m{^\Q$udom\E/?$}) {
6754: $ownaccess = 1;
1.1040 raeburn 6755: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6756: unless ($uri =~ m{\.\./}) {
6757: $ownaccess = 1;
6758: }
6759: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6760: my $now = time;
6761: if ($uri =~ m{^([^/]+)/?$}) {
6762: my $adom = $1;
6763: foreach my $key (keys(%env)) {
1.1042 raeburn 6764: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6765: my ($start,$end) = split('.',$env{$key});
6766: if (($now >= $start) && (!$end || $end < $now)) {
6767: $ownaccess = 1;
6768: last;
6769: }
6770: }
6771: }
6772: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6773: my $adom = $1;
6774: my $aname = $2;
1.1042 raeburn 6775: foreach my $role ('ca','aa') {
6776: if ($env{"user.role.$role./$adom/$aname"}) {
6777: my ($start,$end) =
6778: split('.',$env{"user.role.$role./$adom/$aname"});
6779: if (($now >= $start) && (!$end || $end < $now)) {
6780: $ownaccess = 1;
6781: last;
6782: }
1.1039 raeburn 6783: }
6784: }
6785: }
6786: }
6787: }
6788: }
6789: }
6790:
1.52 www 6791: # Course
6792:
1.620 albertel 6793: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6794: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6795: $thisallowed.=$1;
6796: }
1.52 www 6797: }
1.29 www 6798:
1.52 www 6799: # Domain
6800:
1.620 albertel 6801: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6802: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6803: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6804: $thisallowed.=$1;
6805: }
1.12 www 6806: }
1.52 www 6807:
1.1141 raeburn 6808: # User who is not author or co-author might still be able to edit
6809: # resource of an author in the domain (e.g., if Domain Coordinator).
6810: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6811: (&allowed('mdc',$env{'request.course.id'}))) {
6812: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6813: $thisallowed.=$1;
6814: }
6815: }
6816:
1.52 www 6817: # Course: uri itself is a course
1.66 www 6818: my $courseuri=$uri;
6819: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6820: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6821:
1.620 albertel 6822: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6823: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6824: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6825: $thisallowed.=$1;
6826: }
1.12 www 6827: }
1.29 www 6828:
1.665 albertel 6829: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6830: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6831: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6832: $thisallowed='';
1.671 raeburn 6833: my ($match)=&is_on_map($uri);
6834: if ($match) {
6835: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6836: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6837: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6838: if (@blockers > 0) {
6839: $thisallowed = 'B';
6840: } else {
6841: $thisallowed.=$1;
6842: }
1.671 raeburn 6843: }
6844: } else {
1.705 albertel 6845: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6846: if ($refuri) {
6847: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6848: $thisallowed='F';
1.671 raeburn 6849: } else {
6850: $refuri=&declutter($refuri);
6851: my ($match) = &is_on_map($refuri);
6852: if ($match) {
1.1162 raeburn 6853: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6854: if (@blockers > 0) {
6855: $thisallowed = 'B';
6856: } else {
6857: $thisallowed='F';
6858: }
1.671 raeburn 6859: }
1.669 raeburn 6860: }
1.671 raeburn 6861: }
6862: }
1.314 www 6863: }
1.492 albertel 6864:
1.766 albertel 6865: if ($priv eq 'bre'
6866: && $thisallowed ne 'F'
6867: && $thisallowed ne '2'
6868: && &is_portfolio_url($uri)) {
1.1270 raeburn 6869: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 6870: }
1.1250 raeburn 6871:
1.52 www 6872: # Full access at system, domain or course-wide level? Exit.
1.29 www 6873: if ($thisallowed=~/F/) {
6874: return 'F';
6875: }
6876:
1.52 www 6877: # If this is generating or modifying users, exit with special codes
1.29 www 6878:
1.643 www 6879: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6880: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6881: my ($audom,$auname)=split('/',$uri);
1.643 www 6882: # no author name given, so this just checks on the general right to make a co-author in this domain
6883: unless ($auname) { return $thisallowed; }
6884: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6885: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6886: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6887: ($audom ne $env{'request.role.domain'}))) { return ''; }
6888: }
1.52 www 6889: return $thisallowed;
6890: }
6891: #
1.103 harris41 6892: # Gathered so far: system, domain and course wide privileges
1.52 www 6893: #
6894: # Course: See if uri or referer is an individual resource that is part of
6895: # the course
6896:
1.620 albertel 6897: if ($env{'request.course.id'}) {
1.232 www 6898:
1.620 albertel 6899: $courseprivid=$env{'request.course.id'};
6900: if ($env{'request.course.sec'}) {
6901: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6902: }
6903: $courseprivid=~s/\_/\//;
6904: my $checkreferer=1;
1.232 www 6905: my ($match,$cond)=&is_on_map($uri);
6906: if ($match) {
6907: $statecond=$cond;
1.620 albertel 6908: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6909: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6910: my $value = $1;
6911: if ($priv eq 'bre') {
6912: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6913: if (@blockers > 0) {
6914: $thisallowed = 'B';
6915: } else {
6916: $thisallowed.=$value;
6917: }
6918: } else {
6919: $thisallowed.=$value;
6920: }
1.52 www 6921: $checkreferer=0;
6922: }
1.29 www 6923: }
1.83 www 6924:
1.148 www 6925: if ($checkreferer) {
1.620 albertel 6926: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6927: unless ($refuri) {
1.800 albertel 6928: foreach my $key (keys(%env)) {
6929: if ($key=~/^httpref\..*\*/) {
6930: my $pattern=$key;
1.156 www 6931: $pattern=~s/^httpref\.\/res\///;
1.148 www 6932: $pattern=~s/\*/\[\^\/\]\+/g;
6933: $pattern=~s/\//\\\//g;
1.152 www 6934: if ($orguri=~/$pattern/) {
1.800 albertel 6935: $refuri=$env{$key};
1.148 www 6936: }
6937: }
1.191 harris41 6938: }
1.148 www 6939: }
1.232 www 6940:
1.148 www 6941: if ($refuri) {
1.152 www 6942: $refuri=&declutter($refuri);
1.232 www 6943: my ($match,$cond)=&is_on_map($refuri);
6944: if ($match) {
6945: my $refstatecond=$cond;
1.620 albertel 6946: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6947: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6948: my $value = $1;
6949: if ($priv eq 'bre') {
6950: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6951: if (@blockers > 0) {
6952: $thisallowed = 'B';
6953: } else {
6954: $thisallowed.=$value;
6955: }
6956: } else {
6957: $thisallowed.=$value;
6958: }
1.53 www 6959: $uri=$refuri;
6960: $statecond=$refstatecond;
1.52 www 6961: }
6962: }
1.148 www 6963: }
1.29 www 6964: }
1.52 www 6965: }
1.29 www 6966:
1.52 www 6967: #
1.103 harris41 6968: # Gathered now: all privileges that could apply, and condition number
1.52 www 6969: #
6970: #
6971: # Full or no access?
6972: #
1.29 www 6973:
1.52 www 6974: if ($thisallowed=~/F/) {
6975: return 'F';
6976: }
1.29 www 6977:
1.52 www 6978: unless ($thisallowed) {
6979: return '';
6980: }
1.29 www 6981:
1.52 www 6982: # Restrictions exist, deal with them
6983: #
6984: # C:according to course preferences
6985: # R:according to resource settings
6986: # L:unless locked
6987: # X:according to user session state
6988: #
6989:
6990: # Possibly locked functionality, check all courses
1.54 www 6991: # Locks might take effect only after 10 minutes cache expiration for other
6992: # courses, and 2 minutes for current course
1.52 www 6993:
6994: my $envkey;
6995: if ($thisallowed=~/L/) {
1.1000 raeburn 6996: foreach $envkey (keys(%env)) {
1.54 www 6997: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6998: my $courseid=$2;
6999: my $roleid=$1.'.'.$2;
1.92 www 7000: $courseid=~s/^\///;
1.54 www 7001: my $expiretime=600;
1.620 albertel 7002: if ($env{'request.role'} eq $roleid) {
1.54 www 7003: $expiretime=120;
7004: }
7005: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7006: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7007: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7008: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7009: }
1.620 albertel 7010: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7011: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7012: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7013: &log($env{'user.domain'},$env{'user.name'},
7014: $env{'user.home'},
1.57 www 7015: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7016: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7017: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7018: return '';
7019: }
7020: }
1.620 albertel 7021: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7022: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7023: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7024: &log($env{'user.domain'},$env{'user.name'},
7025: $env{'user.home'},
1.57 www 7026: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7027: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7028: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7029: return '';
7030: }
7031: }
7032: }
1.29 www 7033: }
1.52 www 7034: }
7035:
7036: #
7037: # Rest of the restrictions depend on selected course
7038: #
7039:
1.620 albertel 7040: unless ($env{'request.course.id'}) {
1.766 albertel 7041: if ($thisallowed eq 'A') {
7042: return 'A';
1.814 raeburn 7043: } elsif ($thisallowed eq 'B') {
7044: return 'B';
1.766 albertel 7045: } else {
7046: return '1';
7047: }
1.52 www 7048: }
1.29 www 7049:
1.52 www 7050: #
7051: # Now user is definitely in a course
7052: #
1.53 www 7053:
7054:
7055: # Course preferences
7056:
7057: if ($thisallowed=~/C/) {
1.620 albertel 7058: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7059: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7060: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7061: =~/\Q$rolecode\E/) {
1.1103 raeburn 7062: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7063: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7064: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7065: $env{'request.course.id'});
7066: }
1.237 www 7067: return '';
7068: }
7069:
1.620 albertel 7070: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7071: =~/\Q$unamedom\E/) {
1.1103 raeburn 7072: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7073: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7074: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7075: $env{'request.course.id'});
7076: }
1.54 www 7077: return '';
7078: }
1.53 www 7079: }
7080:
7081: # Resource preferences
7082:
7083: if ($thisallowed=~/R/) {
1.620 albertel 7084: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7085: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7086: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7087: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7088: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7089: }
7090: return '';
1.54 www 7091: }
1.53 www 7092: }
1.30 www 7093:
1.246 www 7094: # Restricted by state or randomout?
1.30 www 7095:
1.52 www 7096: if ($thisallowed=~/X/) {
1.620 albertel 7097: if ($env{'acc.randomout'}) {
1.579 albertel 7098: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7099: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7100: return '';
7101: }
1.247 www 7102: }
7103: if (&condval($statecond)) {
1.52 www 7104: return '2';
7105: } else {
7106: return '';
7107: }
7108: }
1.30 www 7109:
1.766 albertel 7110: if ($thisallowed eq 'A') {
7111: return 'A';
1.814 raeburn 7112: } elsif ($thisallowed eq 'B') {
7113: return 'B';
1.766 albertel 7114: }
1.52 www 7115: return 'F';
1.232 www 7116: }
1.1162 raeburn 7117:
1.1192 raeburn 7118: # ------------------------------------------- Check construction space access
7119:
7120: sub constructaccess {
7121: my ($url,$setpriv)=@_;
7122:
7123: # We do not allow editing of previous versions of files
7124: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7125:
7126: # Get username and domain from URL
7127: my ($ownername,$ownerdomain,$ownerhome);
7128:
7129: ($ownerdomain,$ownername) =
7130: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7131:
7132: # The URL does not really point to any authorspace, forget it
7133: unless (($ownername) && ($ownerdomain)) { return ''; }
7134:
7135: # Now we need to see if the user has access to the authorspace of
7136: # $ownername at $ownerdomain
7137:
7138: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7139: # Real author for this?
7140: $ownerhome = $env{'user.home'};
7141: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7142: return ($ownername,$ownerdomain,$ownerhome);
7143: }
7144: } else {
7145: # Co-author for this?
7146: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7147: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7148: $ownerhome = &homeserver($ownername,$ownerdomain);
7149: return ($ownername,$ownerdomain,$ownerhome);
7150: }
7151: }
7152:
7153: # We don't have any access right now. If we are not possibly going to do anything about this,
7154: # we might as well leave
7155: unless ($setpriv) { return ''; }
7156:
7157: # Backdoor access?
7158: my $allowed=&allowed('eco',$ownerdomain);
7159: # Nope
7160: unless ($allowed) { return ''; }
7161: # Looks like we may have access, but could be locked by the owner of the construction space
7162: if ($allowed eq 'U') {
7163: my %blocked=&get('environment',['domcoord.author'],
7164: $ownerdomain,$ownername);
7165: # Is blocked by owner
7166: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7167: }
7168: if (($allowed eq 'F') || ($allowed eq 'U')) {
7169: # Grant temporary access
7170: my $then=$env{'user.login.time'};
1.1209 raeburn 7171: my $update=$env{'user.update.time'};
1.1192 raeburn 7172: if (!$update) { $update = $then; }
7173: my $refresh=$env{'user.refresh.time'};
7174: if (!$refresh) { $refresh = $update; }
7175: my $now = time;
7176: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7177: $now,'ca','constructaccess');
7178: $ownerhome = &homeserver($ownername,$ownerdomain);
7179: return($ownername,$ownerdomain,$ownerhome);
7180: }
7181: # No business here
7182: return '';
7183: }
7184:
1.1162 raeburn 7185: sub get_comm_blocks {
7186: my ($cdom,$cnum) = @_;
7187: if ($cdom eq '' || $cnum eq '') {
7188: return unless ($env{'request.course.id'});
7189: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7190: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7191: }
7192: my %commblocks;
7193: my $hashid=$cdom.'_'.$cnum;
7194: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7195: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7196: %commblocks = %{$blocksref};
7197: } else {
7198: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7199: my $cachetime = 600;
7200: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7201: }
7202: return %commblocks;
7203: }
7204:
7205: sub has_comm_blocking {
7206: my ($priv,$symb,$uri,$blocks) = @_;
7207: return unless ($env{'request.course.id'});
7208: return unless ($priv eq 'bre');
7209: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7210: my %commblocks;
7211: if (ref($blocks) eq 'HASH') {
7212: %commblocks = %{$blocks};
7213: } else {
7214: %commblocks = &get_comm_blocks();
7215: }
7216: return unless (keys(%commblocks) > 0);
7217: if (!$symb) { $symb=&symbread($uri,1); }
7218: my ($map,$resid,undef)=&decode_symb($symb);
7219: my %tocheck = (
7220: maps => $map,
7221: resources => $symb,
7222: );
7223: my @blockers;
7224: my $now = time;
1.1163 raeburn 7225: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7226: foreach my $block (keys(%commblocks)) {
7227: if ($block =~ /^(\d+)____(\d+)$/) {
7228: my ($start,$end) = ($1,$2);
7229: if ($start <= $now && $end >= $now) {
7230: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7231: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7232: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7233: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7234: unless (grep(/^\Q$block\E$/,@blockers)) {
7235: push(@blockers,$block);
7236: }
7237: }
7238: }
7239: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7240: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7241: unless (grep(/^\Q$block\E$/,@blockers)) {
7242: push(@blockers,$block);
7243: }
7244: }
7245: }
7246: }
7247: }
7248: }
7249: } elsif ($block =~ /^firstaccess____(.+)$/) {
7250: my $item = $1;
1.1163 raeburn 7251: my @to_test;
1.1162 raeburn 7252: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7253: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7254: my $check_interval;
7255: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7256: my @interval;
7257: my $type = 'map';
7258: if ($item eq 'course') {
7259: $type = 'course';
7260: @interval=&EXT("resource.0.interval");
7261: } else {
7262: if ($item =~ /___\d+___/) {
7263: $type = 'resource';
7264: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7265: if (ref($navmap)) {
7266: my $res = $navmap->getBySymb($item);
7267: push(@to_test,$res);
7268: }
1.1162 raeburn 7269: } else {
7270: my $mapsymb = &symbread($item,1);
7271: if ($mapsymb) {
7272: if (ref($navmap)) {
7273: my $mapres = $navmap->getBySymb($mapsymb);
1.1280 ! raeburn 7274: @to_test = $mapres->retrieveResources($mapres);
1.1163 raeburn 7275: foreach my $res (@to_test) {
1.1162 raeburn 7276: my $symb = $res->symb();
7277: next if ($symb eq $mapsymb);
7278: if ($symb ne '') {
7279: @interval=&EXT("resource.0.interval",$symb);
1.1280 ! raeburn 7280: if ($interval[1] eq 'map') {
! 7281: last;
! 7282: }
1.1162 raeburn 7283: }
7284: }
7285: }
7286: }
7287: }
7288: }
7289: if ($interval[0] =~ /\d+/) {
7290: my $first_access;
7291: if ($type eq 'resource') {
7292: $first_access=&get_first_access($interval[1],$item);
7293: } elsif ($type eq 'map') {
7294: $first_access=&get_first_access($interval[1],undef,$item);
7295: } else {
7296: $first_access=&get_first_access($interval[1]);
7297: }
7298: if ($first_access) {
7299: my $timesup = $first_access+$interval[0];
7300: if ($timesup > $now) {
1.1163 raeburn 7301: foreach my $res (@to_test) {
7302: if ($res->is_problem()) {
7303: if ($res->completable()) {
7304: unless (grep(/^\Q$block\E$/,@blockers)) {
7305: push(@blockers,$block);
7306: }
7307: last;
7308: }
7309: }
1.1162 raeburn 7310: }
7311: }
7312: }
7313: }
7314: }
7315: }
7316: }
7317: }
7318: }
7319: return @blockers;
7320: }
7321:
7322: sub check_docs_block {
7323: my ($docsblock,$tocheck) =@_;
7324: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7325: return;
7326: }
7327: if (ref($docsblock->{'maps'}) eq 'HASH') {
7328: if ($tocheck->{'maps'}) {
7329: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7330: return 1;
7331: }
7332: }
7333: }
7334: if (ref($docsblock->{'resources'}) eq 'HASH') {
7335: if ($tocheck->{'resources'}) {
7336: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7337: return 1;
7338: }
7339: }
7340: }
7341: return;
7342: }
7343:
1.1133 foxr 7344: #
7345: # Removes the versino from a URI and
7346: # splits it in to its filename and path to the filename.
7347: # Seems like File::Basename could have done this more clearly.
7348: # Parameters:
7349: # $uri - input URI
7350: # Returns:
7351: # Two element list consisting of
7352: # $pathname - the URI up to and excluding the trailing /
7353: # $filename - The part of the URI following the last /
7354: # NOTE:
7355: # Another realization of this is simply:
7356: # use File::Basename;
7357: # ...
7358: # $uri = shift;
7359: # $filename = basename($uri);
7360: # $path = dirname($uri);
7361: # return ($filename, $path);
7362: #
7363: # The implementation below is probably faster however.
7364: #
1.710 albertel 7365: sub split_uri_for_cond {
7366: my $uri=&deversion(&declutter(shift));
7367: my @uriparts=split(/\//,$uri);
7368: my $filename=pop(@uriparts);
7369: my $pathname=join('/',@uriparts);
7370: return ($pathname,$filename);
7371: }
1.232 www 7372: # --------------------------------------------------- Is a resource on the map?
7373:
7374: sub is_on_map {
1.710 albertel 7375: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7376: #Trying to find the conditional for the file
1.620 albertel 7377: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7378: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7379: if ($match) {
1.289 bowersj2 7380: return (1,$1);
7381: } else {
1.434 www 7382: return (0,0);
1.289 bowersj2 7383: }
1.12 www 7384: }
7385:
1.427 www 7386: # --------------------------------------------------------- Get symb from alias
7387:
7388: sub get_symb_from_alias {
7389: my $symb=shift;
7390: my ($map,$resid,$url)=&decode_symb($symb);
7391: # Already is a symb
7392: if ($url) { return $symb; }
7393: # Must be an alias
7394: my $aliassymb='';
7395: my %bighash;
1.620 albertel 7396: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7397: &GDBM_READER(),0640)) {
7398: my $rid=$bighash{'mapalias_'.$symb};
7399: if ($rid) {
7400: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7401: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7402: $resid,$bighash{'src_'.$rid});
1.427 www 7403: }
7404: untie %bighash;
7405: }
7406: return $aliassymb;
7407: }
7408:
1.12 www 7409: # ----------------------------------------------------------------- Define Role
7410:
7411: sub definerole {
7412: if (allowed('mcr','/')) {
7413: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7414: foreach my $role (split(':',$sysrole)) {
7415: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7416: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7417: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7418: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7419: return "refused:s:$crole&$cqual";
7420: }
7421: }
1.191 harris41 7422: }
1.800 albertel 7423: foreach my $role (split(':',$domrole)) {
7424: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7425: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7426: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7427: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7428: return "refused:d:$crole&$cqual";
7429: }
7430: }
1.191 harris41 7431: }
1.800 albertel 7432: foreach my $role (split(':',$courole)) {
7433: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7434: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7435: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7436: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7437: return "refused:c:$crole&$cqual";
7438: }
7439: }
1.191 harris41 7440: }
1.620 albertel 7441: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7442: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7443: "rolesdef_$rolename=".
7444: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7445: return reply($command,$env{'user.home'});
1.12 www 7446: } else {
7447: return 'refused';
7448: }
1.105 harris41 7449: }
7450:
7451: # ---------------- Make a metadata query against the network of library servers
7452:
7453: sub metadata_query {
1.1237 raeburn 7454: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7455: my %rhash;
1.845 albertel 7456: my %libserv = &all_library();
1.244 matthew 7457: my @server_list = (defined($server_array) ? @$server_array
7458: : keys(%libserv) );
7459: for my $server (@server_list) {
1.1237 raeburn 7460: my $domains = '';
7461: if (ref($domains_hash) eq 'HASH') {
7462: $domains = $domains_hash->{$server};
7463: }
1.118 harris41 7464: unless ($custom or $customshow) {
1.1237 raeburn 7465: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7466: $rhash{$server}=$reply;
7467: }
7468: else {
7469: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7470: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7471: $server);
7472: $rhash{$server}=$reply;
7473: }
1.112 harris41 7474: }
1.118 harris41 7475: return \%rhash;
1.240 www 7476: }
7477:
7478: # ----------------------------------------- Send log queries and wait for reply
7479:
7480: sub log_query {
7481: my ($uname,$udom,$query,%filters)=@_;
7482: my $uhome=&homeserver($uname,$udom);
7483: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7484: my $uhost=&hostname($uhome);
1.800 albertel 7485: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7486: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7487: $uhome);
1.479 albertel 7488: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7489: return get_query_reply($queryid);
7490: }
7491:
1.818 raeburn 7492: # -------------------------- Update MySQL table for portfolio file
7493:
7494: sub update_portfolio_table {
1.821 raeburn 7495: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7496: if ($group ne '') {
7497: $file_name =~s /^\Q$group\E//;
7498: }
1.818 raeburn 7499: my $homeserver = &homeserver($uname,$udom);
7500: my $queryid=
1.821 raeburn 7501: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7502: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7503: my $reply = &get_query_reply($queryid);
7504: return $reply;
7505: }
7506:
1.899 raeburn 7507: # -------------------------- Update MySQL allusers table
7508:
7509: sub update_allusers_table {
7510: my ($uname,$udom,$names) = @_;
7511: my $homeserver = &homeserver($uname,$udom);
7512: my $queryid=
7513: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7514: 'lastname='.&escape($names->{'lastname'}).'%%'.
7515: 'firstname='.&escape($names->{'firstname'}).'%%'.
7516: 'middlename='.&escape($names->{'middlename'}).'%%'.
7517: 'generation='.&escape($names->{'generation'}).'%%'.
7518: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7519: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7520: return;
1.899 raeburn 7521: }
7522:
1.508 raeburn 7523: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7524:
7525: sub fetch_enrollment_query {
1.511 raeburn 7526: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7527: my $homeserver;
1.547 raeburn 7528: my $maxtries = 1;
1.508 raeburn 7529: if ($context eq 'automated') {
7530: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7531: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7532: } else {
7533: $homeserver = &homeserver($cnum,$dom);
7534: }
1.838 albertel 7535: my $host=&hostname($homeserver);
1.506 raeburn 7536: my $cmd = '';
1.1000 raeburn 7537: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7538: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7539: }
7540: $cmd =~ s/%%$//;
7541: $cmd = &escape($cmd);
7542: my $query = 'fetchenrollment';
1.620 albertel 7543: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7544: unless ($queryid=~/^\Q$host\E\_/) {
7545: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7546: return 'error: '.$queryid;
7547: }
1.506 raeburn 7548: my $reply = &get_query_reply($queryid);
1.547 raeburn 7549: my $tries = 1;
7550: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7551: $reply = &get_query_reply($queryid);
7552: $tries ++;
7553: }
1.526 raeburn 7554: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7555: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7556: } else {
1.901 albertel 7557: my @responses = split(/:/,$reply);
1.515 raeburn 7558: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7559: foreach my $line (@responses) {
7560: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7561: $$replyref{$key} = $value;
7562: }
7563: } else {
1.1117 foxr 7564: my $pathname = LONCAPA::tempdir();
1.800 albertel 7565: foreach my $line (@responses) {
7566: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7567: $$replyref{$key} = $value;
7568: if ($value > 0) {
1.800 albertel 7569: foreach my $item (@{$$affiliatesref{$key}}) {
7570: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7571: my $destname = $pathname.'/'.$filename;
7572: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7573: if ($xml_classlist =~ /^error/) {
7574: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7575: } else {
1.506 raeburn 7576: if ( open(FILE,">$destname") ) {
7577: print FILE &unescape($xml_classlist);
7578: close(FILE);
1.526 raeburn 7579: } else {
7580: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7581: }
7582: }
7583: }
7584: }
7585: }
7586: }
7587: return 'ok';
7588: }
7589: return 'error';
7590: }
7591:
1.242 www 7592: sub get_query_reply {
7593: my $queryid=shift;
1.1117 foxr 7594: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7595: my $reply='';
7596: for (1..100) {
7597: sleep 2;
7598: if (-e $replyfile.'.end') {
1.448 albertel 7599: if (open(my $fh,$replyfile)) {
1.904 albertel 7600: $reply = join('',<$fh>);
7601: close($fh);
1.240 www 7602: } else { return 'error: reply_file_error'; }
1.242 www 7603: return &unescape($reply);
7604: }
1.240 www 7605: }
1.242 www 7606: return 'timeout:'.$queryid;
1.240 www 7607: }
7608:
7609: sub courselog_query {
1.241 www 7610: #
7611: # possible filters:
7612: # url: url or symb
7613: # username
7614: # domain
7615: # action: view, submit, grade
7616: # start: timestamp
7617: # end: timestamp
7618: #
1.240 www 7619: my (%filters)=@_;
1.620 albertel 7620: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7621: if ($filters{'url'}) {
7622: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7623: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7624: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7625: }
1.620 albertel 7626: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7627: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7628: return &log_query($cname,$cdom,'courselog',%filters);
7629: }
7630:
7631: sub userlog_query {
1.858 raeburn 7632: #
7633: # possible filters:
7634: # action: log check role
7635: # start: timestamp
7636: # end: timestamp
7637: #
1.240 www 7638: my ($uname,$udom,%filters)=@_;
7639: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7640: }
7641:
1.506 raeburn 7642: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7643:
7644: sub auto_run {
1.508 raeburn 7645: my ($cnum,$cdom) = @_;
1.876 raeburn 7646: my $response = 0;
7647: my $settings;
7648: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7649: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7650: $settings = $domconfig{'autoenroll'};
7651: if ($settings->{'run'} eq '1') {
7652: $response = 1;
7653: }
7654: } else {
1.934 raeburn 7655: my $homeserver;
7656: if (&is_course($cdom,$cnum)) {
7657: $homeserver = &homeserver($cnum,$cdom);
7658: } else {
7659: $homeserver = &domain($cdom,'primary');
7660: }
7661: if ($homeserver ne 'no_host') {
7662: $response = &reply('autorun:'.$cdom,$homeserver);
7663: }
1.876 raeburn 7664: }
1.506 raeburn 7665: return $response;
7666: }
1.776 albertel 7667:
1.506 raeburn 7668: sub auto_get_sections {
1.508 raeburn 7669: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7670: my $homeserver;
7671: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7672: $homeserver = &homeserver($cnum,$cdom);
7673: }
7674: if (!defined($homeserver)) {
7675: if ($cdom =~ /^$match_domain$/) {
7676: $homeserver = &domain($cdom,'primary');
7677: }
7678: }
7679: my @secs;
7680: if (defined($homeserver)) {
7681: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7682: unless ($response eq 'refused') {
7683: @secs = split(/:/,$response);
7684: }
1.506 raeburn 7685: }
7686: return @secs;
7687: }
1.776 albertel 7688:
1.506 raeburn 7689: sub auto_new_course {
1.1099 raeburn 7690: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7691: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7692: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7693: return $response;
7694: }
1.776 albertel 7695:
1.506 raeburn 7696: sub auto_validate_courseID {
1.508 raeburn 7697: my ($cnum,$cdom,$inst_course_id) = @_;
7698: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7699: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7700: return $response;
7701: }
1.776 albertel 7702:
1.1007 raeburn 7703: sub auto_validate_instcode {
1.1020 raeburn 7704: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7705: my ($homeserver,$response);
7706: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7707: $homeserver = &homeserver($cnum,$cdom);
7708: }
7709: if (!defined($homeserver)) {
7710: if ($cdom =~ /^$match_domain$/) {
7711: $homeserver = &domain($cdom,'primary');
7712: }
7713: }
1.1065 raeburn 7714: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7715: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7716: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7717: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7718: }
7719:
1.506 raeburn 7720: sub auto_create_password {
1.873 raeburn 7721: my ($cnum,$cdom,$authparam,$udom) = @_;
7722: my ($homeserver,$response);
1.506 raeburn 7723: my $create_passwd = 0;
7724: my $authchk = '';
1.873 raeburn 7725: if ($udom =~ /^$match_domain$/) {
7726: $homeserver = &domain($udom,'primary');
7727: }
7728: if ($homeserver eq '') {
7729: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7730: $homeserver = &homeserver($cnum,$cdom);
7731: }
7732: }
7733: if ($homeserver eq '') {
7734: $authchk = 'nodomain';
1.506 raeburn 7735: } else {
1.873 raeburn 7736: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7737: if ($response eq 'refused') {
7738: $authchk = 'refused';
7739: } else {
1.901 albertel 7740: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7741: }
1.506 raeburn 7742: }
7743: return ($authparam,$create_passwd,$authchk);
7744: }
7745:
1.706 raeburn 7746: sub auto_photo_permission {
7747: my ($cnum,$cdom,$students) = @_;
7748: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7749: my ($outcome,$perm_reqd,$conditions) =
7750: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7751: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7752: return (undef,undef);
7753: }
1.706 raeburn 7754: return ($outcome,$perm_reqd,$conditions);
7755: }
7756:
7757: sub auto_checkphotos {
7758: my ($uname,$udom,$pid) = @_;
7759: my $homeserver = &homeserver($uname,$udom);
7760: my ($result,$resulttype);
7761: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7762: &escape($uname).':'.&escape($pid),
7763: $homeserver));
1.709 albertel 7764: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7765: return (undef,undef);
7766: }
1.706 raeburn 7767: if ($outcome) {
7768: ($result,$resulttype) = split(/:/,$outcome);
7769: }
7770: return ($result,$resulttype);
7771: }
7772:
7773: sub auto_photochoice {
7774: my ($cnum,$cdom) = @_;
7775: my $homeserver = &homeserver($cnum,$cdom);
7776: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7777: &escape($cdom),
7778: $homeserver)));
1.709 albertel 7779: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7780: return (undef,undef);
7781: }
1.706 raeburn 7782: return ($update,$comment);
7783: }
7784:
7785: sub auto_photoupdate {
7786: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7787: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7788: my $host=&hostname($homeserver);
1.706 raeburn 7789: my $cmd = '';
7790: my $maxtries = 1;
1.800 albertel 7791: foreach my $affiliate (keys(%{$affiliatesref})) {
7792: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7793: }
7794: $cmd =~ s/%%$//;
7795: $cmd = &escape($cmd);
7796: my $query = 'institutionalphotos';
7797: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7798: unless ($queryid=~/^\Q$host\E\_/) {
7799: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7800: return 'error: '.$queryid;
7801: }
7802: my $reply = &get_query_reply($queryid);
7803: my $tries = 1;
7804: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7805: $reply = &get_query_reply($queryid);
7806: $tries ++;
7807: }
7808: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7809: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7810: } else {
7811: my @responses = split(/:/,$reply);
7812: my $outcome = shift(@responses);
7813: foreach my $item (@responses) {
7814: my ($key,$value) = split(/=/,$item);
7815: $$photo{$key} = $value;
7816: }
7817: return $outcome;
7818: }
7819: return 'error';
7820: }
7821:
1.521 raeburn 7822: sub auto_instcode_format {
1.793 albertel 7823: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7824: $cat_order) = @_;
1.521 raeburn 7825: my $courses = '';
1.772 raeburn 7826: my @homeservers;
1.521 raeburn 7827: if ($caller eq 'global') {
1.841 albertel 7828: my %servers = &get_servers($codedom,'library');
7829: foreach my $tryserver (keys(%servers)) {
7830: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7831: push(@homeservers,$tryserver);
7832: }
1.584 raeburn 7833: }
1.1022 raeburn 7834: } elsif ($caller eq 'requests') {
7835: if ($codedom =~ /^$match_domain$/) {
7836: my $chome = &domain($codedom,'primary');
7837: unless ($chome eq 'no_host') {
7838: push(@homeservers,$chome);
7839: }
7840: }
1.521 raeburn 7841: } else {
1.772 raeburn 7842: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7843: }
1.793 albertel 7844: foreach my $code (keys(%{$instcodes})) {
7845: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7846: }
7847: chop($courses);
1.772 raeburn 7848: my $ok_response = 0;
7849: my $response;
7850: while (@homeservers > 0 && $ok_response == 0) {
7851: my $server = shift(@homeservers);
7852: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7853: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7854: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7855: split(/:/,$response);
1.772 raeburn 7856: %{$codes} = (%{$codes},&str2hash($codes_str));
7857: push(@{$codetitles},&str2array($codetitles_str));
7858: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7859: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7860: $ok_response = 1;
7861: }
7862: }
7863: if ($ok_response) {
1.521 raeburn 7864: return 'ok';
1.772 raeburn 7865: } else {
7866: return $response;
1.521 raeburn 7867: }
7868: }
7869:
1.792 raeburn 7870: sub auto_instcode_defaults {
7871: my ($domain,$returnhash,$code_order) = @_;
7872: my @homeservers;
1.841 albertel 7873:
7874: my %servers = &get_servers($domain,'library');
7875: foreach my $tryserver (keys(%servers)) {
7876: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7877: push(@homeservers,$tryserver);
7878: }
1.792 raeburn 7879: }
1.841 albertel 7880:
1.792 raeburn 7881: my $response;
1.841 albertel 7882: foreach my $server (@homeservers) {
1.792 raeburn 7883: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7884: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7885:
7886: foreach my $pair (split(/\&/,$response)) {
7887: my ($name,$value)=split(/\=/,$pair);
7888: if ($name eq 'code_order') {
7889: @{$code_order} = split(/\&/,&unescape($value));
7890: } else {
7891: $returnhash->{&unescape($name)}=&unescape($value);
7892: }
7893: }
7894: return 'ok';
1.792 raeburn 7895: }
1.841 albertel 7896:
7897: return $response;
1.1003 raeburn 7898: }
7899:
7900: sub auto_possible_instcodes {
1.1007 raeburn 7901: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7902: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7903: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7904: return;
7905: }
1.1003 raeburn 7906: my (@homeservers,$uhome);
7907: if (defined(&domain($domain,'primary'))) {
7908: $uhome=&domain($domain,'primary');
7909: push(@homeservers,&domain($domain,'primary'));
7910: } else {
7911: my %servers = &get_servers($domain,'library');
7912: foreach my $tryserver (keys(%servers)) {
7913: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7914: push(@homeservers,$tryserver);
7915: }
7916: }
7917: }
7918: my $response;
7919: foreach my $server (@homeservers) {
7920: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7921: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7922: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7923: split(':',$response);
7924: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7925: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7926: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7927: my ($name,$value)=split('=',$item);
7928: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7929: }
7930: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7931: my ($name,$value)=split('=',$item);
7932: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7933: }
7934: return 'ok';
7935: }
7936: return $response;
7937: }
1.792 raeburn 7938:
1.1010 raeburn 7939: sub auto_courserequest_checks {
7940: my ($dom) = @_;
1.1020 raeburn 7941: my ($homeserver,%validations);
7942: if ($dom =~ /^$match_domain$/) {
7943: $homeserver = &domain($dom,'primary');
7944: }
7945: unless ($homeserver eq 'no_host') {
7946: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7947: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7948: my @items = split(/&/,$response);
7949: foreach my $item (@items) {
7950: my ($key,$value) = split('=',$item);
7951: $validations{&unescape($key)} = &thaw_unescape($value);
7952: }
7953: }
7954: }
1.1010 raeburn 7955: return %validations;
7956: }
7957:
1.1020 raeburn 7958: sub auto_courserequest_validation {
1.1255 raeburn 7959: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 7960: my ($homeserver,$response);
7961: if ($dom =~ /^$match_domain$/) {
7962: $homeserver = &domain($dom,'primary');
7963: }
1.1255 raeburn 7964: unless ($homeserver eq 'no_host') {
7965: my $customdata;
7966: if (ref($custominfo) eq 'HASH') {
7967: $customdata = &freeze_escape($custominfo);
7968: }
1.1020 raeburn 7969: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7970: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 7971: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7972: $customdata,$homeserver));
1.1020 raeburn 7973: }
7974: return $response;
7975: }
7976:
1.777 albertel 7977: sub auto_validate_class_sec {
1.918 raeburn 7978: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7979: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7980: my $ownerlist;
7981: if (ref($owners) eq 'ARRAY') {
7982: $ownerlist = join(',',@{$owners});
7983: } else {
7984: $ownerlist = $owners;
7985: }
1.773 raeburn 7986: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7987: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7988: return $response;
7989: }
7990:
1.1248 raeburn 7991: sub auto_crsreq_update {
7992: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 7993: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 7994: my ($homeserver,%crsreqresponse);
7995: if ($cdom =~ /^$match_domain$/) {
7996: $homeserver = &domain($cdom,'primary');
7997: }
7998: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7999: my $info;
8000: if (ref($inbound) eq 'HASH') {
8001: $info = &freeze_escape($inbound);
8002: }
8003: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8004: ':'.&escape($action).':'.&escape($ownername).':'.
8005: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8006: &escape($title).':'.&escape($code).':'.
8007: &escape($accessstart).':'.&escape($accessend).':'.$info,
8008: $homeserver);
1.1248 raeburn 8009: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8010: my @items = split(/&/,$response);
8011: foreach my $item (@items) {
8012: my ($key,$value) = split('=',$item);
8013: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8014: }
8015: }
8016: }
8017: return \%crsreqresponse;
8018: }
8019:
1.679 raeburn 8020: # ------------------------------------------------------- Course Group routines
8021:
8022: sub get_coursegroups {
1.809 raeburn 8023: my ($cdom,$cnum,$group,$namespace) = @_;
8024: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8025: }
8026:
1.679 raeburn 8027: sub modify_coursegroup {
8028: my ($cdom,$cnum,$groupsettings) = @_;
8029: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8030: }
8031:
1.809 raeburn 8032: sub toggle_coursegroup_status {
8033: my ($cdom,$cnum,$group,$action) = @_;
8034: my ($from_namespace,$to_namespace);
8035: if ($action eq 'delete') {
8036: $from_namespace = 'coursegroups';
8037: $to_namespace = 'deleted_groups';
8038: } else {
8039: $from_namespace = 'deleted_groups';
8040: $to_namespace = 'coursegroups';
8041: }
8042: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8043: if (my $tmp = &error(%curr_group)) {
8044: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8045: return ('read error',$tmp);
8046: } else {
8047: my %savedsettings = %curr_group;
1.809 raeburn 8048: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8049: my $deloutcome;
8050: if ($result eq 'ok') {
1.809 raeburn 8051: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8052: } else {
8053: return ('write error',$result);
8054: }
8055: if ($deloutcome eq 'ok') {
8056: return 'ok';
8057: } else {
8058: return ('delete error',$deloutcome);
8059: }
8060: }
8061: }
8062:
1.679 raeburn 8063: sub modify_group_roles {
1.957 raeburn 8064: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8065: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8066: my $role = 'gr/'.&escape($userprivs);
8067: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8068: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8069: if ($result eq 'ok') {
8070: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8071: }
1.679 raeburn 8072: return $result;
8073: }
8074:
8075: sub modify_coursegroup_membership {
8076: my ($cdom,$cnum,$membership) = @_;
8077: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8078: return $result;
8079: }
8080:
1.682 raeburn 8081: sub get_active_groups {
8082: my ($udom,$uname,$cdom,$cnum) = @_;
8083: my $now = time;
8084: my %groups = ();
8085: foreach my $key (keys(%env)) {
1.811 albertel 8086: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8087: my ($start,$end) = split(/\./,$env{$key});
8088: if (($end!=0) && ($end<$now)) { next; }
8089: if (($start!=0) && ($start>$now)) { next; }
8090: if ($1 eq $cdom && $2 eq $cnum) {
8091: $groups{$3} = $env{$key} ;
8092: }
8093: }
8094: }
8095: return %groups;
8096: }
8097:
1.683 raeburn 8098: sub get_group_membership {
8099: my ($cdom,$cnum,$group) = @_;
8100: return(&dump('groupmembership',$cdom,$cnum,$group));
8101: }
8102:
8103: sub get_users_groups {
8104: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8105: my @usersgroups;
1.683 raeburn 8106: my $cachetime=1800;
8107:
8108: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8109: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8110: if (defined($cached)) {
1.734 albertel 8111: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8112: } else {
8113: $grouplist = '';
1.816 raeburn 8114: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8115: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8116: my $access_end = $env{'course.'.$courseid.
8117: '.default_enrollment_end_date'};
8118: my $now = time;
8119: foreach my $key (keys(%roleshash)) {
8120: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8121: my $group = $1;
8122: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8123: my $start = $2;
8124: my $end = $1;
8125: if ($start == -1) { next; } # deleted from group
8126: if (($start!=0) && ($start>$now)) { next; }
8127: if (($end!=0) && ($end<$now)) {
8128: if ($access_end && $access_end < $now) {
8129: if ($access_end - $end < 86400) {
8130: push(@usersgroups,$group);
1.733 raeburn 8131: }
8132: }
1.817 raeburn 8133: next;
1.733 raeburn 8134: }
1.817 raeburn 8135: push(@usersgroups,$group);
1.683 raeburn 8136: }
8137: }
8138: }
1.817 raeburn 8139: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8140: $grouplist = join(':',@usersgroups);
8141: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8142: }
1.733 raeburn 8143: return @usersgroups;
1.683 raeburn 8144: }
8145:
8146: sub devalidate_getgroups_cache {
8147: my ($udom,$uname,$cdom,$cnum)=@_;
8148: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8149:
1.683 raeburn 8150: my $hashid="$udom:$uname:$courseid";
8151: &devalidate_cache_new('getgroups',$hashid);
8152: }
8153:
1.12 www 8154: # ------------------------------------------------------------------ Plain Text
8155:
8156: sub plaintext {
1.988 raeburn 8157: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8158: if ($short =~ m{^cr/}) {
1.758 albertel 8159: return (split('/',$short))[-1];
8160: }
1.742 raeburn 8161: if (!defined($cid)) {
8162: $cid = $env{'request.course.id'};
8163: }
8164: my %rolenames = (
1.1008 raeburn 8165: Course => 'std',
8166: Community => 'alt1',
1.742 raeburn 8167: );
1.1037 raeburn 8168: if ($cid ne '') {
8169: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8170: unless ($forcedefault) {
8171: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8172: &Apache::lonlocal::mt_escape(\$roletext);
8173: return &Apache::lonlocal::mt($roletext);
8174: }
8175: }
8176: }
8177: if ((defined($type)) && (defined($rolenames{$type})) &&
8178: (defined($rolenames{$type})) &&
8179: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8180: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8181: } elsif ($cid ne '') {
8182: my $crstype = $env{'course.'.$cid.'.type'};
8183: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8184: (defined($prp{$short}{$rolenames{$crstype}}))) {
8185: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8186: }
1.742 raeburn 8187: }
1.1037 raeburn 8188: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8189: }
8190:
8191: # ----------------------------------------------------------------- Assign Role
8192:
8193: sub assignrole {
1.957 raeburn 8194: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8195: $context)=@_;
1.21 www 8196: my $mrole;
8197: if ($role =~ /^cr\//) {
1.393 www 8198: my $cwosec=$url;
1.811 albertel 8199: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8200: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8201: my $refused = 1;
8202: if ($context eq 'requestcourses') {
8203: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8204: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8205: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8206: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8207: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8208: if ($crsenv{'internal.courseowner'} eq
8209: $env{'user.name'}.':'.$env{'user.domain'}) {
8210: $refused = '';
8211: }
8212: }
8213: }
8214: }
8215: }
8216: if ($refused) {
8217: &logthis('Refused custom assignrole: '.
8218: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8219: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8220: return 'refused';
8221: }
1.104 www 8222: }
1.21 www 8223: $mrole='cr';
1.678 raeburn 8224: } elsif ($role =~ /^gr\//) {
8225: my $cwogrp=$url;
1.811 albertel 8226: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8227: unless (&allowed('mdg',$cwogrp)) {
8228: &logthis('Refused group assignrole: '.
8229: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8230: $env{'user.name'}.' at '.$env{'user.domain'});
8231: return 'refused';
8232: }
8233: $mrole='gr';
1.21 www 8234: } else {
1.82 www 8235: my $cwosec=$url;
1.811 albertel 8236: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8237: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8238: my $refused;
8239: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8240: if (!(&allowed('c'.$role,$url))) {
8241: $refused = 1;
8242: }
8243: } else {
8244: $refused = 1;
8245: }
1.947 raeburn 8246: if ($refused) {
1.1045 raeburn 8247: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8248: if (!$selfenroll && $context eq 'course') {
8249: my %crsenv;
8250: if ($role eq 'cc' || $role eq 'co') {
8251: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8252: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8253: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8254: if ($crsenv{'internal.courseowner'} eq
8255: $env{'user.name'}.':'.$env{'user.domain'}) {
8256: $refused = '';
8257: }
8258: }
8259: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8260: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8261: if ($crsenv{'internal.courseowner'} eq
8262: $env{'user.name'}.':'.$env{'user.domain'}) {
8263: $refused = '';
8264: }
8265: }
8266: }
8267: }
8268: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8269: $refused = '';
1.1017 raeburn 8270: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8271: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8272: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8273: my $wrongcc;
8274: if ($cnum =~ /^$match_community$/) {
8275: $wrongcc = 1 if ($role eq 'cc');
8276: } else {
8277: $wrongcc = 1 if ($role eq 'co');
8278: }
8279: unless ($wrongcc) {
8280: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8281: if ($crsenv{'internal.courseowner'} eq
8282: $env{'user.name'}.':'.$env{'user.domain'}) {
8283: $refused = '';
8284: }
1.1017 raeburn 8285: }
8286: }
1.1183 raeburn 8287: } elsif ($context eq 'requestauthor') {
8288: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8289: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8290: if ($env{'environment.requestauthor'} eq 'automatic') {
8291: $refused = '';
8292: } else {
8293: my %domdefaults = &get_domain_defaults($udom);
8294: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8295: my $checkbystatus;
8296: if ($env{'user.adv'}) {
8297: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8298: if ($disposition eq 'automatic') {
8299: $refused = '';
8300: } elsif ($disposition eq '') {
8301: $checkbystatus = 1;
8302: }
8303: } else {
8304: $checkbystatus = 1;
8305: }
8306: if ($checkbystatus) {
8307: if ($env{'environment.inststatus'}) {
8308: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8309: foreach my $type (@inststatuses) {
8310: if (($type ne '') &&
8311: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8312: $refused = '';
8313: }
8314: }
8315: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8316: $refused = '';
8317: }
8318: }
8319: }
8320: }
8321: }
1.1017 raeburn 8322: }
8323: if ($refused) {
1.947 raeburn 8324: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8325: ' '.$role.' '.$end.' '.$start.' by '.
8326: $env{'user.name'}.' at '.$env{'user.domain'});
8327: return 'refused';
8328: }
1.932 raeburn 8329: }
1.1131 raeburn 8330: } elsif ($role eq 'au') {
8331: if ($url ne '/'.$udom.'/') {
8332: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8333: ' to assign author role for '.$uname.':'.$udom.
8334: ' in domain: '.$url.' refused (wrong domain).');
8335: return 'refused';
8336: }
1.104 www 8337: }
1.21 www 8338: $mrole=$role;
8339: }
1.620 albertel 8340: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8341: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8342: if ($end) { $command.='_'.$end; }
1.21 www 8343: if ($start) {
8344: if ($end) {
1.81 www 8345: $command.='_'.$start;
1.21 www 8346: } else {
1.81 www 8347: $command.='_0_'.$start;
1.21 www 8348: }
8349: }
1.739 raeburn 8350: my $origstart = $start;
8351: my $origend = $end;
1.957 raeburn 8352: my $delflag;
1.357 www 8353: # actually delete
8354: if ($deleteflag) {
1.373 www 8355: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8356: # modify command to delete the role
1.620 albertel 8357: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8358: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8359: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8360: # set start and finish to negative values for userrolelog
8361: $start=-1;
8362: $end=-1;
1.957 raeburn 8363: $delflag = 1;
1.357 www 8364: }
8365: }
8366: # send command
1.349 www 8367: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8368: # log new user role if status is ok
1.349 www 8369: if ($answer eq 'ok') {
1.663 raeburn 8370: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8371: if (($role eq 'cc') || ($role eq 'in') ||
8372: ($role eq 'ep') || ($role eq 'ad') ||
8373: ($role eq 'ta') || ($role eq 'st') ||
8374: ($role=~/^cr/) || ($role eq 'gr') ||
8375: ($role eq 'co')) {
1.1200 raeburn 8376: # for course roles, perform group memberships changes triggered by role change.
8377: unless ($role =~ /^gr/) {
8378: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8379: $origstart,$selfenroll,$context);
8380: }
1.1184 raeburn 8381: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8382: $selfenroll,$context);
8383: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8384: ($role eq 'au') || ($role eq 'dc')) {
8385: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8386: $context);
8387: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8388: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8389: $context);
8390: }
1.1053 raeburn 8391: if ($role eq 'cc') {
8392: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8393: }
1.349 www 8394: }
8395: return $answer;
1.169 harris41 8396: }
8397:
1.1053 raeburn 8398: sub autoupdate_coowners {
8399: my ($url,$end,$start,$uname,$udom) = @_;
8400: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8401: if (($cdom ne '') && ($cnum ne '')) {
8402: my $now = time;
8403: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8404: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8405: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8406: my $instcode = $coursehash{'internal.coursecode'};
8407: if ($instcode ne '') {
1.1056 raeburn 8408: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8409: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8410: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8411: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8412: if ($result eq 'valid') {
8413: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8414: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8415: push(@newcoowners,$coowner);
8416: }
8417: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8418: push(@newcoowners,$uname.':'.$udom);
8419: }
8420: @newcoowners = sort(@newcoowners);
8421: } else {
8422: push(@newcoowners,$uname.':'.$udom);
8423: }
8424: } else {
8425: if ($coursehash{'internal.co-owners'}) {
8426: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8427: unless ($coowner eq $uname.':'.$udom) {
8428: push(@newcoowners,$coowner);
8429: }
8430: }
8431: unless (@newcoowners > 0) {
8432: $delcoowners = 1;
8433: $coowners = '';
8434: }
8435: }
8436: }
8437: if (@newcoowners || $delcoowners) {
8438: &store_coowners($cdom,$cnum,$coursehash{'home'},
8439: $delcoowners,@newcoowners);
8440: }
8441: }
8442: }
8443: }
8444: }
8445: }
8446: }
8447:
8448: sub store_coowners {
8449: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8450: my $cid = $cdom.'_'.$cnum;
8451: my ($coowners,$delresult,$putresult);
8452: if (@newcoowners) {
8453: $coowners = join(',',@newcoowners);
8454: my %coownershash = (
8455: 'internal.co-owners' => $coowners,
8456: );
8457: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8458: if ($putresult eq 'ok') {
8459: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8460: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8461: }
8462: }
8463: }
8464: if ($delcoowners) {
8465: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8466: if ($delresult eq 'ok') {
8467: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8468: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8469: }
8470: }
8471: }
8472: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8473: my %crsinfo =
8474: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8475: if (ref($crsinfo{$cid}) eq 'HASH') {
8476: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8477: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8478: }
8479: }
8480: }
8481:
1.169 harris41 8482: # -------------------------------------------------- Modify user authentication
1.197 www 8483: # Overrides without validation
8484:
1.169 harris41 8485: sub modifyuserauth {
8486: my ($udom,$uname,$umode,$upass)=@_;
8487: my $uhome=&homeserver($uname,$udom);
1.197 www 8488: unless (&allowed('mau',$udom)) { return 'refused'; }
8489: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8490: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8491: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8492: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8493: &escape($upass),$uhome);
1.620 albertel 8494: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8495: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8496: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8497: &log($udom,,$uname,$uhome,
1.620 albertel 8498: 'Authentication changed by '.$env{'user.domain'}.', '.
8499: $env{'user.name'}.', '.$umode.
1.197 www 8500: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8501: unless ($reply eq 'ok') {
1.197 www 8502: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8503: return 'error: '.$reply;
8504: }
1.170 harris41 8505: return 'ok';
1.80 www 8506: }
8507:
1.81 www 8508: # --------------------------------------------------------------- Modify a user
1.80 www 8509:
1.81 www 8510: sub modifyuser {
1.206 matthew 8511: my ($udom, $uname, $uid,
8512: $umode, $upass, $first,
8513: $middle, $last, $gene,
1.1058 raeburn 8514: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8515: $udom= &LONCAPA::clean_domain($udom);
8516: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8517: my $showcandelete = 'none';
8518: if (ref($candelete) eq 'ARRAY') {
8519: if (@{$candelete} > 0) {
8520: $showcandelete = join(', ',@{$candelete});
8521: }
8522: }
1.81 www 8523: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8524: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8525: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8526: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8527: ' desiredhome not specified').
1.620 albertel 8528: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8529: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8530: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8531: my $newuser;
8532: if ($uhome eq 'no_host') {
8533: $newuser = 1;
8534: }
1.80 www 8535: # ----------------------------------------------------------------- Create User
1.406 albertel 8536: if (($uhome eq 'no_host') &&
8537: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8538: my $unhome='';
1.844 albertel 8539: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8540: $unhome = $desiredhome;
1.620 albertel 8541: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8542: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8543: } else { # load balancing routine for determining $unhome
1.81 www 8544: my $loadm=10000000;
1.841 albertel 8545: my %servers = &get_servers($udom,'library');
8546: foreach my $tryserver (keys(%servers)) {
8547: my $answer=reply('load',$tryserver);
8548: if (($answer=~/\d+/) && ($answer<$loadm)) {
8549: $loadm=$answer;
8550: $unhome=$tryserver;
8551: }
1.80 www 8552: }
8553: }
8554: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8555: return 'error: unable to find a home server for '.$uname.
8556: ' in domain '.$udom;
1.80 www 8557: }
8558: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8559: &escape($upass),$unhome);
8560: unless ($reply eq 'ok') {
8561: return 'error: '.$reply;
8562: }
1.230 stredwic 8563: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8564: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8565: return 'error: unable verify users home machine.';
1.80 www 8566: }
1.209 matthew 8567: } # End of creation of new user
1.80 www 8568: # ---------------------------------------------------------------------- Add ID
8569: if ($uid) {
8570: $uid=~tr/A-Z/a-z/;
8571: my %uidhash=&idrget($udom,$uname);
1.196 www 8572: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8573: && (!$forceid)) {
1.80 www 8574: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8575: return 'error: user id "'.$uid.'" does not match '.
8576: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8577: }
8578: } else {
8579: &idput($udom,($uname => $uid));
8580: }
8581: }
8582: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8583: my @tmp=&get('environment',
1.899 raeburn 8584: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8585: 'permanentemail','inststatus'],
1.134 albertel 8586: $udom,$uname);
1.1075 raeburn 8587: my (%names,%oldnames);
1.313 matthew 8588: if ($tmp[0] =~ m/^error:.*/) {
8589: %names=();
8590: } else {
8591: %names = @tmp;
1.1075 raeburn 8592: %oldnames = %names;
1.313 matthew 8593: }
1.388 www 8594: #
1.1058 raeburn 8595: # If name, email and/or uid are blank (e.g., because an uploaded file
8596: # of users did not contain them), do not overwrite existing values
8597: # unless field is in $candelete array ref.
8598: #
8599:
8600: my @fields = ('firstname','middlename','lastname','generation',
8601: 'permanentemail','id');
8602: my %newvalues;
8603: if (ref($candelete) eq 'ARRAY') {
8604: foreach my $field (@fields) {
8605: if (grep(/^\Q$field\E$/,@{$candelete})) {
8606: if ($field eq 'firstname') {
8607: $names{$field} = $first;
8608: } elsif ($field eq 'middlename') {
8609: $names{$field} = $middle;
8610: } elsif ($field eq 'lastname') {
8611: $names{$field} = $last;
8612: } elsif ($field eq 'generation') {
8613: $names{$field} = $gene;
8614: } elsif ($field eq 'permanentemail') {
8615: $names{$field} = $email;
8616: } elsif ($field eq 'id') {
8617: $names{$field} = $uid;
8618: }
8619: }
8620: }
8621: }
1.388 www 8622: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8623: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8624: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8625: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8626: if ($email) {
8627: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8628: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8629: }
1.899 raeburn 8630: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8631: if (defined($inststatus)) {
8632: $names{'inststatus'} = '';
8633: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8634: if (ref($usertypes) eq 'HASH') {
8635: my @okstatuses;
8636: foreach my $item (split(/:/,$inststatus)) {
8637: if (defined($usertypes->{$item})) {
8638: push(@okstatuses,$item);
8639: }
8640: }
8641: if (@okstatuses) {
8642: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8643: }
8644: }
8645: }
1.1075 raeburn 8646: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8647: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8648: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8649: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8650: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8651: } else {
8652: $logmsg .= ' during self creation';
8653: }
1.1075 raeburn 8654: my $changed;
8655: if ($newuser) {
8656: $changed = 1;
8657: } else {
8658: foreach my $field (@fields) {
8659: if ($names{$field} ne $oldnames{$field}) {
8660: $changed = 1;
8661: last;
8662: }
8663: }
8664: }
8665: unless ($changed) {
8666: $logmsg = 'No changes in user information needed for: '.$logmsg;
8667: &logthis($logmsg);
8668: return 'ok';
8669: }
8670: my $reply = &put('environment', \%names, $udom,$uname);
8671: if ($reply ne 'ok') {
8672: return 'error: '.$reply;
8673: }
1.1087 raeburn 8674: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8675: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8676: }
1.1075 raeburn 8677: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8678: &devalidate_cache_new('namescache',$uname.':'.$udom);
8679: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8680: &logthis($logmsg);
1.134 albertel 8681: return 'ok';
1.80 www 8682: }
8683:
1.81 www 8684: # -------------------------------------------------------------- Modify student
1.80 www 8685:
1.81 www 8686: sub modifystudent {
8687: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8688: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8689: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8690: if (!$cid) {
1.620 albertel 8691: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8692: return 'not_in_class';
8693: }
1.80 www 8694: }
8695: # --------------------------------------------------------------- Make the user
1.81 www 8696: my $reply=&modifyuser
1.209 matthew 8697: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8698: $desiredhome,$email,$inststatus);
1.80 www 8699: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8700: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8701: # student's environment
1.297 matthew 8702: $uid = undef if (!$forceid);
1.455 albertel 8703: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8704: $gene,$usec,$end,$start,$type,$locktype,
8705: $cid,$selfenroll,$context,$credits);
1.297 matthew 8706: return $reply;
8707: }
8708:
8709: sub modify_student_enrollment {
1.1216 raeburn 8710: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8711: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8712: my ($cdom,$cnum,$chome);
8713: if (!$cid) {
1.620 albertel 8714: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8715: return 'not_in_class';
8716: }
1.620 albertel 8717: $cdom=$env{'course.'.$cid.'.domain'};
8718: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8719: } else {
8720: ($cdom,$cnum)=split(/_/,$cid);
8721: }
1.620 albertel 8722: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8723: if (!$chome) {
1.457 raeburn 8724: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8725: }
1.455 albertel 8726: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8727: # Make sure the user exists
1.81 www 8728: my $uhome=&homeserver($uname,$udom);
8729: if (($uhome eq '') || ($uhome eq 'no_host')) {
8730: return 'error: no such user';
8731: }
1.297 matthew 8732: # Get student data if we were not given enough information
8733: if (!defined($first) || $first eq '' ||
8734: !defined($last) || $last eq '' ||
8735: !defined($uid) || $uid eq '' ||
8736: !defined($middle) || $middle eq '' ||
8737: !defined($gene) || $gene eq '') {
1.294 matthew 8738: # They did not supply us with enough data to enroll the student, so
8739: # we need to pick up more information.
1.297 matthew 8740: my %tmp = &get('environment',
1.294 matthew 8741: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8742: ,$udom,$uname);
8743:
1.800 albertel 8744: #foreach my $key (keys(%tmp)) {
8745: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8746: #}
1.294 matthew 8747: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8748: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8749: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8750: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8751: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8752: }
1.556 albertel 8753: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8754: my $user = "$uname:$udom";
8755: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8756: my $reply=cput('classlist',
1.1148 raeburn 8757: {$user =>
1.1216 raeburn 8758: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8759: $cdom,$cnum);
1.1148 raeburn 8760: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8761: &devalidate_getsection_cache($udom,$uname,$cid);
8762: } else {
1.81 www 8763: return 'error: '.$reply;
8764: }
1.297 matthew 8765: # Add student role to user
1.83 www 8766: my $uurl='/'.$cid;
1.81 www 8767: $uurl=~s/\_/\//g;
8768: if ($usec) {
8769: $uurl.='/'.$usec;
8770: }
1.1148 raeburn 8771: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8772: $selfenroll,$context);
8773: if ($result ne 'ok') {
8774: if ($old_entry{$user} ne '') {
8775: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8776: } else {
8777: $reply = &del('classlist',[$user],$cdom,$cnum);
8778: }
8779: }
8780: return $result;
1.21 www 8781: }
8782:
1.556 albertel 8783: sub format_name {
8784: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8785: my $name;
8786: if ($first ne 'lastname') {
8787: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8788: } else {
8789: if ($lastname=~/\S/) {
8790: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8791: $name=~s/\s+,/,/;
8792: } else {
8793: $name.= $firstname.' '.$middlename.' '.$generation;
8794: }
8795: }
8796: $name=~s/^\s+//;
8797: $name=~s/\s+$//;
8798: $name=~s/\s+/ /g;
8799: return $name;
8800: }
8801:
1.84 www 8802: # ------------------------------------------------- Write to course preferences
8803:
8804: sub writecoursepref {
8805: my ($courseid,%prefs)=@_;
8806: $courseid=~s/^\///;
8807: $courseid=~s/\_/\//g;
8808: my ($cdomain,$cnum)=split(/\//,$courseid);
8809: my $chome=homeserver($cnum,$cdomain);
8810: if (($chome eq '') || ($chome eq 'no_host')) {
8811: return 'error: no such course';
8812: }
8813: my $cstring='';
1.800 albertel 8814: foreach my $pref (keys(%prefs)) {
8815: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8816: }
1.84 www 8817: $cstring=~s/\&$//;
8818: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8819: }
8820:
8821: # ---------------------------------------------------------- Make/modify course
8822:
8823: sub createcourse {
1.741 raeburn 8824: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8825: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8826: $url=&declutter($url);
8827: my $cid='';
1.1028 raeburn 8828: if ($context eq 'requestcourses') {
8829: my $can_create = 0;
8830: my ($ownername,$ownerdom) = split(':',$course_owner);
8831: if ($udom eq $ownerdom) {
8832: if (&usertools_access($ownername,$ownerdom,$category,undef,
8833: $context)) {
8834: $can_create = 1;
8835: }
8836: } else {
8837: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8838: $category);
8839: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8840: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8841: if (@curr > 0) {
8842: my @options = qw(approval validate autolimit);
8843: my $optregex = join('|',@options);
8844: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8845: $can_create = 1;
8846: }
8847: }
8848: }
8849: }
8850: if ($can_create) {
8851: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8852: unless (&allowed('ccc',$udom)) {
8853: return 'refused';
8854: }
1.1017 raeburn 8855: }
8856: } else {
8857: return 'refused';
8858: }
1.1028 raeburn 8859: } elsif (!&allowed('ccc',$udom)) {
8860: return 'refused';
1.84 www 8861: }
1.1011 raeburn 8862: # --------------------------------------------------------------- Get Unique ID
8863: my $uname;
8864: if ($cnum =~ /^$match_courseid$/) {
8865: my $chome=&homeserver($cnum,$udom,'true');
8866: if (($chome eq '') || ($chome eq 'no_host')) {
8867: $uname = $cnum;
8868: } else {
1.1038 raeburn 8869: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8870: }
8871: } else {
1.1038 raeburn 8872: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8873: }
8874: return $uname if ($uname =~ /^error/);
8875: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8876: if (!defined($course_server)) {
8877: if (defined(&domain($udom,'primary'))) {
8878: $course_server = &domain($udom,'primary');
8879: } else {
8880: $course_server = $env{'user.home'};
8881: }
8882: }
8883: my %host_servers =
8884: &Apache::lonnet::get_servers($udom,'library');
8885: unless ($host_servers{$course_server}) {
8886: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8887: }
1.84 www 8888: # ------------------------------------------------------------- Make the course
8889: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8890: $course_server);
1.84 www 8891: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8892: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8893: if (($uhome eq '') || ($uhome eq 'no_host')) {
8894: return 'error: no such course';
8895: }
1.271 www 8896: # ----------------------------------------------------------------- Course made
1.516 raeburn 8897: # log existence
1.1029 raeburn 8898: my $now = time;
1.918 raeburn 8899: my $newcourse = {
8900: $udom.'_'.$uname => {
1.921 raeburn 8901: description => $description,
8902: inst_code => $inst_code,
8903: owner => $course_owner,
8904: type => $crstype,
1.1029 raeburn 8905: creator => $env{'user.name'}.':'.
8906: $env{'user.domain'},
8907: created => $now,
8908: context => $context,
1.918 raeburn 8909: },
8910: };
1.921 raeburn 8911: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8912: # set toplevel url
1.271 www 8913: my $topurl=$url;
8914: unless ($nonstandard) {
8915: # ------------------------------------------ For standard courses, make top url
8916: my $mapurl=&clutter($url);
1.278 www 8917: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8918: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8919: <map>
8920: <resource id="1" type="start"></resource>
8921: <resource id="2" src="$mapurl"></resource>
8922: <resource id="3" type="finish"></resource>
8923: <link index="1" from="1" to="2"></link>
8924: <link index="2" from="2" to="3"></link>
8925: </map>
8926: ENDINITMAP
8927: $topurl=&declutter(
1.638 albertel 8928: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8929: );
8930: }
8931: # ----------------------------------------------------------- Write preferences
1.84 www 8932: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8933: ('description' => $description,
8934: 'url' => $topurl,
8935: 'internal.creator' => $env{'user.name'}.':'.
8936: $env{'user.domain'},
8937: 'internal.created' => $now,
8938: 'internal.creationcontext' => $context)
8939: );
1.84 www 8940: return '/'.$udom.'/'.$uname;
8941: }
8942:
1.1011 raeburn 8943: # ------------------------------------------------------------------- Create ID
8944: sub generate_coursenum {
1.1038 raeburn 8945: my ($udom,$crstype) = @_;
1.1011 raeburn 8946: my $domdesc = &domain($udom);
8947: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8948: my $first;
8949: if ($crstype eq 'Community') {
8950: $first = '0';
8951: } else {
8952: $first = int(1+rand(9));
8953: }
8954: my $uname=$first.
1.1011 raeburn 8955: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8956: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8957: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8958: # ----------------------------------------------- Make sure that does not exist
8959: my $uhome=&homeserver($uname,$udom,'true');
8960: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8961: if ($crstype eq 'Community') {
8962: $first = '0';
8963: } else {
8964: $first = int(1+rand(9));
8965: }
8966: $uname=$first.
1.1011 raeburn 8967: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8968: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8969: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8970: $uhome=&homeserver($uname,$udom,'true');
8971: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8972: return 'error: unable to generate unique course-ID';
8973: }
8974: }
8975: return $uname;
8976: }
8977:
1.813 albertel 8978: sub is_course {
1.1167 droeschl 8979: my ($cdom, $cnum) = scalar(@_) == 1 ?
8980: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8981:
8982: return unless $cdom and $cnum;
8983:
8984: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8985: '.');
8986:
1.1219 raeburn 8987: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8988: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8989: }
8990:
1.1015 raeburn 8991: sub store_userdata {
8992: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8993: my $result;
1.1016 raeburn 8994: if ($datakey ne '') {
1.1013 raeburn 8995: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8996: if ($udom eq '' || $uname eq '') {
8997: $udom = $env{'user.domain'};
8998: $uname = $env{'user.name'};
8999: }
9000: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9001: if (($uhome eq '') || ($uhome eq 'no_host')) {
9002: $result = 'error: no_host';
9003: } else {
9004: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9005: $storehash->{'host'} = $perlvar{'lonHostID'};
9006:
9007: my $namevalue='';
9008: foreach my $key (keys(%{$storehash})) {
9009: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9010: }
9011: $namevalue=~s/\&$//;
1.1224 raeburn 9012: unless ($namespace eq 'courserequests') {
9013: $datakey = &escape($datakey);
9014: }
1.1105 raeburn 9015: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9016: $namevalue,$uhome);
1.1013 raeburn 9017: }
9018: } else {
9019: $result = 'error: data to store was not a hash reference';
9020: }
9021: } else {
9022: $result= 'error: invalid requestkey';
9023: }
9024: return $result;
9025: }
9026:
1.21 www 9027: # ---------------------------------------------------------- Assign Custom Role
9028:
9029: sub assigncustomrole {
1.957 raeburn 9030: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9031: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9032: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9033: }
9034:
9035: # ----------------------------------------------------------------- Revoke Role
9036:
9037: sub revokerole {
1.957 raeburn 9038: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9039: my $now=time;
1.965 raeburn 9040: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9041: }
9042:
9043: # ---------------------------------------------------------- Revoke Custom Role
9044:
9045: sub revokecustomrole {
1.957 raeburn 9046: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9047: my $now=time;
1.357 www 9048: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9049: $deleteflag,$selfenroll,$context);
1.17 www 9050: }
9051:
1.533 banghart 9052: # ------------------------------------------------------------ Disk usage
1.535 albertel 9053: sub diskusage {
1.955 raeburn 9054: my ($udom,$uname,$directorypath,$getpropath)=@_;
9055: $directorypath =~ s/\/$//;
9056: my $listing=&reply('du2:'.&escape($directorypath).':'
9057: .&escape($getpropath).':'.&escape($uname).':'
9058: .&escape($udom),homeserver($uname,$udom));
9059: if ($listing eq 'unknown_cmd') {
9060: if ($getpropath) {
9061: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9062: }
9063: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9064: }
1.514 albertel 9065: return $listing;
1.512 banghart 9066: }
9067:
1.566 banghart 9068: sub is_locked {
1.1096 raeburn 9069: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9070: my @check;
9071: my $is_locked;
1.1093 raeburn 9072: push (@check,$file_name);
1.613 albertel 9073: my %locked = &get('file_permissions',\@check,
1.620 albertel 9074: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9075: my ($tmp)=keys(%locked);
9076: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9077:
1.566 banghart 9078: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9079: $is_locked = 'false';
9080: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9081: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9082: $is_locked = 'true';
1.1096 raeburn 9083: if (ref($which) eq 'ARRAY') {
9084: push(@{$which},$entry);
9085: } else {
9086: last;
9087: }
1.745 raeburn 9088: }
9089: }
1.566 banghart 9090: } else {
9091: $is_locked = 'false';
9092: }
1.1093 raeburn 9093: return $is_locked;
1.566 banghart 9094: }
9095:
1.759 albertel 9096: sub declutter_portfile {
9097: my ($file) = @_;
1.833 albertel 9098: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9099: return $file;
9100: }
9101:
1.559 banghart 9102: # ------------------------------------------------------------- Mark as Read Only
9103:
9104: sub mark_as_readonly {
9105: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9106: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9107: my ($tmp)=keys(%current_permissions);
9108: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9109: foreach my $file (@{$files}) {
1.759 albertel 9110: $file = &declutter_portfile($file);
1.561 banghart 9111: push(@{$current_permissions{$file}},$what);
1.559 banghart 9112: }
1.613 albertel 9113: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9114: return;
9115: }
9116:
1.572 banghart 9117: # ------------------------------------------------------------Save Selected Files
9118:
9119: sub save_selected_files {
9120: my ($user, $path, @files) = @_;
9121: my $filename = $user."savedfiles";
1.573 banghart 9122: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9123: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9124: foreach my $file (@files) {
1.620 albertel 9125: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9126: }
9127: foreach my $file (@other_files) {
1.574 banghart 9128: print (OUT $file."\n");
1.572 banghart 9129: }
1.574 banghart 9130: close (OUT);
1.572 banghart 9131: return 'ok';
9132: }
9133:
1.574 banghart 9134: sub clear_selected_files {
9135: my ($user) = @_;
9136: my $filename = $user."savedfiles";
1.1117 foxr 9137: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9138: print (OUT undef);
9139: close (OUT);
9140: return ("ok");
9141: }
9142:
1.572 banghart 9143: sub files_in_path {
9144: my ($user, $path) = @_;
9145: my $filename = $user."savedfiles";
9146: my %return_files;
1.1117 foxr 9147: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9148: while (my $line_in = <IN>) {
1.574 banghart 9149: chomp ($line_in);
9150: my @paths_and_file = split (m!/!, $line_in);
9151: my $file_part = pop (@paths_and_file);
9152: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9153: $path_part.='/';
9154: my $path_and_file = $path_part.$file_part;
9155: if ($path_part eq $path) {
9156: $return_files{$file_part}= 'selected';
9157: }
9158: }
1.574 banghart 9159: close (IN);
9160: return (\%return_files);
1.572 banghart 9161: }
9162:
9163: # called in portfolio select mode, to show files selected NOT in current directory
9164: sub files_not_in_path {
9165: my ($user, $path) = @_;
9166: my $filename = $user."savedfiles";
9167: my @return_files;
9168: my $path_part;
1.1117 foxr 9169: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9170: while (my $line = <IN>) {
1.572 banghart 9171: #ok, I know it's clunky, but I want it to work
1.800 albertel 9172: my @paths_and_file = split(m|/|, $line);
9173: my $file_part = pop(@paths_and_file);
9174: chomp($file_part);
9175: my $path_part = join('/', @paths_and_file);
1.572 banghart 9176: $path_part .= '/';
9177: my $path_and_file = $path_part.$file_part;
9178: if ($path_part ne $path) {
1.800 albertel 9179: push(@return_files, ($path_and_file));
1.572 banghart 9180: }
9181: }
1.800 albertel 9182: close(OUT);
1.574 banghart 9183: return (@return_files);
1.572 banghart 9184: }
9185:
1.1273 raeburn 9186: #------------------------------Submitted/Handedback Portfolio Files Versioning
9187:
9188: sub portfiles_versioning {
9189: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9190: my $portfolio_root = '/userfiles/portfolio';
9191: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9192: foreach my $file (@{$portfiles}) {
9193: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9194: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9195: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9196: my $getpropath = 1;
9197: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9198: $stu_name,$getpropath);
9199: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9200: my $new_answer =
9201: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9202: if ($new_answer ne 'problem getting file') {
9203: push(@{$versioned_portfiles}, $directory.$new_answer);
9204: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9205: [$symb,$env{'request.course.id'},'graded']);
9206: }
9207: }
9208: }
9209:
9210: sub get_next_version {
9211: my ($answer_name, $answer_ext, $dir_list) = @_;
9212: my $version;
9213: if (ref($dir_list) eq 'ARRAY') {
9214: foreach my $row (@{$dir_list}) {
9215: my ($file) = split(/\&/,$row,2);
9216: my ($file_name,$file_version,$file_ext) =
9217: &file_name_version_ext($file);
9218: if (($file_name eq $answer_name) &&
9219: ($file_ext eq $answer_ext)) {
9220: # gets here if filename and extension match,
9221: # regardless of version
9222: if ($file_version ne '') {
9223: # a versioned file is found so save it for later
9224: if ($file_version > $version) {
9225: $version = $file_version;
9226: }
9227: }
9228: }
9229: }
9230: }
9231: $version ++;
9232: return($version);
9233: }
9234:
9235: sub version_selected_portfile {
9236: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9237: my ($answer_name,$answer_ver,$answer_ext) =
9238: &file_name_version_ext($file_name);
9239: my $new_answer;
9240: $env{'form.copy'} =
9241: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9242: if($env{'form.copy'} eq '-1') {
9243: $new_answer = 'problem getting file';
9244: } else {
9245: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9246: my $copy_result =
9247: &finishuserfileupload($stu_name,$domain,'copy',
9248: '/portfolio'.$directory.$new_answer);
9249: }
9250: undef($env{'form.copy'});
9251: return ($new_answer);
9252: }
9253:
9254: sub file_name_version_ext {
9255: my ($file)=@_;
9256: my @file_parts = split(/\./, $file);
9257: my ($name,$version,$ext);
9258: if (@file_parts > 1) {
9259: $ext=pop(@file_parts);
9260: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9261: $version=pop(@file_parts);
9262: }
9263: $name=join('.',@file_parts);
9264: } else {
9265: $name=join('.',@file_parts);
9266: }
9267: return($name,$version,$ext);
9268: }
9269:
1.745 raeburn 9270: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9271:
1.745 raeburn 9272: sub get_portfile_permissions {
9273: my ($domain,$user) = @_;
1.613 albertel 9274: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9275: my ($tmp)=keys(%current_permissions);
9276: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9277: return \%current_permissions;
9278: }
9279:
9280: #---------------------------------------------Get portfolio file access controls
9281:
1.749 raeburn 9282: sub get_access_controls {
1.745 raeburn 9283: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9284: my %access;
9285: my $real_file = $file;
9286: $file =~ s/\.meta$//;
1.745 raeburn 9287: if (defined($file)) {
1.749 raeburn 9288: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9289: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9290: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9291: }
9292: }
1.745 raeburn 9293: } else {
1.749 raeburn 9294: foreach my $key (keys(%{$current_permissions})) {
9295: if ($key =~ /\0accesscontrol$/) {
9296: if (defined($group)) {
9297: if ($key !~ m-^\Q$group\E/-) {
9298: next;
9299: }
9300: }
9301: my ($fullpath) = split(/\0/,$key);
9302: if (ref($$current_permissions{$key}) eq 'HASH') {
9303: foreach my $control (keys(%{$$current_permissions{$key}})) {
9304: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9305: }
9306: }
9307: }
9308: }
9309: }
9310: return %access;
9311: }
9312:
9313: sub modify_access_controls {
9314: my ($file_name,$changes,$domain,$user)=@_;
9315: my ($outcome,$deloutcome);
9316: my %store_permissions;
9317: my %new_values;
9318: my %new_control;
9319: my %translation;
9320: my @deletions = ();
9321: my $now = time;
9322: if (exists($$changes{'activate'})) {
9323: if (ref($$changes{'activate'}) eq 'HASH') {
9324: my @newitems = sort(keys(%{$$changes{'activate'}}));
9325: my $numnew = scalar(@newitems);
9326: for (my $i=0; $i<$numnew; $i++) {
9327: my $newkey = $newitems[$i];
9328: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9329: if ($newkey =~ /^\d+:/) {
9330: $newkey =~ s/^(\d+)/$newid/;
9331: $translation{$1} = $newid;
9332: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9333: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9334: $translation{$1} = $newid;
9335: }
1.749 raeburn 9336: $new_values{$file_name."\0".$newkey} =
9337: $$changes{'activate'}{$newitems[$i]};
9338: $new_control{$newkey} = $now;
9339: }
9340: }
9341: }
9342: my %todelete;
9343: my %changed_items;
9344: foreach my $action ('delete','update') {
9345: if (exists($$changes{$action})) {
9346: if (ref($$changes{$action}) eq 'HASH') {
9347: foreach my $key (keys(%{$$changes{$action}})) {
9348: my ($itemnum) = ($key =~ /^([^:]+):/);
9349: if ($action eq 'delete') {
9350: $todelete{$itemnum} = 1;
9351: } else {
9352: $changed_items{$itemnum} = $key;
9353: }
9354: }
1.745 raeburn 9355: }
9356: }
1.749 raeburn 9357: }
9358: # get lock on access controls for file.
9359: my $lockhash = {
9360: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9361: ':'.$env{'user.domain'},
9362: };
9363: my $tries = 0;
9364: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9365:
9366: while (($gotlock ne 'ok') && $tries <3) {
9367: $tries ++;
9368: sleep 1;
9369: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9370: }
9371: if ($gotlock eq 'ok') {
9372: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9373: my ($tmp)=keys(%curr_permissions);
9374: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9375: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9376: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9377: if (ref($curr_controls) eq 'HASH') {
9378: foreach my $control_item (keys(%{$curr_controls})) {
9379: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9380: if (defined($todelete{$itemnum})) {
9381: push(@deletions,$file_name."\0".$control_item);
9382: } else {
9383: if (defined($changed_items{$itemnum})) {
9384: $new_control{$changed_items{$itemnum}} = $now;
9385: push(@deletions,$file_name."\0".$control_item);
9386: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9387: } else {
9388: $new_control{$control_item} = $$curr_controls{$control_item};
9389: }
9390: }
1.745 raeburn 9391: }
9392: }
9393: }
1.970 raeburn 9394: my ($group);
9395: if (&is_course($domain,$user)) {
9396: ($group,my $file) = split(/\//,$file_name,2);
9397: }
1.749 raeburn 9398: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9399: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9400: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9401: # remove lock
9402: my @del_lock = ($file_name."\0".'locked_access_records');
9403: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9404: my $sqlresult =
1.970 raeburn 9405: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9406: $group);
1.749 raeburn 9407: } else {
9408: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9409: }
1.749 raeburn 9410: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9411: }
9412:
1.827 raeburn 9413: sub make_public_indefinitely {
1.1271 raeburn 9414: my (@requrl) = @_;
9415: return &automated_portfile_access('public',\@requrl);
9416: }
9417:
9418: sub automated_portfile_access {
9419: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9420: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9421: return 'invalid';
9422: }
1.1271 raeburn 9423: my %urls;
9424: if (ref($addsref) eq 'ARRAY') {
9425: foreach my $requrl (@{$addsref}) {
9426: if (&is_portfolio_url($requrl)) {
9427: unless (exists($urls{$requrl})) {
9428: $urls{$requrl} = 'add';
9429: }
9430: }
9431: }
9432: }
9433: if (ref($delsref) eq 'ARRAY') {
9434: foreach my $requrl (@{$delsref}) {
9435: if (&is_portfolio_url($requrl)) {
9436: unless (exists($urls{$requrl})) {
9437: $urls{$requrl} = 'delete';
9438: }
9439: }
9440: }
9441: }
9442: unless (keys(%urls)) {
9443: return 'invalid';
9444: }
9445: my $ip;
9446: if ($accesstype eq 'ip') {
9447: if (ref($info) eq 'HASH') {
9448: if ($info->{'ip'} ne '') {
9449: $ip = $info->{'ip'};
9450: }
9451: }
9452: if ($ip eq '') {
9453: return 'invalid';
9454: }
9455: }
9456: my $errors;
1.827 raeburn 9457: my $now = time;
1.1271 raeburn 9458: my %current_perms;
9459: foreach my $requrl (sort(keys(%urls))) {
9460: my $action;
9461: if ($urls{$requrl} eq 'add') {
9462: $action = 'activate';
9463: } else {
9464: $action = 'none';
9465: }
9466: my $aclnum = 0;
1.827 raeburn 9467: my (undef,$udom,$unum,$file_name,$group) =
9468: &parse_portfolio_url($requrl);
1.1271 raeburn 9469: unless (exists($current_perms{$unum.':'.$udom})) {
9470: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9471: }
9472: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9473: $group,$file_name);
9474: foreach my $key (keys(%{$access_controls{$file_name}})) {
9475: my ($num,$scope,$end,$start) =
9476: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9477: if ($scope eq $accesstype) {
9478: if (($start <= $now) && ($end == 0)) {
9479: if ($accesstype eq 'ip') {
9480: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9481: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9482: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9483: if ($urls{$requrl} eq 'add') {
9484: $action = 'none';
9485: last;
9486: } else {
9487: $action = 'delete';
9488: $aclnum = $num;
9489: last;
9490: }
9491: }
9492: }
9493: }
9494: } elsif ($accesstype eq 'public') {
9495: if ($urls{$requrl} eq 'add') {
9496: $action = 'none';
9497: last;
9498: } else {
9499: $action = 'delete';
9500: $aclnum = $num;
9501: last;
9502: }
9503: }
9504: } elsif ($accesstype eq 'public') {
1.827 raeburn 9505: $action = 'update';
9506: $aclnum = $num;
1.1271 raeburn 9507: last;
1.827 raeburn 9508: }
9509: }
9510: }
9511: if ($action eq 'none') {
1.1271 raeburn 9512: next;
1.827 raeburn 9513: } else {
9514: my %changes;
9515: my $newend = 0;
9516: my $newstart = $now;
1.1271 raeburn 9517: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 9518: $changes{$action}{$newkey} = {
1.1271 raeburn 9519: type => $accesstype,
1.827 raeburn 9520: time => {
9521: start => $newstart,
9522: end => $newend,
9523: },
9524: };
1.1271 raeburn 9525: if ($accesstype eq 'ip') {
9526: $changes{$action}{$newkey}{'ip'} = [$ip];
9527: }
1.827 raeburn 9528: my ($outcome,$deloutcome,$new_values,$translation) =
9529: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 9530: unless ($outcome eq 'ok') {
9531: $errors .= $outcome.' ';
9532: }
1.827 raeburn 9533: }
1.1271 raeburn 9534: }
9535: if ($errors) {
9536: $errors =~ s/\s$//;
9537: return $errors;
1.827 raeburn 9538: } else {
1.1271 raeburn 9539: return 'ok';
1.827 raeburn 9540: }
9541: }
9542:
1.745 raeburn 9543: #------------------------------------------------------Get Marked as Read Only
9544:
9545: sub get_marked_as_readonly {
9546: my ($domain,$user,$what,$group) = @_;
9547: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9548: my @readonly_files;
1.629 banghart 9549: my $cmp1=$what;
9550: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9551: while (my ($file_name,$value) = each(%{$current_permissions})) {
9552: if (defined($group)) {
9553: if ($file_name !~ m-^\Q$group\E/-) {
9554: next;
9555: }
9556: }
1.561 banghart 9557: if (ref($value) eq "ARRAY"){
9558: foreach my $stored_what (@{$value}) {
1.629 banghart 9559: my $cmp2=$stored_what;
1.759 albertel 9560: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9561: $cmp2=join('',@{$stored_what});
1.745 raeburn 9562: }
1.629 banghart 9563: if ($cmp1 eq $cmp2) {
1.561 banghart 9564: push(@readonly_files, $file_name);
1.745 raeburn 9565: last;
1.563 banghart 9566: } elsif (!defined($what)) {
9567: push(@readonly_files, $file_name);
1.745 raeburn 9568: last;
1.561 banghart 9569: }
9570: }
1.745 raeburn 9571: }
1.561 banghart 9572: }
9573: return @readonly_files;
9574: }
1.577 banghart 9575: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9576:
1.577 banghart 9577: sub get_marked_as_readonly_hash {
1.745 raeburn 9578: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9579: my %readonly_files;
1.745 raeburn 9580: while (my ($file_name,$value) = each(%{$current_permissions})) {
9581: if (defined($group)) {
9582: if ($file_name !~ m-^\Q$group\E/-) {
9583: next;
9584: }
9585: }
1.577 banghart 9586: if (ref($value) eq "ARRAY"){
9587: foreach my $stored_what (@{$value}) {
1.745 raeburn 9588: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9589: foreach my $lock_descriptor(@{$stored_what}) {
9590: if ($lock_descriptor eq 'graded') {
9591: $readonly_files{$file_name} = 'graded';
9592: } elsif ($lock_descriptor eq 'handback') {
9593: $readonly_files{$file_name} = 'handback';
9594: } else {
9595: if (!exists($readonly_files{$file_name})) {
9596: $readonly_files{$file_name} = 'locked';
9597: }
9598: }
1.745 raeburn 9599: }
1.750 banghart 9600: }
1.577 banghart 9601: }
9602: }
9603: }
9604: return %readonly_files;
9605: }
1.559 banghart 9606: # ------------------------------------------------------------ Unmark as Read Only
9607:
9608: sub unmark_as_readonly {
1.629 banghart 9609: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9610: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9611: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9612: $file_name = &declutter_portfile($file_name);
1.634 albertel 9613: my $symb_crs = $what;
9614: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9615: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9616: my ($tmp)=keys(%current_permissions);
9617: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9618: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9619: foreach my $file (@readonly_files) {
1.759 albertel 9620: my $clean_file = &declutter_portfile($file);
9621: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9622: my $current_locks = $current_permissions{$file};
1.563 banghart 9623: my @new_locks;
9624: my @del_keys;
9625: if (ref($current_locks) eq "ARRAY"){
9626: foreach my $locker (@{$current_locks}) {
1.632 albertel 9627: my $compare=$locker;
1.749 raeburn 9628: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9629: $compare=join('',@{$locker});
1.746 raeburn 9630: if ($compare ne $symb_crs) {
9631: push(@new_locks, $locker);
9632: }
1.563 banghart 9633: }
9634: }
1.650 albertel 9635: if (scalar(@new_locks) > 0) {
1.563 banghart 9636: $current_permissions{$file} = \@new_locks;
9637: } else {
9638: push(@del_keys, $file);
1.613 albertel 9639: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9640: delete($current_permissions{$file});
1.563 banghart 9641: }
9642: }
1.561 banghart 9643: }
1.613 albertel 9644: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9645: return;
9646: }
1.512 banghart 9647:
1.17 www 9648: # ------------------------------------------------------------ Directory lister
9649:
9650: sub dirlist {
1.955 raeburn 9651: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9652: $uri=~s/^\///;
9653: $uri=~s/\/$//;
1.253 stredwic 9654: my ($udom, $uname);
1.955 raeburn 9655: if ($getuserdir) {
1.253 stredwic 9656: $udom = $userdomain;
9657: $uname = $username;
1.955 raeburn 9658: } else {
9659: (undef,$udom,$uname)=split(/\//,$uri);
9660: if(defined($userdomain)) {
9661: $udom = $userdomain;
9662: }
9663: if(defined($username)) {
9664: $uname = $username;
9665: }
1.253 stredwic 9666: }
1.955 raeburn 9667: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9668:
1.955 raeburn 9669: $dirRoot = $perlvar{'lonDocRoot'};
9670: if (defined($getpropath)) {
9671: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9672: $dirRoot =~ s/\/$//;
1.955 raeburn 9673: } elsif (defined($getuserdir)) {
9674: my $subdir=$uname.'__';
9675: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9676: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9677: ."/$udom/$subdir/$uname";
9678: } elsif (defined($alternateRoot)) {
9679: $dirRoot = $alternateRoot;
1.751 banghart 9680: }
1.253 stredwic 9681:
9682: if($udom) {
9683: if($uname) {
1.1135 raeburn 9684: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9685: if ($uhome eq 'no_host') {
9686: return ([],'no_host');
9687: }
1.955 raeburn 9688: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9689: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9690: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9691: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9692: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9693: } else {
9694: @listing_results = map { &unescape($_); } split(/:/,$listing);
9695: }
1.605 matthew 9696: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9697: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9698: @listing_results = split(/:/,$listing);
9699: } else {
9700: @listing_results = map { &unescape($_); } split(/:/,$listing);
9701: }
1.1135 raeburn 9702: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9703: ($listing eq 'rejected') || ($listing eq 'refused') ||
9704: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9705: return ([],$listing);
9706: } else {
9707: return (\@listing_results);
1.1135 raeburn 9708: }
1.955 raeburn 9709: } elsif(!$alternateRoot) {
1.1136 raeburn 9710: my (%allusers,%listerror);
1.841 albertel 9711: my %servers = &get_servers($udom,'library');
1.955 raeburn 9712: foreach my $tryserver (keys(%servers)) {
9713: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9714: &escape($udom),$tryserver);
9715: if ($listing eq 'unknown_cmd') {
9716: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9717: $udom, $tryserver);
9718: } else {
9719: @listing_results = map { &unescape($_); } split(/:/,$listing);
9720: }
1.841 albertel 9721: if ($listing eq 'unknown_cmd') {
9722: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9723: $udom, $tryserver);
9724: @listing_results = split(/:/,$listing);
9725: } else {
9726: @listing_results =
9727: map { &unescape($_); } split(/:/,$listing);
9728: }
1.1136 raeburn 9729: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9730: ($listing eq 'rejected') || ($listing eq 'refused') ||
9731: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9732: $listerror{$tryserver} = $listing;
9733: } else {
1.841 albertel 9734: foreach my $line (@listing_results) {
9735: my ($entry) = split(/&/,$line,2);
9736: $allusers{$entry} = 1;
9737: }
9738: }
1.253 stredwic 9739: }
1.1136 raeburn 9740: my @alluserslist=();
1.800 albertel 9741: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9742: push(@alluserslist,$user.'&user');
1.253 stredwic 9743: }
1.1136 raeburn 9744: return (\@alluserslist);
1.253 stredwic 9745: } else {
1.1136 raeburn 9746: return ([],'missing username');
1.253 stredwic 9747: }
1.955 raeburn 9748: } elsif(!defined($getpropath)) {
1.1136 raeburn 9749: my $path = $perlvar{'lonDocRoot'}.'/res/';
9750: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9751: return (\@all_domains);
1.955 raeburn 9752: } else {
1.1136 raeburn 9753: return ([],'missing domain');
1.275 stredwic 9754: }
9755: }
9756:
9757: # --------------------------------------------- GetFileTimestamp
9758: # This function utilizes dirlist and returns the date stamp for
9759: # when it was last modified. It will also return an error of -1
9760: # if an error occurs
9761:
9762: sub GetFileTimestamp {
1.955 raeburn 9763: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9764: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9765: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9766: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9767: undef,$getuserdir);
9768: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9769: return -1;
9770: }
9771: if (ref($fileref) eq 'ARRAY') {
9772: my @stats = split('&',$fileref->[0]);
1.375 matthew 9773: # @stats contains first the filename, then the stat output
9774: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9775: } else {
9776: return -1;
1.253 stredwic 9777: }
1.26 www 9778: }
9779:
1.712 albertel 9780: sub stat_file {
9781: my ($uri) = @_;
1.787 albertel 9782: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9783:
1.955 raeburn 9784: my ($udom,$uname,$file);
1.712 albertel 9785: if ($uri =~ m-^/(uploaded|editupload)/-) {
9786: ($udom,$uname,$file) =
1.811 albertel 9787: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9788: $file = 'userfiles/'.$file;
9789: }
9790: if ($uri =~ m-^/res/-) {
9791: ($udom,$uname) =
1.807 albertel 9792: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9793: $file = $uri;
9794: }
9795:
9796: if (!$udom || !$uname || !$file) {
9797: # unable to handle the uri
9798: return ();
9799: }
1.956 raeburn 9800: my $getpropath;
9801: if ($file =~ /^userfiles\//) {
9802: $getpropath = 1;
9803: }
1.1136 raeburn 9804: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9805: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9806: return ();
9807: } else {
9808: if (ref($listref) eq 'ARRAY') {
9809: my @stats = split('&',$listref->[0]);
9810: shift(@stats); #filename is first
9811: return @stats;
9812: }
1.712 albertel 9813: }
9814: return ();
9815: }
9816:
1.26 www 9817: # -------------------------------------------------------- Value of a Condition
9818:
1.713 albertel 9819: # gets the value of a specific preevaluated condition
9820: # stored in the string $env{user.state.<cid>}
9821: # or looks up a condition reference in the bighash and if if hasn't
9822: # already been evaluated recurses into docondval to get the value of
9823: # the condition, then memoizing it to
9824: # $env{user.state.<cid>.<condition>}
1.40 www 9825: sub directcondval {
9826: my $number=shift;
1.620 albertel 9827: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9828: &Apache::lonuserstate::evalstate();
9829: }
1.713 albertel 9830: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9831: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9832: } elsif ($number =~ /^_/) {
9833: my $sub_condition;
9834: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9835: &GDBM_READER(),0640)) {
9836: $sub_condition=$bighash{'conditions'.$number};
9837: untie(%bighash);
9838: }
9839: my $value = &docondval($sub_condition);
1.949 raeburn 9840: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9841: return $value;
9842: }
1.620 albertel 9843: if ($env{'user.state.'.$env{'request.course.id'}}) {
9844: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9845: } else {
9846: return 2;
9847: }
9848: }
9849:
1.713 albertel 9850: # get the collection of conditions for this resource
1.26 www 9851: sub condval {
9852: my $condidx=shift;
1.54 www 9853: my $allpathcond='';
1.713 albertel 9854: foreach my $cond (split(/\|/,$condidx)) {
9855: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9856: $allpathcond.=
9857: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9858: }
1.191 harris41 9859: }
1.54 www 9860: $allpathcond=~s/\|$//;
1.713 albertel 9861: return &docondval($allpathcond);
9862: }
9863:
9864: #evaluates an expression of conditions
9865: sub docondval {
9866: my ($allpathcond) = @_;
9867: my $result=0;
9868: if ($env{'request.course.id'}
9869: && defined($allpathcond)) {
9870: my $operand='|';
9871: my @stack;
9872: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9873: if ($chunk eq '(') {
9874: push @stack,($operand,$result);
9875: } elsif ($chunk eq ')') {
9876: my $before=pop @stack;
9877: if (pop @stack eq '&') {
9878: $result=$result>$before?$before:$result;
9879: } else {
9880: $result=$result>$before?$result:$before;
9881: }
9882: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9883: $operand=$chunk;
9884: } else {
9885: my $new=directcondval($chunk);
9886: if ($operand eq '&') {
9887: $result=$result>$new?$new:$result;
9888: } else {
9889: $result=$result>$new?$result:$new;
9890: }
9891: }
9892: }
1.26 www 9893: }
9894: return $result;
1.421 albertel 9895: }
9896:
9897: # ---------------------------------------------------- Devalidate courseresdata
9898:
9899: sub devalidatecourseresdata {
9900: my ($coursenum,$coursedomain)=@_;
9901: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9902: &devalidate_cache_new('courseres',$hashid);
1.28 www 9903: }
9904:
1.763 www 9905:
1.200 www 9906: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9907: #
9908: # Parameters:
9909: # $coursenum - Number of the course.
9910: # $coursedomain - Domain at which the course was created.
9911: # Returns:
9912: # A hash of the course parameters along (I think) with timestamps
9913: # and version info.
1.877 foxr 9914:
1.624 albertel 9915: sub get_courseresdata {
9916: my ($coursenum,$coursedomain)=@_;
1.200 www 9917: my $coursehom=&homeserver($coursenum,$coursedomain);
9918: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9919: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9920: my %dumpreply;
1.417 albertel 9921: unless (defined($cached)) {
1.624 albertel 9922: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9923: $result=\%dumpreply;
1.251 albertel 9924: my ($tmp) = keys(%dumpreply);
9925: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9926: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9927: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9928: return $tmp;
1.416 albertel 9929: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9930: $result=undef;
1.599 albertel 9931: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9932: }
9933: }
1.624 albertel 9934: return $result;
9935: }
9936:
1.633 albertel 9937: sub devalidateuserresdata {
9938: my ($uname,$udom)=@_;
9939: my $hashid="$udom:$uname";
9940: &devalidate_cache_new('userres',$hashid);
9941: }
9942:
1.624 albertel 9943: sub get_userresdata {
9944: my ($uname,$udom)=@_;
9945: #most student don\'t have any data set, check if there is some data
9946: if (&EXT_cache_status($udom,$uname)) { return undef; }
9947:
9948: my $hashid="$udom:$uname";
9949: my ($result,$cached)=&is_cached_new('userres',$hashid);
9950: if (!defined($cached)) {
9951: my %resourcedata=&dump('resourcedata',$udom,$uname);
9952: $result=\%resourcedata;
9953: &do_cache_new('userres',$hashid,$result,600);
9954: }
9955: my ($tmp)=keys(%$result);
9956: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9957: return $result;
9958: }
9959: #error 2 occurs when the .db doesn't exist
9960: if ($tmp!~/error: 2 /) {
1.672 albertel 9961: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9962: " Trying to get resource data for ".
9963: $uname." at ".$udom.": ".
9964: $tmp."</font>");
9965: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9966: #&EXT_cache_set($udom,$uname);
9967: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9968: undef($tmp); # not really an error so don't send it back
1.624 albertel 9969: }
9970: return $tmp;
9971: }
1.879 foxr 9972: #----------------------------------------------- resdata - return resource data
9973: # Purpose:
9974: # Return resource data for either users or for a course.
9975: # Parameters:
9976: # $name - Course/user name.
9977: # $domain - Name of the domain the user/course is registered on.
9978: # $type - Type of thing $name is (must be 'course' or 'user'
9979: # @which - Array of names of resources desired.
9980: # Returns:
9981: # The value of the first reasource in @which that is found in the
9982: # resource hash.
9983: # Exceptional Conditions:
9984: # If the $type passed in is not valid (not the string 'course' or
9985: # 'user', an undefined reference is returned.
9986: # If none of the resources are found, an undef is returned
1.624 albertel 9987: sub resdata {
9988: my ($name,$domain,$type,@which)=@_;
9989: my $result;
9990: if ($type eq 'course') {
9991: $result=&get_courseresdata($name,$domain);
9992: } elsif ($type eq 'user') {
9993: $result=&get_userresdata($name,$domain);
9994: }
9995: if (!ref($result)) { return $result; }
1.251 albertel 9996: foreach my $item (@which) {
1.927 albertel 9997: if (defined($result->{$item->[0]})) {
9998: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9999: }
1.250 albertel 10000: }
1.291 albertel 10001: return undef;
1.200 www 10002: }
10003:
1.1236 raeburn 10004: sub get_numsuppfiles {
10005: my ($cnum,$cdom,$ignorecache)=@_;
10006: my $hashid=$cnum.':'.$cdom;
10007: my ($suppcount,$cached);
10008: unless ($ignorecache) {
10009: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10010: }
10011: unless (defined($cached)) {
10012: my $chome=&homeserver($cnum,$cdom);
10013: unless ($chome eq 'no_host') {
10014: ($suppcount,my $errors) = (0,0);
10015: my $suppmap = 'supplemental.sequence';
10016: ($suppcount,$errors) =
10017: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10018: }
10019: &do_cache_new('suppcount',$hashid,$suppcount,600);
10020: }
10021: return $suppcount;
10022: }
10023:
1.379 matthew 10024: #
10025: # EXT resource caching routines
10026: #
10027:
10028: sub clear_EXT_cache_status {
1.383 albertel 10029: &delenv('cache.EXT.');
1.379 matthew 10030: }
10031:
10032: sub EXT_cache_status {
10033: my ($target_domain,$target_user) = @_;
1.383 albertel 10034: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10035: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10036: # We know already the user has no data
10037: return 1;
10038: } else {
10039: return 0;
10040: }
10041: }
10042:
10043: sub EXT_cache_set {
10044: my ($target_domain,$target_user) = @_;
1.383 albertel 10045: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10046: #&appenv({$cachename => time});
1.379 matthew 10047: }
10048:
1.28 www 10049: # --------------------------------------------------------- Value of a Variable
1.58 www 10050: sub EXT {
1.715 albertel 10051:
1.1228 raeburn 10052: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10053: unless ($varname) { return ''; }
1.218 albertel 10054: #get real user name/domain, courseid and symb
10055: my $courseid;
1.359 albertel 10056: my $publicuser;
1.427 www 10057: if ($symbparm) {
10058: $symbparm=&get_symb_from_alias($symbparm);
10059: }
1.218 albertel 10060: if (!($uname && $udom)) {
1.790 albertel 10061: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10062: if (!$symbparm) { $symbparm=$cursymb; }
10063: } else {
1.620 albertel 10064: $courseid=$env{'request.course.id'};
1.218 albertel 10065: }
1.48 www 10066: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10067: my $rest;
1.320 albertel 10068: if (defined($therest[0])) {
1.48 www 10069: $rest=join('.',@therest);
10070: } else {
10071: $rest='';
10072: }
1.320 albertel 10073:
1.57 www 10074: my $qualifierrest=$qualifier;
10075: if ($rest) { $qualifierrest.='.'.$rest; }
10076: my $spacequalifierrest=$space;
10077: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10078: if ($realm eq 'user') {
1.48 www 10079: # --------------------------------------------------------------- user.resource
10080: if ($space eq 'resource') {
1.651 albertel 10081: if ( (defined($Apache::lonhomework::parsing_a_problem)
10082: || defined($Apache::lonhomework::parsing_a_task))
10083: &&
1.744 albertel 10084: ($symbparm eq &symbread()) ) {
10085: # if we are in the middle of processing the resource the
10086: # get the value we are planning on committing
10087: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10088: return $Apache::lonhomework::results{$qualifierrest};
10089: } else {
10090: return $Apache::lonhomework::history{$qualifierrest};
10091: }
1.335 albertel 10092: } else {
1.359 albertel 10093: my %restored;
1.620 albertel 10094: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10095: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10096: } else {
10097: %restored=&restore($symbparm,$courseid,$udom,$uname);
10098: }
1.335 albertel 10099: return $restored{$qualifierrest};
10100: }
1.48 www 10101: # ----------------------------------------------------------------- user.access
10102: } elsif ($space eq 'access') {
1.218 albertel 10103: # FIXME - not supporting calls for a specific user
1.48 www 10104: return &allowed($qualifier,$rest);
10105: # ------------------------------------------ user.preferences, user.environment
10106: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10107: if (($uname eq $env{'user.name'}) &&
10108: ($udom eq $env{'user.domain'})) {
10109: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10110: } else {
1.359 albertel 10111: my %returnhash;
10112: if (!$publicuser) {
10113: %returnhash=&userenvironment($udom,$uname,
10114: $qualifierrest);
10115: }
1.218 albertel 10116: return $returnhash{$qualifierrest};
10117: }
1.48 www 10118: # ----------------------------------------------------------------- user.course
10119: } elsif ($space eq 'course') {
1.218 albertel 10120: # FIXME - not supporting calls for a specific user
1.620 albertel 10121: return $env{join('.',('request.course',$qualifier))};
1.48 www 10122: # ------------------------------------------------------------------- user.role
10123: } elsif ($space eq 'role') {
1.218 albertel 10124: # FIXME - not supporting calls for a specific user
1.620 albertel 10125: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10126: if ($qualifier eq 'value') {
10127: return $role;
10128: } elsif ($qualifier eq 'extent') {
10129: return $where;
10130: }
10131: # ----------------------------------------------------------------- user.domain
10132: } elsif ($space eq 'domain') {
1.218 albertel 10133: return $udom;
1.48 www 10134: # ------------------------------------------------------------------- user.name
10135: } elsif ($space eq 'name') {
1.218 albertel 10136: return $uname;
1.48 www 10137: # ---------------------------------------------------- Any other user namespace
1.29 www 10138: } else {
1.359 albertel 10139: my %reply;
10140: if (!$publicuser) {
10141: %reply=&get($space,[$qualifierrest],$udom,$uname);
10142: }
10143: return $reply{$qualifierrest};
1.48 www 10144: }
1.236 www 10145: } elsif ($realm eq 'query') {
10146: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10147: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10148: [$spacequalifierrest]);
1.620 albertel 10149: return $env{'form.'.$spacequalifierrest};
1.236 www 10150: } elsif ($realm eq 'request') {
1.48 www 10151: # ------------------------------------------------------------- request.browser
10152: if ($space eq 'browser') {
1.1145 bisitz 10153: return $env{'browser.'.$qualifier};
1.57 www 10154: # ------------------------------------------------------------ request.filename
10155: } else {
1.620 albertel 10156: return $env{'request.'.$spacequalifierrest};
1.29 www 10157: }
1.28 www 10158: } elsif ($realm eq 'course') {
1.48 www 10159: # ---------------------------------------------------------- course.description
1.620 albertel 10160: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10161: } elsif ($realm eq 'resource') {
1.165 www 10162:
1.620 albertel 10163: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10164: if (!$symbparm) { $symbparm=&symbread(); }
10165: }
1.693 albertel 10166:
1.1232 raeburn 10167: if ($qualifier eq '') {
10168: if ($space eq 'title') {
10169: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10170: return &gettitle($symbparm);
10171: }
1.693 albertel 10172:
1.1232 raeburn 10173: if ($space eq 'map') {
10174: my ($map) = &decode_symb($symbparm);
10175: return &symbread($map);
10176: }
10177: if ($space eq 'maptitle') {
10178: my ($map) = &decode_symb($symbparm);
10179: return &gettitle($map);
10180: }
10181: if ($space eq 'filename') {
10182: if ($symbparm) {
10183: return &clutter((&decode_symb($symbparm))[2]);
10184: }
10185: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10186: }
1.1232 raeburn 10187:
1.1233 raeburn 10188: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10189: if ($space eq 'visibleparts') {
10190: my $navmap = Apache::lonnavmaps::navmap->new();
10191: my $item;
10192: if (ref($navmap)) {
10193: my $res = $navmap->getBySymb($symbparm);
10194: my $parts = $res->parts();
10195: if (ref($parts) eq 'ARRAY') {
10196: $item = join(',',@{$parts});
10197: }
10198: undef($navmap);
1.1232 raeburn 10199: }
1.1233 raeburn 10200: return $item;
1.1232 raeburn 10201: }
10202: }
10203: }
1.693 albertel 10204:
10205: my ($section, $group, @groups);
1.593 albertel 10206: my ($courselevelm,$courselevel);
1.1228 raeburn 10207: if (($courseid eq '') && ($cid)) {
10208: $courseid = $cid;
10209: }
10210: if (($symbparm && $courseid) &&
10211: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10212:
1.218 albertel 10213: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10214:
1.60 www 10215: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10216: my $symbp=$symbparm;
1.735 albertel 10217: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10218:
10219: my $symbparm=$symbp.'.'.$spacequalifierrest;
10220: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10221:
1.620 albertel 10222: if (($env{'user.name'} eq $uname) &&
10223: ($env{'user.domain'} eq $udom)) {
10224: $section=$env{'request.course.sec'};
1.733 raeburn 10225: @groups = split(/:/,$env{'request.course.groups'});
10226: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10227: } else {
1.539 albertel 10228: if (! defined($usection)) {
1.551 albertel 10229: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10230: } else {
10231: $section = $usection;
10232: }
1.733 raeburn 10233: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10234: }
10235:
10236: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10237: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10238: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10239:
1.593 albertel 10240: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10241: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10242: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10243:
1.60 www 10244: # ----------------------------------------------------------- first, check user
1.624 albertel 10245:
10246: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10247: ([$courselevelr,'resource'],
10248: [$courselevelm,'map' ],
10249: [$courselevel, 'course' ]));
1.931 albertel 10250: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10251:
1.594 albertel 10252: # ------------------------------------------------ second, check some of course
1.684 raeburn 10253: my $coursereply;
1.691 raeburn 10254: if (@groups > 0) {
10255: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10256: $mapparm,$spacequalifierrest);
1.927 albertel 10257: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10258: }
1.96 www 10259:
1.684 raeburn 10260: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10261: $env{'course.'.$courseid.'.domain'},
10262: 'course',
10263: ([$seclevelr, 'resource'],
10264: [$seclevelm, 'map' ],
10265: [$seclevel, 'course' ],
10266: [$courselevelr,'resource']));
10267: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10268:
1.60 www 10269: # ------------------------------------------------------ third, check map parms
1.218 albertel 10270: my %parmhash=();
10271: my $thisparm='';
10272: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10273: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10274: &GDBM_READER(),0640)) {
1.218 albertel 10275: $thisparm=$parmhash{$symbparm};
10276: untie(%parmhash);
10277: }
1.927 albertel 10278: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10279: }
1.594 albertel 10280: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10281:
1.218 albertel 10282: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10283: my $filename;
10284: if (!$symbparm) { $symbparm=&symbread(); }
10285: if ($symbparm) {
1.409 www 10286: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10287: } else {
1.620 albertel 10288: $filename=$env{'request.filename'};
1.282 albertel 10289: }
10290: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10291: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10292: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10293: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10294:
1.927 albertel 10295: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10296: if ($symbparm && defined($courseid) &&
1.620 albertel 10297: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10298: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10299: $env{'course.'.$courseid.'.domain'},
10300: 'course',
1.927 albertel 10301: ([$courselevelm,'map' ],
10302: [$courselevel, 'course']));
10303: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10304: }
1.145 www 10305: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10306: unless ($space eq '0') {
1.336 albertel 10307: my @parts=split(/_/,$space);
10308: my $id=pop(@parts);
10309: my $part=join('_',@parts);
10310: if ($part eq '') { $part='0'; }
1.927 albertel 10311: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10312: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10313: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10314: }
1.395 albertel 10315: if ($recurse) { return undef; }
10316: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10317: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10318: # ---------------------------------------------------- Any other user namespace
10319: } elsif ($realm eq 'environment') {
10320: # ----------------------------------------------------------------- environment
1.620 albertel 10321: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10322: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10323: } else {
1.770 albertel 10324: if ($uname eq 'anonymous' && $udom eq '') {
10325: return '';
10326: }
1.219 albertel 10327: my %returnhash=&userenvironment($udom,$uname,
10328: $spacequalifierrest);
10329: return $returnhash{$spacequalifierrest};
10330: }
1.28 www 10331: } elsif ($realm eq 'system') {
1.48 www 10332: # ----------------------------------------------------------------- system.time
10333: if ($space eq 'time') {
10334: return time;
10335: }
1.696 albertel 10336: } elsif ($realm eq 'server') {
10337: # ----------------------------------------------------------------- system.time
10338: if ($space eq 'name') {
10339: return $ENV{'SERVER_NAME'};
10340: }
1.28 www 10341: }
1.48 www 10342: return '';
1.61 www 10343: }
10344:
1.927 albertel 10345: sub get_reply {
10346: my ($reply_value) = @_;
1.940 raeburn 10347: if (ref($reply_value) eq 'ARRAY') {
10348: if (wantarray) {
10349: return @$reply_value;
10350: }
10351: return $reply_value->[0];
10352: } else {
10353: return $reply_value;
1.927 albertel 10354: }
10355: }
10356:
1.691 raeburn 10357: sub check_group_parms {
10358: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10359: my @groupitems = ();
10360: my $resultitem;
1.927 albertel 10361: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10362: foreach my $group (@{$groups}) {
10363: foreach my $level (@levels) {
1.927 albertel 10364: my $item = $courseid.'.['.$group.'].'.$level->[0];
10365: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10366: }
10367: }
10368: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10369: $env{'course.'.$courseid.'.domain'},
10370: 'course',@groupitems);
10371: return $coursereply;
10372: }
10373:
10374: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10375: my ($courseid,@groups) = @_;
10376: @groups = sort(@groups);
1.691 raeburn 10377: return @groups;
10378: }
10379:
1.395 albertel 10380: sub packages_tab_default {
10381: my ($uri,$varname)=@_;
10382: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10383:
10384: my (@extension,@specifics,$do_default);
10385: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10386: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10387: if ($pack_type eq 'default') {
10388: $do_default=1;
10389: } elsif ($pack_type eq 'extension') {
10390: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10391: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10392: # only look at packages defaults for packages that this id is
1.738 albertel 10393: push(@specifics,[$package,$pack_type,$pack_part]);
10394: }
10395: }
10396: # first look for a package that matches the requested part id
10397: foreach my $package (@specifics) {
10398: my (undef,$pack_type,$pack_part)=@{$package};
10399: next if ($pack_part ne $part);
10400: if (defined($packagetab{"$pack_type&$name&default"})) {
10401: return $packagetab{"$pack_type&$name&default"};
10402: }
10403: }
10404: # look for any possible matching non extension_ package
10405: foreach my $package (@specifics) {
10406: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10407: if (defined($packagetab{"$pack_type&$name&default"})) {
10408: return $packagetab{"$pack_type&$name&default"};
10409: }
1.585 albertel 10410: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10411: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10412: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10413: }
10414: }
1.738 albertel 10415: # look for any posible extension_ match
10416: foreach my $package (@extension) {
10417: my ($package,$pack_type)=@{$package};
10418: if (defined($packagetab{"$pack_type&$name&default"})) {
10419: return $packagetab{"$pack_type&$name&default"};
10420: }
10421: if (defined($packagetab{$package."&$name&default"})) {
10422: return $packagetab{$package."&$name&default"};
10423: }
10424: }
10425: # look for a global default setting
10426: if ($do_default && defined($packagetab{"default&$name&default"})) {
10427: return $packagetab{"default&$name&default"};
10428: }
1.395 albertel 10429: return undef;
10430: }
10431:
1.334 albertel 10432: sub add_prefix_and_part {
10433: my ($prefix,$part)=@_;
10434: my $keyroot;
10435: if (defined($prefix) && $prefix !~ /^__/) {
10436: # prefix that has a part already
10437: $keyroot=$prefix;
10438: } elsif (defined($prefix)) {
10439: # prefix that is missing a part
10440: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10441: } else {
10442: # no prefix at all
10443: if (defined($part)) { $keyroot='_'.$part; }
10444: }
10445: return $keyroot;
10446: }
10447:
1.71 www 10448: # ---------------------------------------------------------------- Get metadata
10449:
1.599 albertel 10450: my %metaentry;
1.1070 www 10451: my %importedpartids;
1.71 www 10452: sub metadata {
1.176 www 10453: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10454: $uri=&declutter($uri);
1.288 albertel 10455: # if it is a non metadata possible uri return quickly
1.529 albertel 10456: if (($uri eq '') ||
10457: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10458: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10459: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10460: return undef;
10461: }
1.1261 raeburn 10462: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10463: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10464: return undef;
1.288 albertel 10465: }
1.73 www 10466: my $filename=$uri;
10467: $uri=~s/\.meta$//;
1.172 www 10468: #
10469: # Is the metadata already cached?
1.177 www 10470: # Look at timestamp of caching
1.172 www 10471: # Everything is cached by the main uri, libraries are never directly cached
10472: #
1.428 albertel 10473: if (!defined($liburi)) {
1.599 albertel 10474: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10475: if (defined($cached)) { return $result->{':'.$what}; }
10476: }
10477: {
1.1069 www 10478: # Imported parts would go here
1.1070 www 10479: my %importedids=();
10480: my @origfileimportpartids=();
1.1069 www 10481: my $importedparts=0;
1.172 www 10482: #
10483: # Is this a recursive call for a library?
10484: #
1.599 albertel 10485: # if (! exists($metacache{$uri})) {
10486: # $metacache{$uri}={};
10487: # }
1.924 albertel 10488: my $cachetime = 60*60;
1.171 www 10489: if ($liburi) {
10490: $liburi=&declutter($liburi);
10491: $filename=$liburi;
1.401 bowersj2 10492: } else {
1.599 albertel 10493: &devalidate_cache_new('meta',$uri);
10494: undef(%metaentry);
1.401 bowersj2 10495: }
1.140 www 10496: my %metathesekeys=();
1.73 www 10497: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10498: my $metastring;
1.1140 www 10499: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10500: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10501: $metastring =
1.929 albertel 10502: &Apache::lonnet::ssi_body($which,
1.924 albertel 10503: ('grade_target' => 'meta'));
10504: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10505: } elsif (($uri !~ m -^(editupload)/-) &&
10506: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10507: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10508: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10509: $metastring=&getfile($file);
1.489 albertel 10510: }
1.208 albertel 10511: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10512: my $token;
1.140 www 10513: undef %metathesekeys;
1.71 www 10514: while ($token=$parser->get_token) {
1.339 albertel 10515: if ($token->[0] eq 'S') {
10516: if (defined($token->[2]->{'package'})) {
1.172 www 10517: #
10518: # This is a package - get package info
10519: #
1.339 albertel 10520: my $package=$token->[2]->{'package'};
10521: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10522: if (defined($token->[2]->{'id'})) {
10523: $keyroot.='_'.$token->[2]->{'id'};
10524: }
1.599 albertel 10525: if ($metaentry{':packages'}) {
10526: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10527: } else {
1.599 albertel 10528: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10529: }
1.736 albertel 10530: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10531: my $part=$keyroot;
10532: $part=~s/^\_//;
1.736 albertel 10533: if ($pack_entry=~/^\Q$package\E\&/ ||
10534: $pack_entry=~/^\Q$package\E_0\&/) {
10535: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10536: # ignore package.tab specified default values
10537: # here &package_tab_default() will fetch those
10538: if ($subp eq 'default') { next; }
1.736 albertel 10539: my $value=$packagetab{$pack_entry};
1.432 albertel 10540: my $unikey;
10541: if ($pack =~ /_0$/) {
10542: $unikey='parameter_0_'.$name;
10543: $part=0;
10544: } else {
10545: $unikey='parameter'.$keyroot.'_'.$name;
10546: }
1.339 albertel 10547: if ($subp eq 'display') {
10548: $value.=' [Part: '.$part.']';
10549: }
1.599 albertel 10550: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10551: $metathesekeys{$unikey}=1;
1.599 albertel 10552: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10553: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10554: }
1.599 albertel 10555: if (defined($metaentry{':'.$unikey.'.default'})) {
10556: $metaentry{':'.$unikey}=
10557: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10558: }
1.339 albertel 10559: }
10560: }
10561: } else {
1.172 www 10562: #
10563: # This is not a package - some other kind of start tag
1.339 albertel 10564: #
10565: my $entry=$token->[1];
1.1068 www 10566: my $unikey='';
1.175 www 10567:
1.339 albertel 10568: if ($entry eq 'import') {
1.175 www 10569: #
10570: # Importing a library here
1.339 albertel 10571: #
1.1067 www 10572: my $location=$parser->get_text('/import');
10573: my $dir=$filename;
10574: $dir=~s|[^/]*$||;
10575: $location=&filelocation($dir,$location);
1.1069 www 10576:
1.1068 www 10577: my $importmode=$token->[2]->{'importmode'};
10578: if ($importmode eq 'problem') {
1.1069 www 10579: # Import as problem/response
1.1068 www 10580: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10581: } elsif ($importmode eq 'part') {
10582: # Import as part(s)
1.1069 www 10583: $importedparts=1;
10584: # We need to get the original file and the imported file to get the part order correct
10585: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10586: # Load and inspect original file
1.1070 www 10587: if ($#origfileimportpartids<0) {
10588: undef(%importedpartids);
10589: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10590: my $origfile=&getfile($origfilelocation);
10591: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10592: }
10593:
1.1069 www 10594: # Load and inspect imported file
10595: my $impfile=&getfile($location);
10596: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10597: if ($#impfilepartids>=0) {
10598: # This problem had parts
1.1070 www 10599: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10600: } else {
10601: # Importing by turning a single problem into a problem part
10602: # It gets the import-tags ID as part-ID
10603: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10604: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10605: }
1.1068 www 10606: } else {
10607: # Normal import
10608: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10609: if (defined($token->[2]->{'id'})) {
10610: $unikey.='_'.$token->[2]->{'id'};
10611: }
1.1067 www 10612: }
10613:
1.339 albertel 10614: if ($depthcount<20) {
1.736 albertel 10615: my $metadata =
10616: &metadata($uri,'keys', $location,$unikey,
10617: $depthcount+1);
10618: foreach my $meta (split(',',$metadata)) {
10619: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10620: $metathesekeys{$meta}=1;
1.339 albertel 10621: }
1.1068 www 10622:
10623: }
1.1067 www 10624: } else {
10625: #
10626: # Not importing, some other kind of non-package, non-library start tag
10627: #
10628: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10629: if (defined($token->[2]->{'id'})) {
10630: $unikey.='_'.$token->[2]->{'id'};
10631: }
1.339 albertel 10632: if (defined($token->[2]->{'name'})) {
10633: $unikey.='_'.$token->[2]->{'name'};
10634: }
10635: $metathesekeys{$unikey}=1;
1.736 albertel 10636: foreach my $param (@{$token->[3]}) {
10637: $metaentry{':'.$unikey.'.'.$param} =
10638: $token->[2]->{$param};
1.339 albertel 10639: }
10640: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10641: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10642: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10643: # only ws inside the tag, and not in default, so use default
10644: # as value
1.599 albertel 10645: $metaentry{':'.$unikey}=$default;
1.908 albertel 10646: } elsif ( $internaltext =~ /\S/ ) {
10647: # something interesting inside the tag
10648: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10649: } else {
1.908 albertel 10650: # no interesting values, don't set a default
1.339 albertel 10651: }
1.172 www 10652: # end of not-a-package not-a-library import
1.339 albertel 10653: }
1.172 www 10654: # end of not-a-package start tag
1.339 albertel 10655: }
1.172 www 10656: # the next is the end of "start tag"
1.339 albertel 10657: }
10658: }
1.483 albertel 10659: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10660: $extension = lc($extension);
10661: if ($extension eq 'htm') { $extension='html'; }
10662:
1.737 albertel 10663: foreach my $key (keys(%packagetab)) {
1.483 albertel 10664: #no specific packages #how's our extension
10665: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10666: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10667: \%metathesekeys);
10668: }
1.883 albertel 10669:
10670: if (!exists($metaentry{':packages'})
10671: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10672: foreach my $key (keys(%packagetab)) {
1.483 albertel 10673: #no specific packages well let's get default then
10674: if ($key!~/^default&/) { next; }
1.488 albertel 10675: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10676: \%metathesekeys);
10677: }
10678: }
1.338 www 10679: # are there custom rights to evaluate
1.599 albertel 10680: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10681:
1.338 www 10682: #
10683: # Importing a rights file here
1.339 albertel 10684: #
10685: unless ($depthcount) {
1.599 albertel 10686: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10687: my $dir=$filename;
10688: $dir=~s|[^/]*$||;
10689: $location=&filelocation($dir,$location);
1.736 albertel 10690: my $rights_metadata =
10691: &metadata($uri,'keys',$location,'_rights',
10692: $depthcount+1);
10693: foreach my $rights (split(',',$rights_metadata)) {
10694: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10695: $metathesekeys{$rights}=1;
1.339 albertel 10696: }
10697: }
10698: }
1.737 albertel 10699: # uniqifiy package listing
10700: my %seen;
10701: my @uniq_packages =
10702: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10703: $metaentry{':packages'} = join(',',@uniq_packages);
10704:
1.1070 www 10705: if ($importedparts) {
10706: # We had imported parts and need to rebuild partorder
10707: $metaentry{':partorder'}='';
10708: $metathesekeys{'partorder'}=1;
10709: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10710: if ($origfileimportpartids[$index] eq 'part') {
10711: # original part, part of the problem
10712: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10713: } else {
10714: # we have imported parts at this position
10715: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10716: }
10717: }
10718: $metaentry{':partorder'}=~s/^\,//;
10719: }
10720:
1.737 albertel 10721: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10722: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 10723: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10724: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10725: # this is the end of "was not already recently cached
1.71 www 10726: }
1.599 albertel 10727: return $metaentry{':'.$what};
1.261 albertel 10728: }
10729:
1.488 albertel 10730: sub metadata_create_package_def {
1.483 albertel 10731: my ($uri,$key,$package,$metathesekeys)=@_;
10732: my ($pack,$name,$subp)=split(/\&/,$key);
10733: if ($subp eq 'default') { next; }
10734:
1.599 albertel 10735: if (defined($metaentry{':packages'})) {
10736: $metaentry{':packages'}.=','.$package;
1.483 albertel 10737: } else {
1.599 albertel 10738: $metaentry{':packages'}=$package;
1.483 albertel 10739: }
10740: my $value=$packagetab{$key};
10741: my $unikey;
10742: $unikey='parameter_0_'.$name;
1.599 albertel 10743: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10744: $$metathesekeys{$unikey}=1;
1.599 albertel 10745: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10746: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10747: }
1.599 albertel 10748: if (defined($metaentry{':'.$unikey.'.default'})) {
10749: $metaentry{':'.$unikey}=
10750: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10751: }
10752: }
10753:
1.261 albertel 10754: sub metadata_generate_part0 {
10755: my ($metadata,$metacache,$uri) = @_;
10756: my %allnames;
1.737 albertel 10757: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10758: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10759: my $part=$$metacache{':'.$metakey.'.part'};
10760: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10761: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10762: $allnames{$name}=$part;
10763: }
10764: }
10765: }
10766: foreach my $name (keys(%allnames)) {
10767: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10768: my $key=":parameter_0_$name";
1.261 albertel 10769: $$metacache{"$key.part"}='0';
10770: $$metacache{"$key.name"}=$name;
1.428 albertel 10771: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10772: $allnames{$name}.'_'.$name.
10773: '.type'};
1.428 albertel 10774: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10775: '.display'};
1.644 www 10776: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10777: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10778: $$metacache{"$key.display"}=$olddis;
10779: }
1.71 www 10780: }
10781:
1.764 albertel 10782: # ------------------------------------------------------ Devalidate title cache
10783:
10784: sub devalidate_title_cache {
10785: my ($url)=@_;
10786: if (!$env{'request.course.id'}) { return; }
10787: my $symb=&symbread($url);
10788: if (!$symb) { return; }
10789: my $key=$env{'request.course.id'}."\0".$symb;
10790: &devalidate_cache_new('title',$key);
10791: }
10792:
1.1014 droeschl 10793: # ------------------------------------------------- Get the title of a course
10794:
10795: sub current_course_title {
10796: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10797: }
1.301 www 10798: # ------------------------------------------------- Get the title of a resource
10799:
10800: sub gettitle {
10801: my $urlsymb=shift;
10802: my $symb=&symbread($urlsymb);
1.534 albertel 10803: if ($symb) {
1.620 albertel 10804: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10805: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10806: if (defined($cached)) {
10807: return $result;
10808: }
1.534 albertel 10809: my ($map,$resid,$url)=&decode_symb($symb);
10810: my $title='';
1.907 albertel 10811: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10812: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10813: } else {
10814: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10815: &GDBM_READER(),0640)) {
10816: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10817: $title=$bighash{'title_'.$mapid.'.'.$resid};
10818: untie(%bighash);
10819: }
1.534 albertel 10820: }
10821: $title=~s/\&colon\;/\:/gs;
10822: if ($title) {
1.1159 www 10823: # Remember both $symb and $title for dynamic metadata
10824: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10825: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10826: # Cache this title and then return it
1.599 albertel 10827: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10828: }
10829: $urlsymb=$url;
10830: }
10831: my $title=&metadata($urlsymb,'title');
10832: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10833: return $title;
1.301 www 10834: }
1.613 albertel 10835:
1.614 albertel 10836: sub get_slot {
10837: my ($which,$cnum,$cdom)=@_;
10838: if (!$cnum || !$cdom) {
1.790 albertel 10839: (undef,my $courseid)=&whichuser();
1.620 albertel 10840: $cdom=$env{'course.'.$courseid.'.domain'};
10841: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10842: }
1.703 albertel 10843: my $key=join("\0",'slots',$cdom,$cnum,$which);
10844: my %slotinfo;
10845: if (exists($remembered{$key})) {
10846: $slotinfo{$which} = $remembered{$key};
10847: } else {
10848: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10849: &Apache::lonhomework::showhash(%slotinfo);
10850: my ($tmp)=keys(%slotinfo);
10851: if ($tmp=~/^error:/) { return (); }
10852: $remembered{$key} = $slotinfo{$which};
10853: }
1.616 albertel 10854: if (ref($slotinfo{$which}) eq 'HASH') {
10855: return %{$slotinfo{$which}};
10856: }
10857: return $slotinfo{$which};
1.614 albertel 10858: }
1.1150 raeburn 10859:
10860: sub get_reservable_slots {
10861: my ($cnum,$cdom,$uname,$udom) = @_;
10862: my $now = time;
10863: my $reservable_info;
10864: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10865: if (exists($remembered{$key})) {
10866: $reservable_info = $remembered{$key};
10867: } else {
10868: my %resv;
10869: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10870: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10871: $reservable_info = \%resv;
10872: $remembered{$key} = $reservable_info;
10873: }
10874: return $reservable_info;
10875: }
10876:
10877: sub get_course_slots {
10878: my ($cnum,$cdom) = @_;
10879: my $hashid=$cnum.':'.$cdom;
10880: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10881: if (defined($cached)) {
10882: if (ref($result) eq 'HASH') {
10883: return %{$result};
10884: }
10885: } else {
10886: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10887: my ($tmp) = keys(%slots);
10888: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10889: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10890: return %slots;
10891: }
10892: }
10893: return;
10894: }
10895:
10896: sub devalidate_slots_cache {
10897: my ($cnum,$cdom)=@_;
10898: my $hashid=$cnum.':'.$cdom;
10899: &devalidate_cache_new('allslots',$hashid);
10900: }
10901:
1.1181 raeburn 10902: sub get_coursechange {
10903: my ($cdom,$cnum) = @_;
10904: if ($cdom eq '' || $cnum eq '') {
10905: return unless ($env{'request.course.id'});
10906: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10907: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10908: }
10909: my $hashid=$cdom.'_'.$cnum;
10910: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10911: if ((defined($cached)) && ($change ne '')) {
10912: return $change;
10913: } else {
10914: my %crshash;
10915: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10916: if ($crshash{'internal.contentchange'} eq '') {
10917: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10918: if ($change eq '') {
10919: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10920: $change = $crshash{'internal.created'};
10921: }
10922: } else {
10923: $change = $crshash{'internal.contentchange'};
10924: }
10925: my $cachetime = 600;
10926: &do_cache_new('crschange',$hashid,$change,$cachetime);
10927: }
10928: return $change;
10929: }
10930:
10931: sub devalidate_coursechange_cache {
10932: my ($cnum,$cdom)=@_;
10933: my $hashid=$cnum.':'.$cdom;
10934: &devalidate_cache_new('crschange',$hashid);
10935: }
10936:
1.31 www 10937: # ------------------------------------------------- Update symbolic store links
10938:
10939: sub symblist {
10940: my ($mapname,%newhash)=@_;
1.438 www 10941: $mapname=&deversion(&declutter($mapname));
1.31 www 10942: my %hash;
1.620 albertel 10943: if (($env{'request.course.fn'}) && (%newhash)) {
10944: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10945: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10946: foreach my $url (keys(%newhash)) {
1.711 albertel 10947: next if ($url eq 'last_known'
10948: && $env{'form.no_update_last_known'});
10949: $hash{declutter($url)}=&encode_symb($mapname,
10950: $newhash{$url}->[1],
10951: $newhash{$url}->[0]);
1.191 harris41 10952: }
1.31 www 10953: if (untie(%hash)) {
10954: return 'ok';
10955: }
10956: }
10957: }
10958: return 'error';
1.212 www 10959: }
10960:
10961: # --------------------------------------------------------------- Verify a symb
10962:
10963: sub symbverify {
1.1190 raeburn 10964: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10965: my $thisfn=$thisurl;
1.439 www 10966: $thisfn=&declutter($thisfn);
1.215 www 10967: # direct jump to resource in page or to a sequence - will construct own symbs
10968: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10969: # check URL part
1.409 www 10970: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10971:
1.431 www 10972: unless ($url eq $thisfn) { return 0; }
1.213 www 10973:
1.216 www 10974: $symb=&symbclean($symb);
1.510 www 10975: $thisurl=&deversion($thisurl);
1.439 www 10976: $thisfn=&deversion($thisfn);
1.213 www 10977:
10978: my %bighash;
10979: my $okay=0;
1.431 www 10980:
1.620 albertel 10981: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10982: &GDBM_READER(),0640)) {
1.1204 raeburn 10983: my $noclutter;
1.1032 raeburn 10984: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10985: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10986: if ($map =~ m{^uploaded/.+\.page$}) {
10987: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10988: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10989: $noclutter = 1;
10990: }
10991: }
10992: my $ids;
10993: if ($noclutter) {
10994: $ids=$bighash{'ids_'.$thisurl};
10995: } else {
10996: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10997: }
1.1102 raeburn 10998: unless ($ids) {
10999: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11000: $ids=$bighash{$idkey};
1.216 www 11001: }
11002: if ($ids) {
11003: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11004: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11005: $symb =~ s/\?.+$//;
1.1202 raeburn 11006: }
1.800 albertel 11007: foreach my $id (split(/\,/,$ids)) {
11008: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11009: if (
11010: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11011: eq $symb) {
11012: if (ref($encstate)) {
11013: $$encstate = $bighash{'encrypted_'.$id};
11014: }
1.620 albertel 11015: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11016: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11017: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11018: $okay=1;
1.1202 raeburn 11019: last;
1.582 albertel 11020: }
11021: }
1.216 www 11022: }
11023: }
1.213 www 11024: untie(%bighash);
11025: }
11026: return $okay;
1.31 www 11027: }
11028:
1.210 www 11029: # --------------------------------------------------------------- Clean-up symb
11030:
11031: sub symbclean {
11032: my $symb=shift;
1.568 albertel 11033: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11034: # remove version from map
11035: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11036:
1.210 www 11037: # remove version from URL
11038: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11039:
1.507 www 11040: # remove wrapper
11041:
1.510 www 11042: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11043: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11044: return $symb;
1.409 www 11045: }
11046:
11047: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11048:
11049: sub encode_symb {
11050: my ($map,$resid,$url)=@_;
11051: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11052: }
1.409 www 11053:
11054: sub decode_symb {
1.568 albertel 11055: my $symb=shift;
11056: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11057: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11058: return (&fixversion($map),$resid,&fixversion($url));
11059: }
11060:
11061: sub fixversion {
11062: my $fn=shift;
1.609 banghart 11063: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11064: my %bighash;
11065: my $uri=&clutter($fn);
1.620 albertel 11066: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11067: # is this cached?
1.599 albertel 11068: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11069: if (defined($cached)) { return $result; }
11070: # unfortunately not cached, or expired
1.620 albertel 11071: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11072: &GDBM_READER(),0640)) {
11073: if ($bighash{'version_'.$uri}) {
11074: my $version=$bighash{'version_'.$uri};
1.444 www 11075: unless (($version eq 'mostrecent') ||
11076: ($version==&getversion($uri))) {
1.440 www 11077: $uri=~s/\.(\w+)$/\.$version\.$1/;
11078: }
11079: }
11080: untie %bighash;
1.413 www 11081: }
1.599 albertel 11082: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11083: }
11084:
11085: sub deversion {
11086: my $url=shift;
11087: $url=~s/\.\d+\.(\w+)$/\.$1/;
11088: return $url;
1.210 www 11089: }
11090:
1.31 www 11091: # ------------------------------------------------------ Return symb list entry
11092:
11093: sub symbread {
1.249 www 11094: my ($thisfn,$donotrecurse)=@_;
1.1265 raeburn 11095: my $cache_str='request.symbread.cached.'.$thisfn;
11096: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 11097: # no filename provided? try from environment
1.1265 raeburn 11098: unless ($thisfn) {
1.620 albertel 11099: if ($env{'request.symb'}) {
11100: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11101: }
1.620 albertel 11102: $thisfn=$env{'request.filename'};
1.44 www 11103: }
1.569 albertel 11104: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11105: # is that filename actually a symb? Verify, clean, and return
11106: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11107: if (&symbverify($thisfn,$1)) {
1.620 albertel 11108: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11109: }
1.242 www 11110: }
1.44 www 11111: $thisfn=declutter($thisfn);
1.31 www 11112: my %hash;
1.37 www 11113: my %bighash;
11114: my $syval='';
1.620 albertel 11115: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11116: my $targetfn = $thisfn;
1.609 banghart 11117: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11118: $targetfn = 'adm/wrapper/'.$thisfn;
11119: }
1.687 albertel 11120: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11121: $targetfn=$1;
11122: }
1.620 albertel 11123: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11124: &GDBM_READER(),0640)) {
1.481 raeburn 11125: $syval=$hash{$targetfn};
1.37 www 11126: untie(%hash);
11127: }
11128: # ---------------------------------------------------------- There was an entry
11129: if ($syval) {
1.601 albertel 11130: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11131: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11132: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11133: #return $env{$cache_str}='';
1.601 albertel 11134: #}
11135: #$syval.=$1;
11136: #}
1.37 www 11137: } else {
11138: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11139: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11140: &GDBM_READER(),0640)) {
1.37 www 11141: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11142: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11143: unless ($ids) {
11144: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11145: }
11146: unless ($ids) {
11147: # alias?
11148: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11149: }
1.37 www 11150: if ($ids) {
11151: # ------------------------------------------------------------------- Has ID(s)
11152: my @possibilities=split(/\,/,$ids);
1.39 www 11153: if ($#possibilities==0) {
11154: # ----------------------------------------------- There is only one possibility
1.37 www 11155: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11156: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11157: $resid,$thisfn);
1.249 www 11158: } elsif (!$donotrecurse) {
1.39 www 11159: # ------------------------------------------ There is more than one possibility
11160: my $realpossible=0;
1.800 albertel 11161: foreach my $id (@possibilities) {
11162: my $file=$bighash{'src_'.$id};
1.39 www 11163: if (&allowed('bre',$file)) {
1.800 albertel 11164: my ($mapid,$resid)=split(/\./,$id);
1.39 www 11165: if ($bighash{'map_type_'.$mapid} ne 'page') {
11166: $realpossible++;
1.626 albertel 11167: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11168: $resid,$thisfn);
1.39 www 11169: }
11170: }
1.191 harris41 11171: }
1.39 www 11172: if ($realpossible!=1) { $syval=''; }
1.249 www 11173: } else {
11174: $syval='';
1.37 www 11175: }
11176: }
11177: untie(%bighash)
1.481 raeburn 11178: }
1.31 www 11179: }
1.62 www 11180: if ($syval) {
1.620 albertel 11181: return $env{$cache_str}=$syval;
1.62 www 11182: }
1.31 www 11183: }
1.949 raeburn 11184: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11185: return $env{$cache_str}='';
1.31 www 11186: }
11187:
11188: # ---------------------------------------------------------- Return random seed
11189:
1.32 www 11190: sub numval {
11191: my $txt=shift;
11192: $txt=~tr/A-J/0-9/;
11193: $txt=~tr/a-j/0-9/;
11194: $txt=~tr/K-T/0-9/;
11195: $txt=~tr/k-t/0-9/;
11196: $txt=~tr/U-Z/0-5/;
11197: $txt=~tr/u-z/0-5/;
11198: $txt=~s/\D//g;
1.564 albertel 11199: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11200: return int($txt);
1.368 albertel 11201: }
11202:
1.484 albertel 11203: sub numval2 {
11204: my $txt=shift;
11205: $txt=~tr/A-J/0-9/;
11206: $txt=~tr/a-j/0-9/;
11207: $txt=~tr/K-T/0-9/;
11208: $txt=~tr/k-t/0-9/;
11209: $txt=~tr/U-Z/0-5/;
11210: $txt=~tr/u-z/0-5/;
11211: $txt=~s/\D//g;
11212: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11213: my $total;
11214: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11215: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11216: return int($total);
11217: }
11218:
1.575 albertel 11219: sub numval3 {
11220: use integer;
11221: my $txt=shift;
11222: $txt=~tr/A-J/0-9/;
11223: $txt=~tr/a-j/0-9/;
11224: $txt=~tr/K-T/0-9/;
11225: $txt=~tr/k-t/0-9/;
11226: $txt=~tr/U-Z/0-5/;
11227: $txt=~tr/u-z/0-5/;
11228: $txt=~s/\D//g;
11229: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11230: my $total;
11231: foreach my $val (@txts) { $total+=$val; }
11232: if ($_64bit) { $total=(($total<<32)>>32); }
11233: return $total;
11234: }
11235:
1.675 albertel 11236: sub digest {
11237: my ($data)=@_;
11238: my $digest=&Digest::MD5::md5($data);
11239: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11240: my ($e,$f);
11241: {
11242: use integer;
11243: $e=($a+$b);
11244: $f=($c+$d);
11245: if ($_64bit) {
11246: $e=(($e<<32)>>32);
11247: $f=(($f<<32)>>32);
11248: }
11249: }
11250: if (wantarray) {
11251: return ($e,$f);
11252: } else {
11253: my $g;
11254: {
11255: use integer;
11256: $g=($e+$f);
11257: if ($_64bit) {
11258: $g=(($g<<32)>>32);
11259: }
11260: }
11261: return $g;
11262: }
11263: }
11264:
1.368 albertel 11265: sub latest_rnd_algorithm_id {
1.675 albertel 11266: return '64bit5';
1.366 albertel 11267: }
1.32 www 11268:
1.503 albertel 11269: sub get_rand_alg {
11270: my ($courseid)=@_;
1.790 albertel 11271: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11272: if ($courseid) {
1.620 albertel 11273: return $env{"course.$courseid.rndseed"};
1.503 albertel 11274: }
11275: return &latest_rnd_algorithm_id();
11276: }
11277:
1.562 albertel 11278: sub validCODE {
11279: my ($CODE)=@_;
11280: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11281: return 0;
11282: }
11283:
1.491 albertel 11284: sub getCODE {
1.620 albertel 11285: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11286: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11287: defined($Apache::lonhomework::parsing_a_task) ) &&
11288: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11289: return $Apache::lonhomework::history{'resource.CODE'};
11290: }
11291: return undef;
11292: }
1.1133 foxr 11293: #
11294: # Determines the random seed for a specific context:
11295: #
11296: # parameters:
11297: # symb - in course context the symb for the seed.
11298: # course_id - The course id of the form domain_coursenum.
11299: # domain - Domain for the user.
11300: # course - Course for the user.
11301: # cenv - environment of the course.
11302: #
11303: # NOTE:
11304: # All parameters are picked out of the environment if missing
11305: # or not defined.
11306: # If a symb cannot be determined the current time is used instead.
11307: #
11308: # For a given well defined symb, courside, domain, username,
11309: # and course environment, the seed is reproducible.
11310: #
1.31 www 11311: sub rndseed {
1.1133 foxr 11312: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11313: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11314: if (!defined($symb)) {
1.366 albertel 11315: unless ($symb=$wsymb) { return time; }
11316: }
1.1146 foxr 11317: if (!defined $courseid) {
11318: $courseid=$wcourseid;
11319: }
11320: if (!defined $domain) { $domain=$wdomain; }
11321: if (!defined $username) { $username=$wusername }
1.1133 foxr 11322:
11323: my $which;
11324: if (defined($cenv->{'rndseed'})) {
11325: $which = $cenv->{'rndseed'};
11326: } else {
11327: $which =&get_rand_alg($courseid);
11328: }
1.491 albertel 11329: if (defined(&getCODE())) {
1.1133 foxr 11330:
1.675 albertel 11331: if ($which eq '64bit5') {
11332: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11333: } elsif ($which eq '64bit4') {
1.575 albertel 11334: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11335: } else {
11336: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11337: }
1.675 albertel 11338: } elsif ($which eq '64bit5') {
11339: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11340: } elsif ($which eq '64bit4') {
11341: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11342: } elsif ($which eq '64bit3') {
11343: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11344: } elsif ($which eq '64bit2') {
11345: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11346: } elsif ($which eq '64bit') {
11347: return &rndseed_64bit($symb,$courseid,$domain,$username);
11348: }
11349: return &rndseed_32bit($symb,$courseid,$domain,$username);
11350: }
11351:
11352: sub rndseed_32bit {
11353: my ($symb,$courseid,$domain,$username)=@_;
11354: {
11355: use integer;
11356: my $symbchck=unpack("%32C*",$symb) << 27;
11357: my $symbseed=numval($symb) << 22;
11358: my $namechck=unpack("%32C*",$username) << 17;
11359: my $nameseed=numval($username) << 12;
11360: my $domainseed=unpack("%32C*",$domain) << 7;
11361: my $courseseed=unpack("%32C*",$courseid);
11362: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11363: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11364: #&logthis("rndseed :$num:$symb");
1.564 albertel 11365: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11366: return $num;
11367: }
11368: }
11369:
11370: sub rndseed_64bit {
11371: my ($symb,$courseid,$domain,$username)=@_;
11372: {
11373: use integer;
11374: my $symbchck=unpack("%32S*",$symb) << 21;
11375: my $symbseed=numval($symb) << 10;
11376: my $namechck=unpack("%32S*",$username);
11377:
11378: my $nameseed=numval($username) << 21;
11379: my $domainseed=unpack("%32S*",$domain) << 10;
11380: my $courseseed=unpack("%32S*",$courseid);
11381:
11382: my $num1=$symbchck+$symbseed+$namechck;
11383: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11384: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11385: #&logthis("rndseed :$num:$symb");
1.564 albertel 11386: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11387: return "$num1,$num2";
1.155 albertel 11388: }
1.366 albertel 11389: }
11390:
1.443 albertel 11391: sub rndseed_64bit2 {
11392: my ($symb,$courseid,$domain,$username)=@_;
11393: {
11394: use integer;
11395: # strings need to be an even # of cahracters long, it it is odd the
11396: # last characters gets thrown away
11397: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11398: my $symbseed=numval($symb) << 10;
11399: my $namechck=unpack("%32S*",$username.' ');
11400:
11401: my $nameseed=numval($username) << 21;
1.501 albertel 11402: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11403: my $courseseed=unpack("%32S*",$courseid.' ');
11404:
11405: my $num1=$symbchck+$symbseed+$namechck;
11406: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11407: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11408: #&logthis("rndseed :$num:$symb");
1.803 albertel 11409: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11410: return "$num1,$num2";
11411: }
11412: }
11413:
11414: sub rndseed_64bit3 {
11415: my ($symb,$courseid,$domain,$username)=@_;
11416: {
11417: use integer;
11418: # strings need to be an even # of cahracters long, it it is odd the
11419: # last characters gets thrown away
11420: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11421: my $symbseed=numval2($symb) << 10;
11422: my $namechck=unpack("%32S*",$username.' ');
11423:
11424: my $nameseed=numval2($username) << 21;
1.443 albertel 11425: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11426: my $courseseed=unpack("%32S*",$courseid.' ');
11427:
11428: my $num1=$symbchck+$symbseed+$namechck;
11429: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11430: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11431: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11432: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11433:
1.503 albertel 11434: return "$num1:$num2";
1.443 albertel 11435: }
11436: }
11437:
1.575 albertel 11438: sub rndseed_64bit4 {
11439: my ($symb,$courseid,$domain,$username)=@_;
11440: {
11441: use integer;
11442: # strings need to be an even # of cahracters long, it it is odd the
11443: # last characters gets thrown away
11444: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11445: my $symbseed=numval3($symb) << 10;
11446: my $namechck=unpack("%32S*",$username.' ');
11447:
11448: my $nameseed=numval3($username) << 21;
11449: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11450: my $courseseed=unpack("%32S*",$courseid.' ');
11451:
11452: my $num1=$symbchck+$symbseed+$namechck;
11453: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11454: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11455: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11456: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11457:
1.575 albertel 11458: return "$num1:$num2";
11459: }
11460: }
11461:
1.675 albertel 11462: sub rndseed_64bit5 {
11463: my ($symb,$courseid,$domain,$username)=@_;
11464: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11465: return "$num1:$num2";
11466: }
11467:
1.366 albertel 11468: sub rndseed_CODE_64bit {
11469: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11470: {
1.366 albertel 11471: use integer;
1.443 albertel 11472: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11473: my $symbseed=numval2($symb);
1.491 albertel 11474: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11475: my $CODEseed=numval(&getCODE());
1.443 albertel 11476: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11477: my $num1=$symbseed+$CODEchck;
11478: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11479: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11480: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11481: if ($_64bit) { $num1=(($num1<<32)>>32); }
11482: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11483: return "$num1:$num2";
1.366 albertel 11484: }
11485: }
11486:
1.575 albertel 11487: sub rndseed_CODE_64bit4 {
11488: my ($symb,$courseid,$domain,$username)=@_;
11489: {
11490: use integer;
11491: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11492: my $symbseed=numval3($symb);
11493: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11494: my $CODEseed=numval3(&getCODE());
11495: my $courseseed=unpack("%32S*",$courseid.' ');
11496: my $num1=$symbseed+$CODEchck;
11497: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11498: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11499: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11500: if ($_64bit) { $num1=(($num1<<32)>>32); }
11501: if ($_64bit) { $num2=(($num2<<32)>>32); }
11502: return "$num1:$num2";
11503: }
11504: }
11505:
1.675 albertel 11506: sub rndseed_CODE_64bit5 {
11507: my ($symb,$courseid,$domain,$username)=@_;
11508: my $code = &getCODE();
11509: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11510: return "$num1:$num2";
11511: }
11512:
1.366 albertel 11513: sub setup_random_from_rndseed {
11514: my ($rndseed)=@_;
1.503 albertel 11515: if ($rndseed =~/([,:])/) {
1.1262 raeburn 11516: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11517: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11518: &Math::Random::random_set_seed_from_phrase($rndseed);
11519: } else {
11520: &Math::Random::random_set_seed($num1,$num2);
11521: }
1.366 albertel 11522: } else {
11523: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11524: }
1.36 albertel 11525: }
11526:
1.474 albertel 11527: sub latest_receipt_algorithm_id {
1.835 albertel 11528: return 'receipt3';
1.474 albertel 11529: }
11530:
1.480 www 11531: sub recunique {
11532: my $fucourseid=shift;
11533: my $unique;
1.835 albertel 11534: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11535: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11536: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11537: } else {
11538: $unique=$perlvar{'lonReceipt'};
11539: }
11540: return unpack("%32C*",$unique);
11541: }
11542:
11543: sub recprefix {
11544: my $fucourseid=shift;
11545: my $prefix;
1.835 albertel 11546: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11547: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11548: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11549: } else {
11550: $prefix=$perlvar{'lonHostID'};
11551: }
11552: return unpack("%32C*",$prefix);
11553: }
11554:
1.76 www 11555: sub ireceipt {
1.474 albertel 11556: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11557:
11558: my $return =&recprefix($fucourseid).'-';
11559:
11560: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11561: $env{'request.state'} eq 'construct') {
11562: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11563: return $return;
11564: }
11565:
1.76 www 11566: my $cuname=unpack("%32C*",$funame);
11567: my $cudom=unpack("%32C*",$fudom);
11568: my $cucourseid=unpack("%32C*",$fucourseid);
11569: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11570: my $cunique=&recunique($fucourseid);
1.474 albertel 11571: my $cpart=unpack("%32S*",$part);
1.835 albertel 11572: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11573:
1.790 albertel 11574: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11575:
11576: $return.= ($cunique%$cuname+
11577: $cunique%$cudom+
11578: $cusymb%$cuname+
11579: $cusymb%$cudom+
11580: $cucourseid%$cuname+
11581: $cucourseid%$cudom+
11582: $cpart%$cuname+
11583: $cpart%$cudom);
11584: } else {
11585: $return.= ($cunique%$cuname+
11586: $cunique%$cudom+
11587: $cusymb%$cuname+
11588: $cusymb%$cudom+
11589: $cucourseid%$cuname+
11590: $cucourseid%$cudom);
11591: }
11592: return $return;
1.76 www 11593: }
11594:
11595: sub receipt {
1.474 albertel 11596: my ($part)=@_;
1.790 albertel 11597: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11598: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11599: }
1.260 ng 11600:
1.790 albertel 11601: sub whichuser {
11602: my ($passedsymb)=@_;
11603: my ($symb,$courseid,$domain,$name,$publicuser);
11604: if (defined($env{'form.grade_symb'})) {
11605: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11606: my $allowed=&allowed('vgr',$tmp_courseid);
11607: if (!$allowed &&
11608: exists($env{'request.course.sec'}) &&
11609: $env{'request.course.sec'} !~ /^\s*$/) {
11610: $allowed=&allowed('vgr',$tmp_courseid.
11611: '/'.$env{'request.course.sec'});
11612: }
11613: if ($allowed) {
11614: ($symb)=&get_env_multiple('form.grade_symb');
11615: $courseid=$tmp_courseid;
11616: ($domain)=&get_env_multiple('form.grade_domain');
11617: ($name)=&get_env_multiple('form.grade_username');
11618: return ($symb,$courseid,$domain,$name,$publicuser);
11619: }
11620: }
11621: if (!$passedsymb) {
11622: $symb=&symbread();
11623: } else {
11624: $symb=$passedsymb;
11625: }
11626: $courseid=$env{'request.course.id'};
11627: $domain=$env{'user.domain'};
11628: $name=$env{'user.name'};
11629: if ($name eq 'public' && $domain eq 'public') {
11630: if (!defined($env{'form.username'})) {
11631: $env{'form.username'}.=time.rand(10000000);
11632: }
11633: $name.=$env{'form.username'};
11634: }
11635: return ($symb,$courseid,$domain,$name,$publicuser);
11636:
11637: }
11638:
1.36 albertel 11639: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11640: # returns either the contents of the file or
11641: # -1 if the file doesn't exist
1.481 raeburn 11642: #
11643: # if the target is a file that was uploaded via DOCS,
11644: # a check will be made to see if a current copy exists on the local server,
11645: # if it does this will be served, otherwise a copy will be retrieved from
11646: # the home server for the course and stored in /home/httpd/html/userfiles on
11647: # the local server.
1.472 albertel 11648:
1.36 albertel 11649: sub getfile {
1.538 albertel 11650: my ($file) = @_;
1.609 banghart 11651: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11652: &repcopy($file);
11653: return &readfile($file);
11654: }
11655:
11656: sub repcopy_userfile {
11657: my ($file)=@_;
1.1142 raeburn 11658: my $londocroot = $perlvar{'lonDocRoot'};
11659: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11660: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11661: my ($cdom,$cnum,$filename) =
1.811 albertel 11662: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11663: my $uri="/uploaded/$cdom/$cnum/$filename";
11664: if (-e "$file") {
1.828 www 11665: # we already have a local copy, check it out
1.538 albertel 11666: my @fileinfo = stat($file);
1.828 www 11667: my $rtncode;
11668: my $info;
1.538 albertel 11669: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11670: if ($lwpresp ne 'ok') {
1.828 www 11671: # there is no such file anymore, even though we had a local copy
1.482 albertel 11672: if ($rtncode eq '404') {
1.538 albertel 11673: unlink($file);
1.482 albertel 11674: }
11675: return -1;
11676: }
11677: if ($info < $fileinfo[9]) {
1.828 www 11678: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11679: return 'ok';
1.828 www 11680: } else {
11681: # the file is outdated, get rid of it
11682: unlink($file);
1.482 albertel 11683: }
1.828 www 11684: }
11685: # one way or the other, at this point, we don't have the file
11686: # construct the correct path for the file
11687: my @parts = ($cdom,$cnum);
11688: if ($filename =~ m|^(.+)/[^/]+$|) {
11689: push @parts, split(/\//,$1);
11690: }
11691: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11692: foreach my $part (@parts) {
11693: $path .= '/'.$part;
11694: if (!-e $path) {
11695: mkdir($path,0770);
1.482 albertel 11696: }
11697: }
1.828 www 11698: # now the path exists for sure
11699: # get a user agent
11700: my $ua=new LWP::UserAgent;
11701: my $transferfile=$file.'.in.transfer';
11702: # FIXME: this should flock
11703: if (-e $transferfile) { return 'ok'; }
11704: my $request;
11705: $uri=~s/^\///;
1.980 raeburn 11706: my $homeserver = &homeserver($cnum,$cdom);
11707: my $protocol = $protocol{$homeserver};
11708: $protocol = 'http' if ($protocol ne 'https');
11709: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11710: my $response=$ua->request($request,$transferfile);
11711: # did it work?
11712: if ($response->is_error()) {
11713: unlink($transferfile);
11714: &logthis("Userfile repcopy failed for $uri");
11715: return -1;
11716: }
11717: # worked, rename the transfer file
11718: rename($transferfile,$file);
1.607 raeburn 11719: return 'ok';
1.481 raeburn 11720: }
11721:
1.517 albertel 11722: sub tokenwrapper {
11723: my $uri=shift;
1.980 raeburn 11724: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11725: $uri=~s|^/||;
1.620 albertel 11726: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11727: my $token=$1;
1.552 albertel 11728: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11729: if ($udom && $uname && $file) {
11730: $file=~s|(\?\.*)*$||;
1.949 raeburn 11731: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11732: my $homeserver = &homeserver($uname,$udom);
11733: my $protocol = $protocol{$homeserver};
11734: $protocol = 'http' if ($protocol ne 'https');
11735: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11736: (($uri=~/\?/)?'&':'?').'token='.$token.
11737: '&tokenissued='.$perlvar{'lonHostID'};
11738: } else {
11739: return '/adm/notfound.html';
11740: }
11741: }
11742:
1.828 www 11743: # call with reqtype HEAD: get last modification time
11744: # call with reqtype GET: get the file contents
11745: # Do not call this with reqtype GET for large files! It loads everything into memory
11746: #
1.481 raeburn 11747: sub getuploaded {
11748: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11749: $uri=~s/^\///;
1.980 raeburn 11750: my $homeserver = &homeserver($cnum,$cdom);
11751: my $protocol = $protocol{$homeserver};
11752: $protocol = 'http' if ($protocol ne 'https');
11753: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11754: my $ua=new LWP::UserAgent;
11755: my $request=new HTTP::Request($reqtype,$uri);
11756: my $response=$ua->request($request);
11757: $$rtncode = $response->code;
1.482 albertel 11758: if (! $response->is_success()) {
11759: return 'failed';
11760: }
11761: if ($reqtype eq 'HEAD') {
1.486 www 11762: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11763: } elsif ($reqtype eq 'GET') {
11764: $$info = $response->content;
1.472 albertel 11765: }
1.482 albertel 11766: return 'ok';
1.36 albertel 11767: }
11768:
1.481 raeburn 11769: sub readfile {
11770: my $file = shift;
11771: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11772: my $fh;
11773: open($fh,"<$file");
11774: my $a='';
1.800 albertel 11775: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11776: return $a;
11777: }
11778:
1.36 albertel 11779: sub filelocation {
1.590 banghart 11780: my ($dir,$file) = @_;
11781: my $location;
11782: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11783:
11784: if ($file =~ m-^/adm/-) {
11785: $file=~s-^/adm/wrapper/-/-;
11786: $file=~s-^/adm/coursedocs/showdoc/-/-;
11787: }
1.882 albertel 11788:
1.1139 www 11789: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11790: $location = $file;
1.609 banghart 11791: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11792: my ($udom,$uname,$filename)=
1.811 albertel 11793: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11794: my $home=&homeserver($uname,$udom);
11795: my $is_me=0;
11796: my @ids=¤t_machine_ids();
11797: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11798: if ($is_me) {
1.1117 foxr 11799: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11800: } else {
11801: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11802: $udom.'/'.$uname.'/'.$filename;
11803: }
1.882 albertel 11804: } elsif ($file =~ m-^/adm/-) {
11805: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11806: } else {
11807: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11808: $file=~s:^/(res|priv)/:/:;
11809: my $space=$1;
1.590 banghart 11810: if ( !( $file =~ m:^/:) ) {
11811: $location = $dir. '/'.$file;
11812: } else {
1.1142 raeburn 11813: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11814: }
1.59 albertel 11815: }
1.590 banghart 11816: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11817: while ($location=~m{/\.\./}) {
11818: if ($location =~ m{/[^/]+/\.\./}) {
11819: $location=~ s{/[^/]+/\.\./}{/}g;
11820: } else {
11821: $location=~ s{/\.\./}{/}g;
11822: }
11823: } #remove dir/..
1.590 banghart 11824: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11825: return $location;
1.46 www 11826: }
1.36 albertel 11827:
1.46 www 11828: sub hreflocation {
11829: my ($dir,$file)=@_;
1.980 raeburn 11830: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11831: $file=filelocation($dir,$file);
1.700 albertel 11832: } elsif ($file=~m-^/adm/-) {
11833: $file=~s-^/adm/wrapper/-/-;
11834: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11835: }
11836: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11837: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11838: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11839: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11840: {/uploaded/$1/$2/}x;
1.46 www 11841: }
1.913 albertel 11842: if ($file=~ m{^/userfiles/}) {
11843: $file =~ s{^/userfiles/}{/uploaded/};
11844: }
1.462 albertel 11845: return $file;
1.465 albertel 11846: }
11847:
1.1139 www 11848:
11849:
11850:
11851:
1.465 albertel 11852: sub current_machine_domains {
1.853 albertel 11853: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11854: }
11855:
11856: sub machine_domains {
11857: my ($hostname) = @_;
1.465 albertel 11858: my @domains;
1.838 albertel 11859: my %hostname = &all_hostnames();
1.465 albertel 11860: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11861: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11862: if ($hostname eq $name) {
1.844 albertel 11863: push(@domains,&host_domain($id));
1.465 albertel 11864: }
11865: }
11866: return @domains;
11867: }
11868:
11869: sub current_machine_ids {
1.853 albertel 11870: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11871: }
11872:
11873: sub machine_ids {
11874: my ($hostname) = @_;
11875: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11876: my @ids;
1.888 albertel 11877: my %name_to_host = &all_names();
1.889 albertel 11878: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11879: return @{ $name_to_host{$hostname} };
11880: }
11881: return;
1.31 www 11882: }
11883:
1.824 raeburn 11884: sub additional_machine_domains {
11885: my @domains;
11886: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11887: while( my $line = <$fh>) {
11888: $line =~ s/\s//g;
11889: push(@domains,$line);
11890: }
11891: return @domains;
11892: }
11893:
11894: sub default_login_domain {
11895: my $domain = $perlvar{'lonDefDomain'};
11896: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11897: foreach my $posdom (¤t_machine_domains(),
11898: &additional_machine_domains()) {
11899: if (lc($posdom) eq lc($testdomain)) {
11900: $domain=$posdom;
11901: last;
11902: }
11903: }
11904: return $domain;
11905: }
11906:
1.31 www 11907: # ------------------------------------------------------------- Declutters URLs
11908:
11909: sub declutter {
11910: my $thisfn=shift;
1.569 albertel 11911: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 11912: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11913: $thisfn=~s{^/home/httpd/html}{};
11914: }
1.31 www 11915: $thisfn=~s/^\///;
1.697 albertel 11916: $thisfn=~s|^adm/wrapper/||;
11917: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11918: $thisfn=~s/^res\///;
1.1172 bisitz 11919: $thisfn=~s/^priv\///;
1.1032 raeburn 11920: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11921: $thisfn=~s/\?.+$//;
11922: }
1.268 www 11923: return $thisfn;
11924: }
11925:
11926: # ------------------------------------------------------------- Clutter up URLs
11927:
11928: sub clutter {
11929: my $thisfn='/'.&declutter(shift);
1.887 albertel 11930: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11931: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11932: $thisfn='/res'.$thisfn;
11933: }
1.1031 raeburn 11934: if ($thisfn !~m|^/adm|) {
11935: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11936: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11937: } else {
11938: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11939: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11940: if ($embstyle eq 'ssi'
11941: || ($embstyle eq 'hdn')
11942: || ($embstyle eq 'rat')
11943: || ($embstyle eq 'prv')
11944: || ($embstyle eq 'ign')) {
11945: #do nothing with these
11946: } elsif (($embstyle eq 'img')
1.695 albertel 11947: || ($embstyle eq 'emb')
11948: || ($embstyle eq 'wrp')) {
11949: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11950: } elsif ($embstyle eq 'unk'
11951: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11952: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11953: } else {
1.718 www 11954: # &logthis("Got a blank emb style");
1.695 albertel 11955: }
1.694 albertel 11956: }
11957: }
1.31 www 11958: return $thisfn;
1.12 www 11959: }
11960:
1.787 albertel 11961: sub clutter_with_no_wrapper {
11962: my $uri = &clutter(shift);
11963: if ($uri =~ m-^/adm/-) {
11964: $uri =~ s-^/adm/wrapper/-/-;
11965: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11966: }
11967: return $uri;
11968: }
11969:
1.557 albertel 11970: sub freeze_escape {
11971: my ($value)=@_;
11972: if (ref($value)) {
11973: $value=&nfreeze($value);
11974: return '__FROZEN__'.&escape($value);
11975: }
11976: return &escape($value);
11977: }
11978:
1.11 www 11979:
1.557 albertel 11980: sub thaw_unescape {
11981: my ($value)=@_;
11982: if ($value =~ /^__FROZEN__/) {
11983: substr($value,0,10,undef);
11984: $value=&unescape($value);
11985: return &thaw($value);
11986: }
11987: return &unescape($value);
11988: }
11989:
1.436 albertel 11990: sub correct_line_ends {
11991: my ($result)=@_;
11992: $$result =~s/\r\n/\n/mg;
11993: $$result =~s/\r/\n/mg;
1.415 albertel 11994: }
1.1 albertel 11995: # ================================================================ Main Program
11996:
1.184 www 11997: sub goodbye {
1.204 albertel 11998: &logthis("Starting Shut down");
1.443 albertel 11999: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12000: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12001: #converted
1.599 albertel 12002: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12003: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12004: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12005: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12006: #1.1 only
1.870 albertel 12007: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12008: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12009: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12010: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12011: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12012: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12013: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12014: &flushcourselogs();
12015: &logthis("Shutting down");
12016: }
12017:
1.852 albertel 12018: sub get_dns {
1.1210 raeburn 12019: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12020: if (!$ignore_cache) {
12021: my ($content,$cached)=
12022: &Apache::lonnet::is_cached_new('dns',$url);
12023: if ($cached) {
1.1210 raeburn 12024: &$func($content,$hashref);
1.869 albertel 12025: return;
12026: }
12027: }
12028:
12029: my %alldns;
1.852 albertel 12030: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12031: foreach my $dns (<$config>) {
12032: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12033: my $line = $1;
12034: my ($host,$protocol) = split(/:/,$line);
12035: if ($protocol ne 'https') {
12036: $protocol = 'http';
12037: }
12038: $alldns{$host} = $protocol;
1.869 albertel 12039: }
12040: while (%alldns) {
1.1263 raeburn 12041: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12042: my $ua=new LWP::UserAgent;
1.1134 raeburn 12043: $ua->timeout(30);
1.979 raeburn 12044: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12045: my $response=$ua->request($request);
1.979 raeburn 12046: delete($alldns{$dns});
1.852 albertel 12047: next if ($response->is_error());
12048: my @content = split("\n",$response->content);
1.1210 raeburn 12049: unless ($nocache) {
1.1219 raeburn 12050: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12051: }
12052: &$func(\@content,$hashref);
1.869 albertel 12053: return;
1.852 albertel 12054: }
12055: close($config);
1.871 albertel 12056: my $which = (split('/',$url))[3];
12057: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12058: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12059: my @content = <$config>;
1.1210 raeburn 12060: &$func(\@content,$hashref);
12061: return;
12062: }
12063:
12064: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12065: sub parse_dns_checksums_tab {
1.1210 raeburn 12066: my ($lines,$hashref) = @_;
1.1264 raeburn 12067: my $lonhost = $perlvar{'lonHostID'};
12068: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12069: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12070: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12071: my $webconfdir = '/etc/httpd/conf';
12072: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12073: $webconfdir = '/etc/apache2';
12074: } elsif ($distro =~ /^sles(\d+)$/) {
12075: if ($1 >= 10) {
12076: $webconfdir = '/etc/apache2';
12077: }
12078: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12079: if ($1 >= 10.0) {
12080: $webconfdir = '/etc/apache2';
12081: }
12082: }
1.1210 raeburn 12083: my ($release,$timestamp) = split(/\-/,$loncaparev);
12084: my (%chksum,%revnum);
12085: if (ref($lines) eq 'ARRAY') {
12086: chomp(@{$lines});
1.1238 raeburn 12087: my $version = shift(@{$lines});
12088: if ($version eq $release) {
1.1210 raeburn 12089: foreach my $line (@{$lines}) {
1.1238 raeburn 12090: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12091: if ($file =~ m{^/etc/httpd/conf}) {
12092: if ($webconfdir eq '/etc/apache2') {
12093: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12094: }
12095: }
1.1238 raeburn 12096: $chksum{$file} = $shasum;
12097: $revnum{$file} = $version;
1.1210 raeburn 12098: }
12099: if (ref($hashref) eq 'HASH') {
12100: %{$hashref} = (
12101: sums => \%chksum,
12102: versions => \%revnum,
12103: );
12104: }
12105: }
12106: }
1.869 albertel 12107: return;
1.852 albertel 12108: }
1.1210 raeburn 12109:
12110: sub fetch_dns_checksums {
1.1238 raeburn 12111: my %checksums;
12112: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12113: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12114: my ($release,$timestamp) = split(/\-/,$loncaparev);
12115: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12116: \%checksums);
1.1210 raeburn 12117: return \%checksums;
12118: }
12119:
1.327 albertel 12120: # ------------------------------------------------------------ Read domain file
12121: {
1.852 albertel 12122: my $loaded;
1.846 albertel 12123: my %domain;
12124:
1.852 albertel 12125: sub parse_domain_tab {
12126: my ($lines) = @_;
12127: foreach my $line (@$lines) {
12128: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12129:
1.846 albertel 12130: chomp($line);
1.852 albertel 12131: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12132: my %this_domain;
12133: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12134: 'lang_def', 'city', 'longi', 'lati',
12135: 'primary') {
12136: $this_domain{$field} = shift(@elements);
12137: }
12138: $domain{$name} = \%this_domain;
1.852 albertel 12139: }
12140: }
1.864 albertel 12141:
12142: sub reset_domain_info {
12143: undef($loaded);
12144: undef(%domain);
12145: }
12146:
1.852 albertel 12147: sub load_domain_tab {
1.869 albertel 12148: my ($ignore_cache) = @_;
12149: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 12150: my $fh;
12151: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12152: my @lines = <$fh>;
12153: &parse_domain_tab(\@lines);
1.448 albertel 12154: }
1.852 albertel 12155: close($fh);
12156: $loaded = 1;
1.327 albertel 12157: }
1.846 albertel 12158:
12159: sub domain {
1.852 albertel 12160: &load_domain_tab() if (!$loaded);
12161:
1.846 albertel 12162: my ($name,$what) = @_;
12163: return if ( !exists($domain{$name}) );
12164:
12165: if (!$what) {
12166: return $domain{$name}{'description'};
12167: }
12168: return $domain{$name}{$what};
12169: }
1.974 raeburn 12170:
12171: sub domain_info {
12172: &load_domain_tab() if (!$loaded);
12173: return %domain;
12174: }
12175:
1.327 albertel 12176: }
12177:
12178:
1.1 albertel 12179: # ------------------------------------------------------------- Read hosts file
12180: {
1.838 albertel 12181: my %hostname;
1.844 albertel 12182: my %hostdom;
1.845 albertel 12183: my %libserv;
1.852 albertel 12184: my $loaded;
1.888 albertel 12185: my %name_to_host;
1.1074 raeburn 12186: my %internetdom;
1.1107 raeburn 12187: my %LC_dns_serv;
1.852 albertel 12188:
12189: sub parse_hosts_tab {
12190: my ($file) = @_;
12191: foreach my $configline (@$file) {
12192: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12193: chomp($configline);
12194: if ($configline =~ /^\^/) {
12195: if ($configline =~ /^\^([\w.\-]+)/) {
12196: $LC_dns_serv{$1} = 1;
12197: }
12198: next;
12199: }
1.1074 raeburn 12200: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12201: $name=~s/\s//g;
12202: if ($id && $domain && $role && $name) {
12203: $hostname{$id}=$name;
1.888 albertel 12204: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12205: $hostdom{$id}=$domain;
12206: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12207: if (defined($protocol)) {
12208: if ($protocol eq 'https') {
12209: $protocol{$id} = $protocol;
12210: } else {
12211: $protocol{$id} = 'http';
12212: }
1.968 raeburn 12213: } else {
1.969 raeburn 12214: $protocol{$id} = 'http';
1.968 raeburn 12215: }
1.1074 raeburn 12216: if (defined($intdom)) {
12217: $internetdom{$id} = $intdom;
12218: }
1.852 albertel 12219: }
12220: }
12221: }
1.864 albertel 12222:
12223: sub reset_hosts_info {
1.897 albertel 12224: &purge_remembered();
1.864 albertel 12225: &reset_domain_info();
12226: &reset_hosts_ip_info();
1.892 albertel 12227: undef(%name_to_host);
1.864 albertel 12228: undef(%hostname);
12229: undef(%hostdom);
12230: undef(%libserv);
12231: undef($loaded);
12232: }
1.1 albertel 12233:
1.852 albertel 12234: sub load_hosts_tab {
1.869 albertel 12235: my ($ignore_cache) = @_;
12236: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12237: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12238: my @config = <$config>;
12239: &parse_hosts_tab(\@config);
12240: close($config);
12241: $loaded=1;
1.1 albertel 12242: }
1.852 albertel 12243:
1.838 albertel 12244: sub hostname {
1.852 albertel 12245: &load_hosts_tab() if (!$loaded);
12246:
1.838 albertel 12247: my ($lonid) = @_;
12248: return $hostname{$lonid};
12249: }
1.845 albertel 12250:
1.838 albertel 12251: sub all_hostnames {
1.852 albertel 12252: &load_hosts_tab() if (!$loaded);
12253:
1.838 albertel 12254: return %hostname;
12255: }
1.845 albertel 12256:
1.888 albertel 12257: sub all_names {
12258: &load_hosts_tab() if (!$loaded);
12259:
12260: return %name_to_host;
12261: }
12262:
1.974 raeburn 12263: sub all_host_domain {
12264: &load_hosts_tab() if (!$loaded);
12265: return %hostdom;
12266: }
12267:
1.845 albertel 12268: sub is_library {
1.852 albertel 12269: &load_hosts_tab() if (!$loaded);
12270:
1.845 albertel 12271: return exists($libserv{$_[0]});
12272: }
12273:
12274: sub all_library {
1.852 albertel 12275: &load_hosts_tab() if (!$loaded);
12276:
1.845 albertel 12277: return %libserv;
12278: }
12279:
1.1062 droeschl 12280: sub unique_library {
12281: #2x reverse removes all hostnames that appear more than once
12282: my %unique = reverse &all_library();
12283: return reverse %unique;
12284: }
12285:
1.841 albertel 12286: sub get_servers {
1.852 albertel 12287: &load_hosts_tab() if (!$loaded);
12288:
1.841 albertel 12289: my ($domain,$type) = @_;
12290: my %possible_hosts = ($type eq 'library') ? %libserv
12291: : %hostname;
12292: my %result;
1.842 albertel 12293: if (ref($domain) eq 'ARRAY') {
12294: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12295: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12296: $result{$host} = $hostname;
12297: }
12298: }
12299: } else {
12300: while ( my ($host,$hostname) = each(%possible_hosts)) {
12301: if ($hostdom{$host} eq $domain) {
12302: $result{$host} = $hostname;
12303: }
1.841 albertel 12304: }
12305: }
12306: return %result;
12307: }
1.845 albertel 12308:
1.1062 droeschl 12309: sub get_unique_servers {
12310: my %unique = reverse &get_servers(@_);
12311: return reverse %unique;
12312: }
12313:
1.844 albertel 12314: sub host_domain {
1.852 albertel 12315: &load_hosts_tab() if (!$loaded);
12316:
1.844 albertel 12317: my ($lonid) = @_;
12318: return $hostdom{$lonid};
12319: }
12320:
1.841 albertel 12321: sub all_domains {
1.852 albertel 12322: &load_hosts_tab() if (!$loaded);
12323:
1.841 albertel 12324: my %seen;
12325: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12326: return @uniq;
12327: }
1.1074 raeburn 12328:
12329: sub internet_dom {
12330: &load_hosts_tab() if (!$loaded);
12331:
12332: my ($lonid) = @_;
12333: return $internetdom{$lonid};
12334: }
1.1107 raeburn 12335:
12336: sub is_LC_dns {
12337: &load_hosts_tab() if (!$loaded);
12338:
12339: my ($hostname) = @_;
12340: return exists($LC_dns_serv{$hostname});
12341: }
12342:
1.1 albertel 12343: }
12344:
1.847 albertel 12345: {
12346: my %iphost;
1.856 albertel 12347: my %name_to_ip;
12348: my %lonid_to_ip;
1.869 albertel 12349:
1.847 albertel 12350: sub get_hosts_from_ip {
12351: my ($ip) = @_;
12352: my %iphosts = &get_iphost();
12353: if (ref($iphosts{$ip})) {
12354: return @{$iphosts{$ip}};
12355: }
12356: return;
1.839 albertel 12357: }
1.864 albertel 12358:
12359: sub reset_hosts_ip_info {
12360: undef(%iphost);
12361: undef(%name_to_ip);
12362: undef(%lonid_to_ip);
12363: }
1.856 albertel 12364:
12365: sub get_host_ip {
12366: my ($lonid) = @_;
12367: if (exists($lonid_to_ip{$lonid})) {
12368: return $lonid_to_ip{$lonid};
12369: }
12370: my $name=&hostname($lonid);
12371: my $ip = gethostbyname($name);
12372: return if (!$ip || length($ip) ne 4);
12373: $ip=inet_ntoa($ip);
12374: $name_to_ip{$name} = $ip;
12375: $lonid_to_ip{$lonid} = $ip;
12376: return $ip;
12377: }
1.847 albertel 12378:
12379: sub get_iphost {
1.869 albertel 12380: my ($ignore_cache) = @_;
1.894 albertel 12381:
1.869 albertel 12382: if (!$ignore_cache) {
12383: if (%iphost) {
12384: return %iphost;
12385: }
12386: my ($ip_info,$cached)=
12387: &Apache::lonnet::is_cached_new('iphost','iphost');
12388: if ($cached) {
12389: %iphost = %{$ip_info->[0]};
12390: %name_to_ip = %{$ip_info->[1]};
12391: %lonid_to_ip = %{$ip_info->[2]};
12392: return %iphost;
12393: }
12394: }
1.894 albertel 12395:
12396: # get yesterday's info for fallback
12397: my %old_name_to_ip;
12398: my ($ip_info,$cached)=
12399: &Apache::lonnet::is_cached_new('iphost','iphost');
12400: if ($cached) {
12401: %old_name_to_ip = %{$ip_info->[1]};
12402: }
12403:
1.888 albertel 12404: my %name_to_host = &all_names();
12405: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12406: my $ip;
12407: if (!exists($name_to_ip{$name})) {
12408: $ip = gethostbyname($name);
12409: if (!$ip || length($ip) ne 4) {
1.894 albertel 12410: if (defined($old_name_to_ip{$name})) {
12411: $ip = $old_name_to_ip{$name};
12412: &logthis("Can't find $name defaulting to old $ip");
12413: } else {
12414: &logthis("Name $name no IP found");
12415: next;
12416: }
12417: } else {
12418: $ip=inet_ntoa($ip);
1.847 albertel 12419: }
12420: $name_to_ip{$name} = $ip;
12421: } else {
12422: $ip = $name_to_ip{$name};
1.653 albertel 12423: }
1.888 albertel 12424: foreach my $id (@{ $name_to_host{$name} }) {
12425: $lonid_to_ip{$id} = $ip;
12426: }
12427: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12428: }
1.1219 raeburn 12429: &do_cache_new('iphost','iphost',
12430: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12431: 48*60*60);
1.869 albertel 12432:
1.847 albertel 12433: return %iphost;
1.598 albertel 12434: }
12435:
1.992 raeburn 12436: #
12437: # Given a DNS returns the loncapa host name for that DNS
12438: #
12439: sub host_from_dns {
12440: my ($dns) = @_;
12441: my @hosts;
12442: my $ip;
12443:
1.993 raeburn 12444: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12445: $ip = $name_to_ip{$dns};
12446: }
12447: if (!$ip) {
12448: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12449: if (length($ip) == 4) {
12450: $ip = &IO::Socket::inet_ntoa($ip);
12451: }
12452: }
12453: if ($ip) {
12454: @hosts = get_hosts_from_ip($ip);
12455: return $hosts[0];
12456: }
12457: return undef;
1.986 foxr 12458: }
1.992 raeburn 12459:
1.1074 raeburn 12460: sub get_internet_names {
12461: my ($lonid) = @_;
12462: return if ($lonid eq '');
12463: my ($idnref,$cached)=
12464: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12465: if ($cached) {
12466: return $idnref;
12467: }
12468: my $ip = &get_host_ip($lonid);
12469: my @hosts = &get_hosts_from_ip($ip);
12470: my %iphost = &get_iphost();
12471: my (@idns,%seen);
12472: foreach my $id (@hosts) {
12473: my $dom = &host_domain($id);
12474: my $prim_id = &domain($dom,'primary');
12475: my $prim_ip = &get_host_ip($prim_id);
12476: next if ($seen{$prim_ip});
12477: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12478: foreach my $id (@{$iphost{$prim_ip}}) {
12479: my $intdom = &internet_dom($id);
12480: unless (grep(/^\Q$intdom\E$/,@idns)) {
12481: push(@idns,$intdom);
12482: }
12483: }
12484: }
12485: $seen{$prim_ip} = 1;
12486: }
1.1219 raeburn 12487: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12488: }
12489:
1.986 foxr 12490: }
12491:
1.1079 raeburn 12492: sub all_loncaparevs {
1.1249 raeburn 12493: 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 12494: }
12495:
1.1227 raeburn 12496: # ---------------------------------------------------------- Read loncaparev table
12497: {
12498: sub load_loncaparevs {
12499: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12500: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12501: while (my $configline=<$config>) {
12502: chomp($configline);
12503: my ($hostid,$loncaparev)=split(/:/,$configline);
12504: $loncaparevs{$hostid}=$loncaparev;
12505: }
12506: close($config);
12507: }
12508: }
12509: }
12510: }
12511:
12512: # ---------------------------------------------------------- Read serverhostID table
12513: {
12514: sub load_serverhomeIDs {
12515: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12516: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12517: while (my $configline=<$config>) {
12518: chomp($configline);
12519: my ($name,$id)=split(/:/,$configline);
12520: $serverhomeIDs{$name}=$id;
12521: }
12522: close($config);
12523: }
12524: }
12525: }
12526: }
12527:
12528:
1.862 albertel 12529: BEGIN {
12530:
12531: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12532: unless ($readit) {
12533: {
12534: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12535: %perlvar = (%perlvar,%{$configvars});
12536: }
12537:
12538:
1.1 albertel 12539: # ------------------------------------------------------ Read spare server file
12540: {
1.448 albertel 12541: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12542:
12543: while (my $configline=<$config>) {
12544: chomp($configline);
1.284 matthew 12545: if ($configline) {
1.784 albertel 12546: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12547: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12548: push(@{ $spareid{$type} }, $host);
1.1 albertel 12549: }
12550: }
1.448 albertel 12551: close($config);
1.1 albertel 12552: }
1.11 www 12553: # ------------------------------------------------------------ Read permissions
12554: {
1.448 albertel 12555: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12556:
12557: while (my $configline=<$config>) {
1.448 albertel 12558: chomp($configline);
12559: if ($configline) {
12560: my ($role,$perm)=split(/ /,$configline);
12561: if ($perm ne '') { $pr{$role}=$perm; }
12562: }
1.11 www 12563: }
1.448 albertel 12564: close($config);
1.11 www 12565: }
12566:
12567: # -------------------------------------------- Read plain texts for permissions
12568: {
1.448 albertel 12569: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12570:
12571: while (my $configline=<$config>) {
1.448 albertel 12572: chomp($configline);
12573: if ($configline) {
1.742 raeburn 12574: my ($short,@plain)=split(/:/,$configline);
12575: %{$prp{$short}} = ();
12576: if (@plain > 0) {
12577: $prp{$short}{'std'} = $plain[0];
12578: for (my $i=1; $i<@plain; $i++) {
12579: $prp{$short}{'alt'.$i} = $plain[$i];
12580: }
12581: }
1.448 albertel 12582: }
1.135 www 12583: }
1.448 albertel 12584: close($config);
1.135 www 12585: }
12586:
12587: # ---------------------------------------------------------- Read package table
12588: {
1.448 albertel 12589: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12590:
12591: while (my $configline=<$config>) {
1.483 albertel 12592: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12593: chomp($configline);
12594: my ($short,$plain)=split(/:/,$configline);
12595: my ($pack,$name)=split(/\&/,$short);
12596: if ($plain ne '') {
12597: $packagetab{$pack.'&'.$name.'&name'}=$name;
12598: $packagetab{$short}=$plain;
12599: }
1.11 www 12600: }
1.448 albertel 12601: close($config);
1.329 matthew 12602: }
12603:
1.1073 raeburn 12604: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12605:
12606: &load_loncaparevs();
1.1073 raeburn 12607:
1.1074 raeburn 12608: # ---------------------------------------------------------- Read serverhostID table
12609:
1.1227 raeburn 12610: &load_serverhomeIDs();
12611:
12612: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12613: {
12614: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12615: if (-e $file) {
12616: my $parser = HTML::LCParser->new($file);
12617: while (my $token = $parser->get_token()) {
12618: if ($token->[0] eq 'S') {
12619: my $item = $token->[1];
12620: my $name = $token->[2]{'name'};
12621: my $value = $token->[2]{'value'};
12622: if ($item ne '' && $name ne '' && $value ne '') {
12623: my $release = $parser->get_text();
12624: $release =~ s/(^\s*|\s*$ )//gx;
12625: $needsrelease{$item.':'.$name.':'.$value} = $release;
12626: }
12627: }
12628: }
12629: }
1.1073 raeburn 12630: }
12631:
1.1138 raeburn 12632: # ---------------------------------------------------------- Read managers table
12633: {
12634: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12635: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12636: while (my $configline=<$config>) {
12637: chomp($configline);
12638: next if ($configline =~ /^\#/);
12639: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12640: $managerstab{$configline} = 1;
12641: }
12642: }
12643: close($config);
12644: }
12645: }
12646: }
12647:
1.329 matthew 12648: # ------------- set up temporary directory
12649: {
1.1117 foxr 12650: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12651:
1.11 www 12652: }
12653:
1.794 albertel 12654: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12655: 'compress_threshold'=> 20_000,
12656: });
1.185 www 12657:
1.281 www 12658: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12659: $dumpcount=0;
1.958 www 12660: $locknum=0;
1.22 www 12661:
1.163 harris41 12662: &logtouch();
1.672 albertel 12663: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12664: $readit=1;
1.564 albertel 12665: {
12666: use integer;
12667: my $test=(2**32)+1;
1.568 albertel 12668: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12669: &logthis(" Detected 64bit platform ($_64bit)");
12670: }
1.195 www 12671: }
1.1 albertel 12672: }
1.179 www 12673:
1.1 albertel 12674: 1;
1.191 harris41 12675: __END__
12676:
1.243 albertel 12677: =pod
12678:
1.191 harris41 12679: =head1 NAME
12680:
1.243 albertel 12681: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12682:
12683: =head1 SYNOPSIS
12684:
1.243 albertel 12685: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12686:
12687: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12688:
1.243 albertel 12689: Common parameters:
12690:
12691: =over 4
12692:
12693: =item *
12694:
12695: $uname : an internal username (if $cname expecting a course Id specifically)
12696:
12697: =item *
12698:
12699: $udom : a domain (if $cdom expecting a course's domain specifically)
12700:
12701: =item *
12702:
12703: $symb : a resource instance identifier
12704:
12705: =item *
12706:
12707: $namespace : the name of a .db file that contains the data needed or
12708: being set.
12709:
12710: =back
12711:
1.394 bowersj2 12712: =head1 OVERVIEW
1.191 harris41 12713:
1.394 bowersj2 12714: lonnet provides subroutines which interact with the
12715: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12716: about classes, users, and resources.
1.243 albertel 12717:
12718: For many of these objects you can also use this to store data about
12719: them or modify them in various ways.
1.191 harris41 12720:
1.394 bowersj2 12721: =head2 Symbs
1.191 harris41 12722:
1.394 bowersj2 12723: To identify a specific instance of a resource, LON-CAPA uses symbols
12724: or "symbs"X<symb>. These identifiers are built from the URL of the
12725: map, the resource number of the resource in the map, and the URL of
12726: the resource itself. The latter is somewhat redundant, but might help
12727: if maps change.
12728:
12729: An example is
12730:
12731: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12732:
12733: The respective map entry is
12734:
12735: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12736: title="Problem 2">
12737: </resource>
12738:
12739: Symbs are used by the random number generator, as well as to store and
12740: restore data specific to a certain instance of for example a problem.
12741:
12742: =head2 Storing And Retrieving Data
12743:
12744: X<store()>X<cstore()>X<restore()>Three of the most important functions
12745: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12746: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12747: is is the non-critical message twin of cstore. These functions are for
12748: handlers to store a perl hash to a user's permanent data space in an
12749: easy manner, and to retrieve it again on another call. It is expected
12750: that a handler would use this once at the beginning to retrieve data,
12751: and then again once at the end to send only the new data back.
12752:
12753: The data is stored in the user's data directory on the user's
12754: homeserver under the ID of the course.
12755:
12756: The hash that is returned by restore will have all of the previous
12757: value for all of the elements of the hash.
12758:
12759: Example:
12760:
12761: #creating a hash
12762: my %hash;
12763: $hash{'foo'}='bar';
12764:
12765: #storing it
12766: &Apache::lonnet::cstore(\%hash);
12767:
12768: #changing a value
12769: $hash{'foo'}='notbar';
12770:
12771: #adding a new value
12772: $hash{'bar'}='foo';
12773: &Apache::lonnet::cstore(\%hash);
12774:
12775: #retrieving the hash
12776: my %history=&Apache::lonnet::restore();
12777:
12778: #print the hash
12779: foreach my $key (sort(keys(%history))) {
12780: print("\%history{$key} = $history{$key}");
12781: }
12782:
12783: Will print out:
1.191 harris41 12784:
1.394 bowersj2 12785: %history{1:foo} = bar
12786: %history{1:keys} = foo:timestamp
12787: %history{1:timestamp} = 990455579
12788: %history{2:bar} = foo
12789: %history{2:foo} = notbar
12790: %history{2:keys} = foo:bar:timestamp
12791: %history{2:timestamp} = 990455580
12792: %history{bar} = foo
12793: %history{foo} = notbar
12794: %history{timestamp} = 990455580
12795: %history{version} = 2
12796:
12797: Note that the special hash entries C<keys>, C<version> and
12798: C<timestamp> were added to the hash. C<version> will be equal to the
12799: total number of versions of the data that have been stored. The
12800: C<timestamp> attribute will be the UNIX time the hash was
12801: stored. C<keys> is available in every historical section to list which
12802: keys were added or changed at a specific historical revision of a
12803: hash.
12804:
12805: B<Warning>: do not store the hash that restore returns directly. This
12806: will cause a mess since it will restore the historical keys as if the
12807: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12808:
1.394 bowersj2 12809: Calling convention:
1.191 harris41 12810:
1.1225 raeburn 12811: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 12812: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 12813:
1.394 bowersj2 12814: For more detailed information, see lonnet specific documentation.
1.191 harris41 12815:
1.394 bowersj2 12816: =head1 RETURN MESSAGES
1.191 harris41 12817:
1.394 bowersj2 12818: =over 4
1.191 harris41 12819:
1.394 bowersj2 12820: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12821:
1.394 bowersj2 12822: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12823: when the connection is brought back up
1.191 harris41 12824:
1.394 bowersj2 12825: =item * B<con_failed>: unable to contact remote host and unable to save message
12826: for later delivery
1.191 harris41 12827:
1.967 bisitz 12828: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12829:
1.394 bowersj2 12830: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12831: that was requested
1.191 harris41 12832:
1.243 albertel 12833: =back
1.191 harris41 12834:
1.243 albertel 12835: =head1 PUBLIC SUBROUTINES
1.191 harris41 12836:
1.243 albertel 12837: =head2 Session Environment Functions
1.191 harris41 12838:
1.243 albertel 12839: =over 4
1.191 harris41 12840:
1.394 bowersj2 12841: =item *
12842: X<appenv()>
1.949 raeburn 12843: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12844: the user envirnoment file, and will be restored for each access this
1.620 albertel 12845: user makes during this session, also modifies the %env for the current
1.949 raeburn 12846: process. Optional rolesarrayref - if defined contains a reference to an array
12847: of roles which are exempt from the restriction on modifying user.role entries
12848: in the user's environment.db and in %env.
1.191 harris41 12849:
12850: =item *
1.394 bowersj2 12851: X<delenv()>
1.987 raeburn 12852: B<delenv($delthis,$regexp)>: removes all items from the session
12853: environment file that begin with $delthis. If the
12854: optional second arg - $regexp - is true, $delthis is treated as a
12855: regular expression, otherwise \Q$delthis\E is used.
12856: The values are also deleted from the current processes %env.
1.191 harris41 12857:
1.795 albertel 12858: =item * get_env_multiple($name)
12859:
12860: gets $name from the %env hash, it seemlessly handles the cases where multiple
12861: values may be defined and end up as an array ref.
12862:
12863: returns an array of values
12864:
1.243 albertel 12865: =back
12866:
12867: =head2 User Information
1.191 harris41 12868:
1.243 albertel 12869: =over 4
1.191 harris41 12870:
12871: =item *
1.394 bowersj2 12872: X<queryauthenticate()>
12873: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12874: authentication scheme
12875:
12876: =item *
1.394 bowersj2 12877: X<authenticate()>
1.1073 raeburn 12878: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12879: authenticate user from domain's lib servers (first use the current
12880: one). C<$upass> should be the users password.
1.1073 raeburn 12881: $checkdefauth is optional (value is 1 if a check should be made to
12882: authenticate user using default authentication method, and allow
12883: account creation if username does not have account in the domain).
12884: $clientcancheckhost is optional (value is 1 if checking whether the
12885: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12886:
12887: =item *
1.394 bowersj2 12888: X<homeserver()>
12889: B<homeserver($uname,$udom)>: find the server which has
12890: the user's directory and files (there must be only one), this caches
12891: the answer, and also caches if there is a borken connection.
1.191 harris41 12892:
12893: =item *
1.394 bowersj2 12894: X<idget()>
12895: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12896: (IDs are a unique resource in a domain, there must be only 1 ID per
12897: username, and only 1 username per ID in a specific domain) (returns
12898: hash: id=>name,id=>name)
1.191 harris41 12899:
12900: =item *
1.394 bowersj2 12901: X<idrget()>
12902: B<idrget($udom,@unames)>: find the IDs behind a list of
12903: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12904:
12905: =item *
1.394 bowersj2 12906: X<idput()>
12907: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12908:
12909: =item *
1.394 bowersj2 12910: X<rolesinit()>
1.1169 droeschl 12911: B<rolesinit($udom,$username)>: get user privileges.
12912: returns user role, first access and timer interval hashes
1.243 albertel 12913:
12914: =item *
1.1171 droeschl 12915: X<privileged()>
12916: B<privileged($username,$domain)>: returns a true if user has a
12917: privileged and active role (i.e. su or dc), false otherwise.
12918:
12919: =item *
1.551 albertel 12920: X<getsection()>
12921: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12922: course $cname, return section name/number or '' for "not in course"
12923: and '-1' for "no section"
12924:
12925: =item *
1.394 bowersj2 12926: X<userenvironment()>
12927: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12928: passed in @what from the requested user's environment, returns a hash
12929:
1.858 raeburn 12930: =item *
12931: X<userlog_query()>
1.859 albertel 12932: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12933: activity.log file. %filters defines filters applied when parsing the
12934: log file. These can be start or end timestamps, or the type of action
12935: - log to look for Login or Logout events, check for Checkin or
12936: Checkout, role for role selection. The response is in the form
12937: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12938: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12939:
1.243 albertel 12940: =back
12941:
12942: =head2 User Roles
12943:
12944: =over 4
12945:
12946: =item *
12947:
1.810 raeburn 12948: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12949: F: full access
12950: U,I,K: authentication modes (cxx only)
12951: '': forbidden
12952: 1: user needs to choose course
12953: 2: browse allowed
1.766 albertel 12954: A: passphrase authentication needed
1.243 albertel 12955:
12956: =item *
12957:
1.1192 raeburn 12958: constructaccess($url,$setpriv) : check for access to construction space URL
12959:
12960: See if the owner domain and name in the URL match those in the
12961: expected environment. If so, return three element list
12962: ($ownername,$ownerdomain,$ownerhome).
12963:
12964: Otherwise return the null string.
12965:
12966: If second argument 'setpriv' is true, it assigns the privileges,
12967: and returns the same three element list, unless the owner has
12968: blocked "ad hoc" Domain Coordinator access to the Author Space,
12969: in which case the null string is returned.
12970:
12971: =item *
12972:
1.243 albertel 12973: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12974: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12975: and course level
12976:
12977: =item *
12978:
1.988 raeburn 12979: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12980: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12981: $type is Course (default) or Community.
1.988 raeburn 12982: If $forcedefault evaluates to true, text returned will be default
12983: text for $type. Otherwise, if this is a course, the text returned
12984: will be a custom name for the role (if defined in the course's
12985: environment). If no custom name is defined the default is returned.
12986:
1.832 raeburn 12987: =item *
12988:
1.1219 raeburn 12989: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12990: All arguments are optional. Returns a hash of a roles, either for
12991: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12992: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12993: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12994: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12995: For each key, value is set to colon-separated start and end times for
12996: the role. If no username and domain are specified, will default to
1.934 raeburn 12997: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12998: of role statuses (active, future or previous), roles
12999: (e.g., cc,in, st etc.) and domains of the roles which can be used
13000: to restrict the list of roles reported. If no array ref is
13001: provided for types, will default to return only active roles.
1.834 albertel 13002:
1.1195 raeburn 13003: =item *
13004:
13005: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 13006: user: $uname:$udom has a role in the course: $cdom_$cnum.
13007:
13008: Additional optional arguments are: $type (if role checking is to be restricted
13009: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13010: available roles) or future (roles available in the future), and
13011: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13012: have active Domain Coordinator role in course's domain or in additional
13013: domains (specified in 'Domains to check for privileged users' in course
13014: environment -- set via: Course Settings -> Classlists and staff listing).
13015:
13016: =item *
13017:
13018: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13019: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13020: $possdomains and $possroles are optional array refs -- to domains to check and
13021: roles to check. If $possdomains is not specified, a dump will be done of the
13022: users' roles.db to check for a dc or su role in any domain. This can be
13023: time consuming if &privileged is called repeatedly (e.g., when displaying a
13024: classlist), so in such cases, supplying a $possdomains array is preferred, as
13025: this then allows &privileged_by_domain() to be used, which caches the identity
13026: of privileged users, eliminating the need for repeated calls to &dump().
13027:
13028: =item *
13029:
13030: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13031: where the outer hash keys are domains specified in the $possdomains array ref,
13032: next inner hash keys are privileged roles specified in the $roles array ref,
13033: and the innermost hash contains key = value pairs for username:domain = end:start
13034: for active or future "privileged" users with that role in that domain. To avoid
13035: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13036: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13037:
1.243 albertel 13038: =back
13039:
13040: =head2 User Modification
13041:
13042: =over 4
13043:
13044: =item *
13045:
1.957 raeburn 13046: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13047: user for the level given by URL. Optional start and end dates (leave empty
13048: string or zero for "no date")
1.191 harris41 13049:
13050: =item *
13051:
1.243 albertel 13052: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13053: change a users, password, possible return values are: ok,
13054: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13055: refused
1.191 harris41 13056:
13057: =item *
13058:
1.243 albertel 13059: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13060:
13061: =item *
13062:
1.1058 raeburn 13063: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13064: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13065:
13066: will update user information (firstname,middlename,lastname,generation,
13067: permanentemail), and if forceid is true, student/employee ID also.
13068: A user's institutional affiliation(s) can also be updated.
13069: User information fields will not be overwritten with empty entries
13070: unless the field is included in the $candelete array reference.
13071: This array is included when a single user is modified via "Manage Users",
13072: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13073:
13074: =item *
13075:
1.286 matthew 13076: modifystudent
13077:
1.957 raeburn 13078: modify a student's enrollment and identification information.
1.1235 raeburn 13079: The course id is resolved based on the current user's environment.
13080: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13081: associated with a course.
13082:
1.297 matthew 13083: This call is essentially a wrapper for lonnet::modifyuser and
13084: lonnet::modify_student_enrollment
1.286 matthew 13085:
13086: Inputs:
13087:
13088: =over 4
13089:
1.957 raeburn 13090: =item B<$udom> Student's loncapa domain
1.286 matthew 13091:
1.957 raeburn 13092: =item B<$uname> Student's loncapa login name
1.286 matthew 13093:
1.964 bisitz 13094: =item B<$uid> Student/Employee ID
1.286 matthew 13095:
1.957 raeburn 13096: =item B<$umode> Student's authentication mode
1.286 matthew 13097:
1.957 raeburn 13098: =item B<$upass> Student's password
1.286 matthew 13099:
1.957 raeburn 13100: =item B<$first> Student's first name
1.286 matthew 13101:
1.957 raeburn 13102: =item B<$middle> Student's middle name
1.286 matthew 13103:
1.957 raeburn 13104: =item B<$last> Student's last name
1.286 matthew 13105:
1.957 raeburn 13106: =item B<$gene> Student's generation
1.286 matthew 13107:
1.957 raeburn 13108: =item B<$usec> Student's section in course
1.286 matthew 13109:
13110: =item B<$end> Unix time of the roles expiration
13111:
13112: =item B<$start> Unix time of the roles start date
13113:
13114: =item B<$forceid> If defined, allow $uid to be changed
13115:
13116: =item B<$desiredhome> server to use as home server for student
13117:
1.957 raeburn 13118: =item B<$email> Student's permanent e-mail address
13119:
13120: =item B<$type> Type of enrollment (auto or manual)
13121:
1.963 raeburn 13122: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13123:
13124: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13125:
1.963 raeburn 13126: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13127:
1.963 raeburn 13128: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13129:
1.1216 raeburn 13130: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13131:
13132: =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 13133:
1.286 matthew 13134: =back
1.297 matthew 13135:
13136: =item *
13137:
13138: modify_student_enrollment
13139:
1.1235 raeburn 13140: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13141: 'role.request.course' must be defined for this function to proceed.
13142:
13143: Inputs:
13144:
13145: =over 4
13146:
1.1235 raeburn 13147: =item $udom, student's domain
1.297 matthew 13148:
1.1235 raeburn 13149: =item $uname, student's name
1.297 matthew 13150:
1.1235 raeburn 13151: =item $uid, student's user id
1.297 matthew 13152:
1.1235 raeburn 13153: =item $first, student's first name
1.297 matthew 13154:
13155: =item $middle
13156:
13157: =item $last
13158:
13159: =item $gene
13160:
13161: =item $usec
13162:
13163: =item $end
13164:
13165: =item $start
13166:
1.957 raeburn 13167: =item $type
13168:
13169: =item $locktype
13170:
13171: =item $cid
13172:
13173: =item $selfenroll
13174:
13175: =item $context
13176:
1.1216 raeburn 13177: =item $credits, number of credits student will earn from this class
13178:
1.297 matthew 13179: =back
13180:
1.191 harris41 13181:
13182: =item *
13183:
1.243 albertel 13184: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13185: custom role; give a custom role to a user for the level given by URL. Specify
13186: name and domain of role author, and role name
1.191 harris41 13187:
13188: =item *
13189:
1.243 albertel 13190: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13191:
13192: =item *
13193:
1.243 albertel 13194: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13195:
13196: =back
13197:
13198: =head2 Course Infomation
13199:
13200: =over 4
1.191 harris41 13201:
13202: =item *
13203:
1.1118 foxr 13204: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13205: specified course id, including all environment settings for the
13206: course, the description of the course will be in the hash under the
13207: key 'description'
1.191 harris41 13208:
1.1118 foxr 13209: $options is an optional parameter that if supplied is a hash reference that controls
13210: what how this function works. It has the following key/values:
13211:
13212: =over 4
13213:
13214: =item freshen_cache
13215:
13216: If defined, and the environment cache for the course is valid, it is
13217: returned in the returned hash.
13218:
13219: =item one_time
13220:
13221: If defined, the last cache time is set to _now_
13222:
13223: =item user
13224:
13225: If defined, the supplied username is used instead of the current user.
13226:
13227:
13228: =back
13229:
1.191 harris41 13230: =item *
13231:
1.624 albertel 13232: resdata($name,$domain,$type,@which) : request for current parameter
13233: setting for a specific $type, where $type is either 'course' or 'user',
13234: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 13235: answers for 10 minutes.
1.243 albertel 13236:
1.877 foxr 13237: =item *
13238:
13239: get_courseresdata($courseid, $domain) : dump the entire course resource
13240: data base, returning a hash that is keyed by the resource name and has
13241: values that are the resource value. I believe that the timestamps and
13242: versions are also returned.
13243:
1.1236 raeburn 13244: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13245: supplemental content area. This routine caches the number of files for
13246: 10 minutes.
13247:
1.243 albertel 13248: =back
13249:
13250: =head2 Course Modification
13251:
13252: =over 4
1.191 harris41 13253:
13254: =item *
13255:
1.243 albertel 13256: writecoursepref($courseid,%prefs) : write preferences (environment
13257: database) for a course
1.191 harris41 13258:
13259: =item *
13260:
1.1011 raeburn 13261: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13262:
13263: =item *
13264:
1.1038 raeburn 13265: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13266:
1.1167 droeschl 13267: =item *
13268:
13269: is_course($courseid), is_course($cdom, $cnum)
13270:
13271: Accepts either a combined $courseid (in the form of domain_courseid) or the
13272: two component version $cdom, $cnum. It checks if the specified course exists.
13273:
13274: Returns:
13275: undef if the course doesn't exist, otherwise
13276: in scalar context the combined courseid.
13277: in list context the two components of the course identifier, domain and
13278: courseid.
13279:
1.243 albertel 13280: =back
13281:
13282: =head2 Resource Subroutines
13283:
13284: =over 4
1.191 harris41 13285:
13286: =item *
13287:
1.243 albertel 13288: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13289:
13290: =item *
13291:
1.243 albertel 13292: repcopy($filename) : subscribes to the requested file, and attempts to
13293: replicate from the owning library server, Might return
1.607 raeburn 13294: 'unavailable', 'not_found', 'forbidden', 'ok', or
13295: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13296: resource. Expects the local filesystem pathname
13297: (/home/httpd/html/res/....)
13298:
13299: =back
13300:
13301: =head2 Resource Information
13302:
13303: =over 4
1.191 harris41 13304:
13305: =item *
13306:
1.1228 raeburn 13307: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13308: and returns the value of a variety of different possible values,
13309: $varname should be a request string, and the other parameters can be
13310: used to specify who and what one is asking about. Ordinarily, $cid
13311: does not need to be specified, as it is retrived from
13312: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13313: within lonuserstate::loadmap() when initializing a course, before
13314: $env{'request.course.id'} has been set, so it needs to be provided
13315: in that one case.
1.243 albertel 13316:
13317: Possible values for $varname are environment.lastname (or other item
13318: from the envirnment hash), user.name (or someother aspect about the
13319: user), resource.0.maxtries (or some other part and parameter of a
13320: resource)
1.204 albertel 13321:
13322: =item *
13323:
1.243 albertel 13324: directcondval($number) : get current value of a condition; reads from a state
13325: string
1.204 albertel 13326:
13327: =item *
13328:
1.243 albertel 13329: condval($condidx) : value of condition index based on state
1.204 albertel 13330:
13331: =item *
13332:
1.243 albertel 13333: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13334: resource's metadata, $what should be either a specific key, or either
13335: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13336: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13337:
13338: this function automatically caches all requests
1.191 harris41 13339:
13340: =item *
13341:
1.243 albertel 13342: metadata_query($query,$custom,$customshow) : make a metadata query against the
13343: network of library servers; returns file handle of where SQL and regex results
13344: will be stored for query
1.191 harris41 13345:
13346: =item *
13347:
1.243 albertel 13348: symbread($filename) : return symbolic list entry (filename argument optional);
13349: returns the data handle
1.191 harris41 13350:
13351: =item *
13352:
1.1190 raeburn 13353: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13354: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13355: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13356: on failure, user must be in a course, as it assumes the existence of
13357: the course initial hash, and uses $env('request.course.id'}. The third
13358: arg is an optional reference to a scalar. If this arg is passed in the
13359: call to symbverify, it will be set to 1 if the symb has been set to be
13360: encrypted; otherwise it will be null.
1.191 harris41 13361:
13362: =item *
13363:
1.243 albertel 13364: symbclean($symb) : removes versions numbers from a symb, returns the
13365: cleaned symb
1.191 harris41 13366:
13367: =item *
13368:
1.243 albertel 13369: is_on_map($uri) : checks if the $uri is somewhere on the current
13370: course map, user must be in a course for it to work.
1.191 harris41 13371:
13372: =item *
13373:
1.243 albertel 13374: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13375:
13376: =item *
13377:
1.243 albertel 13378: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13379: a random seed, all arguments are optional, if they aren't sent it uses the
13380: environment to derive them. Note: if symb isn't sent and it can't get one
13381: from &symbread it will use the current time as its return value
1.191 harris41 13382:
13383: =item *
13384:
1.243 albertel 13385: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13386: unfakeable, receipt
1.191 harris41 13387:
13388: =item *
13389:
1.620 albertel 13390: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13391:
13392: =item *
13393:
1.243 albertel 13394: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13395:
13396: =item *
13397:
1.243 albertel 13398: 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 13399:
13400: =item *
13401:
1.243 albertel 13402: 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 13403:
13404: =item *
13405:
1.243 albertel 13406: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13407:
13408: =item *
13409:
1.243 albertel 13410: devalidate($symb) : devalidate temporary spreadsheet calculations,
13411: forcing spreadsheet to reevaluate the resource scores next time.
13412:
1.1195 raeburn 13413: =item *
13414:
1.1196 raeburn 13415: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13416: when viewing in course context.
1.1195 raeburn 13417:
1.1196 raeburn 13418: input: six args -- filename (decluttered), course number, course domain,
13419: url, symb (if registered) and group (if this is a
13420: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13421:
1.1196 raeburn 13422: output: array of five scalars --
1.1195 raeburn 13423: $cfile -- url for file editing if editable on current server
13424: $home -- homeserver of resource (i.e., for author if published,
13425: or course if uploaded.).
13426: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13427: $forceedit -- 1 if icon/link should be to go to edit mode
13428: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13429:
13430: =item *
13431:
13432: is_course_upload($file,$cnum,$cdom)
13433:
13434: Used in course context to determine if current file was uploaded to
13435: the course (i.e., would be found in /userfiles/docs on the course's
13436: homeserver.
13437:
13438: input: 3 args -- filename (decluttered), course number and course domain.
13439: output: boolean -- 1 if file was uploaded.
13440:
1.243 albertel 13441: =back
13442:
13443: =head2 Storing/Retreiving Data
13444:
13445: =over 4
1.191 harris41 13446:
13447: =item *
13448:
1.1269 raeburn 13449: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13450: permanently for this url; hashref needs to be given and should be a \%hashname;
13451: the remaining args aren't required and if they aren't passed or are '' they will
13452: be derived from the env (with the exception of $laststore, which is an
13453: optional arg used when a user's submission is stored in grading).
13454: $laststore is $version=$timestamp, where $version is the most recent version
13455: number retrieved for the corresponding $symb in the $namespace db file, and
13456: $timestamp is the timestamp for that transaction (UNIX time).
13457: $laststore is currently only passed when cstore() is called by
13458: structuretags::finalize_storage().
1.191 harris41 13459:
13460: =item *
13461:
1.1269 raeburn 13462: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13463: but uses critical subroutine
1.191 harris41 13464:
13465: =item *
13466:
1.243 albertel 13467: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13468: all args are optional
1.191 harris41 13469:
13470: =item *
13471:
1.717 albertel 13472: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13473: dumps the complete (or key matching regexp) namespace into a hash
13474: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13475: normally &store()ed into
13476:
13477: $range should be either an integer '100' (give me the first 100
13478: matching records)
13479: or be two integers sperated by a - with no spaces
13480: '30-50' (give me the 30th through the 50th matching
13481: records)
13482:
13483:
13484: =item *
13485:
1.1269 raeburn 13486: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13487: replaces a &store() version of data with a replacement set of data
13488: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 13489: reference. If $tolog is true, the transaction is logged in the courselog
13490: with an action=PUTSTORE.
1.717 albertel 13491:
13492: =item *
13493:
1.243 albertel 13494: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13495: works very similar to store/cstore, but all data is stored in a
13496: temporary location and can be reset using tmpreset, $storehash should
13497: be a hash reference, returns nothing on success
1.191 harris41 13498:
13499: =item *
13500:
1.243 albertel 13501: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13502: similar to restore, but all data is stored in a temporary location and
13503: can be reset using tmpreset. Returns a hash of values on success,
13504: error string otherwise.
1.191 harris41 13505:
13506: =item *
13507:
1.243 albertel 13508: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13509: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13510:
13511: =item *
13512:
1.243 albertel 13513: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13514: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13515:
13516: =item *
13517:
1.243 albertel 13518: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13519: namesp ($udom and $uname are optional)
1.191 harris41 13520:
13521: =item *
13522:
1.702 albertel 13523: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13524: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13525: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13526:
1.702 albertel 13527: $range should be either an integer '100' (give me the first 100
13528: matching records)
13529: or be two integers sperated by a - with no spaces
13530: '30-50' (give me the 30th through the 50th matching
13531: records)
1.449 matthew 13532: =item *
13533:
13534: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13535: $store can be a scalar, an array reference, or if the amount to be
13536: incremented is > 1, a hash reference.
13537:
13538: ($udom and $uname are optional)
1.191 harris41 13539:
13540: =item *
13541:
1.243 albertel 13542: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13543: ($udom and $uname are optional)
1.191 harris41 13544:
13545: =item *
13546:
1.243 albertel 13547: cput($namespace,$storehash,$udom,$uname) : critical put
13548: ($udom and $uname are optional)
1.191 harris41 13549:
13550: =item *
13551:
1.748 albertel 13552: newput($namespace,$storehash,$udom,$uname) :
13553:
13554: Attempts to store the items in the $storehash, but only if they don't
13555: currently exist, if this succeeds you can be certain that you have
13556: successfully created a new key value pair in the $namespace db.
13557:
13558:
13559: Args:
13560: $namespace: name of database to store values to
13561: $storehash: hashref to store to the db
13562: $udom: (optional) domain of user containing the db
13563: $uname: (optional) name of user caontaining the db
13564:
13565: Returns:
13566: 'ok' -> succeeded in storing all keys of $storehash
13567: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13568: least <key> already existed in the db (other
13569: requested keys may also already exist)
1.967 bisitz 13570: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13571: 'con_lost' -> unable to contact request server
13572: 'refused' -> action was not allowed by remote machine
13573:
13574:
13575: =item *
13576:
1.243 albertel 13577: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13578: reference filled in from namesp (encrypts the return communication)
13579: ($udom and $uname are optional)
1.191 harris41 13580:
13581: =item *
13582:
1.243 albertel 13583: log($udom,$name,$home,$message) : write to permanent log for user; use
13584: critical subroutine
13585:
1.806 raeburn 13586: =item *
13587:
1.860 raeburn 13588: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13589: array reference filled in from namespace found in domain level on either
13590: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13591:
13592: =item *
13593:
1.860 raeburn 13594: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13595: domain level either on specified domain server ($uhome) or primary domain
13596: server ($udom and $uhome are optional)
1.806 raeburn 13597:
1.943 raeburn 13598: =item *
13599:
1.1240 raeburn 13600: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13601: for: authentication, language, quotas, timezone, date locale, and portal URL in
13602: the target domain.
13603:
13604: May also include additional key => value pairs for the following groups:
13605:
13606: =over
13607:
13608: =item
13609: disk quotas (MB allocated by default to portfolios and authoring spaces).
13610:
13611: =over
13612:
13613: =item defaultquota, authorquota
13614:
13615: =back
13616:
13617: =item
13618: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13619: portfolio for users).
13620:
13621: =over
13622:
13623: =item
13624: aboutme, blog, webdav, portfolio
13625:
13626: =back
13627:
13628: =item
13629: requestcourses: ability to request courses, and how requests are processed.
13630:
13631: =over
13632:
13633: =item
1.1246 raeburn 13634: official, unofficial, community, textbook
1.1240 raeburn 13635:
13636: =back
13637:
13638: =item
13639: inststatus: types of institutional affiliation, and order in which they are displayed.
13640:
13641: =over
13642:
13643: =item
1.1256 raeburn 13644: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 13645:
13646: =back
13647:
13648: =item
13649: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13650: for course's uploaded content.
13651:
13652: =over
13653:
13654: =item
1.1246 raeburn 13655: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13656: communityquota, textbookquota
1.1240 raeburn 13657:
13658: =back
13659:
13660: =item
13661: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13662: on your servers.
13663:
13664: =over
13665:
13666: =item
13667: remotesessions, hostedsessions
13668:
13669: =back
13670:
13671: =back
13672:
13673: In cases where a domain coordinator has never used the "Set Domain Configuration"
13674: utility to create a configuration.db file on a domain's primary library server
13675: only the following domain defaults: auth_def, auth_arg_def, lang_def
13676: -- corresponding values are authentication type (internal, krb4, krb5,
13677: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13678: will be available. Values are retrieved from cache (if current), unless the
13679: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13680: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13681:
13682: Typical usage:
1.943 raeburn 13683:
1.1240 raeburn 13684: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13685:
1.243 albertel 13686: =back
13687:
13688: =head2 Network Status Functions
13689:
13690: =over 4
1.191 harris41 13691:
13692: =item *
13693:
1.1137 raeburn 13694: dirlist() : return directory list based on URI (first arg).
13695:
13696: Inputs: 1 required, 5 optional.
13697:
13698: =over
13699:
13700: =item
13701: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13702:
13703: =item
13704: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13705:
13706: =item
13707: $username - username of user/course to be listed. Extracted from $uri if absent.
13708:
13709: =item
13710: $getpropath - boolean: 1 if prepend path using &propath().
13711:
13712: =item
13713: $getuserdir - boolean: 1 if prepend path for "userfiles".
13714:
13715: =item
13716: $alternateRoot - path to prepend in place of path from $uri.
13717:
13718: =back
13719:
13720: Returns: Array of up to two items.
13721:
13722: =over
13723:
13724: a reference to an array of files/subdirectories
13725:
13726: =over
13727:
13728: Each element in the array of files/subdirectories is a & separated list of
13729: item name and the result of running stat on the item. If dirlist was requested
13730: for a file instead of a directory, the item name will be ''. For a directory
13731: listing, if the item is a metadata file, the element will end &N&M
13732: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13733: default copyright set (1).
13734:
13735: =back
13736:
13737: a scalar containing error condition (if encountered).
13738:
13739: =over
13740:
13741: =item
13742: no_host (no homeserver identified for $username:$domain).
13743:
13744: =item
13745: no_such_host (server contacted for listing not identified as valid host).
13746:
13747: =item
13748: con_lost (connection to remote server failed).
13749:
13750: =item
13751: refused (invalid $username:$domain received on lond side).
13752:
13753: =item
13754: no_such_dir (directory at specified path on lond side does not exist).
13755:
13756: =item
13757: empty (directory at specified path on lond side is empty).
13758:
13759: =over
13760:
13761: This is currently not encountered because the &ls3, &ls2,
13762: &ls (_handler) routines on the lond side do not filter out
13763: . and .. from a directory listing.
13764:
13765: =back
13766:
13767: =back
13768:
13769: =back
1.191 harris41 13770:
13771: =item *
13772:
1.243 albertel 13773: spareserver() : find server with least workload from spare.tab
13774:
1.986 foxr 13775:
13776: =item *
13777:
13778: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13779: if there is no corresponding loncapa host.
13780:
1.243 albertel 13781: =back
13782:
1.986 foxr 13783:
1.243 albertel 13784: =head2 Apache Request
13785:
13786: =over 4
1.191 harris41 13787:
13788: =item *
13789:
1.243 albertel 13790: ssi($url,%hash) : server side include, does a complete request cycle on url to
13791: localhost, posts hash
13792:
13793: =back
13794:
13795: =head2 Data to String to Data
13796:
13797: =over 4
1.191 harris41 13798:
13799: =item *
13800:
1.243 albertel 13801: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13802: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13803:
13804: =item *
13805:
1.243 albertel 13806: hashref2str($hashref) : convert a hashref into a string complete with
13807: escaping and '=' and '&' separators, supports elements that are
13808: arrayrefs and hashrefs
1.191 harris41 13809:
13810: =item *
13811:
1.243 albertel 13812: arrayref2str($arrayref) : convert an arrayref into a string complete
13813: with escaping and '&' separators, supports elements that are arrayrefs
13814: and hashrefs
1.191 harris41 13815:
13816: =item *
13817:
1.243 albertel 13818: str2hash($string) : convert string to hash using unescaping and
13819: splitting on '=' and '&', supports elements that are arrayrefs and
13820: hashrefs
1.191 harris41 13821:
13822: =item *
13823:
1.243 albertel 13824: str2array($string) : convert string to hash using unescaping and
13825: splitting on '&', supports elements that are arrayrefs and hashrefs
13826:
13827: =back
13828:
13829: =head2 Logging Routines
13830:
13831:
13832: These routines allow one to make log messages in the lonnet.log and
13833: lonnet.perm logfiles.
1.191 harris41 13834:
1.1119 foxr 13835: =over 4
13836:
1.191 harris41 13837: =item *
13838:
1.243 albertel 13839: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13840:
13841: =item *
13842:
1.243 albertel 13843: logthis() : append message to the normal lonnet.log file, it gets
13844: preiodically rolled over and deleted.
1.191 harris41 13845:
13846: =item *
13847:
1.243 albertel 13848: logperm() : append a permanent message to lonnet.perm.log, this log
13849: file never gets deleted by any automated portion of the system, only
13850: messages of critical importance should go in here.
13851:
1.1119 foxr 13852:
1.243 albertel 13853: =back
13854:
13855: =head2 General File Helper Routines
13856:
13857: =over 4
1.191 harris41 13858:
13859: =item *
13860:
1.481 raeburn 13861: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13862: (a) files in /uploaded
13863: (i) If a local copy of the file exists -
13864: compares modification date of local copy with last-modified date for
13865: definitive version stored on home server for course. If local copy is
13866: stale, requests a new version from the home server and stores it.
13867: If the original has been removed from the home server, then local copy
13868: is unlinked.
13869: (ii) If local copy does not exist -
13870: requests the file from the home server and stores it.
13871:
13872: If $caller is 'uploadrep':
13873: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13874: for request for files originally uploaded via DOCS.
13875: - returns 'ok' if fresh local copy now available, -1 otherwise.
13876:
13877: Otherwise:
13878: This indicates a call from the content generation phase of the request.
13879: - returns the entire contents of the file or -1.
13880:
13881: (b) files in /res
13882: - returns the entire contents of a file or -1;
13883: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13884:
1.712 albertel 13885:
13886: =item *
13887:
13888: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13889: reference
13890:
13891: returns either a stat() list of data about the file or an empty list
13892: if the file doesn't exist or couldn't find out about it (connection
13893: problems or user unknown)
13894:
1.191 harris41 13895: =item *
13896:
1.243 albertel 13897: filelocation($dir,$file) : returns file system location of a file
13898: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13899: directory that relative $file lookups are to looked in ($dir of /a/dir
13900: and a file of ../bob will become /a/bob)
1.191 harris41 13901:
13902: =item *
13903:
13904: hreflocation($dir,$file) : returns file system location or a URL; same as
13905: filelocation except for hrefs
13906:
13907: =item *
13908:
1.1261 raeburn 13909: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13910: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 13911:
1.243 albertel 13912: =back
13913:
1.608 albertel 13914: =head2 Usererfile file routines (/uploaded*)
13915:
13916: =over 4
13917:
13918: =item *
13919:
13920: userfileupload(): main rotine for putting a file in a user or course's
13921: filespace, arguments are,
13922:
1.620 albertel 13923: formname - required - this is the name of the element in $env where the
1.608 albertel 13924: filename, and the contents of the file to create/modifed exist
1.620 albertel 13925: the filename is in $env{'form.'.$formname.'.filename'} and the
13926: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13927: context - if coursedoc, store the file in the course of the active role
13928: of the current user;
13929: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13930: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13931: subdir - required - subdirectory to put the file in under ../userfiles/
13932: if undefined, it will be placed in "unknown"
13933:
13934: (This routine calls clean_filename() to remove any dangerous
13935: characters from the filename, and then calls finuserfileupload() to
13936: complete the transaction)
13937:
13938: returns either the url of the uploaded file (/uploaded/....) if successful
13939: and /adm/notfound.html if unsuccessful
13940:
13941: =item *
13942:
13943: clean_filename(): routine for cleaing a filename up for storage in
13944: userfile space, argument is:
13945:
13946: filename - proposed filename
13947:
13948: returns: the new clean filename
13949:
13950: =item *
13951:
1.1090 raeburn 13952: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13953: userspace, probably shouldn't be called directly
13954:
13955: docuname: username or courseid of destination for the file
13956: docudom: domain of user/course of destination for the file
13957: formname: same as for userfileupload()
1.1090 raeburn 13958: fname: filename (including subdirectories) for the file
13959: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13960: allfiles: reference to hash used to store objects found by parser
13961: codebase: reference to hash used for codebases of java objects found by parser
13962: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13963: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13964: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13965: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13966: context: if 'overwrite', will move the uploaded file from its temporary location to
13967: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13968: mimetype: reference to scalar to accommodate mime type determined
13969: from File::MMagic if $parser = parse.
1.608 albertel 13970:
13971: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13972: and /adm/notfound.html if unsuccessful (or an error message if context
13973: was 'overwrite').
13974:
1.608 albertel 13975:
13976: =item *
13977:
13978: renameuserfile(): renames an existing userfile to a new name
13979:
13980: Args:
13981: docuname: username or courseid of destination for the file
13982: docudom: domain of user/course of destination for the file
13983: old: current file name (including any subdirs under userfiles)
13984: new: desired file name (including any subdirs under userfiles)
13985:
13986: =item *
13987:
13988: mkdiruserfile(): creates a directory is a userfiles dir
13989:
13990: Args:
13991: docuname: username or courseid of destination for the file
13992: docudom: domain of user/course of destination for the file
13993: dir: dir to create (including any subdirs under userfiles)
13994:
13995: =item *
13996:
13997: removeuserfile(): removes a file that exists in userfiles
13998:
13999: Args:
14000: docuname: username or courseid of destination for the file
14001: docudom: domain of user/course of destination for the file
14002: fname: filname to delete (including any subdirs under userfiles)
14003:
14004: =item *
14005:
14006: removeuploadedurl(): convience function for removeuserfile()
14007:
14008: Args:
14009: url: a full /uploaded/... url to delete
14010:
1.747 albertel 14011: =item *
14012:
14013: get_portfile_permissions():
14014: Args:
14015: domain: domain of user or course contain the portfolio files
14016: user: name of user or num of course contain the portfolio files
14017: Returns:
14018: hashref of a dump of the proper file_permissions.db
14019:
14020:
14021: =item *
14022:
14023: get_access_controls():
14024:
14025: Args:
14026: current_permissions: the hash ref returned from get_portfile_permissions()
14027: group: (optional) the group you want the files associated with
14028: file: (optional) the file you want access info on
14029:
14030: Returns:
1.749 raeburn 14031: a hash (keys are file names) of hashes containing
14032: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14033: values are XML containing access control settings (see below)
1.747 albertel 14034:
14035: Internal notes:
14036:
1.749 raeburn 14037: access controls are stored in file_permissions.db as key=value pairs.
14038: key -> path to file/file_name\0uniqueID:scope_end_start
14039: where scope -> public,guest,course,group,domains or users.
14040: end -> UNIX time for end of access (0 -> no end date)
14041: start -> UNIX time for start of access
14042:
14043: value -> XML description of access control
14044: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14045: <start></start>
14046: <end></end>
14047:
14048: <password></password> for scope type = guest
14049:
14050: <domain></domain> for scope type = course or group
14051: <number></number>
14052: <roles id="">
14053: <role></role>
14054: <access></access>
14055: <section></section>
14056: <group></group>
14057: </roles>
14058:
14059: <dom></dom> for scope type = domains
14060:
14061: <users> for scope type = users
14062: <user>
14063: <uname></uname>
14064: <udom></udom>
14065: </user>
14066: </users>
14067: </scope>
14068:
14069: Access data is also aggregated for each file in an additional key=value pair:
14070: key -> path to file/file_name\0accesscontrol
14071: value -> reference to hash
14072: hash contains key = value pairs
14073: where key = uniqueID:scope_end_start
14074: value = UNIX time record was last updated
14075:
14076: Used to improve speed of look-ups of access controls for each file.
14077:
14078: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14079:
1.1198 raeburn 14080: =item *
14081:
1.749 raeburn 14082: modify_access_controls():
14083:
14084: Modifies access controls for a portfolio file
14085: Args
14086: 1. file name
14087: 2. reference to hash of required changes,
14088: 3. domain
14089: 4. username
14090: where domain,username are the domain of the portfolio owner
14091: (either a user or a course)
14092:
14093: Returns:
14094: 1. result of additions or updates ('ok' or 'error', with error message).
14095: 2. result of deletions ('ok' or 'error', with error message).
14096: 3. reference to hash of any new or updated access controls.
14097: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14098: key = integer (inbound ID)
1.1198 raeburn 14099: value = uniqueID
14100:
14101: =item *
14102:
14103: get_timebased_id():
14104:
14105: Attempts to get a unique timestamp-based suffix for use with items added to a
14106: course via the Course Editor (e.g., folders, composite pages,
14107: group bulletin boards).
14108:
14109: Args: (first three required; six others optional)
14110:
14111: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14112: docssequence, or name of group
14113:
14114: 2. keyid (alphanumeric): name of temporary locking key in hash,
14115: e.g., num, boardids
14116:
14117: 3. namespace: name of gdbm file used to store suffixes already assigned;
14118: file will be named nohist_namespace.db
14119:
14120: 4. cdom: domain of course; default is current course domain from %env
14121:
14122: 5. cnum: course number; default is current course number from %env
14123:
14124: 6. idtype: set to concat if an additional digit is to be appended to the
14125: unix timestamp to form the suffix, if the plain timestamp is already
14126: in use. Default is to not do this, but simply increment the unix
14127: timestamp by 1 until a unique key is obtained.
14128:
14129: 7. who: holder of locking key; defaults to user:domain for user.
14130:
14131: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14132: retrying); default is 3.
14133:
14134: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14135:
14136: Returns:
14137:
14138: 1. suffix obtained (numeric)
14139:
14140: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14141:
14142: 3. error: contains (localized) error message if an error occurred.
14143:
1.747 albertel 14144:
1.608 albertel 14145: =back
14146:
1.243 albertel 14147: =head2 HTTP Helper Routines
14148:
14149: =over 4
14150:
1.191 harris41 14151: =item *
14152:
14153: escape() : unpack non-word characters into CGI-compatible hex codes
14154:
14155: =item *
14156:
14157: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14158:
1.243 albertel 14159: =back
14160:
14161: =head1 PRIVATE SUBROUTINES
14162:
14163: =head2 Underlying communication routines (Shouldn't call)
14164:
14165: =over 4
14166:
14167: =item *
14168:
14169: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14170:
14171: =item *
14172:
14173: reply() : uses subreply to send a message to remote machine, logs all failures
14174:
14175: =item *
14176:
14177: critical() : passes a critical message to another server; if cannot
14178: get through then place message in connection buffer directory and
14179: returns con_delayed, if incapable of saving message, returns
14180: con_failed
14181:
14182: =item *
14183:
14184: reconlonc() : tries to reconnect lonc client processes.
14185:
14186: =back
14187:
14188: =head2 Resource Access Logging
14189:
14190: =over 4
14191:
14192: =item *
14193:
14194: flushcourselogs() : flush (save) buffer logs and access logs
14195:
14196: =item *
14197:
14198: courselog($what) : save message for course in hash
14199:
14200: =item *
14201:
14202: courseacclog($what) : save message for course using &courselog(). Perform
14203: special processing for specific resource types (problems, exams, quizzes, etc).
14204:
1.191 harris41 14205: =item *
14206:
14207: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14208: as a PerlChildExitHandler
1.243 albertel 14209:
14210: =back
14211:
14212: =head2 Other
14213:
14214: =over 4
14215:
14216: =item *
14217:
14218: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14219:
14220: =back
14221:
14222: =cut
1.877 foxr 14223:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>