Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.55
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.55! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.54 2014/07/29 05:55:24 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1172.2.36 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.550 foxr 105: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
145: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.448 albertel 157: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.448 albertel 170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
1.1172.2.35 raeburn 355: my ($lonhost,$cachekeys) = @_;
356: my $items;
357: return unless (ref($cachekeys) eq 'ARRAY');
358: my $cachestr = join('&',@{$cachekeys});
359: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 360: }
361:
1.1 albertel 362: # -------------------------------------------------- Non-critical communication
363: sub subreply {
364: my ($cmd,$server)=@_;
1.838 albertel 365: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 366: #
367: # With loncnew process trimming, there's a timing hole between lonc server
368: # process exit and the master server picking up the listen on the AF_UNIX
369: # socket. In that time interval, a lock file will exist:
370:
371: my $lockfile=$peerfile.".lock";
372: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
373: sleep(1);
374: }
375: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 376: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 377: #
1.550 foxr 378: # We'll give the connection a few tries before abandoning it. If
379: # connection is not possible, we'll con_lost back to the client.
380: #
381: my $client;
382: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
383: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
384: Type => SOCK_STREAM,
385: Timeout => 10);
1.869 albertel 386: if ($client) {
1.550 foxr 387: last; # Connected!
1.850 albertel 388: } else {
1.853 albertel 389: &create_connection(&hostname($server),$server);
1.550 foxr 390: }
1.850 albertel 391: sleep(1); # Try again later if failed connection.
1.550 foxr 392: }
393: my $answer;
394: if ($client) {
1.704 albertel 395: print $client "sethost:$server:$cmd\n";
1.550 foxr 396: $answer=<$client>;
397: if (!$answer) { $answer="con_lost"; }
398: chomp($answer);
399: } else {
400: $answer = 'con_lost'; # Failed connection.
401: }
1.1 albertel 402: return $answer;
403: }
404:
405: sub reply {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 408: my $answer=subreply($cmd,$server);
1.65 www 409: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 410: &logthis("<font color=\"blue\">WARNING:".
1.12 www 411: " $cmd to $server returned $answer</font>");
412: }
1.1 albertel 413: return $answer;
414: }
415:
416: # ----------------------------------------------------------- Send USR1 to lonc
417:
418: sub reconlonc {
1.891 albertel 419: my ($lonid) = @_;
420: my $hostname = &hostname($lonid);
421: if ($lonid) {
422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 439: if (open(my $fh,"<$loncfile")) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
467: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
479: if (open($dfh,">$dfilename")) {
480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
484: sleep 2;
485: my $wcmd='';
486: {
1.448 albertel 487: my $dfh;
488: if (open($dfh,"<$dfilename")) {
489: $wcmd=<$dfh>;
490: close($dfh);
491: }
1.1 albertel 492: }
493: chomp($wcmd);
1.7 www 494: if ($wcmd eq $cmd) {
1.672 albertel 495: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 496: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 497: &logperm("D:$server:$cmd");
498: return 'con_delayed';
499: } else {
1.672 albertel 500: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 501: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 502: &logperm("F:$server:$cmd");
503: return 'con_failed';
504: }
505: }
506: }
507: return $answer;
1.405 albertel 508: }
509:
1.755 albertel 510: # ------------------------------------------- check if return value is an error
511:
512: sub error {
513: my ($result) = @_;
1.756 albertel 514: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 515: if ($2 == 2) { return undef; }
516: return $1;
517: }
518: return undef;
519: }
520:
1.783 albertel 521: sub convert_and_load_session_env {
522: my ($lonidsdir,$handle)=@_;
523: my @profile;
524: {
1.917 albertel 525: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
526: if (!$opened) {
1.915 albertel 527: return 0;
528: }
1.783 albertel 529: flock($idf,LOCK_SH);
530: @profile=<$idf>;
531: close($idf);
532: }
533: my %temp_env;
534: foreach my $line (@profile) {
1.786 albertel 535: if ($line !~ m/=/) {
536: return 0;
537: }
1.783 albertel 538: chomp($line);
539: my ($envname,$envvalue)=split(/=/,$line,2);
540: $temp_env{&unescape($envname)} = &unescape($envvalue);
541: }
542: unlink("$lonidsdir/$handle.id");
543: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
544: 0640)) {
545: %disk_env = %temp_env;
546: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
547: untie(%disk_env);
548: }
1.786 albertel 549: return 1;
1.783 albertel 550: }
551:
1.374 www 552: # ------------------------------------------- Transfer profile into environment
1.780 albertel 553: my $env_loaded;
554: sub transfer_profile_to_env {
1.788 albertel 555: my ($lonidsdir,$handle,$force_transfer) = @_;
556: if (!$force_transfer && $env_loaded) { return; }
1.374 www 557:
1.720 albertel 558: if (!defined($lonidsdir)) {
559: $lonidsdir = $perlvar{'lonIDsDir'};
560: }
561: if (!defined($handle)) {
562: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
563: }
564:
1.786 albertel 565: my $convert;
566: {
1.917 albertel 567: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
568: if (!$opened) {
1.915 albertel 569: return;
570: }
1.786 albertel 571: flock($idf,LOCK_SH);
572: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
573: &GDBM_READER(),0640)) {
574: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
575: untie(%disk_env);
576: } else {
577: $convert = 1;
578: }
579: }
580: if ($convert) {
581: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
582: &logthis("Failed to load session, or convert session.");
583: }
1.374 www 584: }
1.783 albertel 585:
1.786 albertel 586: my %remove;
1.783 albertel 587: while ( my $envname = each(%env) ) {
1.433 matthew 588: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
589: if ($time < time-300) {
1.783 albertel 590: $remove{$key}++;
1.433 matthew 591: }
592: }
593: }
1.783 albertel 594:
1.619 albertel 595: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 596: $env_loaded=1;
1.783 albertel 597: foreach my $expired_key (keys(%remove)) {
1.433 matthew 598: &delenv($expired_key);
1.374 www 599: }
1.1 albertel 600: }
601:
1.916 albertel 602: # ---------------------------------------------------- Check for valid session
603: sub check_for_valid_session {
1.1172.2.36 raeburn 604: my ($r,$name,$userhashref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.916 albertel 619: return undef if (!-e "$lonidsdir/$handle.id");
620:
1.917 albertel 621: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
622: return undef if (!$opened);
1.916 albertel 623:
624: flock($idf,LOCK_SH);
625: my %disk_env;
626: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
627: &GDBM_READER(),0640)) {
628: return undef;
629: }
630:
631: if (!defined($disk_env{'user.name'})
632: || !defined($disk_env{'user.domain'})) {
633: return undef;
634: }
1.1172.2.18 raeburn 635:
1.1172.2.36 raeburn 636: if (ref($userhashref) eq 'HASH') {
637: $userhashref->{'name'} = $disk_env{'user.name'};
638: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 639: }
640:
1.916 albertel 641: return $handle;
642: }
643:
1.830 albertel 644: sub timed_flock {
645: my ($file,$lock_type) = @_;
646: my $failed=0;
647: eval {
648: local $SIG{__DIE__}='DEFAULT';
649: local $SIG{ALRM}=sub {
650: $failed=1;
651: die("failed lock");
652: };
653: alarm(13);
654: flock($file,$lock_type);
655: alarm(0);
656: };
657: if ($failed) {
658: return undef;
659: } else {
660: return 1;
661: }
662: }
663:
1.5 www 664: # ---------------------------------------------------------- Append Environment
665:
666: sub appenv {
1.949 raeburn 667: my ($newenv,$roles) = @_;
668: if (ref($newenv) eq 'HASH') {
669: foreach my $key (keys(%{$newenv})) {
670: my $refused = 0;
671: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
672: $refused = 1;
673: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 674: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 675: if (grep(/^\Q$role\E$/,@{$roles})) {
676: $refused = 0;
677: }
678: }
679: }
680: if ($refused) {
681: &logthis("<font color=\"blue\">WARNING: ".
682: "Attempt to modify environment ".$key." to ".$newenv->{$key}
683: .'</font>');
684: delete($newenv->{$key});
685: } else {
686: $env{$key}=$newenv->{$key};
687: }
688: }
689: my $opened = open(my $env_file,'+<',$env{'user.environment'});
690: if ($opened
691: && &timed_flock($env_file,LOCK_EX)
692: &&
693: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
694: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
695: while (my ($key,$value) = each(%{$newenv})) {
696: $disk_env{$key} = $value;
697: }
698: untie(%disk_env);
1.35 www 699: }
1.191 harris41 700: }
1.56 www 701: return 'ok';
702: }
703: # ----------------------------------------------------- Delete from Environment
704:
705: sub delenv {
1.1104 raeburn 706: my ($delthis,$regexp,$roles) = @_;
707: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
708: my $refused = 1;
709: if (ref($roles) eq 'ARRAY') {
710: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
711: if (grep(/^\Q$role\E$/,@{$roles})) {
712: $refused = 0;
713: }
714: }
715: if ($refused) {
716: &logthis("<font color=\"blue\">WARNING: ".
717: "Attempt to delete from environment ".$delthis);
718: return 'error';
719: }
1.56 www 720: }
1.917 albertel 721: my $opened = open(my $env_file,'+<',$env{'user.environment'});
722: if ($opened
1.915 albertel 723: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 724: &&
725: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
726: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 727: foreach my $key (keys(%disk_env)) {
1.987 raeburn 728: if ($regexp) {
729: if ($key=~/^$delthis/) {
730: delete($env{$key});
731: delete($disk_env{$key});
732: }
733: } else {
734: if ($key=~/^\Q$delthis\E/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: }
1.448 albertel 739: }
1.783 albertel 740: untie(%disk_env);
1.5 www 741: }
742: return 'ok';
1.369 albertel 743: }
744:
1.790 albertel 745: sub get_env_multiple {
746: my ($name) = @_;
747: my @values;
748: if (defined($env{$name})) {
749: # exists is it an array
750: if (ref($env{$name})) {
751: @values=@{ $env{$name} };
752: } else {
753: $values[0]=$env{$name};
754: }
755: }
756: return(@values);
757: }
758:
1.958 www 759: # ------------------------------------------------------------------- Locking
760:
761: sub set_lock {
762: my ($text)=@_;
763: $locknum++;
764: my $id=$$.'-'.$locknum;
765: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
766: 'session.lock.'.$id => $text});
767: return $id;
768: }
769:
770: sub get_locks {
771: my $num=0;
772: my %texts=();
773: foreach my $lock (split(/\,/,$env{'session.locks'})) {
774: if ($lock=~/\w/) {
775: $num++;
776: $texts{$lock}=$env{'session.lock.'.$lock};
777: }
778: }
779: return ($num,%texts);
780: }
781:
782: sub remove_lock {
783: my ($id)=@_;
784: my $newlocks='';
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if (($lock=~/\w/) && ($lock ne $id)) {
787: $newlocks.=','.$lock;
788: }
789: }
790: &appenv({'session.locks' => $newlocks});
791: &delenv('session.lock.'.$id);
792: }
793:
794: sub remove_all_locks {
795: my $activelocks=$env{'session.locks'};
796: foreach my $lock (split(/\,/,$env{'session.locks'})) {
797: if ($lock=~/\w/) {
798: &remove_lock($lock);
799: }
800: }
801: }
802:
803:
1.369 albertel 804: # ------------------------------------------ Find out current server userload
805: sub userload {
806: my $numusers=0;
807: {
808: opendir(LONIDS,$perlvar{'lonIDsDir'});
809: my $filename;
810: my $curtime=time;
811: while ($filename=readdir(LONIDS)) {
1.925 albertel 812: next if ($filename eq '.' || $filename eq '..');
813: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 814: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 815: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 816: }
817: closedir(LONIDS);
818: }
819: my $userloadpercent=0;
820: my $maxuserload=$perlvar{'lonUserLoadLim'};
821: if ($maxuserload) {
1.371 albertel 822: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 823: }
1.372 albertel 824: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 825: return $userloadpercent;
1.283 www 826: }
827:
1.1 albertel 828: # ------------------------------ Find server with least workload from spare.tab
1.11 www 829:
1.1 albertel 830: sub spareserver {
1.1083 raeburn 831: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 832: my $spare_server;
1.370 albertel 833: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 834: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
835: : $userloadpercent;
1.1083 raeburn 836: my ($uint_dom,$remotesessions);
837: if (($udom ne '') && (&domain($udom) ne '')) {
838: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
839: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
840: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
841: $remotesessions = $udomdefaults{'remotesessions'};
842: }
1.1123 raeburn 843: my $spareshash = &this_host_spares($udom);
844: if (ref($spareshash) eq 'HASH') {
845: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
846: foreach my $try_server (@{ $spareshash->{'primary'} }) {
847: if ($uint_dom) {
848: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
849: $try_server));
850: }
851: ($spare_server, $lowest_load) =
852: &compare_server_load($try_server, $spare_server, $lowest_load);
853: }
1.1083 raeburn 854: }
1.784 albertel 855:
1.1123 raeburn 856: my $found_server = ($spare_server ne '' && $lowest_load < 100);
857:
858: if (!$found_server) {
859: if (ref($spareshash->{'default'}) eq 'ARRAY') {
860: foreach my $try_server (@{ $spareshash->{'default'} }) {
861: if ($uint_dom) {
862: next unless (&spare_can_host($udom,$uint_dom,
863: $remotesessions,$try_server));
864: }
865: ($spare_server, $lowest_load) =
866: &compare_server_load($try_server, $spare_server, $lowest_load);
867: }
868: }
869: }
1.784 albertel 870: }
871:
872: if (!$want_server_name) {
1.968 raeburn 873: my $protocol = 'http';
874: if ($protocol{$spare_server} eq 'https') {
875: $protocol = $protocol{$spare_server};
876: }
1.1001 raeburn 877: if (defined($spare_server)) {
878: my $hostname = &hostname($spare_server);
1.1083 raeburn 879: if (defined($hostname)) {
1.1001 raeburn 880: $spare_server = $protocol.'://'.$hostname;
881: }
882: }
1.784 albertel 883: }
884: return $spare_server;
885: }
886:
887: sub compare_server_load {
1.1172.2.41 raeburn 888: my ($try_server, $spare_server, $lowest_load, $required) = @_;
889:
890: if ($required) {
891: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
892: my $remoterev = &get_server_loncaparev(undef,$try_server);
893: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
894: if (($major eq '' && $minor eq '') ||
895: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
896: return ($spare_server,$lowest_load);
897: }
898: }
1.784 albertel 899:
900: my $loadans = &reply('load', $try_server);
901: my $userloadans = &reply('userload',$try_server);
902:
903: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 904: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 905: }
906:
907: my $load;
908: if ($loadans =~ /\d/) {
909: if ($userloadans =~ /\d/) {
910: #both are numbers, pick the bigger one
911: $load = ($loadans > $userloadans) ? $loadans
912: : $userloadans;
1.411 albertel 913: } else {
1.784 albertel 914: $load = $loadans;
1.411 albertel 915: }
1.784 albertel 916: } else {
917: $load = $userloadans;
918: }
919:
920: if (($load =~ /\d/) && ($load < $lowest_load)) {
921: $spare_server = $try_server;
922: $lowest_load = $load;
1.370 albertel 923: }
1.784 albertel 924: return ($spare_server,$lowest_load);
1.202 matthew 925: }
1.914 albertel 926:
927: # --------------------------- ask offload servers if user already has a session
928: sub find_existing_session {
929: my ($udom,$uname) = @_;
1.1123 raeburn 930: my $spareshash = &this_host_spares($udom);
931: if (ref($spareshash) eq 'HASH') {
932: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
933: foreach my $try_server (@{ $spareshash->{'primary'} }) {
934: return $try_server if (&has_user_session($try_server, $udom, $uname));
935: }
936: }
937: if (ref($spareshash->{'default'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'default'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
1.914 albertel 942: }
943: return;
944: }
945:
946: # -------------------------------- ask if server already has a session for user
947: sub has_user_session {
948: my ($lonid,$udom,$uname) = @_;
949: my $result = &reply(join(':','userhassession',
950: map {&escape($_)} ($udom,$uname)),$lonid);
951: return 1 if ($result eq 'ok');
952:
953: return 0;
954: }
955:
1.1076 raeburn 956: # --------- determine least loaded server in a user's domain which allows login
957:
958: sub choose_server {
1.1172.2.47 raeburn 959: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 960: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 961: my %servers = &get_servers($udom);
1.1076 raeburn 962: my $lowest_load = 30000;
1.1172.2.47 raeburn 963: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
964: if ($skiploadbal) {
965: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
966: unless (defined($cached)) {
967: my $cachetime = 60*60*24;
968: my %domconfig =
969: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
970: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
971: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
972: $cachetime);
973: }
974: }
975: }
1.1076 raeburn 976: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 977: my $loginvia;
1.1172.2.47 raeburn 978: if ($skiploadbal) {
979: if (ref($balancers) eq 'HASH') {
980: next if (exists($balancers->{$lonhost}));
981: }
982: }
1.1115 raeburn 983: if ($checkloginvia) {
984: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 985: if ($loginvia) {
986: my ($server,$path) = split(/:/,$loginvia);
987: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 988: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 989: if ($login_host eq $server) {
990: $portal_path = $path;
1.1151 raeburn 991: $isredirect = 1;
1.1116 raeburn 992: }
993: } else {
994: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 995: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 996: if ($login_host eq $lonhost) {
997: $portal_path = '';
1.1151 raeburn 998: $isredirect = '';
1.1116 raeburn 999: }
1000: }
1001: } else {
1.1076 raeburn 1002: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1003: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1004: }
1005: }
1006: if ($login_host ne '') {
1.1116 raeburn 1007: $hostname = &hostname($login_host);
1.1076 raeburn 1008: }
1.1151 raeburn 1009: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1010: }
1011:
1.202 matthew 1012: # --------------------------------------------- Try to change a user's password
1013:
1014: sub changepass {
1.799 raeburn 1015: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1016: $currentpass = &escape($currentpass);
1017: $newpass = &escape($newpass);
1.1030 raeburn 1018: my $lonhost = $perlvar{'lonHostID'};
1019: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1020: $server);
1021: if (! $answer) {
1022: &logthis("No reply on password change request to $server ".
1023: "by $uname in domain $udom.");
1024: } elsif ($answer =~ "^ok") {
1025: &logthis("$uname in $udom successfully changed their password ".
1026: "on $server.");
1027: } elsif ($answer =~ "^pwchange_failure") {
1028: &logthis("$uname in $udom was unable to change their password ".
1029: "on $server. The action was blocked by either lcpasswd ".
1030: "or pwchange");
1031: } elsif ($answer =~ "^non_authorized") {
1032: &logthis("$uname in $udom did not get their password correct when ".
1033: "attempting to change it on $server.");
1034: } elsif ($answer =~ "^auth_mode_error") {
1035: &logthis("$uname in $udom attempted to change their password despite ".
1036: "not being locally or internally authenticated on $server.");
1037: } elsif ($answer =~ "^unknown_user") {
1038: &logthis("$uname in $udom attempted to change their password ".
1039: "on $server but were unable to because $server is not ".
1040: "their home server.");
1041: } elsif ($answer =~ "^refused") {
1042: &logthis("$server refused to change $uname in $udom password because ".
1043: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1044: } elsif ($answer =~ "invalid_client") {
1045: &logthis("$server refused to change $uname in $udom password because ".
1046: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1047: }
1048: return $answer;
1.1 albertel 1049: }
1050:
1.169 harris41 1051: # ----------------------- Try to determine user's current authentication scheme
1052:
1053: sub queryauthenticate {
1054: my ($uname,$udom)=@_;
1.456 albertel 1055: my $uhome=&homeserver($uname,$udom);
1056: if (!$uhome) {
1057: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1058: return 'no_host';
1059: }
1060: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1061: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1062: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1063: }
1.456 albertel 1064: return $answer;
1.169 harris41 1065: }
1066:
1.1 albertel 1067: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1068:
1.1 albertel 1069: sub authenticate {
1.1073 raeburn 1070: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1071: $upass=&escape($upass);
1072: $uname= &LONCAPA::clean_username($uname);
1.836 www 1073: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1074: my $newhome;
1.836 www 1075: if ((!$uhome) || ($uhome eq 'no_host')) {
1076: # Maybe the machine was offline and only re-appeared again recently?
1077: &reconlonc();
1078: # One more
1.952 raeburn 1079: $uhome=&homeserver($uname,$udom,1);
1080: if (($uhome eq 'no_host') && $checkdefauth) {
1081: if (defined(&domain($udom,'primary'))) {
1082: $newhome=&domain($udom,'primary');
1083: }
1084: if ($newhome ne '') {
1085: $uhome = $newhome;
1086: }
1087: }
1.836 www 1088: if ((!$uhome) || ($uhome eq 'no_host')) {
1089: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1090: return 'no_host';
1091: }
1.1 albertel 1092: }
1.1073 raeburn 1093: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1094: if ($answer eq 'authorized') {
1.952 raeburn 1095: if ($newhome) {
1096: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1097: return 'no_account_on_host';
1098: } else {
1099: &logthis("User $uname at $udom authorized by $uhome");
1100: return $uhome;
1101: }
1.471 albertel 1102: }
1103: if ($answer eq 'non_authorized') {
1104: &logthis("User $uname at $udom rejected by $uhome");
1105: return 'no_host';
1.9 www 1106: }
1.471 albertel 1107: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1108: return 'no_host';
1109: }
1110:
1.1073 raeburn 1111: sub can_host_session {
1.1074 raeburn 1112: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1113: my $canhost = 1;
1.1074 raeburn 1114: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1115: if (ref($remotesessions) eq 'HASH') {
1116: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1117: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1118: $canhost = 0;
1119: } else {
1120: $canhost = 1;
1121: }
1122: }
1123: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1124: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1125: $canhost = 1;
1126: } else {
1127: $canhost = 0;
1128: }
1129: }
1130: if ($canhost) {
1131: if ($remotesessions->{'version'} ne '') {
1132: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1133: if ($reqmajor ne '' && $reqminor ne '') {
1134: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1135: my $major = $1;
1136: my $minor = $2;
1137: if (($major < $reqmajor ) ||
1138: (($major == $reqmajor) && ($minor < $reqminor))) {
1139: $canhost = 0;
1140: }
1141: } else {
1142: $canhost = 0;
1143: }
1144: }
1145: }
1146: }
1147: }
1148: if ($canhost) {
1149: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1150: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1151: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1152: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1153: if (($uint_dom ne '') &&
1154: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1155: $canhost = 0;
1156: } else {
1157: $canhost = 1;
1158: }
1159: }
1160: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1161: if (($uint_dom ne '') &&
1162: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1163: $canhost = 1;
1164: } else {
1165: $canhost = 0;
1166: }
1167: }
1168: }
1169: }
1170: return $canhost;
1171: }
1172:
1.1083 raeburn 1173: sub spare_can_host {
1174: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1175: my $canhost=1;
1176: my @intdoms;
1177: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1178: if (ref($internet_names) eq 'ARRAY') {
1179: @intdoms = @{$internet_names};
1180: }
1181: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1182: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1183: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1184: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1185: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1186: $canhost = &can_host_session($udom,$try_server,$remoterev,
1187: $remotesessions,
1188: $defdomdefaults{'hostedsessions'});
1189: }
1190: return $canhost;
1191: }
1192:
1.1123 raeburn 1193: sub this_host_spares {
1194: my ($dom) = @_;
1.1126 raeburn 1195: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1196: my @hosts = ¤t_machine_ids();
1197: foreach my $lonhost (@hosts) {
1198: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1199: $dom_in_use = $dom;
1200: $lonhost_in_use = $lonhost;
1.1123 raeburn 1201: last;
1202: }
1203: }
1.1126 raeburn 1204: if ($dom_in_use ne '') {
1205: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1206: }
1207: if (ref($result) ne 'HASH') {
1208: $lonhost_in_use = $perlvar{'lonHostID'};
1209: $dom_in_use = &host_domain($lonhost_in_use);
1210: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1211: if (ref($result) ne 'HASH') {
1212: $result = \%spareid;
1213: }
1214: }
1215: return $result;
1216: }
1217:
1218: sub spares_for_offload {
1219: my ($dom_in_use,$lonhost_in_use) = @_;
1220: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1221: if (defined($cached)) {
1222: return $result;
1223: } else {
1.1126 raeburn 1224: my $cachetime = 60*60*24;
1225: my %domconfig =
1226: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1227: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1228: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1229: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1230: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1231: }
1232: }
1233: }
1234: }
1.1126 raeburn 1235: return;
1.1123 raeburn 1236: }
1237:
1.1129 raeburn 1238: sub get_lonbalancer_config {
1239: my ($servers) = @_;
1240: my ($currbalancer,$currtargets);
1241: if (ref($servers) eq 'HASH') {
1242: foreach my $server (keys(%{$servers})) {
1243: my %what = (
1244: spareid => 1,
1245: perlvar => 1,
1246: );
1247: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1248: if ($result eq 'ok') {
1249: if (ref($returnhash) eq 'HASH') {
1250: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1251: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1252: $currbalancer = $server;
1253: $currtargets = {};
1254: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1255: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1256: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1257: }
1258: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1259: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1260: }
1261: }
1262: last;
1263: }
1264: }
1265: }
1266: }
1267: }
1268: }
1269: return ($currbalancer,$currtargets);
1270: }
1271:
1272: sub check_loadbalancing {
1273: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1274: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1275: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1276: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1277: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1278: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1279: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1280: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1281: my $serverhomedom = &host_domain($lonhost);
1282:
1283: my $cachetime = 60*60*24;
1284:
1285: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1286: $dom_in_use = $udom;
1287: $homeintdom = 1;
1288: } else {
1289: $dom_in_use = $serverhomedom;
1290: }
1291: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1292: unless (defined($cached)) {
1293: my %domconfig =
1294: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1295: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1296: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1297: }
1298: }
1299: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1300: ($is_balancer,$currtargets,$currrules) =
1301: &check_balancer_result($result,@hosts);
1.1129 raeburn 1302: if ($is_balancer) {
1303: if (ref($currrules) eq 'HASH') {
1304: if ($homeintdom) {
1305: if ($uname ne '') {
1306: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1307: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1308: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1309: $rule_in_effect = $currrules->{'_LC_author'};
1310: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1311: $rule_in_effect = $currrules->{'_LC_adv'}
1312: }
1313: }
1314: if ($rule_in_effect eq '') {
1315: my %userenv = &userenvironment($udom,$uname,'inststatus');
1316: if ($userenv{'inststatus'} ne '') {
1317: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1318: my ($othertitle,$usertypes,$types) =
1319: &Apache::loncommon::sorted_inst_types($udom);
1320: if (ref($types) eq 'ARRAY') {
1321: foreach my $type (@{$types}) {
1322: if (grep(/^\Q$type\E$/,@statuses)) {
1323: if (exists($currrules->{$type})) {
1324: $rule_in_effect = $currrules->{$type};
1325: }
1326: }
1327: }
1328: }
1329: } else {
1330: if (exists($currrules->{'default'})) {
1331: $rule_in_effect = $currrules->{'default'};
1332: }
1333: }
1334: }
1335: } else {
1336: if (exists($currrules->{'default'})) {
1337: $rule_in_effect = $currrules->{'default'};
1338: }
1339: }
1340: } else {
1341: if ($currrules->{'_LC_external'} ne '') {
1342: $rule_in_effect = $currrules->{'_LC_external'};
1343: }
1344: }
1345: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1346: $uname,$udom);
1347: }
1348: }
1349: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1350: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1351: unless (defined($cached)) {
1352: my %domconfig =
1353: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1354: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1355: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1356: }
1357: }
1358: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1359: ($is_balancer,$currtargets,$currrules) =
1360: &check_balancer_result($result,@hosts);
1361: if ($is_balancer) {
1.1129 raeburn 1362: if (ref($currrules) eq 'HASH') {
1363: if ($currrules->{'_LC_internetdom'} ne '') {
1364: $rule_in_effect = $currrules->{'_LC_internetdom'};
1365: }
1366: }
1367: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1368: $uname,$udom);
1369: }
1370: } else {
1371: if ($perlvar{'lonBalancer'} eq 'yes') {
1372: $is_balancer = 1;
1373: $offloadto = &this_host_spares($dom_in_use);
1374: }
1375: }
1376: } else {
1377: if ($perlvar{'lonBalancer'} eq 'yes') {
1378: $is_balancer = 1;
1379: $offloadto = &this_host_spares($dom_in_use);
1380: }
1381: }
1.1172.2.5 raeburn 1382: if ($is_balancer) {
1383: my $lowest_load = 30000;
1384: if (ref($offloadto) eq 'HASH') {
1385: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1386: foreach my $try_server (@{$offloadto->{'primary'}}) {
1387: ($otherserver,$lowest_load) =
1388: &compare_server_load($try_server,$otherserver,$lowest_load);
1389: }
1.1129 raeburn 1390: }
1.1172.2.5 raeburn 1391: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1392:
1.1172.2.5 raeburn 1393: if (!$found_server) {
1394: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1395: foreach my $try_server (@{$offloadto->{'default'}}) {
1396: ($otherserver,$lowest_load) =
1397: &compare_server_load($try_server,$otherserver,$lowest_load);
1398: }
1399: }
1400: }
1401: } elsif (ref($offloadto) eq 'ARRAY') {
1402: if (@{$offloadto} == 1) {
1403: $otherserver = $offloadto->[0];
1404: } elsif (@{$offloadto} > 1) {
1405: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1406: ($otherserver,$lowest_load) =
1407: &compare_server_load($try_server,$otherserver,$lowest_load);
1408: }
1409: }
1410: }
1.1172.2.5 raeburn 1411: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1412: $is_balancer = 0;
1413: if ($uname ne '' && $udom ne '') {
1414: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1415:
1416: &appenv({'user.loadbalexempt' => $lonhost,
1417: 'user.loadbalcheck.time' => time});
1418: }
1.1129 raeburn 1419: }
1420: }
1421: }
1422: return ($is_balancer,$otherserver);
1423: }
1424:
1.1172.2.12 raeburn 1425: sub check_balancer_result {
1426: my ($result,@hosts) = @_;
1427: my ($is_balancer,$currtargets,$currrules);
1428: if (ref($result) eq 'HASH') {
1429: if ($result->{'lonhost'} ne '') {
1430: my $currbalancer = $result->{'lonhost'};
1431: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1432: $is_balancer = 1;
1433: $currtargets = $result->{'targets'};
1434: $currrules = $result->{'rules'};
1435: }
1436: } else {
1437: foreach my $key (keys(%{$result})) {
1438: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1439: (ref($result->{$key}) eq 'HASH')) {
1440: $is_balancer = 1;
1441: $currrules = $result->{$key}{'rules'};
1442: $currtargets = $result->{$key}{'targets'};
1443: last;
1444: }
1445: }
1446: }
1447: }
1448: return ($is_balancer,$currtargets,$currrules);
1449: }
1450:
1.1129 raeburn 1451: sub get_loadbalancer_targets {
1452: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1453: my $offloadto;
1.1172.2.4 raeburn 1454: if ($rule_in_effect eq 'none') {
1455: return [$perlvar{'lonHostID'}];
1456: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1457: $offloadto = $currtargets;
1458: } else {
1459: if ($rule_in_effect eq 'homeserver') {
1460: my $homeserver = &homeserver($uname,$udom);
1461: if ($homeserver ne 'no_host') {
1462: $offloadto = [$homeserver];
1463: }
1464: } elsif ($rule_in_effect eq 'externalbalancer') {
1465: my %domconfig =
1466: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1467: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1468: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1469: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1470: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1471: }
1472: }
1473: } else {
1.1172.2.7 raeburn 1474: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1475: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1476: if (&hostname($remotebalancer) ne '') {
1477: $offloadto = [$remotebalancer];
1478: }
1479: }
1480: } elsif (&hostname($rule_in_effect) ne '') {
1481: $offloadto = [$rule_in_effect];
1482: }
1483: }
1484: return $offloadto;
1485: }
1486:
1.1127 raeburn 1487: sub internet_dom_servers {
1488: my ($dom) = @_;
1489: my (%uniqservers,%servers);
1490: my $primaryserver = &hostname(&domain($dom,'primary'));
1491: my @machinedoms = &machine_domains($primaryserver);
1492: foreach my $mdom (@machinedoms) {
1493: my %currservers = %servers;
1494: my %server = &get_servers($mdom);
1495: %servers = (%currservers,%server);
1496: }
1497: my %by_hostname;
1498: foreach my $id (keys(%servers)) {
1499: push(@{$by_hostname{$servers{$id}}},$id);
1500: }
1501: foreach my $hostname (sort(keys(%by_hostname))) {
1502: if (@{$by_hostname{$hostname}} > 1) {
1503: my $match = 0;
1504: foreach my $id (@{$by_hostname{$hostname}}) {
1505: if (&host_domain($id) eq $dom) {
1506: $uniqservers{$id} = $hostname;
1507: $match = 1;
1508: }
1509: }
1510: unless ($match) {
1511: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1512: }
1513: } else {
1514: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1515: }
1516: }
1517: return %uniqservers;
1518: }
1519:
1.1 albertel 1520: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1521:
1.599 albertel 1522: my %homecache;
1.1 albertel 1523: sub homeserver {
1.230 stredwic 1524: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1525: my $index="$uname:$udom";
1.426 albertel 1526:
1.599 albertel 1527: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1528:
1529: my %servers = &get_servers($udom,'library');
1530: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1531: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1532: exists($badServerCache{$tryserver}));
1.841 albertel 1533:
1534: my $answer=reply("home:$udom:$uname",$tryserver);
1535: if ($answer eq 'found') {
1536: delete($badServerCache{$tryserver});
1537: return $homecache{$index}=$tryserver;
1538: } elsif ($answer eq 'no_host') {
1539: $badServerCache{$tryserver}=1;
1540: }
1.1 albertel 1541: }
1542: return 'no_host';
1.70 www 1543: }
1544:
1545: # ------------------------------------- Find the usernames behind a list of IDs
1546:
1547: sub idget {
1548: my ($udom,@ids)=@_;
1549: my %returnhash=();
1550:
1.841 albertel 1551: my %servers = &get_servers($udom,'library');
1552: foreach my $tryserver (keys(%servers)) {
1553: my $idlist=join('&',@ids);
1554: $idlist=~tr/A-Z/a-z/;
1555: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1556: my @answer=();
1557: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1558: @answer=split(/\&/,$reply);
1559: } ;
1560: my $i;
1561: for ($i=0;$i<=$#ids;$i++) {
1562: if ($answer[$i]) {
1563: $returnhash{$ids[$i]}=$answer[$i];
1564: }
1565: }
1566: }
1.70 www 1567: return %returnhash;
1568: }
1569:
1570: # ------------------------------------- Find the IDs behind a list of usernames
1571:
1572: sub idrget {
1573: my ($udom,@unames)=@_;
1574: my %returnhash=();
1.800 albertel 1575: foreach my $uname (@unames) {
1576: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1577: }
1.70 www 1578: return %returnhash;
1579: }
1580:
1581: # ------------------------------- Store away a list of names and associated IDs
1582:
1583: sub idput {
1584: my ($udom,%ids)=@_;
1585: my %servers=();
1.800 albertel 1586: foreach my $uname (keys(%ids)) {
1587: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1588: my $uhom=&homeserver($uname,$udom);
1.70 www 1589: if ($uhom ne 'no_host') {
1.800 albertel 1590: my $id=&escape($ids{$uname});
1.70 www 1591: $id=~tr/A-Z/a-z/;
1.800 albertel 1592: my $esc_unam=&escape($uname);
1.70 www 1593: if ($servers{$uhom}) {
1.800 albertel 1594: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1595: } else {
1.800 albertel 1596: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1597: }
1598: }
1.191 harris41 1599: }
1.800 albertel 1600: foreach my $server (keys(%servers)) {
1601: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1602: }
1.344 www 1603: }
1604:
1.1172.2.30 raeburn 1605: # ---------------------------------------- Delete unwanted IDs from ids.db file
1606:
1607: sub iddel {
1608: my ($udom,$idshashref,$uhome)=@_;
1609: my %result=();
1610: unless (ref($idshashref) eq 'HASH') {
1611: return %result;
1612: }
1613: my %servers=();
1614: while (my ($id,$uname) = each(%{$idshashref})) {
1615: my $uhom;
1616: if ($uhome) {
1617: $uhom = $uhome;
1618: } else {
1619: $uhom=&homeserver($uname,$udom);
1620: }
1621: if ($uhom ne 'no_host') {
1622: if ($servers{$uhom}) {
1623: $servers{$uhom}.='&'.&escape($id);
1624: } else {
1625: $servers{$uhom}=&escape($id);
1626: }
1627: }
1628: }
1629: foreach my $server (keys(%servers)) {
1630: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1631: }
1632: return %result;
1633: }
1634:
1.1023 raeburn 1635: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1636: sub dump_dom {
1.1165 droeschl 1637: my ($namespace, $udom, $regexp) = @_;
1638:
1639: $udom ||= $env{'user.domain'};
1640:
1641: return () unless $udom;
1642:
1643: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1644: }
1645:
1.1023 raeburn 1646: # ------------------------------------------ get items from domain db files
1.806 raeburn 1647:
1648: sub get_dom {
1.860 raeburn 1649: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1650: my $items='';
1651: foreach my $item (@$storearr) {
1652: $items.=&escape($item).'&';
1653: }
1654: $items=~s/\&$//;
1.860 raeburn 1655: if (!$udom) {
1656: $udom=$env{'user.domain'};
1657: if (defined(&domain($udom,'primary'))) {
1658: $uhome=&domain($udom,'primary');
1659: } else {
1.874 albertel 1660: undef($uhome);
1.860 raeburn 1661: }
1662: } else {
1663: if (!$uhome) {
1664: if (defined(&domain($udom,'primary'))) {
1665: $uhome=&domain($udom,'primary');
1666: }
1667: }
1668: }
1669: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1670: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1671: my %returnhash;
1.875 albertel 1672: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1673: return %returnhash;
1674: }
1.806 raeburn 1675: my @pairs=split(/\&/,$rep);
1676: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1677: return @pairs;
1678: }
1679: my $i=0;
1680: foreach my $item (@$storearr) {
1681: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1682: $i++;
1683: }
1684: return %returnhash;
1685: } else {
1.880 banghart 1686: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1687: }
1688: }
1689:
1690: # -------------------------------------------- put items in domain db files
1691:
1692: sub put_dom {
1.860 raeburn 1693: my ($namespace,$storehash,$udom,$uhome)=@_;
1694: if (!$udom) {
1695: $udom=$env{'user.domain'};
1696: if (defined(&domain($udom,'primary'))) {
1697: $uhome=&domain($udom,'primary');
1698: } else {
1.874 albertel 1699: undef($uhome);
1.860 raeburn 1700: }
1701: } else {
1702: if (!$uhome) {
1703: if (defined(&domain($udom,'primary'))) {
1704: $uhome=&domain($udom,'primary');
1705: }
1706: }
1707: }
1708: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1709: my $items='';
1710: foreach my $item (keys(%$storehash)) {
1711: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1712: }
1713: $items=~s/\&$//;
1714: return &reply("putdom:$udom:$namespace:$items",$uhome);
1715: } else {
1.860 raeburn 1716: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1717: }
1718: }
1719:
1.1023 raeburn 1720: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1721: sub newput_dom {
1.1023 raeburn 1722: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1723: my $result;
1724: if (!$udom) {
1725: $udom=$env{'user.domain'};
1726: }
1.1023 raeburn 1727: if ($udom) {
1728: my $uname = &get_domainconfiguser($udom);
1729: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1730: }
1731: return $result;
1732: }
1733:
1.1023 raeburn 1734: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1735: sub del_dom {
1.1023 raeburn 1736: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1737: if (ref($storearr) eq 'ARRAY') {
1738: if (!$udom) {
1739: $udom=$env{'user.domain'};
1740: }
1.1023 raeburn 1741: if ($udom) {
1742: my $uname = &get_domainconfiguser($udom);
1743: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1744: }
1745: }
1746: }
1747:
1.1023 raeburn 1748: # ----------------------------------construct domainconfig user for a domain
1749: sub get_domainconfiguser {
1750: my ($udom) = @_;
1751: return $udom.'-domainconfig';
1752: }
1753:
1.837 raeburn 1754: sub retrieve_inst_usertypes {
1755: my ($udom) = @_;
1756: my (%returnhash,@order);
1.989 raeburn 1757: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1758: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1759: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1760: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1761: } else {
1762: if (defined(&domain($udom,'primary'))) {
1763: my $uhome=&domain($udom,'primary');
1764: my $rep=&reply("inst_usertypes:$udom",$uhome);
1765: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1766: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1767: return (\%returnhash,\@order);
1768: }
1769: my ($hashitems,$orderitems) = split(/:/,$rep);
1770: my @pairs=split(/\&/,$hashitems);
1771: foreach my $item (@pairs) {
1772: my ($key,$value)=split(/=/,$item,2);
1773: $key = &unescape($key);
1774: next if ($key =~ /^error: 2 /);
1775: $returnhash{$key}=&thaw_unescape($value);
1776: }
1777: my @esc_order = split(/\&/,$orderitems);
1778: foreach my $item (@esc_order) {
1779: push(@order,&unescape($item));
1780: }
1781: } else {
1.1172.2.44 raeburn 1782: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1783: }
1.1172.2.44 raeburn 1784: return (\%returnhash,\@order);
1.837 raeburn 1785: }
1786: }
1787:
1.868 raeburn 1788: sub is_domainimage {
1789: my ($url) = @_;
1790: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1791: if (&domain($1) ne '') {
1792: return '1';
1793: }
1794: }
1795: return;
1796: }
1797:
1.899 raeburn 1798: sub inst_directory_query {
1799: my ($srch) = @_;
1800: my $udom = $srch->{'srchdomain'};
1801: my %results;
1802: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1803: my $outcome;
1.899 raeburn 1804: if ($homeserver ne '') {
1.904 albertel 1805: my $queryid=&reply("querysend:instdirsearch:".
1806: &escape($srch->{'srchby'}).':'.
1807: &escape($srch->{'srchterm'}).':'.
1808: &escape($srch->{'srchtype'}),$homeserver);
1809: my $host=&hostname($homeserver);
1810: if ($queryid !~/^\Q$host\E\_/) {
1811: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1812: return;
1813: }
1814: my $response = &get_query_reply($queryid);
1815: my $maxtries = 5;
1816: my $tries = 1;
1817: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1818: $response = &get_query_reply($queryid);
1819: $tries ++;
1820: }
1821:
1822: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1823: if ($response eq 'unavailable') {
1824: $outcome = $response;
1825: } else {
1826: $outcome = 'ok';
1827: my @matches = split(/\n/,$response);
1828: foreach my $match (@matches) {
1829: my ($key,$value) = split(/=/,$match);
1830: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1831: }
1.899 raeburn 1832: }
1833: }
1834: }
1.909 raeburn 1835: return ($outcome,%results);
1.899 raeburn 1836: }
1837:
1838: sub usersearch {
1839: my ($srch) = @_;
1840: my $dom = $srch->{'srchdomain'};
1841: my %results;
1842: my %libserv = &all_library();
1843: my $query = 'usersearch';
1844: foreach my $tryserver (keys(%libserv)) {
1845: if (&host_domain($tryserver) eq $dom) {
1846: my $host=&hostname($tryserver);
1847: my $queryid=
1.911 raeburn 1848: &reply("querysend:".&escape($query).':'.
1849: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1850: &escape($srch->{'srchtype'}).':'.
1851: &escape($srch->{'srchterm'}),$tryserver);
1852: if ($queryid !~/^\Q$host\E\_/) {
1853: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1854: next;
1.899 raeburn 1855: }
1856: my $reply = &get_query_reply($queryid);
1857: my $maxtries = 1;
1858: my $tries = 1;
1859: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1860: $reply = &get_query_reply($queryid);
1861: $tries ++;
1862: }
1863: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1864: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1865: } else {
1.911 raeburn 1866: my @matches;
1867: if ($reply =~ /\n/) {
1868: @matches = split(/\n/,$reply);
1869: } else {
1870: @matches = split(/\&/,$reply);
1871: }
1.899 raeburn 1872: foreach my $match (@matches) {
1873: my ($uname,$udom,%userhash);
1.911 raeburn 1874: foreach my $entry (split(/:/,$match)) {
1875: my ($key,$value) =
1876: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1877: $userhash{$key} = $value;
1878: if ($key eq 'username') {
1879: $uname = $value;
1880: } elsif ($key eq 'domain') {
1881: $udom = $value;
1.911 raeburn 1882: }
1.899 raeburn 1883: }
1884: $results{$uname.':'.$udom} = \%userhash;
1885: }
1886: }
1887: }
1888: }
1889: return %results;
1890: }
1891:
1.912 raeburn 1892: sub get_instuser {
1893: my ($udom,$uname,$id) = @_;
1894: my $homeserver = &domain($udom,'primary');
1895: my ($outcome,%results);
1896: if ($homeserver ne '') {
1897: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1898: &escape($id).':'.&escape($udom),$homeserver);
1899: my $host=&hostname($homeserver);
1900: if ($queryid !~/^\Q$host\E\_/) {
1901: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1902: return;
1903: }
1904: my $response = &get_query_reply($queryid);
1905: my $maxtries = 5;
1906: my $tries = 1;
1907: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1908: $response = &get_query_reply($queryid);
1909: $tries ++;
1910: }
1911: if (!&error($response) && $response ne 'refused') {
1912: if ($response eq 'unavailable') {
1913: $outcome = $response;
1914: } else {
1915: $outcome = 'ok';
1916: my @matches = split(/\n/,$response);
1917: foreach my $match (@matches) {
1918: my ($key,$value) = split(/=/,$match);
1919: $results{&unescape($key)} = &thaw_unescape($value);
1920: }
1921: }
1922: }
1923: }
1924: my %userinfo;
1925: if (ref($results{$uname}) eq 'HASH') {
1926: %userinfo = %{$results{$uname}};
1927: }
1928: return ($outcome,%userinfo);
1929: }
1930:
1931: sub inst_rulecheck {
1.923 raeburn 1932: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1933: my %returnhash;
1934: if ($udom ne '') {
1935: if (ref($rules) eq 'ARRAY') {
1936: @{$rules} = map {&escape($_);} (@{$rules});
1937: my $rulestr = join(':',@{$rules});
1938: my $homeserver=&domain($udom,'primary');
1939: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1940: my $response;
1941: if ($item eq 'username') {
1942: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1943: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1944: $homeserver));
1.923 raeburn 1945: } elsif ($item eq 'id') {
1946: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1947: ':'.&escape($id).':'.$rulestr,
1948: $homeserver));
1.945 raeburn 1949: } elsif ($item eq 'selfcreate') {
1950: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1951: &escape($udom).':'.&escape($uname).
1952: ':'.$rulestr,$homeserver));
1.923 raeburn 1953: }
1.912 raeburn 1954: if ($response ne 'refused') {
1955: my @pairs=split(/\&/,$response);
1956: foreach my $item (@pairs) {
1957: my ($key,$value)=split(/=/,$item,2);
1958: $key = &unescape($key);
1959: next if ($key =~ /^error: 2 /);
1960: $returnhash{$key}=&thaw_unescape($value);
1961: }
1962: }
1963: }
1964: }
1965: }
1966: return %returnhash;
1967: }
1968:
1969: sub inst_userrules {
1.923 raeburn 1970: my ($udom,$check) = @_;
1.912 raeburn 1971: my (%ruleshash,@ruleorder);
1972: if ($udom ne '') {
1973: my $homeserver=&domain($udom,'primary');
1974: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1975: my $response;
1976: if ($check eq 'id') {
1977: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1978: $homeserver);
1.943 raeburn 1979: } elsif ($check eq 'email') {
1980: $response=&reply('instemailrules:'.&escape($udom),
1981: $homeserver);
1.923 raeburn 1982: } else {
1983: $response=&reply('instuserrules:'.&escape($udom),
1984: $homeserver);
1985: }
1.912 raeburn 1986: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1987: ($response ne 'unknown_cmd') &&
1.912 raeburn 1988: ($response ne 'no_such_host')) {
1989: my ($hashitems,$orderitems) = split(/:/,$response);
1990: my @pairs=split(/\&/,$hashitems);
1991: foreach my $item (@pairs) {
1992: my ($key,$value)=split(/=/,$item,2);
1993: $key = &unescape($key);
1994: next if ($key =~ /^error: 2 /);
1995: $ruleshash{$key}=&thaw_unescape($value);
1996: }
1997: my @esc_order = split(/\&/,$orderitems);
1998: foreach my $item (@esc_order) {
1999: push(@ruleorder,&unescape($item));
2000: }
2001: }
2002: }
2003: }
2004: return (\%ruleshash,\@ruleorder);
2005: }
2006:
1.976 raeburn 2007: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2008:
2009: sub get_domain_defaults {
1.1172.2.35 raeburn 2010: my ($domain,$ignore_cache) = @_;
2011: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2012: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2013: unless ($ignore_cache) {
2014: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2015: if (defined($cached)) {
2016: if (ref($result) eq 'HASH') {
2017: return %{$result};
2018: }
1.943 raeburn 2019: }
2020: }
2021: my %domdefaults;
2022: my %domconfig =
1.989 raeburn 2023: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2024: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2025: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2026: 'requestauthor','selfenrollment',
2027: 'coursecategories'],$domain);
1.1172.2.41 raeburn 2028: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2029: if (ref($domconfig{'defaults'}) eq 'HASH') {
2030: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2031: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2032: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2033: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2034: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2035: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2036: } else {
2037: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2038: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2039: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2040: }
1.976 raeburn 2041: if (ref($domconfig{'quotas'}) eq 'HASH') {
2042: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2043: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2044: } else {
2045: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2046: }
1.1172.2.6 raeburn 2047: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2048: foreach my $item (@usertools) {
2049: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2050: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2051: }
2052: }
1.1172.2.29 raeburn 2053: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2054: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2055: }
1.976 raeburn 2056: }
1.985 raeburn 2057: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2058: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2059: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2060: }
2061: }
1.1172.2.9 raeburn 2062: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2063: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2064: }
1.989 raeburn 2065: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2066: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2067: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2068: }
2069: }
1.1047 raeburn 2070: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.41 raeburn 2071: foreach my $type (@coursetypes) {
2072: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2073: unless ($type eq 'community') {
2074: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2075: }
2076: }
2077: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2078: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2079: }
1.1172.2.30 raeburn 2080: }
1.1047 raeburn 2081: }
1.1073 raeburn 2082: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2083: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2084: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2085: }
2086: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2087: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2088: }
2089: }
1.1172.2.41 raeburn 2090: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2091: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2092: my @settings = ('types','registered','enroll_dates','access_dates','section',
2093: 'approval','limit');
2094: foreach my $type (@coursetypes) {
2095: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2096: my @mgrdc = ();
2097: foreach my $item (@settings) {
2098: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2099: push(@mgrdc,$item);
2100: }
2101: }
2102: if (@mgrdc) {
2103: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2104: }
2105: }
2106: }
2107: }
2108: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2109: foreach my $type (@coursetypes) {
2110: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2111: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2112: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2113: }
2114: }
2115: }
2116: }
2117: }
1.1172.2.46 raeburn 2118: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2119: $domdefaults{'catauth'} = 'std';
2120: $domdefaults{'catunauth'} = 'std';
2121: if ($domconfig{'coursecategories'}{'auth'}) {
2122: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2123: }
2124: if ($domconfig{'coursecategories'}{'unauth'}) {
2125: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2126: }
2127: }
1.1172.2.23 raeburn 2128: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2129: return %domdefaults;
2130: }
2131:
1.344 www 2132: # --------------------------------------------------- Assign a key to a student
2133:
2134: sub assign_access_key {
1.364 www 2135: #
2136: # a valid key looks like uname:udom#comments
2137: # comments are being appended
2138: #
1.498 www 2139: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2140: $kdom=
1.620 albertel 2141: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2142: $knum=
1.620 albertel 2143: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2144: $cdom=
1.620 albertel 2145: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2146: $cnum=
1.620 albertel 2147: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2148: $udom=$env{'user.name'} unless (defined($udom));
2149: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2150: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2151: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2152: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2153: # assigned to this person
2154: # - this should not happen,
1.345 www 2155: # unless something went wrong
2156: # the first time around
2157: # ready to assign
1.364 www 2158: $logentry=$1.'; '.$logentry;
1.496 www 2159: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2160: $kdom,$knum) eq 'ok') {
1.345 www 2161: # key now belongs to user
1.346 www 2162: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2163: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2164: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2165: return 'ok';
2166: } else {
2167: return
2168: 'error: Count not permanently assign key, will need to be re-entered later.';
2169: }
2170: } else {
2171: return 'error: Could not assign key, try again later.';
2172: }
1.364 www 2173: } elsif (!$existing{$ckey}) {
1.345 www 2174: # the key does not exist
2175: return 'error: The key does not exist';
2176: } else {
2177: # the key is somebody else's
2178: return 'error: The key is already in use';
2179: }
1.344 www 2180: }
2181:
1.364 www 2182: # ------------------------------------------ put an additional comment on a key
2183:
2184: sub comment_access_key {
2185: #
2186: # a valid key looks like uname:udom#comments
2187: # comments are being appended
2188: #
2189: my ($ckey,$cdom,$cnum,$logentry)=@_;
2190: $cdom=
1.620 albertel 2191: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2192: $cnum=
1.620 albertel 2193: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2194: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2195: if ($existing{$ckey}) {
2196: $existing{$ckey}.='; '.$logentry;
2197: # ready to assign
1.367 www 2198: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2199: $cdom,$cnum) eq 'ok') {
2200: return 'ok';
2201: } else {
2202: return 'error: Count not store comment.';
2203: }
2204: } else {
2205: # the key does not exist
2206: return 'error: The key does not exist';
2207: }
2208: }
2209:
1.344 www 2210: # ------------------------------------------------------ Generate a set of keys
2211:
2212: sub generate_access_keys {
1.364 www 2213: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2214: $cdom=
1.620 albertel 2215: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2216: $cnum=
1.620 albertel 2217: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2218: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2219: unless (($cdom) && ($cnum)) { return 0; }
2220: if ($number>10000) { return 0; }
2221: sleep(2); # make sure don't get same seed twice
2222: srand(time()^($$+($$<<15))); # from "Programming Perl"
2223: my $total=0;
2224: for (my $i=1;$i<=$number;$i++) {
2225: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2226: sprintf("%lx",int(100000*rand)).'-'.
2227: sprintf("%lx",int(100000*rand));
2228: $newkey=~s/1/g/g; # folks mix up 1 and l
2229: $newkey=~s/0/h/g; # and also 0 and O
2230: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2231: if ($existing{$newkey}) {
2232: $i--;
2233: } else {
1.364 www 2234: if (&put('accesskeys',
2235: { $newkey => '# generated '.localtime().
1.620 albertel 2236: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2237: '; '.$logentry },
2238: $cdom,$cnum) eq 'ok') {
1.344 www 2239: $total++;
2240: }
2241: }
2242: }
1.620 albertel 2243: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2244: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2245: return $total;
2246: }
2247:
2248: # ------------------------------------------------------- Validate an accesskey
2249:
2250: sub validate_access_key {
2251: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2252: $cdom=
1.620 albertel 2253: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2254: $cnum=
1.620 albertel 2255: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2256: $udom=$env{'user.domain'} unless (defined($udom));
2257: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2258: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2259: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2260: }
2261:
2262: # ------------------------------------- Find the section of student in a course
1.652 albertel 2263: sub devalidate_getsection_cache {
2264: my ($udom,$unam,$courseid)=@_;
2265: my $hashid="$udom:$unam:$courseid";
2266: &devalidate_cache_new('getsection',$hashid);
2267: }
1.298 matthew 2268:
1.815 albertel 2269: sub courseid_to_courseurl {
2270: my ($courseid) = @_;
2271: #already url style courseid
2272: return $courseid if ($courseid =~ m{^/});
2273:
2274: if (exists($env{'course.'.$courseid.'.num'})) {
2275: my $cnum = $env{'course.'.$courseid.'.num'};
2276: my $cdom = $env{'course.'.$courseid.'.domain'};
2277: return "/$cdom/$cnum";
2278: }
2279:
2280: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2281: if (exists($courseinfo{'num'})) {
2282: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2283: }
2284:
2285: return undef;
2286: }
2287:
1.298 matthew 2288: sub getsection {
2289: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2290: my $cachetime=1800;
1.551 albertel 2291:
2292: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2293: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2294: if (defined($cached)) { return $result; }
2295:
1.298 matthew 2296: my %Pending;
2297: my %Expired;
2298: #
2299: # Each role can either have not started yet (pending), be active,
2300: # or have expired.
2301: #
2302: # If there is an active role, we are done.
2303: #
2304: # If there is more than one role which has not started yet,
2305: # choose the one which will start sooner
2306: # If there is one role which has not started yet, return it.
2307: #
2308: # If there is more than one expired role, choose the one which ended last.
2309: # If there is a role which has expired, return it.
2310: #
1.815 albertel 2311: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2312: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2313: foreach my $key (keys(%roleshash)) {
1.479 albertel 2314: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2315: my $section=$1;
2316: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2317: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2318: my $now=time;
1.548 albertel 2319: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2320: $Expired{$end}=$section;
2321: next;
2322: }
1.548 albertel 2323: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2324: $Pending{$start}=$section;
2325: next;
2326: }
1.599 albertel 2327: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2328: }
2329: #
2330: # Presumedly there will be few matching roles from the above
2331: # loop and the sorting time will be negligible.
2332: if (scalar(keys(%Pending))) {
2333: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2334: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2335: }
2336: if (scalar(keys(%Expired))) {
2337: my @sorted = sort {$a <=> $b} keys(%Expired);
2338: my $time = pop(@sorted);
1.599 albertel 2339: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2340: }
1.599 albertel 2341: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2342: }
1.70 www 2343:
1.599 albertel 2344: sub save_cache {
2345: &purge_remembered();
1.722 albertel 2346: #&Apache::loncommon::validate_page();
1.620 albertel 2347: undef(%env);
1.780 albertel 2348: undef($env_loaded);
1.599 albertel 2349: }
1.452 albertel 2350:
1.599 albertel 2351: my $to_remember=-1;
2352: my %remembered;
2353: my %accessed;
2354: my $kicks=0;
2355: my $hits=0;
1.849 albertel 2356: sub make_key {
2357: my ($name,$id) = @_;
1.872 albertel 2358: if (length($id) > 65
2359: && length(&escape($id)) > 200) {
2360: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2361: }
1.849 albertel 2362: return &escape($name.':'.$id);
2363: }
2364:
1.599 albertel 2365: sub devalidate_cache_new {
2366: my ($name,$id,$debug) = @_;
2367: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2368: $id=&make_key($name,$id);
1.599 albertel 2369: $memcache->delete($id);
2370: delete($remembered{$id});
2371: delete($accessed{$id});
2372: }
2373:
2374: sub is_cached_new {
2375: my ($name,$id,$debug) = @_;
1.849 albertel 2376: $id=&make_key($name,$id);
1.599 albertel 2377: if (exists($remembered{$id})) {
1.1133 foxr 2378: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2379: $accessed{$id}=[&gettimeofday()];
2380: $hits++;
2381: return ($remembered{$id},1);
2382: }
2383: my $value = $memcache->get($id);
2384: if (!(defined($value))) {
2385: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2386: return (undef,undef);
1.416 albertel 2387: }
1.599 albertel 2388: if ($value eq '__undef__') {
2389: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2390: $value=undef;
2391: }
2392: &make_room($id,$value,$debug);
2393: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2394: return ($value,1);
2395: }
2396:
2397: sub do_cache_new {
2398: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2399: $id=&make_key($name,$id);
1.599 albertel 2400: my $setvalue=$value;
2401: if (!defined($setvalue)) {
2402: $setvalue='__undef__';
2403: }
1.623 albertel 2404: if (!defined($time) ) {
2405: $time=600;
2406: }
1.599 albertel 2407: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2408: my $result = $memcache->set($id,$setvalue,$time);
2409: if (! $result) {
1.872 albertel 2410: &logthis("caching of id -> $id failed");
1.910 albertel 2411: $memcache->disconnect_all();
1.872 albertel 2412: }
1.600 albertel 2413: # need to make a copy of $value
1.919 albertel 2414: &make_room($id,$value,$debug);
1.599 albertel 2415: return $value;
2416: }
2417:
2418: sub make_room {
2419: my ($id,$value,$debug)=@_;
1.919 albertel 2420:
2421: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2422: : $value;
1.599 albertel 2423: if ($to_remember<0) { return; }
2424: $accessed{$id}=[&gettimeofday()];
2425: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2426: my $to_kick;
2427: my $max_time=0;
2428: foreach my $other (keys(%accessed)) {
2429: if (&tv_interval($accessed{$other}) > $max_time) {
2430: $to_kick=$other;
2431: $max_time=&tv_interval($accessed{$other});
2432: }
2433: }
2434: delete($remembered{$to_kick});
2435: delete($accessed{$to_kick});
2436: $kicks++;
2437: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2438: return;
2439: }
2440:
1.599 albertel 2441: sub purge_remembered {
1.604 albertel 2442: #&logthis("Tossing ".scalar(keys(%remembered)));
2443: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2444: undef(%remembered);
2445: undef(%accessed);
1.428 albertel 2446: }
1.70 www 2447: # ------------------------------------- Read an entry from a user's environment
2448:
2449: sub userenvironment {
2450: my ($udom,$unam,@what)=@_;
1.976 raeburn 2451: my $items;
2452: foreach my $item (@what) {
2453: $items.=&escape($item).'&';
2454: }
2455: $items=~s/\&$//;
1.70 www 2456: my %returnhash=();
1.1009 raeburn 2457: my $uhome = &homeserver($unam,$udom);
2458: unless ($uhome eq 'no_host') {
2459: my @answer=split(/\&/,
2460: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2461: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2462: return %returnhash;
2463: }
1.1009 raeburn 2464: my $i;
2465: for ($i=0;$i<=$#what;$i++) {
2466: $returnhash{$what[$i]}=&unescape($answer[$i]);
2467: }
1.70 www 2468: }
2469: return %returnhash;
1.1 albertel 2470: }
2471:
1.617 albertel 2472: # ---------------------------------------------------------- Get a studentphoto
2473: sub studentphoto {
2474: my ($udom,$unam,$ext) = @_;
2475: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2476: if (defined($env{'request.course.id'})) {
1.708 raeburn 2477: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2478: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2479: return(&retrievestudentphoto($udom,$unam,$ext));
2480: } else {
2481: my ($result,$perm_reqd)=
1.707 albertel 2482: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2483: if ($result eq 'ok') {
2484: if (!($perm_reqd eq 'yes')) {
2485: return(&retrievestudentphoto($udom,$unam,$ext));
2486: }
2487: }
2488: }
2489: }
2490: } else {
2491: my ($result,$perm_reqd) =
1.707 albertel 2492: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2493: if ($result eq 'ok') {
2494: if (!($perm_reqd eq 'yes')) {
2495: return(&retrievestudentphoto($udom,$unam,$ext));
2496: }
2497: }
2498: }
2499: return '/adm/lonKaputt/lonlogo_broken.gif';
2500: }
2501:
2502: sub retrievestudentphoto {
2503: my ($udom,$unam,$ext,$type) = @_;
2504: my $home=&Apache::lonnet::homeserver($unam,$udom);
2505: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2506: if ($ret eq 'ok') {
2507: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2508: if ($type eq 'thumbnail') {
2509: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2510: }
2511: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2512: return $tokenurl;
2513: } else {
2514: if ($type eq 'thumbnail') {
2515: return '/adm/lonKaputt/genericstudent_tn.gif';
2516: } else {
2517: return '/adm/lonKaputt/lonlogo_broken.gif';
2518: }
1.617 albertel 2519: }
2520: }
2521:
1.263 www 2522: # -------------------------------------------------------------------- New chat
2523:
2524: sub chatsend {
1.724 raeburn 2525: my ($newentry,$anon,$group)=@_;
1.620 albertel 2526: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2527: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2528: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2529: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2530: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2531: &escape($newentry)).':'.$group,$chome);
1.292 www 2532: }
2533:
2534: # ------------------------------------------ Find current version of a resource
2535:
2536: sub getversion {
2537: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2538: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2539: return ¤tversion(&filelocation('',$fname));
2540: }
2541:
2542: sub currentversion {
2543: my $fname=shift;
2544: my $author=$fname;
2545: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2546: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2547: my $home=&homeserver($uname,$udom);
1.292 www 2548: if ($home eq 'no_host') {
2549: return -1;
2550: }
1.1112 www 2551: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2552: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2553: return -1;
2554: }
1.1112 www 2555: return $answer;
1.263 www 2556: }
2557:
1.1111 www 2558: #
2559: # Return special version number of resource if set by override, empty otherwise
2560: #
2561: sub usedversion {
2562: my $fname=shift;
2563: unless ($fname) { $fname=$env{'request.uri'}; }
2564: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2565: if ($urlversion) { return $urlversion; }
2566: return '';
2567: }
2568:
1.1 albertel 2569: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2570:
1.1 albertel 2571: sub subscribe {
2572: my $fname=shift;
1.761 raeburn 2573: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2574: $fname=~s/[\n\r]//g;
1.1 albertel 2575: my $author=$fname;
2576: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2577: my ($udom,$uname)=split(/\//,$author);
2578: my $home=homeserver($uname,$udom);
1.335 albertel 2579: if ($home eq 'no_host') {
2580: return 'not_found';
1.1 albertel 2581: }
2582: my $answer=reply("sub:$fname",$home);
1.64 www 2583: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2584: $answer.=' by '.$home;
2585: }
1.1 albertel 2586: return $answer;
2587: }
2588:
1.8 www 2589: # -------------------------------------------------------------- Replicate file
2590:
2591: sub repcopy {
2592: my $filename=shift;
1.23 www 2593: $filename=~s/\/+/\//g;
1.1142 raeburn 2594: my $londocroot = $perlvar{'lonDocRoot'};
2595: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2596: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2597: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2598: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2599: return &repcopy_userfile($filename);
2600: }
1.532 albertel 2601: $filename=~s/[\n\r]//g;
1.8 www 2602: my $transname="$filename.in.transfer";
1.828 www 2603: # FIXME: this should flock
1.607 raeburn 2604: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2605: my $remoteurl=subscribe($filename);
1.64 www 2606: if ($remoteurl =~ /^con_lost by/) {
2607: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2608: return 'unavailable';
1.8 www 2609: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2610: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2611: return 'not_found';
1.64 www 2612: } elsif ($remoteurl =~ /^rejected by/) {
2613: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2614: return 'forbidden';
1.20 www 2615: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2616: return 'ok';
1.8 www 2617: } else {
1.290 www 2618: my $author=$filename;
2619: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2620: my ($udom,$uname)=split(/\//,$author);
2621: my $home=homeserver($uname,$udom);
2622: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2623: my @parts=split(/\//,$filename);
2624: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2625: if ($path ne "$londocroot/res") {
1.8 www 2626: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2627: return 'bad_request';
1.8 www 2628: }
2629: my $count;
2630: for ($count=5;$count<$#parts;$count++) {
2631: $path.="/$parts[$count]";
2632: if ((-e $path)!=1) {
2633: mkdir($path,0777);
2634: }
2635: }
2636: my $ua=new LWP::UserAgent;
2637: my $request=new HTTP::Request('GET',"$remoteurl");
2638: my $response=$ua->request($request,$transname);
2639: if ($response->is_error()) {
2640: unlink($transname);
2641: my $message=$response->status_line;
1.672 albertel 2642: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2643: ." LWP get: $message: $filename</font>");
1.607 raeburn 2644: return 'unavailable';
1.8 www 2645: } else {
1.16 www 2646: if ($remoteurl!~/\.meta$/) {
2647: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2648: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2649: if ($mresponse->is_error()) {
2650: unlink($filename.'.meta');
2651: &logthis(
1.672 albertel 2652: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2653: }
2654: }
1.8 www 2655: rename($transname,$filename);
1.607 raeburn 2656: return 'ok';
1.8 www 2657: }
1.290 www 2658: }
1.8 www 2659: }
1.330 www 2660: }
2661:
2662: # ------------------------------------------------ Get server side include body
2663: sub ssi_body {
1.381 albertel 2664: my ($filelink,%form)=@_;
1.606 matthew 2665: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2666: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2667: }
1.953 www 2668: my $output='';
2669: my $response;
1.980 raeburn 2670: if ($filelink=~/^https?\:/) {
1.954 raeburn 2671: ($output,$response)=&externalssi($filelink);
1.953 www 2672: } else {
1.1004 droeschl 2673: $filelink .= $filelink=~/\?/ ? '&' : '?';
2674: $filelink .= 'inhibitmenu=yes';
1.953 www 2675: ($output,$response)=&ssi($filelink,%form);
2676: }
1.778 albertel 2677: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2678: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2679: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2680: if (wantarray) {
2681: return ($output, $response);
2682: } else {
2683: return $output;
2684: }
1.8 www 2685: }
2686:
1.15 www 2687: # --------------------------------------------------------- Server Side Include
2688:
1.782 albertel 2689: sub absolute_url {
2690: my ($host_name) = @_;
2691: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2692: if ($host_name eq '') {
2693: $host_name = $ENV{'SERVER_NAME'};
2694: }
2695: return $protocol.$host_name;
2696: }
2697:
1.942 foxr 2698: #
2699: # Server side include.
2700: # Parameters:
2701: # fn Possibly encrypted resource name/id.
2702: # form Hash that describes how the rendering should be done
2703: # and other things.
1.944 foxr 2704: # Returns:
1.950 raeburn 2705: # Scalar context: The content of the response.
2706: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2707: #
1.15 www 2708: sub ssi {
2709:
1.944 foxr 2710: my ($fn,%form)=@_;
1.15 www 2711: my $ua=new LWP::UserAgent;
1.23 www 2712: my $request;
1.711 albertel 2713:
2714: $form{'no_update_last_known'}=1;
1.895 albertel 2715: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2716: if (%form) {
1.782 albertel 2717: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2718: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2719: } else {
1.782 albertel 2720: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2721: }
2722:
1.15 www 2723: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2724: my $response= $ua->request($request);
1.944 foxr 2725: if (wantarray) {
1.1172.2.3 raeburn 2726: return ($response->content, $response);
1.944 foxr 2727: } else {
1.1172.2.3 raeburn 2728: return $response->content;
1.942 foxr 2729: }
1.324 www 2730: }
2731:
2732: sub externalssi {
2733: my ($url)=@_;
2734: my $ua=new LWP::UserAgent;
2735: my $request=new HTTP::Request('GET',$url);
2736: my $response=$ua->request($request);
1.954 raeburn 2737: if (wantarray) {
2738: return ($response->content, $response);
2739: } else {
2740: return $response->content;
2741: }
1.15 www 2742: }
1.254 www 2743:
1.492 albertel 2744: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2745:
2746: sub allowuploaded {
2747: my ($srcurl,$url)=@_;
2748: $url=&clutter(&declutter($url));
2749: my $dir=$url;
2750: $dir=~s/\/[^\/]+$//;
2751: my %httpref=();
2752: my $httpurl=&hreflocation('',$url);
2753: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2754: &Apache::lonnet::appenv(\%httpref);
1.254 www 2755: }
1.477 raeburn 2756:
1.1172.2.13 raeburn 2757: #
2758: # Determine if the current user should be able to edit a particular resource,
2759: # when viewing in course context.
2760: # (a) When viewing resource used to determine if "Edit" item is included in
2761: # Functions.
2762: # (b) When displaying folder contents in course editor, used to determine if
2763: # "Edit" link will be displayed alongside resource.
2764: #
2765: # input: six args -- filename (decluttered), course number, course domain,
2766: # url, symb (if registered) and group (if this is a group
2767: # item -- e.g., bulletin board, group page etc.).
2768: # output: array of five scalars --
2769: # $cfile -- url for file editing if editable on current server
2770: # $home -- homeserver of resource (i.e., for author if published,
2771: # or course if uploaded.).
2772: # $switchserver -- 1 if server switch will be needed.
2773: # $forceedit -- 1 if icon/link should be to go to edit mode
2774: # $forceview -- 1 if icon/link should be to go to view mode
2775: #
2776:
2777: sub can_edit_resource {
2778: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2779: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2780: #
2781: # For aboutme pages user can only edit his/her own.
2782: #
2783: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2784: my ($sdom,$sname) = ($1,$2);
2785: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2786: $home = $env{'user.home'};
2787: $cfile = $resurl;
2788: if ($env{'form.forceedit'}) {
2789: $forceview = 1;
2790: } else {
2791: $forceedit = 1;
2792: }
2793: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2794: } else {
2795: return;
2796: }
2797: }
2798:
2799: if ($env{'request.course.id'}) {
2800: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2801: if ($group ne '') {
2802: # if this is a group homepage or group bulletin board, check group privs
2803: my $allowed = 0;
2804: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2805: if ((&allowed('mdg',$env{'request.course.id'}.
2806: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2807: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2808: $allowed = 1;
2809: }
2810: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2811: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2812: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2813: $allowed = 1;
2814: }
2815: }
2816: if ($allowed) {
2817: $home=&homeserver($cnum,$cdom);
2818: if ($env{'form.forceedit'}) {
2819: $forceview = 1;
2820: } else {
2821: $forceedit = 1;
2822: }
2823: $cfile = $resurl;
2824: } else {
2825: return;
2826: }
2827: } else {
1.1172.2.15 raeburn 2828: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2829: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2830: return;
2831: }
2832: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2833: #
2834: # No edit allowed where CC has switched to student role.
2835: #
2836: return;
2837: }
2838: }
2839: }
2840:
2841: if ($file ne '') {
2842: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2843: if (&is_course_upload($file,$cnum,$cdom)) {
2844: $uploaded = 1;
2845: $incourse = 1;
2846: if ($file =~/\.(htm|html|css|js|txt)$/) {
2847: $cfile = &hreflocation('',$file);
2848: if ($env{'form.forceedit'}) {
2849: $forceview = 1;
2850: } else {
2851: $forceedit = 1;
2852: }
2853: }
2854: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2855: $incourse = 1;
2856: if ($env{'form.forceedit'}) {
2857: $forceview = 1;
2858: } else {
2859: $forceedit = 1;
2860: }
2861: $cfile = $resurl;
2862: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2863: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2864: $incourse = 1;
2865: if ($env{'form.forceedit'}) {
2866: $forceview = 1;
2867: } else {
2868: $forceedit = 1;
2869: }
2870: $cfile = $resurl;
2871: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2872: $incourse = 1;
2873: $cfile = $resurl.'/smpedit';
2874: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2875: $incourse = 1;
2876: if ($env{'form.forceedit'}) {
2877: $forceview = 1;
2878: } else {
2879: $forceedit = 1;
2880: }
2881: $cfile = $resurl;
1.1172.2.15 raeburn 2882: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2883: $incourse = 1;
2884: if ($env{'form.forceedit'}) {
2885: $forceview = 1;
2886: } else {
2887: $forceedit = 1;
2888: }
2889: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2890: }
2891: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2892: my $template = '/res/lib/templates/simpleproblem.problem';
2893: if (&is_on_map($template)) {
2894: $incourse = 1;
2895: $forceview = 1;
2896: $cfile = $template;
2897: }
2898: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2899: $incourse = 1;
2900: if ($env{'form.forceedit'}) {
2901: $forceview = 1;
2902: } else {
2903: $forceedit = 1;
2904: }
2905: $cfile = $resurl;
2906: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2907: $incourse = 1;
2908: $forceview = 1;
2909: if ($symb) {
2910: my ($map,$id,$res)=&decode_symb($symb);
2911: $env{'request.symb'} = $symb;
2912: $cfile = &clutter($res);
2913: } else {
2914: $cfile = $env{'form.suppurl'};
2915: $cfile =~ s{^http://}{};
2916: $cfile = '/adm/wrapper/ext/'.$cfile;
2917: }
1.1172.2.31 raeburn 2918: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2919: if ($env{'form.forceedit'}) {
2920: $forceview = 1;
2921: } else {
2922: $forceedit = 1;
2923: }
2924: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2925: }
2926: }
2927: if ($uploaded || $incourse) {
2928: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2929: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2930: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2931: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2932: # Check that the user has permission to edit this resource
2933: my $setpriv = 1;
2934: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2935: if (defined($cfudom)) {
2936: $home=&homeserver($cfuname,$cfudom);
2937: $cfile=$file;
2938: }
2939: }
2940: if (($cfile ne '') && (!$incourse || $uploaded) &&
2941: (($home ne '') && ($home ne 'no_host'))) {
2942: my @ids=¤t_machine_ids();
2943: unless (grep(/^\Q$home\E$/,@ids)) {
2944: $switchserver=1;
2945: }
2946: }
2947: }
2948: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2949: }
2950:
2951: sub is_course_upload {
2952: my ($file,$cnum,$cdom) = @_;
2953: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2954: $uploadpath =~ s{^\/}{};
2955: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2956: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2957: return 1;
2958: }
2959: return;
2960: }
2961:
2962: sub in_course {
2963: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2964: if ($hideprivileged) {
2965: my $skipuser;
1.1172.2.23 raeburn 2966: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2967: my @possdoms = ($cdom);
2968: if ($coursehash{'checkforpriv'}) {
2969: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2970: }
2971: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2972: $skipuser = 1;
2973: if ($coursehash{'nothideprivileged'}) {
2974: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2975: my $user;
2976: if ($item =~ /:/) {
2977: $user = $item;
2978: } else {
2979: $user = join(':',split(/[\@]/,$item));
2980: }
2981: if ($user eq $uname.':'.$udom) {
2982: undef($skipuser);
2983: last;
2984: }
2985: }
2986: }
2987: if ($skipuser) {
2988: return 0;
2989: }
2990: }
2991: }
2992: $type ||= 'any';
2993: if (!defined($cdom) || !defined($cnum)) {
2994: my $cid = $env{'request.course.id'};
2995: $cdom = $env{'course.'.$cid.'.domain'};
2996: $cnum = $env{'course.'.$cid.'.num'};
2997: }
2998: my $typesref;
2999: if (($type eq 'any') || ($type eq 'all')) {
3000: $typesref = ['active','previous','future'];
3001: } elsif ($type eq 'previous' || $type eq 'future') {
3002: $typesref = [$type];
3003: }
3004: my %roles = &get_my_roles($uname,$udom,'userroles',
3005: $typesref,undef,[$cdom]);
3006: my ($tmp) = keys(%roles);
3007: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3008: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3009: if (@course_roles > 0) {
3010: return 1;
3011: }
3012: return 0;
3013: }
3014:
1.478 albertel 3015: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3016: # input: action, courseID, current domain, intended
1.637 raeburn 3017: # path to file, source of file, instruction to parse file for objects,
3018: # ref to hash for embedded objects,
3019: # ref to hash for codebase of java objects.
1.1095 raeburn 3020: # reference to scalar to accommodate mime type determined
3021: # from File::MMagic if $parser = parse.
1.637 raeburn 3022: #
1.485 raeburn 3023: # output: url to file (if action was uploaddoc),
3024: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3025: #
1.478 albertel 3026: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3027: # course.
1.477 raeburn 3028: #
1.478 albertel 3029: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3030: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3031: # course's home server.
1.477 raeburn 3032: #
1.478 albertel 3033: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3034: # be copied from $source (current location) to
3035: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3036: # and will then be copied to
3037: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3038: # course's home server.
1.485 raeburn 3039: #
1.481 raeburn 3040: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3041: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3042: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3043: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3044: # in course's home server.
1.637 raeburn 3045: #
1.477 raeburn 3046:
3047: sub process_coursefile {
1.1095 raeburn 3048: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3049: $mimetype)=@_;
1.477 raeburn 3050: my $fetchresult;
1.638 albertel 3051: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3052: if ($action eq 'propagate') {
1.638 albertel 3053: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3054: $home);
1.481 raeburn 3055: } else {
1.477 raeburn 3056: my $fpath = '';
3057: my $fname = $file;
1.478 albertel 3058: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3059: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3060: my $filepath = &build_filepath($fpath);
1.481 raeburn 3061: if ($action eq 'copy') {
3062: if ($source eq '') {
3063: $fetchresult = 'no source file';
3064: return $fetchresult;
3065: } else {
3066: my $destination = $filepath.'/'.$fname;
3067: rename($source,$destination);
3068: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3069: $home);
1.481 raeburn 3070: }
3071: } elsif ($action eq 'uploaddoc') {
3072: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3073: print $fh $env{'form.'.$source};
1.481 raeburn 3074: close($fh);
1.637 raeburn 3075: if ($parser eq 'parse') {
1.1024 raeburn 3076: my $mm = new File::MMagic;
1.1095 raeburn 3077: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3078: if ($type eq 'text/html') {
1.1024 raeburn 3079: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3080: unless ($parse_result eq 'ok') {
3081: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3082: }
1.637 raeburn 3083: }
1.1095 raeburn 3084: if (ref($mimetype)) {
3085: $$mimetype = $type;
3086: }
1.637 raeburn 3087: }
1.477 raeburn 3088: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3089: $home);
1.481 raeburn 3090: if ($fetchresult eq 'ok') {
3091: return '/uploaded/'.$fpath.'/'.$fname;
3092: } else {
3093: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3094: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3095: return '/adm/notfound.html';
3096: }
1.477 raeburn 3097: }
3098: }
1.485 raeburn 3099: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3100: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3101: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3102: }
3103: return $fetchresult;
3104: }
3105:
1.637 raeburn 3106: sub build_filepath {
3107: my ($fpath) = @_;
3108: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3109: unless ($fpath eq '') {
3110: my @parts=split('/',$fpath);
3111: foreach my $part (@parts) {
3112: $filepath.= '/'.$part;
3113: if ((-e $filepath)!=1) {
3114: mkdir($filepath,0777);
3115: }
3116: }
3117: }
3118: return $filepath;
3119: }
3120:
3121: sub store_edited_file {
1.638 albertel 3122: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3123: my $file = $primary_url;
3124: $file =~ s#^/uploaded/$docudom/$docuname/##;
3125: my $fpath = '';
3126: my $fname = $file;
3127: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3128: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3129: my $filepath = &build_filepath($fpath);
3130: open(my $fh,'>'.$filepath.'/'.$fname);
3131: print $fh $content;
3132: close($fh);
1.638 albertel 3133: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3134: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3135: $home);
1.637 raeburn 3136: if ($$fetchresult eq 'ok') {
3137: return '/uploaded/'.$fpath.'/'.$fname;
3138: } else {
1.638 albertel 3139: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3140: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3141: return '/adm/notfound.html';
3142: }
3143: }
3144:
1.531 albertel 3145: sub clean_filename {
1.831 albertel 3146: my ($fname,$args)=@_;
1.315 www 3147: # Replace Windows backslashes by forward slashes
1.257 www 3148: $fname=~s/\\/\//g;
1.831 albertel 3149: if (!$args->{'keep_path'}) {
3150: # Get rid of everything but the actual filename
3151: $fname=~s/^.*\/([^\/]+)$/$1/;
3152: }
1.315 www 3153: # Replace spaces by underscores
3154: $fname=~s/\s+/\_/g;
3155: # Replace all other weird characters by nothing
1.831 albertel 3156: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3157: # Replace all .\d. sequences with _\d. so they no longer look like version
3158: # numbers
3159: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3160: return $fname;
3161: }
1.1051 raeburn 3162: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3163: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3164: # image with the same aspect ratio as the original, but with dimensions which do
3165: # not exceed $resizewidth and $resizeheight.
3166:
1.984 neumanie 3167: sub resizeImage {
1.1051 raeburn 3168: my ($img_path,$resizewidth,$resizeheight) = @_;
3169: my $ima = Image::Magick->new;
3170: my $resized;
3171: if (-e $img_path) {
3172: $ima->Read($img_path);
3173: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3174: my $width = $ima->Get('width');
3175: my $height = $ima->Get('height');
3176: if ($width > $resizewidth) {
3177: my $factor = $width/$resizewidth;
3178: my $newheight = $height/$factor;
3179: $ima->Scale(width=>$resizewidth,height=>$newheight);
3180: $resized = 1;
3181: }
3182: }
3183: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3184: my $width = $ima->Get('width');
3185: my $height = $ima->Get('height');
3186: if ($height > $resizeheight) {
3187: my $factor = $height/$resizeheight;
3188: my $newwidth = $width/$factor;
3189: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3190: $resized = 1;
3191: }
3192: }
3193: if ($resized) {
3194: $ima->Write($img_path);
3195: }
3196: }
3197: return;
1.977 amueller 3198: }
3199:
1.608 albertel 3200: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3201: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3202: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3203: # $context - possible values: coursedoc, existingfile, overwrite,
3204: # canceloverwrite, or ''.
3205: # if 'coursedoc': upload to the current course
3206: # if 'existingfile': write file to tmp/overwrites directory
3207: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3208: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3209: # $subdir - directory in userfile to store the file into
1.858 raeburn 3210: # $parser - instruction to parse file for objects ($parser = parse)
3211: # $allfiles - reference to hash for embedded objects
3212: # $codebase - reference to hash for codebase of java objects
3213: # $desuname - username for permanent storage of uploaded file
3214: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3215: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3216: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3217: # $resizewidth - width (pixels) to which to resize uploaded image
3218: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3219: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3220: # from File::MMagic.
1.858 raeburn 3221: #
1.686 albertel 3222: # output: url of file in userspace, or error: <message>
3223: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3224:
1.531 albertel 3225: sub userfileupload {
1.1090 raeburn 3226: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3227: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3228: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3229: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3230: $fname=&clean_filename($fname);
1.1090 raeburn 3231: # See if there is anything left
1.257 www 3232: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3233: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3234: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3235: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3236: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3237: my $now = time;
1.1090 raeburn 3238: my $filepath;
1.1095 raeburn 3239: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3240: $filepath = 'tmp/helprequests/'.$now;
3241: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3242: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3243: '_'.$env{'user.domain'}.'/pending';
3244: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3245: my ($docuname,$docudom);
3246: if ($destudom) {
3247: $docudom = $destudom;
3248: } else {
3249: $docudom = $env{'user.domain'};
3250: }
3251: if ($destuname) {
3252: $docuname = $destuname;
3253: } else {
3254: $docuname = $env{'user.name'};
3255: }
3256: if (exists($env{'form.group'})) {
3257: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3258: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3259: }
3260: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3261: if ($context eq 'canceloverwrite') {
3262: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3263: if (-e $tempfile) {
3264: my @info = stat($tempfile);
3265: if ($info[9] eq $env{'form.timestamp'}) {
3266: unlink($tempfile);
3267: }
3268: }
3269: return;
1.523 raeburn 3270: }
3271: }
1.1090 raeburn 3272: # Create the directory if not present
1.741 raeburn 3273: my @parts=split(/\//,$filepath);
3274: my $fullpath = $perlvar{'lonDaemons'};
3275: for (my $i=0;$i<@parts;$i++) {
3276: $fullpath .= '/'.$parts[$i];
3277: if ((-e $fullpath)!=1) {
3278: mkdir($fullpath,0777);
3279: }
3280: }
3281: open(my $fh,'>'.$fullpath.'/'.$fname);
3282: print $fh $env{'form.'.$formname};
3283: close($fh);
1.1090 raeburn 3284: if ($context eq 'existingfile') {
3285: my @info = stat($fullpath.'/'.$fname);
3286: return ($fullpath.'/'.$fname,$info[9]);
3287: } else {
3288: return $fullpath.'/'.$fname;
3289: }
1.523 raeburn 3290: }
1.995 raeburn 3291: if ($subdir eq 'scantron') {
3292: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3293: } else {
1.995 raeburn 3294: $fname="$subdir/$fname";
3295: }
1.1090 raeburn 3296: if ($context eq 'coursedoc') {
1.638 albertel 3297: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3298: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3299: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3300: return &finishuserfileupload($docuname,$docudom,
3301: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3302: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3303: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3304: } else {
1.1172.2.21 raeburn 3305: if ($env{'form.folder'}) {
3306: $fname=$env{'form.folder'}.'/'.$fname;
3307: }
1.638 albertel 3308: return &process_coursefile('uploaddoc',$docuname,$docudom,
3309: $fname,$formname,$parser,
1.1095 raeburn 3310: $allfiles,$codebase,$mimetype);
1.481 raeburn 3311: }
1.719 banghart 3312: } elsif (defined($destuname)) {
3313: my $docuname=$destuname;
3314: my $docudom=$destudom;
1.860 raeburn 3315: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3316: $parser,$allfiles,$codebase,
1.1051 raeburn 3317: $thumbwidth,$thumbheight,
1.1095 raeburn 3318: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3319: } else {
1.638 albertel 3320: my $docuname=$env{'user.name'};
3321: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3322: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3323: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3324: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3325: }
1.860 raeburn 3326: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3327: $parser,$allfiles,$codebase,
1.1051 raeburn 3328: $thumbwidth,$thumbheight,
1.1095 raeburn 3329: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3330: }
1.271 www 3331: }
3332:
3333: sub finishuserfileupload {
1.860 raeburn 3334: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3335: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3336: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3337: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3338:
1.860 raeburn 3339: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3340: $file=$fname;
3341: if ($fname=~m|/|) {
3342: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3343: $path.=$fnamepath.'/';
3344: }
1.259 www 3345: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3346: my $count;
3347: for ($count=4;$count<=$#parts;$count++) {
3348: $filepath.="/$parts[$count]";
3349: if ((-e $filepath)!=1) {
3350: mkdir($filepath,0777);
3351: }
3352: }
1.984 neumanie 3353:
1.258 www 3354: # Save the file
3355: {
1.701 albertel 3356: if (!open(FH,'>'.$filepath.'/'.$file)) {
3357: &logthis('Failed to create '.$filepath.'/'.$file);
3358: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3359: return '/adm/notfound.html';
3360: }
1.1090 raeburn 3361: if ($context eq 'overwrite') {
1.1117 foxr 3362: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3363: my $target = $filepath.'/'.$file;
3364: if (-e $source) {
3365: my @info = stat($source);
3366: if ($info[9] eq $env{'form.timestamp'}) {
3367: unless (&File::Copy::move($source,$target)) {
3368: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3369: return "Moving from $source failed";
3370: }
3371: } else {
3372: return "Temporary file: $source had unexpected date/time for last modification";
3373: }
3374: } else {
3375: return "Temporary file: $source missing";
3376: }
3377: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3378: &logthis('Failed to write to '.$filepath.'/'.$file);
3379: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3380: return '/adm/notfound.html';
3381: }
1.570 albertel 3382: close(FH);
1.1051 raeburn 3383: if ($resizewidth && $resizeheight) {
3384: my $mm = new File::MMagic;
3385: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3386: if ($mime_type =~ m{^image/}) {
3387: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3388: }
1.977 amueller 3389: }
1.258 www 3390: }
1.1152 raeburn 3391: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3392: if (ref($mimetype)) {
3393: if ($$mimetype eq '') {
3394: my $mm = new File::MMagic;
3395: my $type = $mm->checktype_filename($filepath.'/'.$file);
3396: $$mimetype = $type;
3397: }
3398: }
3399: }
1.637 raeburn 3400: if ($parser eq 'parse') {
1.1152 raeburn 3401: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3402: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3403: $allfiles,$codebase);
3404: unless ($parse_result eq 'ok') {
3405: &logthis('Failed to parse '.$filepath.$file.
3406: ' for embedded media: '.$parse_result);
3407: }
1.637 raeburn 3408: }
3409: }
1.860 raeburn 3410: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3411: my $input = $filepath.'/'.$file;
3412: my $output = $filepath.'/'.'tn-'.$file;
3413: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3414: system("convert -sample $thumbsize $input $output");
3415: if (-e $filepath.'/'.'tn-'.$file) {
3416: $fetchthumb = 1;
3417: }
3418: }
1.858 raeburn 3419:
1.259 www 3420: # Notify homeserver to grep it
3421: #
1.984 neumanie 3422: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3423: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3424: if ($fetchresult eq 'ok') {
1.860 raeburn 3425: if ($fetchthumb) {
3426: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3427: if ($thumbresult ne 'ok') {
3428: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3429: $docuhome.': '.$thumbresult);
3430: }
3431: }
1.259 www 3432: #
1.258 www 3433: # Return the URL to it
1.494 albertel 3434: return '/uploaded/'.$path.$file;
1.263 www 3435: } else {
1.494 albertel 3436: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3437: ': '.$fetchresult);
1.263 www 3438: return '/adm/notfound.html';
1.858 raeburn 3439: }
1.493 albertel 3440: }
3441:
1.637 raeburn 3442: sub extract_embedded_items {
1.961 raeburn 3443: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3444: my @state = ();
1.1164 raeburn 3445: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3446: my %javafiles = (
3447: codebase => '',
3448: code => '',
3449: archive => ''
3450: );
3451: my %mediafiles = (
3452: src => '',
3453: movie => '',
3454: );
1.648 raeburn 3455: my $p;
3456: if ($content) {
3457: $p = HTML::LCParser->new($content);
3458: } else {
1.961 raeburn 3459: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3460: }
1.641 albertel 3461: while (my $t=$p->get_token()) {
1.640 albertel 3462: if ($t->[0] eq 'S') {
3463: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3464: push(@state, $tagname);
1.648 raeburn 3465: if (lc($tagname) eq 'allow') {
3466: &add_filetype($allfiles,$attr->{'src'},'src');
3467: }
1.640 albertel 3468: if (lc($tagname) eq 'img') {
3469: &add_filetype($allfiles,$attr->{'src'},'src');
3470: }
1.886 albertel 3471: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3472: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3473: &add_filetype($allfiles,$attr->{'href'},'href');
3474: }
1.886 albertel 3475: }
1.645 raeburn 3476: if (lc($tagname) eq 'script') {
1.1164 raeburn 3477: my $src;
1.645 raeburn 3478: if ($attr->{'archive'} =~ /\.jar$/i) {
3479: &add_filetype($allfiles,$attr->{'archive'},'archive');
3480: } else {
1.1164 raeburn 3481: if ($attr->{'src'} ne '') {
3482: $src = $attr->{'src'};
3483: &add_filetype($allfiles,$src,'src');
3484: }
3485: }
3486: my $text = $p->get_trimmed_text();
3487: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3488: my @swfargs = split(/,/,$1);
3489: foreach my $item (@swfargs) {
3490: $item =~ s/["']//g;
3491: $item =~ s/^\s+//;
3492: $item =~ s/\s+$//;
3493: }
3494: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3495: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3496: push(@{$related{$swfargs[0]}},$swfargs[2]);
3497: } else {
3498: $related{$swfargs[0]} = [$swfargs[2]];
3499: }
3500: }
1.645 raeburn 3501: }
3502: }
3503: if (lc($tagname) eq 'link') {
3504: if (lc($attr->{'rel'}) eq 'stylesheet') {
3505: &add_filetype($allfiles,$attr->{'href'},'href');
3506: }
3507: }
1.640 albertel 3508: if (lc($tagname) eq 'object' ||
3509: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3510: foreach my $item (keys(%javafiles)) {
3511: $javafiles{$item} = '';
3512: }
1.1164 raeburn 3513: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3514: $lastids{lc($tagname)} = $attr->{'id'};
3515: }
1.640 albertel 3516: }
3517: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3518: my $name = lc($attr->{'name'});
3519: foreach my $item (keys(%javafiles)) {
3520: if ($name eq $item) {
3521: $javafiles{$item} = $attr->{'value'};
3522: last;
3523: }
3524: }
1.1164 raeburn 3525: my $pathfrom;
1.640 albertel 3526: foreach my $item (keys(%mediafiles)) {
3527: if ($name eq $item) {
1.1164 raeburn 3528: $pathfrom = $attr->{'value'};
3529: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3530: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3531: last;
3532: }
3533: }
1.1164 raeburn 3534: if ($name eq 'flashvars') {
3535: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3536: }
3537: if ($pathfrom ne '') {
3538: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3539: $pathfrom);
3540: }
1.640 albertel 3541: }
3542: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3543: foreach my $item (keys(%javafiles)) {
3544: if ($attr->{$item}) {
3545: $javafiles{$item} = $attr->{$item};
3546: last;
3547: }
3548: }
3549: foreach my $item (keys(%mediafiles)) {
3550: if ($attr->{$item}) {
3551: &add_filetype($allfiles,$attr->{$item},$item);
3552: last;
3553: }
3554: }
1.1164 raeburn 3555: if (lc($tagname) eq 'embed') {
3556: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3557: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3558: $attr->{'src'});
3559: }
3560: }
1.640 albertel 3561: }
1.1172.2.35 raeburn 3562: if (lc($tagname) eq 'iframe') {
3563: my $src = $attr->{'src'} ;
3564: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3565: &add_filetype($allfiles,$src,'src');
3566: } elsif ($src =~ m{^/}) {
3567: if ($env{'request.course.id'}) {
3568: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3569: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3570: my $url = &hreflocation('',$fullpath);
3571: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3572: my $relpath = $1;
3573: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3574: &add_filetype($allfiles,$1,'src');
3575: }
3576: }
3577: }
3578: }
3579: }
1.1164 raeburn 3580: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3581: pop(@state);
1.1164 raeburn 3582: }
1.640 albertel 3583: } elsif ($t->[0] eq 'E') {
3584: my ($tagname) = ($t->[1]);
3585: if ($javafiles{'codebase'} ne '') {
3586: $javafiles{'codebase'} .= '/';
3587: }
3588: if (lc($tagname) eq 'applet' ||
3589: lc($tagname) eq 'object' ||
3590: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3591: ) {
3592: foreach my $item (keys(%javafiles)) {
3593: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3594: my $file=$javafiles{'codebase'}.$javafiles{$item};
3595: &add_filetype($allfiles,$file,$item);
3596: }
3597: }
3598: }
3599: pop @state;
3600: }
3601: }
1.1164 raeburn 3602: foreach my $id (sort(keys(%flashvars))) {
3603: if ($shockwave{$id} ne '') {
3604: my @pairs = split(/\&/,$flashvars{$id});
3605: foreach my $pair (@pairs) {
3606: my ($key,$value) = split(/\=/,$pair);
3607: if ($key eq 'thumb') {
3608: &add_filetype($allfiles,$value,$key);
3609: } elsif ($key eq 'content') {
3610: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3611: my ($ext) = ($value =~ /\.([^.]+)$/);
3612: if ($ext ne '') {
3613: &add_filetype($allfiles,$path.$value,$ext);
3614: }
3615: }
3616: }
3617: }
3618: }
1.637 raeburn 3619: return 'ok';
3620: }
3621:
1.639 albertel 3622: sub add_filetype {
3623: my ($allfiles,$file,$type)=@_;
3624: if (exists($allfiles->{$file})) {
3625: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3626: push(@{$allfiles->{$file}}, &escape($type));
3627: }
3628: } else {
3629: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3630: }
3631: }
3632:
1.1164 raeburn 3633: sub embedded_dependency {
3634: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3635: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3636: if (($identifier ne '') &&
3637: (ref($related->{$identifier}) eq 'ARRAY') &&
3638: ($pathfrom ne '')) {
3639: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3640: foreach my $dep (@{$related->{$identifier}}) {
3641: &add_filetype($allfiles,$path.$dep,'object');
3642: }
3643: }
3644: }
3645: return;
3646: }
3647:
1.493 albertel 3648: sub removeuploadedurl {
1.984 neumanie 3649: my ($url)=@_;
3650: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3651: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3652: }
3653:
3654: sub removeuserfile {
3655: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3656: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3657: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3658: if ($result eq 'ok') {
1.798 raeburn 3659: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3660: my $metafile = $fname.'.meta';
3661: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3662: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3663: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3664: my $sqlresult =
1.823 albertel 3665: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3666: 'portfolio_metadata',$group,
3667: 'delete');
1.798 raeburn 3668: }
3669: }
3670: return $result;
1.257 www 3671: }
1.15 www 3672:
1.530 albertel 3673: sub mkdiruserfile {
3674: my ($docuname,$docudom,$dir)=@_;
3675: my $home=&homeserver($docuname,$docudom);
3676: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3677: }
3678:
1.531 albertel 3679: sub renameuserfile {
3680: my ($docuname,$docudom,$old,$new)=@_;
3681: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3682: my $result = &reply("renameuserfile:$docudom:$docuname:".
3683: &escape("$old").':'.&escape("$new"),$home);
3684: if ($result eq 'ok') {
3685: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3686: my $oldmeta = $old.'.meta';
3687: my $newmeta = $new.'.meta';
3688: my $metaresult =
3689: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3690: my $url = "/uploaded/$docudom/$docuname/$old";
3691: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3692: my $sqlresult =
1.823 albertel 3693: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3694: 'portfolio_metadata',$group,
3695: 'delete');
1.798 raeburn 3696: }
3697: }
3698: return $result;
1.531 albertel 3699: }
3700:
1.14 www 3701: # ------------------------------------------------------------------------- Log
3702:
3703: sub log {
3704: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3705: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3706: }
3707:
3708: # ------------------------------------------------------------------ Course Log
1.352 www 3709: #
3710: # This routine flushes several buffers of non-mission-critical nature
3711: #
1.157 www 3712:
3713: sub flushcourselogs {
1.352 www 3714: &logthis('Flushing log buffers');
3715: #
3716: # course logs
3717: # This is a log of all transactions in a course, which can be used
3718: # for data mining purposes
3719: #
3720: # It also collects the courseid database, which lists last transaction
3721: # times and course titles for all courseids
3722: #
3723: my %courseidbuffer=();
1.921 raeburn 3724: foreach my $crsid (keys(%courselogs)) {
1.352 www 3725: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3726: &escape($courselogs{$crsid}),
3727: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3728: delete $courselogs{$crsid};
3729: } else {
3730: &logthis('Failed to flush log buffer for '.$crsid);
3731: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3732: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3733: " exceeded maximum size, deleting.</font>");
3734: delete $courselogs{$crsid};
3735: }
1.352 www 3736: }
1.920 raeburn 3737: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3738: 'description' => $coursedescrbuf{$crsid},
3739: 'inst_code' => $courseinstcodebuf{$crsid},
3740: 'type' => $coursetypebuf{$crsid},
3741: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3742: };
1.191 harris41 3743: }
1.352 www 3744: #
3745: # Write course id database (reverse lookup) to homeserver of courses
3746: # Is used in pickcourse
3747: #
1.840 albertel 3748: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3749: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3750: $courseidbuffer{$crs_home},
3751: $crs_home,'timeonly');
1.352 www 3752: }
3753: #
3754: # File accesses
3755: # Writes to the dynamic metadata of resources to get hit counts, etc.
3756: #
1.449 matthew 3757: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3758: if ($entry =~ /___count$/) {
3759: my ($dom,$name);
1.807 albertel 3760: ($dom,$name,undef)=
1.811 albertel 3761: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3762: if (! defined($dom) || $dom eq '' ||
3763: ! defined($name) || $name eq '') {
1.620 albertel 3764: my $cid = $env{'request.course.id'};
3765: $dom = $env{'request.'.$cid.'.domain'};
3766: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3767: }
1.450 matthew 3768: my $value = $accesshash{$entry};
3769: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3770: my %temphash=($url => $value);
1.449 matthew 3771: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3772: if ($result eq 'ok') {
3773: delete $accesshash{$entry};
3774: }
3775: } else {
1.811 albertel 3776: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3777: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3778: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3779: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3780: delete $accesshash{$entry};
3781: }
1.185 www 3782: }
1.191 harris41 3783: }
1.352 www 3784: #
3785: # Roles
3786: # Reverse lookup of user roles for course faculty/staff and co-authorship
3787: #
1.800 albertel 3788: foreach my $entry (keys(%userrolehash)) {
1.351 www 3789: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3790: split(/\:/,$entry);
3791: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3792: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3793: $rudom,$runame) eq 'ok') {
3794: delete $userrolehash{$entry};
3795: }
3796: }
1.662 raeburn 3797: #
3798: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3799: #
3800: my %domrolebuffer = ();
1.1000 raeburn 3801: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3802: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3803: if ($domrolebuffer{$rudom}) {
3804: $domrolebuffer{$rudom}.='&'.&escape($entry).
3805: '='.&escape($domainrolehash{$entry});
3806: } else {
3807: $domrolebuffer{$rudom}.=&escape($entry).
3808: '='.&escape($domainrolehash{$entry});
3809: }
3810: delete $domainrolehash{$entry};
3811: }
3812: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3813: my %servers = &get_servers($dom,'library');
3814: foreach my $tryserver (keys(%servers)) {
3815: unless (&reply('domroleput:'.$dom.':'.
3816: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3817: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3818: }
1.662 raeburn 3819: }
3820: }
1.186 www 3821: $dumpcount++;
1.157 www 3822: }
3823:
3824: sub courselog {
3825: my $what=shift;
1.158 www 3826: $what=time.':'.$what;
1.620 albertel 3827: unless ($env{'request.course.id'}) { return ''; }
3828: $coursedombuf{$env{'request.course.id'}}=
3829: $env{'course.'.$env{'request.course.id'}.'.domain'};
3830: $coursenumbuf{$env{'request.course.id'}}=
3831: $env{'course.'.$env{'request.course.id'}.'.num'};
3832: $coursehombuf{$env{'request.course.id'}}=
3833: $env{'course.'.$env{'request.course.id'}.'.home'};
3834: $coursedescrbuf{$env{'request.course.id'}}=
3835: $env{'course.'.$env{'request.course.id'}.'.description'};
3836: $courseinstcodebuf{$env{'request.course.id'}}=
3837: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3838: $courseownerbuf{$env{'request.course.id'}}=
3839: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3840: $coursetypebuf{$env{'request.course.id'}}=
3841: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3842: if (defined $courselogs{$env{'request.course.id'}}) {
3843: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3844: } else {
1.620 albertel 3845: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3846: }
1.620 albertel 3847: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3848: &flushcourselogs();
3849: }
1.158 www 3850: }
3851:
3852: sub courseacclog {
3853: my $fnsymb=shift;
1.620 albertel 3854: unless ($env{'request.course.id'}) { return ''; }
3855: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3856: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3857: $what.=':POST';
1.583 matthew 3858: # FIXME: Probably ought to escape things....
1.800 albertel 3859: foreach my $key (keys(%env)) {
3860: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3861: my $formitem = $1;
3862: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3863: $what.=':'.$formitem.'='.$env{$key};
3864: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3865: $what.=':'.$formitem.'='.$env{$key};
3866: }
1.158 www 3867: }
1.191 harris41 3868: }
1.583 matthew 3869: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3870: # FIXME: We should not be depending on a form parameter that someone
3871: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3872: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3873: $what.= ':POST';
3874: # FIXME: Probably ought to escape things....
3875: foreach my $element ('courseexp','crsfulltext','crsrelated',
3876: 'crsdiscuss') {
1.620 albertel 3877: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3878: }
3879: }
1.158 www 3880: }
3881: &courselog($what);
1.149 www 3882: }
3883:
1.185 www 3884: sub countacc {
3885: my $url=&declutter(shift);
1.458 matthew 3886: return if (! defined($url) || $url eq '');
1.620 albertel 3887: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3888: #
3889: # Mark that this url was used in this course
3890: #
1.620 albertel 3891: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3892: #
3893: # Increase the access count for this resource in this child process
3894: #
1.281 www 3895: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3896: $accesshash{$key}++;
1.185 www 3897: }
1.349 www 3898:
1.361 www 3899: sub linklog {
3900: my ($from,$to)=@_;
3901: $from=&declutter($from);
3902: $to=&declutter($to);
3903: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3904: $accesshash{$to.'___'.$from.'___goto'}=1;
3905: }
1.1160 www 3906:
3907: sub statslog {
3908: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3909: if ($users<2) { return; }
3910: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3911: 'course' => $env{'request.course.id'},
3912: 'sections' => '"all"',
3913: 'num_students' => $users,
3914: 'part' => $part,
3915: 'symb' => $symb,
3916: 'mean_tries' => $av_attempts,
3917: 'deg_of_diff' => $degdiff});
3918: foreach my $key (keys(%dynstore)) {
3919: $accesshash{$key}=$dynstore{$key};
3920: }
3921: }
1.361 www 3922:
1.349 www 3923: sub userrolelog {
3924: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3925: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3926: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3927: $userrolehash
3928: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3929: =$tend.':'.$tstart;
1.662 raeburn 3930: }
1.1169 droeschl 3931: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3932: $userrolehash
3933: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3934: =$tend.':'.$tstart;
3935: }
1.1169 droeschl 3936: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3937: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3938: $domainrolehash
3939: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3940: = $tend.':'.$tstart;
3941: }
1.351 www 3942: }
3943:
1.957 raeburn 3944: sub courserolelog {
3945: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3946: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3947: my $cdom = $1;
3948: my $cnum = $2;
3949: my $sec = $3;
3950: my $namespace = 'rolelog';
3951: my %storehash = (
3952: role => $trole,
3953: start => $tstart,
3954: end => $tend,
3955: selfenroll => $selfenroll,
3956: context => $context,
3957: );
3958: if ($trole eq 'gr') {
3959: $namespace = 'groupslog';
3960: $storehash{'group'} = $sec;
3961: } else {
3962: $storehash{'section'} = $sec;
3963: }
3964: &write_log('course',$namespace,\%storehash,$delflag,$username,
3965: $domain,$cnum,$cdom);
3966: if (($trole ne 'st') || ($sec ne '')) {
3967: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3968: }
3969: }
3970: return;
3971: }
3972:
1.1172.2.9 raeburn 3973: sub domainrolelog {
3974: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3975: if ($area =~ m{^/($match_domain)/$}) {
3976: my $cdom = $1;
3977: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3978: my $namespace = 'rolelog';
3979: my %storehash = (
3980: role => $trole,
3981: start => $tstart,
3982: end => $tend,
3983: context => $context,
3984: );
3985: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3986: $domain,$domconfiguser,$cdom);
3987: }
3988: return;
3989:
3990: }
3991:
3992: sub coauthorrolelog {
3993: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3994: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3995: my $audom = $1;
3996: my $auname = $2;
3997: my $namespace = 'rolelog';
3998: my %storehash = (
3999: role => $trole,
4000: start => $tstart,
4001: end => $tend,
4002: context => $context,
4003: );
4004: &write_log('author',$namespace,\%storehash,$delflag,$username,
4005: $domain,$auname,$audom);
4006: }
4007: return;
4008: }
4009:
1.351 www 4010: sub get_course_adv_roles {
1.948 raeburn 4011: my ($cid,$codes) = @_;
1.620 albertel 4012: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4013: my %coursehash=&coursedescription($cid);
1.988 raeburn 4014: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4015: my %nothide=();
1.800 albertel 4016: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4017: if ($user !~ /:/) {
4018: $nothide{join(':',split(/[\@]/,$user))}=1;
4019: } else {
4020: $nothide{$user}=1;
4021: }
1.470 www 4022: }
1.1172.2.23 raeburn 4023: my @possdoms = ($coursehash{'domain'});
4024: if ($coursehash{'checkforpriv'}) {
4025: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4026: }
1.351 www 4027: my %returnhash=();
4028: my %dumphash=
4029: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4030: my $now=time;
1.997 raeburn 4031: my %privileged;
1.1000 raeburn 4032: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4033: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4034: if (($tstart) && ($tstart<0)) { next; }
4035: if (($tend) && ($tend<$now)) { next; }
4036: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4037: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4038: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4039: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4040: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4041: if ($role eq 'cr') { next; }
1.948 raeburn 4042: if ($codes) {
4043: if ($section) { $role .= ':'.$section; }
4044: if ($returnhash{$role}) {
4045: $returnhash{$role}.=','.$username.':'.$domain;
4046: } else {
4047: $returnhash{$role}=$username.':'.$domain;
4048: }
1.351 www 4049: } else {
1.988 raeburn 4050: my $key=&plaintext($role,$crstype);
1.973 bisitz 4051: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4052: if ($returnhash{$key}) {
4053: $returnhash{$key}.=','.$username.':'.$domain;
4054: } else {
4055: $returnhash{$key}=$username.':'.$domain;
4056: }
1.351 www 4057: }
1.948 raeburn 4058: }
1.400 www 4059: return %returnhash;
4060: }
4061:
4062: sub get_my_roles {
1.937 raeburn 4063: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4064: unless (defined($uname)) { $uname=$env{'user.name'}; }
4065: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4066: my (%dumphash,%nothide);
1.1086 raeburn 4067: if ($context eq 'userroles') {
1.1166 raeburn 4068: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4069: } else {
1.1172.2.23 raeburn 4070: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4071: if ($hidepriv) {
4072: my %coursehash=&coursedescription($udom.'_'.$uname);
4073: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4074: if ($user !~ /:/) {
4075: $nothide{join(':',split(/[\@]/,$user))} = 1;
4076: } else {
4077: $nothide{$user} = 1;
4078: }
4079: }
4080: }
1.858 raeburn 4081: }
1.400 www 4082: my %returnhash=();
4083: my $now=time;
1.999 raeburn 4084: my %privileged;
1.800 albertel 4085: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4086: my ($role,$tend,$tstart);
4087: if ($context eq 'userroles') {
1.1149 raeburn 4088: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4089: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4090: } else {
4091: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4092: }
1.400 www 4093: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4094: my $status = 'active';
1.939 raeburn 4095: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4096: $status = 'previous';
4097: }
4098: if (($tstart) && ($now<$tstart)) {
4099: $status = 'future';
4100: }
4101: if (ref($types) eq 'ARRAY') {
4102: if (!grep(/^\Q$status\E$/,@{$types})) {
4103: next;
4104: }
4105: } else {
4106: if ($status ne 'active') {
4107: next;
4108: }
4109: }
1.867 raeburn 4110: my ($rolecode,$username,$domain,$section,$area);
4111: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4112: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4113: (undef,$domain,$username,$section) = split(/\//,$area);
4114: } else {
4115: ($role,$username,$domain,$section) = split(/\:/,$entry);
4116: }
1.832 raeburn 4117: if (ref($roledoms) eq 'ARRAY') {
4118: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4119: next;
4120: }
4121: }
4122: if (ref($roles) eq 'ARRAY') {
4123: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4124: if ($role =~ /^cr\//) {
4125: if (!grep(/^cr$/,@{$roles})) {
4126: next;
4127: }
1.1104 raeburn 4128: } elsif ($role =~ /^gr\//) {
4129: if (!grep(/^gr$/,@{$roles})) {
4130: next;
4131: }
1.922 raeburn 4132: } else {
4133: next;
4134: }
1.832 raeburn 4135: }
1.867 raeburn 4136: }
1.937 raeburn 4137: if ($hidepriv) {
1.1172.2.23 raeburn 4138: my @privroles = ('dc','su');
1.999 raeburn 4139: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4140: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4141: } else {
1.1172.2.23 raeburn 4142: my $possdoms = [$domain];
4143: if (ref($roledoms) eq 'ARRAY') {
4144: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4145: }
1.1172.2.23 raeburn 4146: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4147: if (!$nothide{$username.':'.$domain}) {
4148: next;
4149: }
4150: }
1.937 raeburn 4151: }
4152: }
1.933 raeburn 4153: if ($withsec) {
4154: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4155: $tstart.':'.$tend;
4156: } else {
4157: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4158: }
1.832 raeburn 4159: }
1.373 www 4160: return %returnhash;
1.399 www 4161: }
4162:
4163: # ----------------------------------------------------- Frontpage Announcements
4164: #
4165: #
4166:
4167: sub postannounce {
4168: my ($server,$text)=@_;
1.844 albertel 4169: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4170: unless ($text=~/\w/) { $text=''; }
4171: return &reply('setannounce:'.&escape($text),$server);
4172: }
4173:
4174: sub getannounce {
1.448 albertel 4175:
4176: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4177: my $announcement='';
1.800 albertel 4178: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4179: close($fh);
1.399 www 4180: if ($announcement=~/\w/) {
4181: return
4182: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4183: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4184: } else {
4185: return '';
4186: }
4187: } else {
4188: return '';
4189: }
1.351 www 4190: }
1.353 www 4191:
4192: # ---------------------------------------------------------- Course ID routines
4193: # Deal with domain's nohist_courseid.db files
4194: #
4195:
4196: sub courseidput {
1.921 raeburn 4197: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4198: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4199: my $outcome;
4200: if ($caller eq 'timeonly') {
4201: my $cids = '';
4202: foreach my $item (keys(%$storehash)) {
4203: $cids.=&escape($item).'&';
4204: }
4205: $cids=~s/\&$//;
4206: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4207: $coursehome);
4208: } else {
4209: my $items = '';
4210: foreach my $item (keys(%$storehash)) {
4211: $items.= &escape($item).'='.
4212: &freeze_escape($$storehash{$item}).'&';
4213: }
4214: $items=~s/\&$//;
4215: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4216: $coursehome);
1.918 raeburn 4217: }
4218: if ($outcome eq 'unknown_cmd') {
4219: my $what;
4220: foreach my $cid (keys(%$storehash)) {
4221: $what .= &escape($cid).'=';
1.921 raeburn 4222: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4223: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4224: }
4225: $what =~ s/\:$/&/;
4226: }
4227: $what =~ s/\&$//;
4228: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4229: } else {
4230: return $outcome;
4231: }
1.353 www 4232: }
4233:
4234: sub courseiddump {
1.921 raeburn 4235: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4236: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4237: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4238: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4239: $hasuniquecode)=@_;
1.918 raeburn 4240: my $as_hash = 1;
4241: my %returnhash;
4242: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4243: my %libserv = &all_library();
4244: foreach my $tryserver (keys(%libserv)) {
4245: if ( ( $hostidflag == 1
4246: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4247: || (!defined($hostidflag)) ) {
4248:
1.918 raeburn 4249: if (($domfilter eq '') ||
4250: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4251: my $rep;
4252: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4253: $rep = &LONCAPA::Lond::dump_course_id_handler(
4254: join(":", (&host_domain($tryserver), $sincefilter,
4255: &escape($descfilter), &escape($instcodefilter),
4256: &escape($ownerfilter), &escape($coursefilter),
4257: &escape($typefilter), &escape($regexp_ok),
4258: $as_hash, &escape($selfenrollonly),
4259: &escape($catfilter), $showhidden, $caller,
4260: &escape($cloner), &escape($cc_clone), $cloneonly,
4261: &escape($createdbefore), &escape($createdafter),
1.1172.2.38 raeburn 4262: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22 raeburn 4263: } else {
4264: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4265: $sincefilter.':'.&escape($descfilter).':'.
4266: &escape($instcodefilter).':'.&escape($ownerfilter).
4267: ':'.&escape($coursefilter).':'.&escape($typefilter).
4268: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4269: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4270: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4271: &escape($cc_clone).':'.$cloneonly.':'.
4272: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38 raeburn 4273: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22 raeburn 4274: $tryserver);
4275: }
4276:
1.918 raeburn 4277: my @pairs=split(/\&/,$rep);
4278: foreach my $item (@pairs) {
4279: my ($key,$value)=split(/\=/,$item,2);
4280: $key = &unescape($key);
4281: next if ($key =~ /^error: 2 /);
4282: my $result = &thaw_unescape($value);
4283: if (ref($result) eq 'HASH') {
4284: $returnhash{$key}=$result;
4285: } else {
1.921 raeburn 4286: my @responses = split(/:/,$value);
4287: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4288: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4289: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4290: }
1.1008 raeburn 4291: }
1.353 www 4292: }
4293: }
4294: }
4295: }
4296: return %returnhash;
4297: }
4298:
1.1055 raeburn 4299: sub courselastaccess {
4300: my ($cdom,$cnum,$hostidref) = @_;
4301: my %returnhash;
4302: if ($cdom && $cnum) {
4303: my $chome = &homeserver($cnum,$cdom);
4304: if ($chome ne 'no_host') {
4305: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4306: &extract_lastaccess(\%returnhash,$rep);
4307: }
4308: } else {
4309: if (!$cdom) { $cdom=''; }
4310: my %libserv = &all_library();
4311: foreach my $tryserver (keys(%libserv)) {
4312: if (ref($hostidref) eq 'ARRAY') {
4313: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4314: }
4315: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4316: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4317: &extract_lastaccess(\%returnhash,$rep);
4318: }
4319: }
4320: }
4321: return %returnhash;
4322: }
4323:
4324: sub extract_lastaccess {
4325: my ($returnhash,$rep) = @_;
4326: if (ref($returnhash) eq 'HASH') {
4327: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4328: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4329: $rep eq '') {
4330: my @pairs=split(/\&/,$rep);
4331: foreach my $item (@pairs) {
4332: my ($key,$value)=split(/\=/,$item,2);
4333: $key = &unescape($key);
4334: next if ($key =~ /^error: 2 /);
4335: $returnhash->{$key} = &thaw_unescape($value);
4336: }
4337: }
4338: }
4339: return;
4340: }
4341:
1.658 raeburn 4342: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4343:
4344: sub dcmailput {
1.685 raeburn 4345: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4346: my $status = &Apache::lonnet::critical(
1.740 www 4347: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4348: &escape($message),$server);
1.662 raeburn 4349: return $status;
4350: }
4351:
1.658 raeburn 4352: sub dcmaildump {
4353: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4354: my %returnhash=();
1.846 albertel 4355:
4356: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4357: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4358: &escape($enddate).':';
4359: my @esc_senders=map { &escape($_)} @$senders;
4360: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4361: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4362: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4363: if (($key) && ($value)) {
4364: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4365: }
4366: }
4367: }
4368: return %returnhash;
4369: }
1.662 raeburn 4370: # ---------------------------------------------------------- Domain roles
4371:
4372: sub get_domain_roles {
4373: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4374: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4375: $startdate = '.';
4376: }
1.1018 raeburn 4377: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4378: $enddate = '.';
4379: }
1.922 raeburn 4380: my $rolelist;
4381: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4382: $rolelist = join('&',@{$roles});
1.922 raeburn 4383: }
1.662 raeburn 4384: my %personnel = ();
1.841 albertel 4385:
4386: my %servers = &get_servers($dom,'library');
4387: foreach my $tryserver (keys(%servers)) {
4388: %{$personnel{$tryserver}}=();
4389: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4390: &escape($startdate).':'.
4391: &escape($enddate).':'.
4392: &escape($rolelist), $tryserver))) {
4393: my ($key,$value) = split(/\=/,$line,2);
4394: if (($key) && ($value)) {
4395: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4396: }
4397: }
1.662 raeburn 4398: }
4399: return %personnel;
4400: }
1.658 raeburn 4401:
1.1057 www 4402: # ----------------------------------------------------------- Interval timing
1.149 www 4403:
1.1153 www 4404: {
4405: # Caches needed for speedup of navmaps
4406: # We don't want to cache this for very long at all (5 seconds at most)
4407: #
4408: # The user for whom we cache
4409: my $cachedkey='';
4410: # The cached times for this user
4411: my %cachedtimes=();
4412: # When this was last done
4413: my $cachedtime=();
4414:
4415: sub load_all_first_access {
1.1154 raeburn 4416: my ($uname,$udom)=@_;
1.1156 www 4417: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4418: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4419: return;
4420: }
4421: $cachedtime=time;
4422: $cachedkey=$uname.':'.$udom;
4423: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4424: }
4425:
1.504 albertel 4426: sub get_first_access {
1.1162 raeburn 4427: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4428: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4429: if ($argsymb) { $symb=$argsymb; }
4430: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4431: if ($argmap) { $map = $argmap; }
1.926 albertel 4432: if ($type eq 'course') {
4433: $res='course';
4434: } elsif ($type eq 'map') {
1.588 albertel 4435: $res=&symbread($map);
4436: } else {
4437: $res=$symb;
4438: }
1.1153 www 4439: &load_all_first_access($uname,$udom);
4440: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4441: }
4442:
4443: sub set_first_access {
1.1162 raeburn 4444: my ($type,$interval)=@_;
1.790 albertel 4445: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4446: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4447: if ($type eq 'course') {
4448: $res='course';
4449: } elsif ($type eq 'map') {
1.588 albertel 4450: $res=&symbread($map);
4451: } else {
4452: $res=$symb;
4453: }
1.1153 www 4454: $cachedkey='';
1.1162 raeburn 4455: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4456: if (!$firstaccess) {
1.1162 raeburn 4457: my $start = time;
4458: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4459: $udom,$uname);
4460: if ($putres eq 'ok') {
4461: &put('timerinterval',{"$courseid\0$res"=>$interval},
4462: $udom,$uname);
4463: &appenv(
4464: {
4465: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4466: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4467: }
4468: );
4469: }
4470: return $putres;
1.505 albertel 4471: }
4472: return 'already_set';
1.504 albertel 4473: }
1.1153 www 4474: }
1.1172.2.32 raeburn 4475:
4476: sub checkout {
4477: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4478: my $now=time;
4479: my $lonhost=$perlvar{'lonHostID'};
4480: my $infostr=&escape(
4481: 'CHECKOUTTOKEN&'.
4482: $tuname.'&'.
4483: $tudom.'&'.
4484: $tcrsid.'&'.
4485: $symb.'&'.
4486: $now.'&'.$ENV{'REMOTE_ADDR'});
4487: my $token=&reply('tmpput:'.$infostr,$lonhost);
4488: if ($token=~/^error\:/) {
4489: &logthis("<font color=\"blue\">WARNING: ".
4490: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4491: "</font>");
4492: return '';
4493: }
4494:
4495: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4496: $token=~tr/a-z/A-Z/;
4497:
4498: my %infohash=('resource.0.outtoken' => $token,
4499: 'resource.0.checkouttime' => $now,
4500: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4501:
4502: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4503: return '';
4504: } else {
4505: &logthis("<font color=\"blue\">WARNING: ".
4506: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4507: "</font>");
4508: }
4509:
4510: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4511: &escape('Checkout '.$infostr.' - '.
4512: $token)) ne 'ok') {
4513: return '';
4514: } else {
4515: &logthis("<font color=\"blue\">WARNING: ".
4516: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4517: "</font>");
4518: }
4519: return $token;
4520: }
4521:
4522: # ------------------------------------------------------------ Check in an item
4523:
4524: sub checkin {
4525: my $token=shift;
4526: my $now=time;
4527: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4528: $lonhost=~tr/A-Z/a-z/;
4529: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4530: $dtoken=~s/\W/\_/g;
4531: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4532: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4533:
4534: unless (($tuname) && ($tudom)) {
4535: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4536: return '';
4537: }
4538:
4539: unless (&allowed('mgr',$tcrsid)) {
4540: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4541: $env{'user.name'}.' - '.$env{'user.domain'});
4542: return '';
4543: }
4544:
4545: my %infohash=('resource.0.intoken' => $token,
4546: 'resource.0.checkintime' => $now,
4547: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4548:
4549: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4550: return '';
4551: }
4552:
4553: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4554: &escape('Checkin - '.$token)) ne 'ok') {
4555: return '';
4556: }
4557:
4558: return ($symb,$tuname,$tudom,$tcrsid);
4559: }
4560:
1.110 www 4561: # --------------------------------------------- Set Expire Date for Spreadsheet
4562:
4563: sub expirespread {
4564: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4565: my $cid=$env{'request.course.id'};
1.110 www 4566: if ($cid) {
4567: my $now=time;
4568: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4569: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4570: $env{'course.'.$cid.'.num'}.
1.110 www 4571: ':nohist_expirationdates:'.
4572: &escape($key).'='.$now,
1.620 albertel 4573: $env{'course.'.$cid.'.home'})
1.110 www 4574: }
4575: return 'ok';
1.14 www 4576: }
4577:
1.109 www 4578: # ----------------------------------------------------- Devalidate Spreadsheets
4579:
4580: sub devalidate {
1.325 www 4581: my ($symb,$uname,$udom)=@_;
1.620 albertel 4582: my $cid=$env{'request.course.id'};
1.109 www 4583: if ($cid) {
1.391 matthew 4584: # delete the stored spreadsheets for
4585: # - the student level sheet of this user in course's homespace
4586: # - the assessment level sheet for this resource
4587: # for this user in user's homespace
1.553 albertel 4588: # - current conditional state info
1.325 www 4589: my $key=$uname.':'.$udom.':';
1.109 www 4590: my $status=
1.299 matthew 4591: &del('nohist_calculatedsheets',
1.391 matthew 4592: [$key.'studentcalc:'],
1.620 albertel 4593: $env{'course.'.$cid.'.domain'},
4594: $env{'course.'.$cid.'.num'})
1.133 albertel 4595: .' '.
4596: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4597: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4598: unless ($status eq 'ok ok') {
4599: &logthis('Could not devalidate spreadsheet '.
1.325 www 4600: $uname.' at '.$udom.' for '.
1.109 www 4601: $symb.': '.$status);
1.133 albertel 4602: }
1.553 albertel 4603: &delenv('user.state.'.$cid);
1.109 www 4604: }
4605: }
4606:
1.265 albertel 4607: sub get_scalar {
4608: my ($string,$end) = @_;
4609: my $value;
4610: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4611: $value = $1;
4612: } elsif ($$string =~ s/^([^&]*?)&//) {
4613: $value = $1;
4614: }
4615: return &unescape($value);
4616: }
4617:
4618: sub array2str {
4619: my (@array) = @_;
4620: my $result=&arrayref2str(\@array);
4621: $result=~s/^__ARRAY_REF__//;
4622: $result=~s/__END_ARRAY_REF__$//;
4623: return $result;
4624: }
4625:
1.204 albertel 4626: sub arrayref2str {
4627: my ($arrayref) = @_;
1.265 albertel 4628: my $result='__ARRAY_REF__';
1.204 albertel 4629: foreach my $elem (@$arrayref) {
1.265 albertel 4630: if(ref($elem) eq 'ARRAY') {
4631: $result.=&arrayref2str($elem).'&';
4632: } elsif(ref($elem) eq 'HASH') {
4633: $result.=&hashref2str($elem).'&';
4634: } elsif(ref($elem)) {
4635: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4636: } else {
4637: $result.=&escape($elem).'&';
4638: }
4639: }
4640: $result=~s/\&$//;
1.265 albertel 4641: $result .= '__END_ARRAY_REF__';
1.204 albertel 4642: return $result;
4643: }
4644:
1.168 albertel 4645: sub hash2str {
1.204 albertel 4646: my (%hash) = @_;
4647: my $result=&hashref2str(\%hash);
1.265 albertel 4648: $result=~s/^__HASH_REF__//;
4649: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4650: return $result;
4651: }
4652:
4653: sub hashref2str {
4654: my ($hashref)=@_;
1.265 albertel 4655: my $result='__HASH_REF__';
1.800 albertel 4656: foreach my $key (sort(keys(%$hashref))) {
4657: if (ref($key) eq 'ARRAY') {
4658: $result.=&arrayref2str($key).'=';
4659: } elsif (ref($key) eq 'HASH') {
4660: $result.=&hashref2str($key).'=';
4661: } elsif (ref($key)) {
1.265 albertel 4662: $result.='=';
1.800 albertel 4663: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4664: } else {
1.1132 raeburn 4665: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4666: }
4667:
1.800 albertel 4668: if(ref($hashref->{$key}) eq 'ARRAY') {
4669: $result.=&arrayref2str($hashref->{$key}).'&';
4670: } elsif(ref($hashref->{$key}) eq 'HASH') {
4671: $result.=&hashref2str($hashref->{$key}).'&';
4672: } elsif(ref($hashref->{$key})) {
1.265 albertel 4673: $result.='&';
1.800 albertel 4674: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4675: } else {
1.800 albertel 4676: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4677: }
4678: }
1.168 albertel 4679: $result=~s/\&$//;
1.265 albertel 4680: $result .= '__END_HASH_REF__';
1.168 albertel 4681: return $result;
4682: }
4683:
4684: sub str2hash {
1.265 albertel 4685: my ($string)=@_;
4686: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4687: return %$hash;
4688: }
4689:
4690: sub str2hashref {
1.168 albertel 4691: my ($string) = @_;
1.265 albertel 4692:
4693: my %hash;
4694:
4695: if($string !~ /^__HASH_REF__/) {
4696: if (! ($string eq '' || !defined($string))) {
4697: $hash{'error'}='Not hash reference';
4698: }
4699: return (\%hash, $string);
4700: }
4701:
4702: $string =~ s/^__HASH_REF__//;
4703:
4704: while($string !~ /^__END_HASH_REF__/) {
4705: #key
4706: my $key='';
4707: if($string =~ /^__HASH_REF__/) {
4708: ($key, $string)=&str2hashref($string);
4709: if(defined($key->{'error'})) {
4710: $hash{'error'}='Bad data';
4711: return (\%hash, $string);
4712: }
4713: } elsif($string =~ /^__ARRAY_REF__/) {
4714: ($key, $string)=&str2arrayref($string);
4715: if($key->[0] eq 'Array reference error') {
4716: $hash{'error'}='Bad data';
4717: return (\%hash, $string);
4718: }
4719: } else {
4720: $string =~ s/^(.*?)=//;
1.267 albertel 4721: $key=&unescape($1);
1.265 albertel 4722: }
4723: $string =~ s/^=//;
4724:
4725: #value
4726: my $value='';
4727: if($string =~ /^__HASH_REF__/) {
4728: ($value, $string)=&str2hashref($string);
4729: if(defined($value->{'error'})) {
4730: $hash{'error'}='Bad data';
4731: return (\%hash, $string);
4732: }
4733: } elsif($string =~ /^__ARRAY_REF__/) {
4734: ($value, $string)=&str2arrayref($string);
4735: if($value->[0] eq 'Array reference error') {
4736: $hash{'error'}='Bad data';
4737: return (\%hash, $string);
4738: }
4739: } else {
4740: $value=&get_scalar(\$string,'__END_HASH_REF__');
4741: }
4742: $string =~ s/^&//;
4743:
4744: $hash{$key}=$value;
1.204 albertel 4745: }
1.265 albertel 4746:
4747: $string =~ s/^__END_HASH_REF__//;
4748:
4749: return (\%hash, $string);
1.204 albertel 4750: }
4751:
4752: sub str2array {
1.265 albertel 4753: my ($string)=@_;
4754: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4755: return @$array;
4756: }
4757:
4758: sub str2arrayref {
1.204 albertel 4759: my ($string) = @_;
1.265 albertel 4760: my @array;
4761:
4762: if($string !~ /^__ARRAY_REF__/) {
4763: if (! ($string eq '' || !defined($string))) {
4764: $array[0]='Array reference error';
4765: }
4766: return (\@array, $string);
4767: }
4768:
4769: $string =~ s/^__ARRAY_REF__//;
4770:
4771: while($string !~ /^__END_ARRAY_REF__/) {
4772: my $value='';
4773: if($string =~ /^__HASH_REF__/) {
4774: ($value, $string)=&str2hashref($string);
4775: if(defined($value->{'error'})) {
4776: $array[0] ='Array reference error';
4777: return (\@array, $string);
4778: }
4779: } elsif($string =~ /^__ARRAY_REF__/) {
4780: ($value, $string)=&str2arrayref($string);
4781: if($value->[0] eq 'Array reference error') {
4782: $array[0] ='Array reference error';
4783: return (\@array, $string);
4784: }
4785: } else {
4786: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4787: }
4788: $string =~ s/^&//;
4789:
4790: push(@array, $value);
1.191 harris41 4791: }
1.265 albertel 4792:
4793: $string =~ s/^__END_ARRAY_REF__//;
4794:
4795: return (\@array, $string);
1.168 albertel 4796: }
4797:
1.167 albertel 4798: # -------------------------------------------------------------------Temp Store
4799:
1.168 albertel 4800: sub tmpreset {
4801: my ($symb,$namespace,$domain,$stuname) = @_;
4802: if (!$symb) {
4803: $symb=&symbread();
1.620 albertel 4804: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4805: }
4806: $symb=escape($symb);
4807:
1.620 albertel 4808: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4809: $namespace=~s/\//\_/g;
4810: $namespace=~s/\W//g;
4811:
1.620 albertel 4812: if (!$domain) { $domain=$env{'user.domain'}; }
4813: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4814: if ($domain eq 'public' && $stuname eq 'public') {
4815: $stuname=$ENV{'REMOTE_ADDR'};
4816: }
1.1117 foxr 4817: my $path=LONCAPA::tempdir();
1.168 albertel 4818: my %hash;
4819: if (tie(%hash,'GDBM_File',
4820: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4821: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4822: foreach my $key (keys(%hash)) {
1.180 albertel 4823: if ($key=~ /:$symb/) {
1.168 albertel 4824: delete($hash{$key});
4825: }
4826: }
4827: }
4828: }
4829:
1.167 albertel 4830: sub tmpstore {
1.168 albertel 4831: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4832:
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:
4839: if (!$namespace) {
4840: # I don't think we would ever want to store this for a course.
4841: # it seems this will only be used if we don't have a course.
1.620 albertel 4842: #$namespace=$env{'request.course.id'};
1.168 albertel 4843: #if (!$namespace) {
1.620 albertel 4844: $namespace=$env{'request.state'};
1.168 albertel 4845: #}
4846: }
4847: $namespace=~s/\//\_/g;
4848: $namespace=~s/\W//g;
1.620 albertel 4849: if (!$domain) { $domain=$env{'user.domain'}; }
4850: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4851: if ($domain eq 'public' && $stuname eq 'public') {
4852: $stuname=$ENV{'REMOTE_ADDR'};
4853: }
1.168 albertel 4854: my $now=time;
4855: my %hash;
1.1117 foxr 4856: my $path=LONCAPA::tempdir();
1.168 albertel 4857: if (tie(%hash,'GDBM_File',
4858: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4859: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4860: $hash{"version:$symb"}++;
4861: my $version=$hash{"version:$symb"};
4862: my $allkeys='';
4863: foreach my $key (keys(%$storehash)) {
4864: $allkeys.=$key.':';
1.591 albertel 4865: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4866: }
4867: $hash{"$version:$symb:timestamp"}=$now;
4868: $allkeys.='timestamp';
4869: $hash{"$version:keys:$symb"}=$allkeys;
4870: if (untie(%hash)) {
4871: return 'ok';
4872: } else {
4873: return "error:$!";
4874: }
4875: } else {
4876: return "error:$!";
4877: }
4878: }
1.167 albertel 4879:
1.168 albertel 4880: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4881:
1.168 albertel 4882: sub tmprestore {
4883: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4884:
1.168 albertel 4885: if (!$symb) {
4886: $symb=&symbread();
1.620 albertel 4887: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4888: }
4889: $symb=escape($symb);
4890:
1.620 albertel 4891: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4892:
1.620 albertel 4893: if (!$domain) { $domain=$env{'user.domain'}; }
4894: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4895: if ($domain eq 'public' && $stuname eq 'public') {
4896: $stuname=$ENV{'REMOTE_ADDR'};
4897: }
1.168 albertel 4898: my %returnhash;
4899: $namespace=~s/\//\_/g;
4900: $namespace=~s/\W//g;
4901: my %hash;
1.1117 foxr 4902: my $path=LONCAPA::tempdir();
1.168 albertel 4903: if (tie(%hash,'GDBM_File',
4904: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4905: &GDBM_READER(),0640)) {
1.168 albertel 4906: my $version=$hash{"version:$symb"};
4907: $returnhash{'version'}=$version;
4908: my $scope;
4909: for ($scope=1;$scope<=$version;$scope++) {
4910: my $vkeys=$hash{"$scope:keys:$symb"};
4911: my @keys=split(/:/,$vkeys);
4912: my $key;
4913: $returnhash{"$scope:keys"}=$vkeys;
4914: foreach $key (@keys) {
1.591 albertel 4915: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4916: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4917: }
4918: }
1.168 albertel 4919: if (!(untie(%hash))) {
4920: return "error:$!";
4921: }
4922: } else {
4923: return "error:$!";
4924: }
4925: return %returnhash;
1.167 albertel 4926: }
4927:
1.9 www 4928: # ----------------------------------------------------------------------- Store
4929:
4930: sub store {
1.124 www 4931: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4932: my $home='';
4933:
1.168 albertel 4934: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4935:
1.213 www 4936: $symb=&symbclean($symb);
1.122 albertel 4937: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4938:
1.620 albertel 4939: if (!$domain) { $domain=$env{'user.domain'}; }
4940: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4941:
4942: &devalidate($symb,$stuname,$domain);
1.109 www 4943:
4944: $symb=escape($symb);
1.187 www 4945: if (!$namespace) {
1.620 albertel 4946: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4947: return '';
4948: }
4949: }
1.620 albertel 4950: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4951:
4952: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4953: $$storehash{'host'}=$perlvar{'lonHostID'};
4954:
1.12 www 4955: my $namevalue='';
1.800 albertel 4956: foreach my $key (keys(%$storehash)) {
4957: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4958: }
1.12 www 4959: $namevalue=~s/\&$//;
1.187 www 4960: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4961: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4962: }
4963:
1.47 www 4964: # -------------------------------------------------------------- Critical Store
4965:
4966: sub cstore {
1.124 www 4967: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4968: my $home='';
4969:
1.168 albertel 4970: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4971:
1.213 www 4972: $symb=&symbclean($symb);
1.122 albertel 4973: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4974:
1.620 albertel 4975: if (!$domain) { $domain=$env{'user.domain'}; }
4976: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4977:
4978: &devalidate($symb,$stuname,$domain);
1.109 www 4979:
4980: $symb=escape($symb);
1.187 www 4981: if (!$namespace) {
1.620 albertel 4982: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4983: return '';
4984: }
4985: }
1.620 albertel 4986: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4987:
4988: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4989: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4990:
1.47 www 4991: my $namevalue='';
1.800 albertel 4992: foreach my $key (keys(%$storehash)) {
4993: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4994: }
1.47 www 4995: $namevalue=~s/\&$//;
1.187 www 4996: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4997: return critical
4998: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4999: }
5000:
1.9 www 5001: # --------------------------------------------------------------------- Restore
5002:
5003: sub restore {
1.124 www 5004: my ($symb,$namespace,$domain,$stuname) = @_;
5005: my $home='';
5006:
1.168 albertel 5007: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5008:
1.122 albertel 5009: if (!$symb) {
1.1172.2.26 raeburn 5010: return if ($namespace eq 'courserequests');
5011: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5012: } else {
1.1172.2.26 raeburn 5013: unless ($namespace eq 'courserequests') {
5014: $symb=&escape(&symbclean($symb));
5015: }
1.122 albertel 5016: }
1.188 www 5017: if (!$namespace) {
1.620 albertel 5018: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5019: return '';
5020: }
5021: }
1.620 albertel 5022: if (!$domain) { $domain=$env{'user.domain'}; }
5023: if (!$stuname) { $stuname=$env{'user.name'}; }
5024: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5025: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5026:
1.12 www 5027: my %returnhash=();
1.800 albertel 5028: foreach my $line (split(/\&/,$answer)) {
5029: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5030: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5031: }
1.75 www 5032: my $version;
5033: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5034: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5035: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5036: }
1.75 www 5037: }
1.13 www 5038: return %returnhash;
1.34 www 5039: }
5040:
5041: # ---------------------------------------------------------- Course Description
1.1118 foxr 5042: #
5043: #
1.34 www 5044:
5045: sub coursedescription {
1.731 albertel 5046: my ($courseid,$args)=@_;
1.34 www 5047: $courseid=~s/^\///;
1.49 www 5048: $courseid=~s/\_/\//g;
1.34 www 5049: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5050: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5051: my $normalid=$cdomain.'_'.$cnum;
5052: # need to always cache even if we get errors otherwise we keep
5053: # trying and trying and trying to get the course description.
5054: my %envhash=();
5055: my %returnhash=();
1.731 albertel 5056:
5057: my $expiretime=600;
5058: if ($env{'request.course.id'} eq $normalid) {
5059: $expiretime=120;
5060: }
5061:
5062: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5063: if (!$args->{'freshen_cache'}
5064: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5065: foreach my $key (keys(%env)) {
5066: next if ($key !~ /^\Q$prefix\E(.*)/);
5067: my ($setting) = $1;
5068: $returnhash{$setting} = $env{$key};
5069: }
5070: return %returnhash;
5071: }
5072:
1.1118 foxr 5073: # get the data again
5074:
1.731 albertel 5075: if (!$args->{'one_time'}) {
5076: $envhash{'course.'.$normalid.'.last_cache'}=time;
5077: }
1.811 albertel 5078:
1.34 www 5079: if ($chome ne 'no_host') {
1.302 albertel 5080: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5081: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5082: my $username = $env{'user.name'}; # Defult username
5083: if(defined $args->{'user'}) {
5084: $username = $args->{'user'};
5085: }
1.129 albertel 5086: $returnhash{'home'}= $chome;
5087: $returnhash{'domain'} = $cdomain;
5088: $returnhash{'num'} = $cnum;
1.741 raeburn 5089: if (!defined($returnhash{'type'})) {
5090: $returnhash{'type'} = 'Course';
5091: }
1.130 albertel 5092: while (my ($name,$value) = each %returnhash) {
1.53 www 5093: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5094: }
1.270 www 5095: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5096: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5097: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5098: $envhash{'course.'.$normalid.'.home'}=$chome;
5099: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5100: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5101: }
5102: }
1.731 albertel 5103: if (!$args->{'one_time'}) {
1.949 raeburn 5104: &appenv(\%envhash);
1.731 albertel 5105: }
1.302 albertel 5106: return %returnhash;
1.461 www 5107: }
5108:
1.1080 raeburn 5109: sub update_released_required {
5110: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5111: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5112: $cid = $env{'request.course.id'};
5113: $cdom = $env{'course.'.$cid.'.domain'};
5114: $cnum = $env{'course.'.$cid.'.num'};
5115: $chome = $env{'course.'.$cid.'.home'};
5116: }
5117: if ($needsrelease) {
5118: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5119: my $needsupdate;
5120: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5121: $needsupdate = 1;
5122: } else {
5123: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5124: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5125: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5126: $needsupdate = 1;
5127: }
5128: }
5129: if ($needsupdate) {
5130: my %needshash = (
5131: 'internal.releaserequired' => $needsrelease,
5132: );
5133: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5134: if ($putresult eq 'ok') {
5135: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5136: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5137: if (ref($crsinfo{$cid}) eq 'HASH') {
5138: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5139: &courseidput($cdom,\%crsinfo,$chome,'notime');
5140: }
5141: }
5142: }
5143: }
5144: return;
5145: }
5146:
1.461 www 5147: # -------------------------------------------------See if a user is privileged
5148:
5149: sub privileged {
1.1172.2.23 raeburn 5150: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5151: my $now = time;
1.1172.2.23 raeburn 5152: my $roles;
5153: if (ref($possroles) eq 'ARRAY') {
5154: $roles = $possroles;
5155: } else {
5156: $roles = ['dc','su'];
5157: }
5158: if (ref($possdomains) eq 'ARRAY') {
5159: my %privileged = &privileged_by_domain($possdomains,$roles);
5160: foreach my $dom (@{$possdomains}) {
5161: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5162: (ref($privileged{$dom}) eq 'HASH')) {
5163: foreach my $role (@{$roles}) {
5164: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5165: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5166: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5167: return 1 unless (($end && $end < $now) ||
5168: ($start && $start > $now));
5169: }
5170: }
5171: }
5172: }
5173: }
5174: } else {
5175: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5176: my $now = time;
1.1170 droeschl 5177:
1.1172.2.23 raeburn 5178: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5179: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5180: if (grep(/^\Q$trole\E$/,@{$roles})) {
5181: return 1 unless ($tend && $tend < $now)
5182: or ($tstart && $tstart > $now);
1.1170 droeschl 5183: }
1.1172.2.23 raeburn 5184: }
5185: }
1.461 www 5186: return 0;
1.9 www 5187: }
1.1 albertel 5188:
1.1172.2.23 raeburn 5189: sub privileged_by_domain {
5190: my ($domains,$roles) = @_;
5191: my %privileged = ();
5192: my $cachetime = 60*60*24;
5193: my $now = time;
5194: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5195: return %privileged;
5196: }
5197: foreach my $dom (@{$domains}) {
5198: next if (ref($privileged{$dom}) eq 'HASH');
5199: my $needroles;
5200: foreach my $role (@{$roles}) {
5201: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5202: if (defined($cached)) {
5203: if (ref($result) eq 'HASH') {
5204: $privileged{$dom}{$role} = $result;
5205: }
5206: } else {
5207: $needroles = 1;
5208: }
5209: }
5210: if ($needroles) {
5211: my %dompersonnel = &get_domain_roles($dom,$roles);
5212: $privileged{$dom} = {};
5213: foreach my $server (keys(%dompersonnel)) {
5214: if (ref($dompersonnel{$server}) eq 'HASH') {
5215: foreach my $item (keys(%{$dompersonnel{$server}})) {
5216: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5217: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5218: next if ($end && $end < $now);
5219: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5220: $dompersonnel{$server}{$item};
5221: }
5222: }
5223: }
5224: if (ref($privileged{$dom}) eq 'HASH') {
5225: foreach my $role (@{$roles}) {
5226: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5227: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5228: } else {
5229: my %hash = ();
5230: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5231: }
5232: }
5233: }
5234: }
5235: }
5236: return %privileged;
5237: }
5238:
1.103 harris41 5239: # -------------------------------------------------------- Get user privileges
1.11 www 5240:
5241: sub rolesinit {
1.1169 droeschl 5242: my ($domain, $username) = @_;
5243: my %userroles = ('user.login.time' => time);
5244: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5245:
5246: # firstaccess and timerinterval are related to timed maps/resources.
5247: # also, blocking can be triggered by an activating timer
5248: # it's saved in the user's %env.
5249: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5250: my %timerinterval = &dump('timerinterval', $domain, $username);
5251: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5252: %timerintchk, %timerintenv);
5253:
1.1162 raeburn 5254: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5255: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5256: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5257: }
1.1169 droeschl 5258:
1.1162 raeburn 5259: foreach my $key (keys(%timerinterval)) {
5260: my ($cid,$rest) = split(/\0/,$key);
5261: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5262: }
1.1169 droeschl 5263:
1.11 www 5264: my %allroles=();
1.1162 raeburn 5265: my %allgroups=();
1.11 www 5266:
1.1169 droeschl 5267: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5268: my $role = $rolesdump{$area};
5269: $area =~ s/\_\w\w$//;
5270:
5271: my ($trole, $tend, $tstart, $group_privs);
5272:
5273: if ($role =~ /^cr/) {
5274: # Custom role, defined by a user
5275: # e.g., user.role.cr/msu/smith/mynewrole
5276: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5277: $trole = $1;
5278: ($tend, $tstart) = split('_', $2);
5279: } else {
5280: $trole = $role;
5281: }
5282: } elsif ($role =~ m|^gr/|) {
5283: # Role of member in a group, defined within a course/community
5284: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5285: ($trole, $tend, $tstart) = split(/_/, $role);
5286: next if $tstart eq '-1';
5287: ($trole, $group_privs) = split(/\//, $trole);
5288: $group_privs = &unescape($group_privs);
5289: } else {
5290: # Just a normal role, defined in roles.tab
5291: ($trole, $tend, $tstart) = split(/_/,$role);
5292: }
5293:
5294: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5295: $username);
5296: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5297:
5298: # role expired or not available yet?
5299: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5300: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5301:
5302: next if $area eq '' or $trole eq '';
5303:
5304: my $spec = "$trole.$area";
5305: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5306:
5307: if ($trole =~ /^cr\//) {
5308: # Custom role, defined by a user
5309: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5310: } elsif ($trole eq 'gr') {
5311: # Role of a member in a group, defined within a course/community
5312: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5313: next;
5314: } else {
5315: # Normal role, defined in roles.tab
5316: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5317: }
5318:
5319: my $cid = $tdomain.'_'.$trest;
5320: unless ($firstaccchk{$cid}) {
5321: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5322: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5323: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5324: $coursetimerstarts{$cid}{$item};
5325: }
5326: }
5327: $firstaccchk{$cid} = 1;
5328: }
5329: unless ($timerintchk{$cid}) {
5330: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5331: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5332: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5333: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5334: }
1.12 www 5335: }
1.1169 droeschl 5336: $timerintchk{$cid} = 1;
1.191 harris41 5337: }
1.11 www 5338: }
1.1169 droeschl 5339:
5340: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5341: \%allroles, \%allgroups);
5342: $env{'user.adv'} = $userroles{'user.adv'};
5343:
1.1162 raeburn 5344: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5345: }
5346:
1.567 raeburn 5347: sub set_arearole {
1.1172.2.19 raeburn 5348: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5349: unless ($nolog) {
1.567 raeburn 5350: # log the associated role with the area
1.1172.2.19 raeburn 5351: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5352: }
1.743 albertel 5353: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5354: }
5355:
5356: sub custom_roleprivs {
5357: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5358: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5359: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5360: if (&hostname($homsvr) ne '') {
1.567 raeburn 5361: my ($rdummy,$roledef)=
5362: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5363: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5364: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5365: if (defined($syspriv)) {
1.1043 raeburn 5366: if ($trest =~ /^$match_community$/) {
5367: $syspriv =~ s/bre\&S//;
5368: }
1.567 raeburn 5369: $$allroles{'cm./'}.=':'.$syspriv;
5370: $$allroles{$spec.'./'}.=':'.$syspriv;
5371: }
5372: if ($tdomain ne '') {
5373: if (defined($dompriv)) {
5374: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5375: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5376: }
5377: if (($trest ne '') && (defined($coursepriv))) {
5378: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5379: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5380: }
5381: }
5382: }
5383: }
5384: }
5385:
1.678 raeburn 5386: sub group_roleprivs {
5387: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5388: my $access = 1;
5389: my $now = time;
5390: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5391: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5392: if ($access) {
1.811 albertel 5393: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5394: $$allgroups{$course}{$group} .=':'.$group_privs;
5395: }
5396: }
1.567 raeburn 5397:
5398: sub standard_roleprivs {
5399: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5400: if (defined($pr{$trole.':s'})) {
5401: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5402: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5403: }
5404: if ($tdomain ne '') {
5405: if (defined($pr{$trole.':d'})) {
5406: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5407: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5408: }
5409: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5410: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5411: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5412: }
5413: }
5414: }
5415:
5416: sub set_userprivs {
1.1064 raeburn 5417: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5418: my $author=0;
5419: my $adv=0;
1.678 raeburn 5420: my %grouproles = ();
5421: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5422: my @groupkeys;
1.1000 raeburn 5423: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5424: push(@groupkeys,$role);
5425: }
5426: if (ref($groups_roles) eq 'HASH') {
5427: foreach my $key (keys(%{$groups_roles})) {
5428: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5429: push(@groupkeys,$key);
5430: }
5431: }
5432: }
5433: if (@groupkeys > 0) {
5434: foreach my $role (@groupkeys) {
5435: my ($trole,$area,$sec,$extendedarea);
5436: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5437: $trole = $1;
5438: $area = $2;
5439: $sec = $3;
5440: $extendedarea = $area.$sec;
5441: if (exists($$allgroups{$area})) {
5442: foreach my $group (keys(%{$$allgroups{$area}})) {
5443: my $spec = $trole.'.'.$extendedarea;
5444: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5445: $$allgroups{$area}{$group};
1.1064 raeburn 5446: }
1.678 raeburn 5447: }
5448: }
5449: }
5450: }
5451: }
1.800 albertel 5452: foreach my $group (keys(%grouproles)) {
5453: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5454: }
1.800 albertel 5455: foreach my $role (keys(%{$allroles})) {
5456: my %thesepriv;
1.941 raeburn 5457: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5458: foreach my $item (split(/:/,$$allroles{$role})) {
5459: if ($item ne '') {
5460: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5461: if ($restrictions eq '') {
5462: $thesepriv{$privilege}='F';
5463: } elsif ($thesepriv{$privilege} ne 'F') {
5464: $thesepriv{$privilege}.=$restrictions;
5465: }
5466: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5467: }
5468: }
5469: my $thesestr='';
1.1104 raeburn 5470: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5471: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5472: }
5473: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5474: }
5475: return ($author,$adv);
5476: }
5477:
1.994 raeburn 5478: sub role_status {
1.1104 raeburn 5479: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5480: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5481: my ($one,$two) = split(m{\./},$rolekey,2);
5482: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5483: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5484: $$where = '/'.$two;
1.994 raeburn 5485: $$trolecode=$$role.'.'.$$where;
5486: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5487: $$tstatus='is';
1.1104 raeburn 5488: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5489: $$tstatus='future';
1.1034 raeburn 5490: if ($$tstart<$now) {
5491: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5492: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5493: my (%allroles,%allgroups,$group_privs,
5494: %groups_roles,@rolecodes);
1.1002 raeburn 5495: my %userroles = (
5496: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5497: );
1.1064 raeburn 5498: @rolecodes = ('cm');
1.1002 raeburn 5499: my $spec=$$role.'.'.$$where;
5500: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5501: if ($$role =~ /^cr\//) {
5502: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5503: push(@rolecodes,'cr');
1.1002 raeburn 5504: } elsif ($$role eq 'gr') {
1.1064 raeburn 5505: push(@rolecodes,$$role);
1.1002 raeburn 5506: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5507: $env{'user.name'});
1.1064 raeburn 5508: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5509: (undef,my $group_privs) = split(/\//,$trole);
5510: $group_privs = &unescape($group_privs);
5511: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5512: 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 5513: &get_groups_roles($tdomain,$trest,
5514: \%course_roles,\@rolecodes,
5515: \%groups_roles);
1.1002 raeburn 5516: } else {
1.1064 raeburn 5517: push(@rolecodes,$$role);
1.1002 raeburn 5518: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5519: }
1.1064 raeburn 5520: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5521: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5522: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5523: }
5524: }
1.1034 raeburn 5525: $$tstatus = 'is';
1.1002 raeburn 5526: }
1.994 raeburn 5527: }
5528: if ($$tend) {
1.1104 raeburn 5529: if ($$tend<$update) {
1.994 raeburn 5530: $$tstatus='expired';
5531: } elsif ($$tend<$now) {
5532: $$tstatus='will_not';
5533: }
5534: }
5535: }
5536: }
5537: }
5538:
1.1104 raeburn 5539: sub get_groups_roles {
5540: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5541: return unless((ref($cdom_courseroles) eq 'HASH') &&
5542: (ref($rolecodes) eq 'ARRAY') &&
5543: (ref($groups_roles) eq 'HASH'));
5544: if (keys(%{$cdom_courseroles}) > 0) {
5545: my ($cnum) = ($rest =~ /^($match_courseid)/);
5546: if ($cdom ne '' && $cnum ne '') {
5547: foreach my $key (keys(%{$cdom_courseroles})) {
5548: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5549: my $crsrole = $1;
5550: my $crssec = $2;
5551: if ($crsrole =~ /^cr/) {
5552: unless (grep(/^cr$/,@{$rolecodes})) {
5553: push(@{$rolecodes},'cr');
5554: }
5555: } else {
5556: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5557: push(@{$rolecodes},$crsrole);
5558: }
5559: }
5560: my $rolekey = "$crsrole./$cdom/$cnum";
5561: if ($crssec ne '') {
5562: $rolekey .= "/$crssec";
5563: }
5564: $rolekey .= './';
5565: $groups_roles->{$rolekey} = $rolecodes;
5566: }
5567: }
5568: }
5569: }
5570: return;
5571: }
5572:
5573: sub delete_env_groupprivs {
5574: my ($where,$courseroles,$possroles) = @_;
5575: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5576: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5577: unless (ref($courseroles->{$udom}) eq 'HASH') {
5578: %{$courseroles->{$udom}} =
5579: &get_my_roles('','','userroles',['active'],
5580: $possroles,[$udom],1);
5581: }
5582: if (ref($courseroles->{$udom}) eq 'HASH') {
5583: foreach my $item (keys(%{$courseroles->{$udom}})) {
5584: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5585: my $area = '/'.$cdom.'/'.$cnum;
5586: my $privkey = "user.priv.$crsrole.$area";
5587: if ($crssec ne '') {
5588: $privkey .= '/'.$crssec;
5589: }
5590: $privkey .= ".$area/$group";
5591: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5592: }
5593: }
5594: return;
5595: }
5596:
1.994 raeburn 5597: sub check_adhoc_privs {
1.1104 raeburn 5598: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5599: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5600: my $setprivs;
1.994 raeburn 5601: if ($env{$cckey}) {
5602: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5603: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5604: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5605: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5606: $setprivs = 1;
1.994 raeburn 5607: }
5608: } else {
1.1088 raeburn 5609: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5610: $setprivs = 1;
1.994 raeburn 5611: }
1.1172.2.9 raeburn 5612: return $setprivs;
1.994 raeburn 5613: }
5614:
5615: sub set_adhoc_privileges {
5616: # role can be cc or ca
1.1088 raeburn 5617: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5618: my $area = '/'.$dcdom.'/'.$pickedcourse;
5619: my $spec = $role.'.'.$area;
5620: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5621: $env{'user.name'},1);
1.994 raeburn 5622: my %ccrole = ();
5623: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5624: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5625: &appenv(\%userroles,[$role,'cm']);
5626: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5627: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5628: &appenv( {'request.role' => $spec,
5629: 'request.role.domain' => $dcdom,
5630: 'request.course.sec' => ''
5631: }
5632: );
5633: my $tadv=0;
5634: if (&allowed('adv') eq 'F') { $tadv=1; }
5635: &appenv({'request.role.adv' => $tadv});
5636: }
1.994 raeburn 5637: }
5638:
1.12 www 5639: # --------------------------------------------------------------- get interface
5640:
5641: sub get {
1.131 albertel 5642: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5643: my $items='';
1.800 albertel 5644: foreach my $item (@$storearr) {
5645: $items.=&escape($item).'&';
1.191 harris41 5646: }
1.12 www 5647: $items=~s/\&$//;
1.620 albertel 5648: if (!$udomain) { $udomain=$env{'user.domain'}; }
5649: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5650: my $uhome=&homeserver($uname,$udomain);
5651:
1.133 albertel 5652: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5653: my @pairs=split(/\&/,$rep);
1.273 albertel 5654: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5655: return @pairs;
5656: }
1.15 www 5657: my %returnhash=();
1.42 www 5658: my $i=0;
1.800 albertel 5659: foreach my $item (@$storearr) {
5660: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5661: $i++;
1.191 harris41 5662: }
1.15 www 5663: return %returnhash;
1.27 www 5664: }
5665:
5666: # --------------------------------------------------------------- del interface
5667:
5668: sub del {
1.133 albertel 5669: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5670: my $items='';
1.800 albertel 5671: foreach my $item (@$storearr) {
5672: $items.=&escape($item).'&';
1.191 harris41 5673: }
1.984 neumanie 5674:
1.27 www 5675: $items=~s/\&$//;
1.620 albertel 5676: if (!$udomain) { $udomain=$env{'user.domain'}; }
5677: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5678: my $uhome=&homeserver($uname,$udomain);
5679: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5680: }
5681:
5682: # -------------------------------------------------------------- dump interface
5683:
1.1172.2.22 raeburn 5684: sub unserialize {
5685: my ($rep, $escapedkeys) = @_;
5686:
5687: return {} if $rep =~ /^error/;
5688:
5689: my %returnhash=();
5690: foreach my $item (split(/\&/,$rep)) {
5691: my ($key, $value) = split(/=/, $item, 2);
5692: $key = unescape($key) unless $escapedkeys;
5693: next if $key =~ /^error: 2 /;
5694: $returnhash{$key} = &thaw_unescape($value);
5695: }
5696: return \%returnhash;
5697: }
5698:
5699: # see Lond::dump_with_regexp
5700: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5701: sub dump {
1.1172.2.22 raeburn 5702: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5703: if (!$udomain) { $udomain=$env{'user.domain'}; }
5704: if (!$uname) { $uname=$env{'user.name'}; }
5705: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5706:
1.1172.2.55! raeburn 5707: if ($regexp) {
! 5708: $regexp=&escape($regexp);
! 5709: } else {
! 5710: $regexp='.';
! 5711: }
1.1172.2.22 raeburn 5712: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5713: # user is hosted on this machine
1.1172.2.55! raeburn 5714: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5715: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5716: return %{&unserialize($reply, $escapedkeys)};
5717: }
1.1166 raeburn 5718: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5719: my @pairs=split(/\&/,$rep);
5720: my %returnhash=();
1.1098 foxr 5721: if (!($rep =~ /^error/ )) {
5722: foreach my $item (@pairs) {
5723: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5724: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5725: next if ($key =~ /^error: 2 /);
5726: $returnhash{$key}=&thaw_unescape($value);
5727: }
1.755 albertel 5728: }
5729: return %returnhash;
1.407 www 5730: }
5731:
1.1098 foxr 5732:
1.717 albertel 5733: # --------------------------------------------------------- dumpstore interface
5734:
5735: sub dumpstore {
5736: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5737: # same as dump but keys must be escaped. They may contain colon separated
5738: # lists of values that may themself contain colons (e.g. symbs).
5739: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5740: }
5741:
1.407 www 5742: # -------------------------------------------------------------- keys interface
5743:
5744: sub getkeys {
5745: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5746: if (!$udomain) { $udomain=$env{'user.domain'}; }
5747: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5748: my $uhome=&homeserver($uname,$udomain);
5749: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5750: my @keyarray=();
1.800 albertel 5751: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5752: next if ($key =~ /^error: 2 /);
1.800 albertel 5753: push(@keyarray,&unescape($key));
1.407 www 5754: }
5755: return @keyarray;
1.318 matthew 5756: }
5757:
1.319 matthew 5758: # --------------------------------------------------------------- currentdump
5759: sub currentdump {
1.328 matthew 5760: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5761: $courseid = $env{'request.course.id'} if (! defined($courseid));
5762: $sdom = $env{'user.domain'} if (! defined($sdom));
5763: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5764: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 5765: my $rep;
5766:
5767: if (grep { $_ eq $uhome } current_machine_ids()) {
5768: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5769: $courseid)));
5770: } else {
5771: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5772: }
5773:
1.318 matthew 5774: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5775: #
1.318 matthew 5776: my %returnhash=();
1.319 matthew 5777: #
5778: if ($rep eq "unknown_cmd") {
5779: # an old lond will not know currentdump
5780: # Do a dump and make it look like a currentdump
1.822 albertel 5781: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5782: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5783: my %hash = @tmp;
5784: @tmp=();
1.424 matthew 5785: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5786: } else {
5787: my @pairs=split(/\&/,$rep);
1.800 albertel 5788: foreach my $pair (@pairs) {
5789: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5790: my ($symb,$param) = split(/:/,$key);
5791: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5792: &thaw_unescape($value);
1.319 matthew 5793: }
1.191 harris41 5794: }
1.12 www 5795: return %returnhash;
1.424 matthew 5796: }
5797:
5798: sub convert_dump_to_currentdump{
5799: my %hash = %{shift()};
5800: my %returnhash;
5801: # Code ripped from lond, essentially. The only difference
5802: # here is the unescaping done by lonnet::dump(). Conceivably
5803: # we might run in to problems with parameter names =~ /^v\./
5804: while (my ($key,$value) = each(%hash)) {
5805: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5806: $symb = &unescape($symb);
5807: $param = &unescape($param);
1.424 matthew 5808: next if ($v eq 'version' || $symb eq 'keys');
5809: next if (exists($returnhash{$symb}) &&
5810: exists($returnhash{$symb}->{$param}) &&
5811: $returnhash{$symb}->{'v.'.$param} > $v);
5812: $returnhash{$symb}->{$param}=$value;
5813: $returnhash{$symb}->{'v.'.$param}=$v;
5814: }
5815: #
5816: # Remove all of the keys in the hashes which keep track of
5817: # the version of the parameter.
5818: while (my ($symb,$param_hash) = each(%returnhash)) {
5819: # use a foreach because we are going to delete from the hash.
5820: foreach my $key (keys(%$param_hash)) {
5821: delete($param_hash->{$key}) if ($key =~ /^v\./);
5822: }
5823: }
5824: return \%returnhash;
1.12 www 5825: }
5826:
1.627 albertel 5827: # ------------------------------------------------------ critical inc interface
5828:
5829: sub cinc {
5830: return &inc(@_,'critical');
5831: }
5832:
1.449 matthew 5833: # --------------------------------------------------------------- inc interface
5834:
5835: sub inc {
1.627 albertel 5836: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5837: if (!$udomain) { $udomain=$env{'user.domain'}; }
5838: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5839: my $uhome=&homeserver($uname,$udomain);
5840: my $items='';
5841: if (! ref($store)) {
5842: # got a single value, so use that instead
5843: $items = &escape($store).'=&';
5844: } elsif (ref($store) eq 'SCALAR') {
5845: $items = &escape($$store).'=&';
5846: } elsif (ref($store) eq 'ARRAY') {
5847: $items = join('=&',map {&escape($_);} @{$store});
5848: } elsif (ref($store) eq 'HASH') {
5849: while (my($key,$value) = each(%{$store})) {
5850: $items.= &escape($key).'='.&escape($value).'&';
5851: }
5852: }
5853: $items=~s/\&$//;
1.627 albertel 5854: if ($critical) {
5855: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5856: } else {
5857: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5858: }
1.449 matthew 5859: }
5860:
1.12 www 5861: # --------------------------------------------------------------- put interface
5862:
5863: sub put {
1.134 albertel 5864: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5865: if (!$udomain) { $udomain=$env{'user.domain'}; }
5866: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5867: my $uhome=&homeserver($uname,$udomain);
1.12 www 5868: my $items='';
1.800 albertel 5869: foreach my $item (keys(%$storehash)) {
5870: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5871: }
1.12 www 5872: $items=~s/\&$//;
1.134 albertel 5873: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5874: }
5875:
1.631 albertel 5876: # ------------------------------------------------------------ newput interface
5877:
5878: sub newput {
5879: my ($namespace,$storehash,$udomain,$uname)=@_;
5880: if (!$udomain) { $udomain=$env{'user.domain'}; }
5881: if (!$uname) { $uname=$env{'user.name'}; }
5882: my $uhome=&homeserver($uname,$udomain);
5883: my $items='';
5884: foreach my $key (keys(%$storehash)) {
5885: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5886: }
5887: $items=~s/\&$//;
5888: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5889: }
5890:
5891: # --------------------------------------------------------- putstore interface
5892:
1.524 raeburn 5893: sub putstore {
1.715 albertel 5894: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5895: if (!$udomain) { $udomain=$env{'user.domain'}; }
5896: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5897: my $uhome=&homeserver($uname,$udomain);
5898: my $items='';
1.715 albertel 5899: foreach my $key (keys(%$storehash)) {
5900: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5901: }
1.715 albertel 5902: $items=~s/\&$//;
1.716 albertel 5903: my $esc_symb=&escape($symb);
5904: my $esc_v=&escape($version);
1.715 albertel 5905: my $reply =
1.716 albertel 5906: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5907: $uhome);
5908: if ($reply eq 'unknown_cmd') {
1.716 albertel 5909: # gfall back to way things use to be done
1.715 albertel 5910: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5911: $uname);
1.524 raeburn 5912: }
1.715 albertel 5913: return $reply;
5914: }
5915:
5916: sub old_putstore {
1.716 albertel 5917: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5918: if (!$udomain) { $udomain=$env{'user.domain'}; }
5919: if (!$uname) { $uname=$env{'user.name'}; }
5920: my $uhome=&homeserver($uname,$udomain);
5921: my %newstorehash;
1.800 albertel 5922: foreach my $item (keys(%$storehash)) {
5923: my $key = $version.':'.&escape($symb).':'.$item;
5924: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5925: }
5926: my $items='';
5927: my %allitems = ();
1.800 albertel 5928: foreach my $item (keys(%newstorehash)) {
5929: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5930: my $key = $1.':keys:'.$2;
5931: $allitems{$key} .= $3.':';
5932: }
1.800 albertel 5933: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5934: }
1.800 albertel 5935: foreach my $item (keys(%allitems)) {
5936: $allitems{$item} =~ s/\:$//;
5937: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5938: }
5939: $items=~s/\&$//;
5940: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5941: }
5942:
1.47 www 5943: # ------------------------------------------------------ critical put interface
5944:
5945: sub cput {
1.134 albertel 5946: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5947: if (!$udomain) { $udomain=$env{'user.domain'}; }
5948: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5949: my $uhome=&homeserver($uname,$udomain);
1.47 www 5950: my $items='';
1.800 albertel 5951: foreach my $item (keys(%$storehash)) {
5952: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5953: }
1.47 www 5954: $items=~s/\&$//;
1.134 albertel 5955: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5956: }
5957:
5958: # -------------------------------------------------------------- eget interface
5959:
5960: sub eget {
1.133 albertel 5961: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5962: my $items='';
1.800 albertel 5963: foreach my $item (@$storearr) {
5964: $items.=&escape($item).'&';
1.191 harris41 5965: }
1.12 www 5966: $items=~s/\&$//;
1.620 albertel 5967: if (!$udomain) { $udomain=$env{'user.domain'}; }
5968: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5969: my $uhome=&homeserver($uname,$udomain);
5970: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5971: my @pairs=split(/\&/,$rep);
5972: my %returnhash=();
1.42 www 5973: my $i=0;
1.800 albertel 5974: foreach my $item (@$storearr) {
5975: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5976: $i++;
1.191 harris41 5977: }
1.12 www 5978: return %returnhash;
5979: }
5980:
1.667 albertel 5981: # ------------------------------------------------------------ tmpput interface
5982: sub tmpput {
1.802 raeburn 5983: my ($storehash,$server,$context)=@_;
1.667 albertel 5984: my $items='';
1.800 albertel 5985: foreach my $item (keys(%$storehash)) {
5986: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5987: }
5988: $items=~s/\&$//;
1.802 raeburn 5989: if (defined($context)) {
5990: $items .= ':'.&escape($context);
5991: }
1.667 albertel 5992: return &reply("tmpput:$items",$server);
5993: }
5994:
5995: # ------------------------------------------------------------ tmpget interface
5996: sub tmpget {
1.688 albertel 5997: my ($token,$server)=@_;
5998: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5999: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6000: my %returnhash;
6001: foreach my $item (split(/\&/,$rep)) {
6002: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6003: next if ($key =~ /^error: 2 /);
1.667 albertel 6004: $returnhash{&unescape($key)}=&thaw_unescape($value);
6005: }
6006: return %returnhash;
6007: }
6008:
1.1113 raeburn 6009: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6010: sub tmpdel {
6011: my ($token,$server)=@_;
6012: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6013: return &reply("tmpdel:$token",$server);
6014: }
6015:
1.1172.2.13 raeburn 6016: # ------------------------------------------------------------ get_timebased_id
6017:
6018: sub get_timebased_id {
6019: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6020: $maxtries) = @_;
6021: my ($newid,$error,$dellock);
6022: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6023: return ('','ok','invalid call to get suffix');
6024: }
6025:
6026: # set defaults for any optional args for which values were not supplied
6027: if ($who eq '') {
6028: $who = $env{'user.name'}.':'.$env{'user.domain'};
6029: }
6030: if (!$locktries) {
6031: $locktries = 3;
6032: }
6033: if (!$maxtries) {
6034: $maxtries = 10;
6035: }
6036:
6037: if (($cdom eq '') || ($cnum eq '')) {
6038: if ($env{'request.course.id'}) {
6039: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6040: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6041: }
6042: if (($cdom eq '') || ($cnum eq '')) {
6043: return ('','ok','call to get suffix not in course context');
6044: }
6045: }
6046:
6047: # construct locking item
6048: my $lockhash = {
6049: $prefix."\0".'locked_'.$keyid => $who,
6050: };
6051: my $tries = 0;
6052:
6053: # attempt to get lock on nohist_$namespace file
6054: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6055: while (($gotlock ne 'ok') && $tries <$locktries) {
6056: $tries ++;
6057: sleep 1;
6058: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6059: }
6060:
6061: # attempt to get unique identifier, based on current timestamp
6062: if ($gotlock eq 'ok') {
6063: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6064: my $id = time;
6065: $newid = $id;
6066: my $idtries = 0;
6067: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6068: if ($idtype eq 'concat') {
6069: $newid = $id.$idtries;
6070: } else {
6071: $newid ++;
6072: }
6073: $idtries ++;
6074: }
6075: if (!exists($inuse{$prefix."\0".$newid})) {
6076: my %new_item = (
6077: $prefix."\0".$newid => $who,
6078: );
6079: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6080: $cdom,$cnum);
6081: if ($putresult ne 'ok') {
6082: undef($newid);
6083: $error = 'error saving new item: '.$putresult;
6084: }
6085: } else {
6086: $error = ('error: no unique suffix available for the new item ');
6087: }
6088: # remove lock
6089: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6090: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6091: } else {
6092: $error = "error: could not obtain lockfile\n";
6093: $dellock = 'ok';
6094: }
6095: return ($newid,$dellock,$error);
6096: }
6097:
1.765 albertel 6098: # -------------------------------------------------- portfolio access checking
6099:
6100: sub portfolio_access {
1.766 albertel 6101: my ($requrl) = @_;
1.765 albertel 6102: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6103: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6104: if ($result) {
6105: my %setters;
6106: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6107: my ($startblock,$endblock) =
6108: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6109: if ($startblock && $endblock) {
6110: return 'B';
6111: }
6112: } else {
6113: my ($startblock,$endblock) =
6114: &Apache::loncommon::blockcheck(\%setters,'port');
6115: if ($startblock && $endblock) {
6116: return 'B';
6117: }
6118: }
6119: }
1.765 albertel 6120: if ($result eq 'ok') {
1.766 albertel 6121: return 'F';
1.765 albertel 6122: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6123: return 'A';
1.765 albertel 6124: }
1.766 albertel 6125: return '';
1.765 albertel 6126: }
6127:
6128: sub get_portfolio_access {
1.767 albertel 6129: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6130:
6131: if (!ref($access_hash)) {
6132: my $current_perms = &get_portfile_permissions($udom,$unum);
6133: my %access_controls = &get_access_controls($current_perms,$group,
6134: $file_name);
6135: $access_hash = $access_controls{$file_name};
6136: }
6137:
1.765 albertel 6138: my ($public,$guest,@domains,@users,@courses,@groups);
6139: my $now = time;
6140: if (ref($access_hash) eq 'HASH') {
6141: foreach my $key (keys(%{$access_hash})) {
6142: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6143: if ($start > $now) {
6144: next;
6145: }
6146: if ($end && $end<$now) {
6147: next;
6148: }
6149: if ($scope eq 'public') {
6150: $public = $key;
6151: last;
6152: } elsif ($scope eq 'guest') {
6153: $guest = $key;
6154: } elsif ($scope eq 'domains') {
6155: push(@domains,$key);
6156: } elsif ($scope eq 'users') {
6157: push(@users,$key);
6158: } elsif ($scope eq 'course') {
6159: push(@courses,$key);
6160: } elsif ($scope eq 'group') {
6161: push(@groups,$key);
6162: }
6163: }
6164: if ($public) {
6165: return 'ok';
6166: }
6167: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6168: if ($guest) {
6169: return $guest;
6170: }
6171: } else {
6172: if (@domains > 0) {
6173: foreach my $domkey (@domains) {
6174: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6175: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6176: return 'ok';
6177: }
6178: }
6179: }
6180: }
6181: if (@users > 0) {
6182: foreach my $userkey (@users) {
1.865 raeburn 6183: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6184: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6185: if (ref($item) eq 'HASH') {
6186: if (($item->{'uname'} eq $env{'user.name'}) &&
6187: ($item->{'udom'} eq $env{'user.domain'})) {
6188: return 'ok';
6189: }
6190: }
6191: }
6192: }
1.765 albertel 6193: }
6194: }
6195: my %roleshash;
6196: my @courses_and_groups = @courses;
6197: push(@courses_and_groups,@groups);
6198: if (@courses_and_groups > 0) {
6199: my (%allgroups,%allroles);
6200: my ($start,$end,$role,$sec,$group);
6201: foreach my $envkey (%env) {
1.1060 raeburn 6202: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6203: my $cid = $2.'_'.$3;
6204: if ($1 eq 'gr') {
6205: $group = $4;
6206: $allgroups{$cid}{$group} = $env{$envkey};
6207: } else {
6208: if ($4 eq '') {
6209: $sec = 'none';
6210: } else {
6211: $sec = $4;
6212: }
6213: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6214: }
1.811 albertel 6215: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6216: my $cid = $2.'_'.$3;
6217: if ($4 eq '') {
6218: $sec = 'none';
6219: } else {
6220: $sec = $4;
6221: }
6222: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6223: }
6224: }
6225: if (keys(%allroles) == 0) {
6226: return;
6227: }
6228: foreach my $key (@courses_and_groups) {
6229: my %content = %{$$access_hash{$key}};
6230: my $cnum = $content{'number'};
6231: my $cdom = $content{'domain'};
6232: my $cid = $cdom.'_'.$cnum;
6233: if (!exists($allroles{$cid})) {
6234: next;
6235: }
6236: foreach my $role_id (keys(%{$content{'roles'}})) {
6237: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6238: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6239: my @status = @{$content{'roles'}{$role_id}{'access'}};
6240: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6241: foreach my $role (keys(%{$allroles{$cid}})) {
6242: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6243: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6244: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6245: if (grep/^all$/,@sections) {
6246: return 'ok';
6247: } else {
6248: if (grep/^$sec$/,@sections) {
6249: return 'ok';
6250: }
6251: }
6252: }
6253: }
6254: if (keys(%{$allgroups{$cid}}) == 0) {
6255: if (grep/^none$/,@groups) {
6256: return 'ok';
6257: }
6258: } else {
6259: if (grep/^all$/,@groups) {
6260: return 'ok';
6261: }
6262: foreach my $group (keys(%{$allgroups{$cid}})) {
6263: if (grep/^$group$/,@groups) {
6264: return 'ok';
6265: }
6266: }
6267: }
6268: }
6269: }
6270: }
6271: }
6272: }
6273: if ($guest) {
6274: return $guest;
6275: }
6276: }
6277: }
6278: return;
6279: }
6280:
6281: sub course_group_datechecker {
6282: my ($dates,$now,$status) = @_;
6283: my ($start,$end) = split(/\./,$dates);
6284: if (!$start && !$end) {
6285: return 'ok';
6286: }
6287: if (grep/^active$/,@{$status}) {
6288: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6289: return 'ok';
6290: }
6291: }
6292: if (grep/^previous$/,@{$status}) {
6293: if ($end > $now ) {
6294: return 'ok';
6295: }
6296: }
6297: if (grep/^future$/,@{$status}) {
6298: if ($start > $now) {
6299: return 'ok';
6300: }
6301: }
6302: return;
6303: }
6304:
6305: sub parse_portfolio_url {
6306: my ($url) = @_;
6307:
6308: my ($type,$udom,$unum,$group,$file_name);
6309:
1.823 albertel 6310: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6311: $type = 1;
6312: $udom = $1;
6313: $unum = $2;
6314: $file_name = $3;
1.823 albertel 6315: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6316: $type = 2;
6317: $udom = $1;
6318: $unum = $2;
6319: $group = $3;
6320: $file_name = $3.'/'.$4;
6321: }
6322: if (wantarray) {
6323: return ($type,$udom,$unum,$file_name,$group);
6324: }
6325: return $type;
6326: }
6327:
6328: sub is_portfolio_url {
6329: my ($url) = @_;
6330: return scalar(&parse_portfolio_url($url));
6331: }
6332:
1.798 raeburn 6333: sub is_portfolio_file {
6334: my ($file) = @_;
1.820 raeburn 6335: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6336: return 1;
6337: }
6338: return;
6339: }
6340:
1.976 raeburn 6341: sub usertools_access {
1.1084 raeburn 6342: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6343: my ($access,%tools);
6344: if ($context eq '') {
6345: $context = 'tools';
6346: }
6347: if ($context eq 'requestcourses') {
6348: %tools = (
6349: official => 1,
6350: unofficial => 1,
1.1006 raeburn 6351: community => 1,
1.1172.2.37 raeburn 6352: textbook => 1,
1.985 raeburn 6353: );
1.1172.2.9 raeburn 6354: } elsif ($context eq 'requestauthor') {
6355: %tools = (
6356: requestauthor => 1,
6357: );
1.985 raeburn 6358: } else {
6359: %tools = (
6360: aboutme => 1,
6361: blog => 1,
1.1172.2.6 raeburn 6362: webdav => 1,
1.985 raeburn 6363: portfolio => 1,
6364: );
6365: }
1.976 raeburn 6366: return if (!defined($tools{$tool}));
6367:
1.1172.2.35 raeburn 6368: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6369: $udom = $env{'user.domain'};
6370: $uname = $env{'user.name'};
6371: }
6372:
1.978 raeburn 6373: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6374: if ($action ne 'reload') {
1.985 raeburn 6375: if ($context eq 'requestcourses') {
6376: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6377: } elsif ($context eq 'requestauthor') {
6378: return $env{'environment.canrequest.author'};
1.985 raeburn 6379: } else {
6380: return $env{'environment.availabletools.'.$tool};
6381: }
6382: }
1.976 raeburn 6383: }
6384:
1.1172.2.9 raeburn 6385: my ($toolstatus,$inststatus,$envkey);
6386: if ($context eq 'requestauthor') {
6387: $envkey = $context;
6388: } else {
6389: $envkey = $context.'.'.$tool;
6390: }
1.976 raeburn 6391:
1.985 raeburn 6392: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6393: ($action ne 'reload')) {
1.1172.2.9 raeburn 6394: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6395: $inststatus = $env{'environment.inststatus'};
6396: } else {
1.1084 raeburn 6397: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6398: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6399: $inststatus = $userenvref->{'inststatus'};
6400: } else {
1.1172.2.9 raeburn 6401: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6402: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6403: $inststatus = $userenv{'inststatus'};
6404: }
1.976 raeburn 6405: }
6406:
6407: if ($toolstatus ne '') {
6408: if ($toolstatus) {
6409: $access = 1;
6410: } else {
6411: $access = 0;
6412: }
6413: return $access;
6414: }
6415:
1.1084 raeburn 6416: my ($is_adv,%domdef);
6417: if (ref($is_advref) eq 'HASH') {
6418: $is_adv = $is_advref->{'is_adv'};
6419: } else {
6420: $is_adv = &is_advanced_user($udom,$uname);
6421: }
6422: if (ref($domdefref) eq 'HASH') {
6423: %domdef = %{$domdefref};
6424: } else {
6425: %domdef = &get_domain_defaults($udom);
6426: }
1.976 raeburn 6427: if (ref($domdef{$tool}) eq 'HASH') {
6428: if ($is_adv) {
6429: if ($domdef{$tool}{'_LC_adv'} ne '') {
6430: if ($domdef{$tool}{'_LC_adv'}) {
6431: $access = 1;
6432: } else {
6433: $access = 0;
6434: }
6435: return $access;
6436: }
6437: }
6438: if ($inststatus ne '') {
6439: my ($hasaccess,$hasnoaccess);
6440: foreach my $affiliation (split(/:/,$inststatus)) {
6441: if ($domdef{$tool}{$affiliation} ne '') {
6442: if ($domdef{$tool}{$affiliation}) {
6443: $hasaccess = 1;
6444: } else {
6445: $hasnoaccess = 1;
6446: }
6447: }
6448: }
6449: if ($hasaccess || $hasnoaccess) {
6450: if ($hasaccess) {
6451: $access = 1;
6452: } elsif ($hasnoaccess) {
6453: $access = 0;
6454: }
6455: return $access;
6456: }
6457: } else {
6458: if ($domdef{$tool}{'default'} ne '') {
6459: if ($domdef{$tool}{'default'}) {
6460: $access = 1;
6461: } elsif ($domdef{$tool}{'default'} == 0) {
6462: $access = 0;
6463: }
6464: return $access;
6465: }
6466: }
6467: } else {
1.1172.2.6 raeburn 6468: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6469: $access = 1;
6470: } else {
6471: $access = 0;
6472: }
1.976 raeburn 6473: return $access;
6474: }
6475: }
6476:
1.1050 raeburn 6477: sub is_course_owner {
6478: my ($cdom,$cnum,$udom,$uname) = @_;
6479: if (($udom eq '') || ($uname eq '')) {
6480: $udom = $env{'user.domain'};
6481: $uname = $env{'user.name'};
6482: }
6483: unless (($udom eq '') || ($uname eq '')) {
6484: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6485: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6486: return 1;
6487: } else {
6488: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6489: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6490: return 1;
6491: }
6492: }
6493: }
6494: }
6495: return;
6496: }
6497:
1.976 raeburn 6498: sub is_advanced_user {
6499: my ($udom,$uname) = @_;
1.1085 raeburn 6500: if ($udom ne '' && $uname ne '') {
6501: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6502: if (wantarray) {
6503: return ($env{'user.adv'},$env{'user.author'});
6504: } else {
6505: return $env{'user.adv'};
6506: }
1.1085 raeburn 6507: }
6508: }
1.976 raeburn 6509: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6510: my %allroles;
1.1128 raeburn 6511: my ($is_adv,$is_author);
1.976 raeburn 6512: foreach my $role (keys(%roleshash)) {
6513: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6514: my $area = '/'.$tdomain.'/'.$trest;
6515: if ($sec ne '') {
6516: $area .= '/'.$sec;
6517: }
6518: if (($area ne '') && ($trole ne '')) {
6519: my $spec=$trole.'.'.$area;
6520: if ($trole =~ /^cr\//) {
6521: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6522: } elsif ($trole ne 'gr') {
6523: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6524: }
1.1128 raeburn 6525: if ($trole eq 'au') {
6526: $is_author = 1;
6527: }
1.976 raeburn 6528: }
6529: }
6530: foreach my $role (keys(%allroles)) {
6531: last if ($is_adv);
6532: foreach my $item (split(/:/,$allroles{$role})) {
6533: if ($item ne '') {
6534: my ($privilege,$restrictions)=split(/&/,$item);
6535: if ($privilege eq 'adv') {
6536: $is_adv = 1;
6537: last;
6538: }
6539: }
6540: }
6541: }
1.1128 raeburn 6542: if (wantarray) {
6543: return ($is_adv,$is_author);
6544: }
1.976 raeburn 6545: return $is_adv;
6546: }
1.798 raeburn 6547:
1.1035 raeburn 6548: sub check_can_request {
1.1036 raeburn 6549: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6550: my $canreq = 0;
6551: my ($types,$typename) = &Apache::loncommon::course_types();
6552: my @options = ('approval','validate','autolimit');
6553: my $optregex = join('|',@options);
6554: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6555: foreach my $type (@{$types}) {
6556: if (&usertools_access($env{'user.name'},
6557: $env{'user.domain'},
6558: $type,undef,'requestcourses')) {
6559: $canreq ++;
1.1036 raeburn 6560: if (ref($request_domains) eq 'HASH') {
6561: push(@{$request_domains->{$type}},$env{'user.domain'});
6562: }
1.1035 raeburn 6563: if ($dom eq $env{'user.domain'}) {
6564: $can_request->{$type} = 1;
6565: }
6566: }
6567: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6568: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6569: if (@curr > 0) {
1.1036 raeburn 6570: foreach my $item (@curr) {
6571: if (ref($request_domains) eq 'HASH') {
6572: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6573: if ($otherdom ne '') {
6574: if (ref($request_domains->{$type}) eq 'ARRAY') {
6575: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6576: push(@{$request_domains->{$type}},$otherdom);
6577: }
6578: } else {
6579: push(@{$request_domains->{$type}},$otherdom);
6580: }
6581: }
6582: }
6583: }
6584: unless($dom eq $env{'user.domain'}) {
6585: $canreq ++;
1.1035 raeburn 6586: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6587: $can_request->{$type} = 1;
6588: }
6589: }
6590: }
6591: }
6592: }
6593: }
6594: return $canreq;
6595: }
6596:
1.341 www 6597: # ---------------------------------------------- Custom access rule evaluation
6598:
6599: sub customaccess {
6600: my ($priv,$uri)=@_;
1.807 albertel 6601: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6602: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6603: $udom = &LONCAPA::clean_domain($udom);
6604: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6605: my $access=0;
1.800 albertel 6606: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6607: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6608: if ($type eq 'user') {
6609: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6610: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6611: if ($tdom) {
6612: if ($tdom ne $env{'user.domain'}) { next; }
6613: }
1.896 albertel 6614: if ($tuname) {
6615: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6616: }
6617: $access=($effect eq 'allow');
6618: last;
6619: }
6620: } else {
6621: if ($role) {
6622: if ($role ne $urole) { next; }
6623: }
6624: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6625: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6626: if ($tdom) {
6627: if ($tdom ne $udom) { next; }
6628: }
6629: if ($tcrs) {
6630: if ($tcrs ne $ucrs) { next; }
6631: }
6632: if ($tsec) {
6633: if ($tsec ne $usec) { next; }
6634: }
6635: $access=($effect eq 'allow');
6636: last;
6637: }
6638: if ($realm eq '' && $role eq '') {
6639: $access=($effect eq 'allow');
6640: }
1.402 bowersj2 6641: }
1.341 www 6642: }
6643: return $access;
6644: }
6645:
1.103 harris41 6646: # ------------------------------------------------- Check for a user privilege
1.12 www 6647:
6648: sub allowed {
1.810 raeburn 6649: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6650: my $ver_orguri=$uri;
1.439 www 6651: $uri=&deversion($uri);
1.152 www 6652: my $orguri=$uri;
1.52 www 6653: $uri=&declutter($uri);
1.809 raeburn 6654:
1.810 raeburn 6655: if ($priv eq 'evb') {
6656: # Evade communication block restrictions for specified role in a course
6657: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6658: return $1;
6659: } else {
6660: return;
6661: }
6662: }
6663:
1.620 albertel 6664: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6665: # Free bre access to adm and meta resources
1.775 albertel 6666: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6667: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6668: && ($priv eq 'bre')) {
1.14 www 6669: return 'F';
1.159 www 6670: }
6671:
1.545 banghart 6672: # Free bre access to user's own portfolio contents
1.714 raeburn 6673: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6674: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6675: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6676: my %setters;
6677: my ($startblock,$endblock) =
6678: &Apache::loncommon::blockcheck(\%setters,'port');
6679: if ($startblock && $endblock) {
6680: return 'B';
6681: } else {
6682: return 'F';
6683: }
1.545 banghart 6684: }
6685:
1.762 raeburn 6686: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6687: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6688: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6689: if (exists($env{'request.course.id'})) {
6690: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6691: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6692: if (($domain eq $cdom) && ($name eq $cnum)) {
6693: my $courseprivid=$env{'request.course.id'};
6694: $courseprivid=~s/\_/\//;
6695: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6696: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6697: return $1;
1.762 raeburn 6698: } else {
6699: if ($env{'request.course.sec'}) {
6700: $courseprivid.='/'.$env{'request.course.sec'};
6701: }
6702: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6703: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6704: return $2;
6705: }
1.714 raeburn 6706: }
6707: }
6708: }
6709: }
6710:
1.159 www 6711: # Free bre to public access
6712:
6713: if ($priv eq 'bre') {
1.238 www 6714: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6715: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6716: return 'F';
6717: }
1.238 www 6718: if ($copyright eq 'priv') {
6719: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6720: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6721: return '';
6722: }
6723: }
6724: if ($copyright eq 'domain') {
6725: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6726: unless (($env{'user.domain'} eq $1) ||
6727: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6728: return '';
6729: }
1.262 matthew 6730: }
1.620 albertel 6731: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6732: # Library role, so allow browsing of resources in this domain.
6733: return 'F';
1.238 www 6734: }
1.341 www 6735: if ($copyright eq 'custom') {
6736: unless (&customaccess($priv,$uri)) { return ''; }
6737: }
1.14 www 6738: }
1.264 matthew 6739: # Domain coordinator is trying to create a course
1.620 albertel 6740: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6741: # uri is the requested domain in this case.
6742: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6743: # a role of dc for the domain in question.
1.620 albertel 6744: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6745: }
1.29 www 6746:
1.52 www 6747: my $thisallowed='';
6748: my $statecond=0;
6749: my $courseprivid='';
6750:
1.1039 raeburn 6751: my $ownaccess;
1.1043 raeburn 6752: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6753: if (($priv eq 'bro') && ($env{'user.author'})) {
6754: if ($uri eq '') {
6755: $ownaccess = 1;
6756: } else {
6757: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6758: my $udom = $env{'user.domain'};
6759: my $uname = $env{'user.name'};
6760: if ($uri =~ m{^\Q$udom\E/?$}) {
6761: $ownaccess = 1;
1.1040 raeburn 6762: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6763: unless ($uri =~ m{\.\./}) {
6764: $ownaccess = 1;
6765: }
6766: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6767: my $now = time;
6768: if ($uri =~ m{^([^/]+)/?$}) {
6769: my $adom = $1;
6770: foreach my $key (keys(%env)) {
1.1042 raeburn 6771: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6772: my ($start,$end) = split('.',$env{$key});
6773: if (($now >= $start) && (!$end || $end < $now)) {
6774: $ownaccess = 1;
6775: last;
6776: }
6777: }
6778: }
6779: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6780: my $adom = $1;
6781: my $aname = $2;
1.1042 raeburn 6782: foreach my $role ('ca','aa') {
6783: if ($env{"user.role.$role./$adom/$aname"}) {
6784: my ($start,$end) =
6785: split('.',$env{"user.role.$role./$adom/$aname"});
6786: if (($now >= $start) && (!$end || $end < $now)) {
6787: $ownaccess = 1;
6788: last;
6789: }
1.1039 raeburn 6790: }
6791: }
6792: }
6793: }
6794: }
6795: }
6796: }
6797:
1.52 www 6798: # Course
6799:
1.620 albertel 6800: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6801: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6802: $thisallowed.=$1;
6803: }
1.52 www 6804: }
1.29 www 6805:
1.52 www 6806: # Domain
6807:
1.620 albertel 6808: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6809: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6810: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6811: $thisallowed.=$1;
6812: }
1.12 www 6813: }
1.52 www 6814:
1.1141 raeburn 6815: # User who is not author or co-author might still be able to edit
6816: # resource of an author in the domain (e.g., if Domain Coordinator).
6817: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6818: (&allowed('mdc',$env{'request.course.id'}))) {
6819: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6820: $thisallowed.=$1;
6821: }
6822: }
6823:
1.52 www 6824: # Course: uri itself is a course
1.66 www 6825: my $courseuri=$uri;
6826: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6827: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6828:
1.620 albertel 6829: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6830: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6831: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6832: $thisallowed.=$1;
6833: }
1.12 www 6834: }
1.29 www 6835:
1.665 albertel 6836: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6837: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6838: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6839: $thisallowed='';
1.671 raeburn 6840: my ($match)=&is_on_map($uri);
6841: if ($match) {
6842: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6843: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6844: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6845: if (@blockers > 0) {
6846: $thisallowed = 'B';
6847: } else {
6848: $thisallowed.=$1;
6849: }
1.671 raeburn 6850: }
6851: } else {
1.705 albertel 6852: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6853: if ($refuri) {
6854: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6855: $thisallowed='F';
1.671 raeburn 6856: } else {
6857: $refuri=&declutter($refuri);
6858: my ($match) = &is_on_map($refuri);
6859: if ($match) {
1.1162 raeburn 6860: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6861: if (@blockers > 0) {
6862: $thisallowed = 'B';
6863: } else {
6864: $thisallowed='F';
6865: }
1.671 raeburn 6866: }
1.669 raeburn 6867: }
1.671 raeburn 6868: }
6869: }
1.314 www 6870: }
1.492 albertel 6871:
1.766 albertel 6872: if ($priv eq 'bre'
6873: && $thisallowed ne 'F'
6874: && $thisallowed ne '2'
6875: && &is_portfolio_url($uri)) {
6876: $thisallowed = &portfolio_access($uri);
6877: }
6878:
1.52 www 6879: # Full access at system, domain or course-wide level? Exit.
1.29 www 6880: if ($thisallowed=~/F/) {
6881: return 'F';
6882: }
6883:
1.52 www 6884: # If this is generating or modifying users, exit with special codes
1.29 www 6885:
1.643 www 6886: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6887: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6888: my ($audom,$auname)=split('/',$uri);
1.643 www 6889: # no author name given, so this just checks on the general right to make a co-author in this domain
6890: unless ($auname) { return $thisallowed; }
6891: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6892: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6893: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6894: ($audom ne $env{'request.role.domain'}))) { return ''; }
6895: }
1.52 www 6896: return $thisallowed;
6897: }
6898: #
1.103 harris41 6899: # Gathered so far: system, domain and course wide privileges
1.52 www 6900: #
6901: # Course: See if uri or referer is an individual resource that is part of
6902: # the course
6903:
1.620 albertel 6904: if ($env{'request.course.id'}) {
1.232 www 6905:
1.620 albertel 6906: $courseprivid=$env{'request.course.id'};
6907: if ($env{'request.course.sec'}) {
6908: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6909: }
6910: $courseprivid=~s/\_/\//;
6911: my $checkreferer=1;
1.232 www 6912: my ($match,$cond)=&is_on_map($uri);
6913: if ($match) {
6914: $statecond=$cond;
1.620 albertel 6915: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6916: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6917: my $value = $1;
6918: if ($priv eq 'bre') {
6919: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6920: if (@blockers > 0) {
6921: $thisallowed = 'B';
6922: } else {
6923: $thisallowed.=$value;
6924: }
6925: } else {
6926: $thisallowed.=$value;
6927: }
1.52 www 6928: $checkreferer=0;
6929: }
1.29 www 6930: }
1.83 www 6931:
1.148 www 6932: if ($checkreferer) {
1.620 albertel 6933: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6934: unless ($refuri) {
1.800 albertel 6935: foreach my $key (keys(%env)) {
6936: if ($key=~/^httpref\..*\*/) {
6937: my $pattern=$key;
1.156 www 6938: $pattern=~s/^httpref\.\/res\///;
1.148 www 6939: $pattern=~s/\*/\[\^\/\]\+/g;
6940: $pattern=~s/\//\\\//g;
1.152 www 6941: if ($orguri=~/$pattern/) {
1.800 albertel 6942: $refuri=$env{$key};
1.148 www 6943: }
6944: }
1.191 harris41 6945: }
1.148 www 6946: }
1.232 www 6947:
1.148 www 6948: if ($refuri) {
1.152 www 6949: $refuri=&declutter($refuri);
1.232 www 6950: my ($match,$cond)=&is_on_map($refuri);
6951: if ($match) {
6952: my $refstatecond=$cond;
1.620 albertel 6953: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6954: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6955: my $value = $1;
6956: if ($priv eq 'bre') {
6957: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6958: if (@blockers > 0) {
6959: $thisallowed = 'B';
6960: } else {
6961: $thisallowed.=$value;
6962: }
6963: } else {
6964: $thisallowed.=$value;
6965: }
1.53 www 6966: $uri=$refuri;
6967: $statecond=$refstatecond;
1.52 www 6968: }
6969: }
1.148 www 6970: }
1.29 www 6971: }
1.52 www 6972: }
1.29 www 6973:
1.52 www 6974: #
1.103 harris41 6975: # Gathered now: all privileges that could apply, and condition number
1.52 www 6976: #
6977: #
6978: # Full or no access?
6979: #
1.29 www 6980:
1.52 www 6981: if ($thisallowed=~/F/) {
6982: return 'F';
6983: }
1.29 www 6984:
1.52 www 6985: unless ($thisallowed) {
6986: return '';
6987: }
1.29 www 6988:
1.52 www 6989: # Restrictions exist, deal with them
6990: #
6991: # C:according to course preferences
6992: # R:according to resource settings
6993: # L:unless locked
6994: # X:according to user session state
6995: #
6996:
6997: # Possibly locked functionality, check all courses
1.54 www 6998: # Locks might take effect only after 10 minutes cache expiration for other
6999: # courses, and 2 minutes for current course
1.52 www 7000:
7001: my $envkey;
7002: if ($thisallowed=~/L/) {
1.1000 raeburn 7003: foreach $envkey (keys(%env)) {
1.54 www 7004: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7005: my $courseid=$2;
7006: my $roleid=$1.'.'.$2;
1.92 www 7007: $courseid=~s/^\///;
1.54 www 7008: my $expiretime=600;
1.620 albertel 7009: if ($env{'request.role'} eq $roleid) {
1.54 www 7010: $expiretime=120;
7011: }
7012: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7013: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7014: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7015: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7016: }
1.620 albertel 7017: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7018: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7019: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7020: &log($env{'user.domain'},$env{'user.name'},
7021: $env{'user.home'},
1.57 www 7022: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7023: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7024: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7025: return '';
7026: }
7027: }
1.620 albertel 7028: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7029: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7030: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7031: &log($env{'user.domain'},$env{'user.name'},
7032: $env{'user.home'},
1.57 www 7033: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7034: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7035: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7036: return '';
7037: }
7038: }
7039: }
1.29 www 7040: }
1.52 www 7041: }
7042:
7043: #
7044: # Rest of the restrictions depend on selected course
7045: #
7046:
1.620 albertel 7047: unless ($env{'request.course.id'}) {
1.766 albertel 7048: if ($thisallowed eq 'A') {
7049: return 'A';
1.814 raeburn 7050: } elsif ($thisallowed eq 'B') {
7051: return 'B';
1.766 albertel 7052: } else {
7053: return '1';
7054: }
1.52 www 7055: }
1.29 www 7056:
1.52 www 7057: #
7058: # Now user is definitely in a course
7059: #
1.53 www 7060:
7061:
7062: # Course preferences
7063:
7064: if ($thisallowed=~/C/) {
1.620 albertel 7065: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7066: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7067: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7068: =~/\Q$rolecode\E/) {
1.1103 raeburn 7069: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7070: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7071: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7072: $env{'request.course.id'});
7073: }
1.237 www 7074: return '';
7075: }
7076:
1.620 albertel 7077: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7078: =~/\Q$unamedom\E/) {
1.1103 raeburn 7079: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7080: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7081: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7082: $env{'request.course.id'});
7083: }
1.54 www 7084: return '';
7085: }
1.53 www 7086: }
7087:
7088: # Resource preferences
7089:
7090: if ($thisallowed=~/R/) {
1.620 albertel 7091: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7092: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7093: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7094: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7095: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7096: }
7097: return '';
1.54 www 7098: }
1.53 www 7099: }
1.30 www 7100:
1.246 www 7101: # Restricted by state or randomout?
1.30 www 7102:
1.52 www 7103: if ($thisallowed=~/X/) {
1.620 albertel 7104: if ($env{'acc.randomout'}) {
1.579 albertel 7105: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7106: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7107: return '';
7108: }
1.247 www 7109: }
7110: if (&condval($statecond)) {
1.52 www 7111: return '2';
7112: } else {
7113: return '';
7114: }
7115: }
1.30 www 7116:
1.766 albertel 7117: if ($thisallowed eq 'A') {
7118: return 'A';
1.814 raeburn 7119: } elsif ($thisallowed eq 'B') {
7120: return 'B';
1.766 albertel 7121: }
1.52 www 7122: return 'F';
1.232 www 7123: }
1.1162 raeburn 7124:
1.1172.2.13 raeburn 7125: # ------------------------------------------- Check construction space access
7126:
7127: sub constructaccess {
7128: my ($url,$setpriv)=@_;
7129:
7130: # We do not allow editing of previous versions of files
7131: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7132:
7133: # Get username and domain from URL
7134: my ($ownername,$ownerdomain,$ownerhome);
7135:
7136: ($ownerdomain,$ownername) =
7137: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7138:
7139: # The URL does not really point to any authorspace, forget it
7140: unless (($ownername) && ($ownerdomain)) { return ''; }
7141:
7142: # Now we need to see if the user has access to the authorspace of
7143: # $ownername at $ownerdomain
7144:
7145: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7146: # Real author for this?
7147: $ownerhome = $env{'user.home'};
7148: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7149: return ($ownername,$ownerdomain,$ownerhome);
7150: }
7151: } else {
7152: # Co-author for this?
7153: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7154: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7155: $ownerhome = &homeserver($ownername,$ownerdomain);
7156: return ($ownername,$ownerdomain,$ownerhome);
7157: }
7158: }
7159:
7160: # We don't have any access right now. If we are not possibly going to do anything about this,
7161: # we might as well leave
7162: unless ($setpriv) { return ''; }
7163:
7164: # Backdoor access?
7165: my $allowed=&allowed('eco',$ownerdomain);
7166: # Nope
7167: unless ($allowed) { return ''; }
7168: # Looks like we may have access, but could be locked by the owner of the construction space
7169: if ($allowed eq 'U') {
7170: my %blocked=&get('environment',['domcoord.author'],
7171: $ownerdomain,$ownername);
7172: # Is blocked by owner
7173: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7174: }
7175: if (($allowed eq 'F') || ($allowed eq 'U')) {
7176: # Grant temporary access
7177: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7178: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7179: if (!$update) { $update = $then; }
7180: my $refresh=$env{'user.refresh.time'};
7181: if (!$refresh) { $refresh = $update; }
7182: my $now = time;
7183: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7184: $now,'ca','constructaccess');
7185: $ownerhome = &homeserver($ownername,$ownerdomain);
7186: return($ownername,$ownerdomain,$ownerhome);
7187: }
7188: # No business here
7189: return '';
7190: }
7191:
1.1162 raeburn 7192: sub get_comm_blocks {
7193: my ($cdom,$cnum) = @_;
7194: if ($cdom eq '' || $cnum eq '') {
7195: return unless ($env{'request.course.id'});
7196: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7197: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7198: }
7199: my %commblocks;
7200: my $hashid=$cdom.'_'.$cnum;
7201: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7202: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7203: %commblocks = %{$blocksref};
7204: } else {
7205: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7206: my $cachetime = 600;
7207: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7208: }
7209: return %commblocks;
7210: }
7211:
7212: sub has_comm_blocking {
7213: my ($priv,$symb,$uri,$blocks) = @_;
7214: return unless ($env{'request.course.id'});
7215: return unless ($priv eq 'bre');
7216: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7217: my %commblocks;
7218: if (ref($blocks) eq 'HASH') {
7219: %commblocks = %{$blocks};
7220: } else {
7221: %commblocks = &get_comm_blocks();
7222: }
7223: return unless (keys(%commblocks) > 0);
7224: if (!$symb) { $symb=&symbread($uri,1); }
7225: my ($map,$resid,undef)=&decode_symb($symb);
7226: my %tocheck = (
7227: maps => $map,
7228: resources => $symb,
7229: );
7230: my @blockers;
7231: my $now = time;
1.1163 raeburn 7232: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7233: foreach my $block (keys(%commblocks)) {
7234: if ($block =~ /^(\d+)____(\d+)$/) {
7235: my ($start,$end) = ($1,$2);
7236: if ($start <= $now && $end >= $now) {
7237: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7238: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7239: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7240: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7241: unless (grep(/^\Q$block\E$/,@blockers)) {
7242: push(@blockers,$block);
7243: }
7244: }
7245: }
7246: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7247: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7248: unless (grep(/^\Q$block\E$/,@blockers)) {
7249: push(@blockers,$block);
7250: }
7251: }
7252: }
7253: }
7254: }
7255: }
7256: } elsif ($block =~ /^firstaccess____(.+)$/) {
7257: my $item = $1;
1.1163 raeburn 7258: my @to_test;
1.1162 raeburn 7259: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7260: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7261: my $check_interval;
7262: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7263: my @interval;
7264: my $type = 'map';
7265: if ($item eq 'course') {
7266: $type = 'course';
7267: @interval=&EXT("resource.0.interval");
7268: } else {
7269: if ($item =~ /___\d+___/) {
7270: $type = 'resource';
7271: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7272: if (ref($navmap)) {
7273: my $res = $navmap->getBySymb($item);
7274: push(@to_test,$res);
7275: }
1.1162 raeburn 7276: } else {
7277: my $mapsymb = &symbread($item,1);
7278: if ($mapsymb) {
7279: if (ref($navmap)) {
7280: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7281: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7282: foreach my $res (@to_test) {
1.1162 raeburn 7283: my $symb = $res->symb();
7284: next if ($symb eq $mapsymb);
7285: if ($symb ne '') {
7286: @interval=&EXT("resource.0.interval",$symb);
7287: last;
7288: }
7289: }
7290: }
7291: }
7292: }
7293: }
7294: if ($interval[0] =~ /\d+/) {
7295: my $first_access;
7296: if ($type eq 'resource') {
7297: $first_access=&get_first_access($interval[1],$item);
7298: } elsif ($type eq 'map') {
7299: $first_access=&get_first_access($interval[1],undef,$item);
7300: } else {
7301: $first_access=&get_first_access($interval[1]);
7302: }
7303: if ($first_access) {
7304: my $timesup = $first_access+$interval[0];
7305: if ($timesup > $now) {
1.1163 raeburn 7306: foreach my $res (@to_test) {
7307: if ($res->is_problem()) {
7308: if ($res->completable()) {
7309: unless (grep(/^\Q$block\E$/,@blockers)) {
7310: push(@blockers,$block);
7311: }
7312: last;
7313: }
7314: }
1.1162 raeburn 7315: }
7316: }
7317: }
7318: }
7319: }
7320: }
7321: }
7322: }
7323: }
7324: return @blockers;
7325: }
7326:
7327: sub check_docs_block {
7328: my ($docsblock,$tocheck) =@_;
7329: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7330: return;
7331: }
7332: if (ref($docsblock->{'maps'}) eq 'HASH') {
7333: if ($tocheck->{'maps'}) {
7334: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7335: return 1;
7336: }
7337: }
7338: }
7339: if (ref($docsblock->{'resources'}) eq 'HASH') {
7340: if ($tocheck->{'resources'}) {
7341: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7342: return 1;
7343: }
7344: }
7345: }
7346: return;
7347: }
7348:
1.1133 foxr 7349: #
7350: # Removes the versino from a URI and
7351: # splits it in to its filename and path to the filename.
7352: # Seems like File::Basename could have done this more clearly.
7353: # Parameters:
7354: # $uri - input URI
7355: # Returns:
7356: # Two element list consisting of
7357: # $pathname - the URI up to and excluding the trailing /
7358: # $filename - The part of the URI following the last /
7359: # NOTE:
7360: # Another realization of this is simply:
7361: # use File::Basename;
7362: # ...
7363: # $uri = shift;
7364: # $filename = basename($uri);
7365: # $path = dirname($uri);
7366: # return ($filename, $path);
7367: #
7368: # The implementation below is probably faster however.
7369: #
1.710 albertel 7370: sub split_uri_for_cond {
7371: my $uri=&deversion(&declutter(shift));
7372: my @uriparts=split(/\//,$uri);
7373: my $filename=pop(@uriparts);
7374: my $pathname=join('/',@uriparts);
7375: return ($pathname,$filename);
7376: }
1.232 www 7377: # --------------------------------------------------- Is a resource on the map?
7378:
7379: sub is_on_map {
1.710 albertel 7380: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7381: #Trying to find the conditional for the file
1.620 albertel 7382: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7383: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7384: if ($match) {
1.289 bowersj2 7385: return (1,$1);
7386: } else {
1.434 www 7387: return (0,0);
1.289 bowersj2 7388: }
1.12 www 7389: }
7390:
1.427 www 7391: # --------------------------------------------------------- Get symb from alias
7392:
7393: sub get_symb_from_alias {
7394: my $symb=shift;
7395: my ($map,$resid,$url)=&decode_symb($symb);
7396: # Already is a symb
7397: if ($url) { return $symb; }
7398: # Must be an alias
7399: my $aliassymb='';
7400: my %bighash;
1.620 albertel 7401: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7402: &GDBM_READER(),0640)) {
7403: my $rid=$bighash{'mapalias_'.$symb};
7404: if ($rid) {
7405: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7406: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7407: $resid,$bighash{'src_'.$rid});
1.427 www 7408: }
7409: untie %bighash;
7410: }
7411: return $aliassymb;
7412: }
7413:
1.12 www 7414: # ----------------------------------------------------------------- Define Role
7415:
7416: sub definerole {
7417: if (allowed('mcr','/')) {
7418: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7419: foreach my $role (split(':',$sysrole)) {
7420: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7421: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7422: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7423: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7424: return "refused:s:$crole&$cqual";
7425: }
7426: }
1.191 harris41 7427: }
1.800 albertel 7428: foreach my $role (split(':',$domrole)) {
7429: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7430: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7431: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7432: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7433: return "refused:d:$crole&$cqual";
7434: }
7435: }
1.191 harris41 7436: }
1.800 albertel 7437: foreach my $role (split(':',$courole)) {
7438: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7439: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7440: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7441: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7442: return "refused:c:$crole&$cqual";
7443: }
7444: }
1.191 harris41 7445: }
1.620 albertel 7446: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7447: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7448: "rolesdef_$rolename=".
7449: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7450: return reply($command,$env{'user.home'});
1.12 www 7451: } else {
7452: return 'refused';
7453: }
1.105 harris41 7454: }
7455:
7456: # ---------------- Make a metadata query against the network of library servers
7457:
7458: sub metadata_query {
1.1172.2.33 raeburn 7459: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7460: my %rhash;
1.845 albertel 7461: my %libserv = &all_library();
1.244 matthew 7462: my @server_list = (defined($server_array) ? @$server_array
7463: : keys(%libserv) );
7464: for my $server (@server_list) {
1.1172.2.33 raeburn 7465: my $domains = '';
7466: if (ref($domains_hash) eq 'HASH') {
7467: $domains = $domains_hash->{$server};
7468: }
1.118 harris41 7469: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7470: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7471: $rhash{$server}=$reply;
7472: }
7473: else {
7474: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7475: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7476: $server);
7477: $rhash{$server}=$reply;
7478: }
1.112 harris41 7479: }
1.118 harris41 7480: return \%rhash;
1.240 www 7481: }
7482:
7483: # ----------------------------------------- Send log queries and wait for reply
7484:
7485: sub log_query {
7486: my ($uname,$udom,$query,%filters)=@_;
7487: my $uhome=&homeserver($uname,$udom);
7488: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7489: my $uhost=&hostname($uhome);
1.800 albertel 7490: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7491: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7492: $uhome);
1.479 albertel 7493: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7494: return get_query_reply($queryid);
7495: }
7496:
1.818 raeburn 7497: # -------------------------- Update MySQL table for portfolio file
7498:
7499: sub update_portfolio_table {
1.821 raeburn 7500: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7501: if ($group ne '') {
7502: $file_name =~s /^\Q$group\E//;
7503: }
1.818 raeburn 7504: my $homeserver = &homeserver($uname,$udom);
7505: my $queryid=
1.821 raeburn 7506: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7507: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7508: my $reply = &get_query_reply($queryid);
7509: return $reply;
7510: }
7511:
1.899 raeburn 7512: # -------------------------- Update MySQL allusers table
7513:
7514: sub update_allusers_table {
7515: my ($uname,$udom,$names) = @_;
7516: my $homeserver = &homeserver($uname,$udom);
7517: my $queryid=
7518: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7519: 'lastname='.&escape($names->{'lastname'}).'%%'.
7520: 'firstname='.&escape($names->{'firstname'}).'%%'.
7521: 'middlename='.&escape($names->{'middlename'}).'%%'.
7522: 'generation='.&escape($names->{'generation'}).'%%'.
7523: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7524: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7525: return;
1.899 raeburn 7526: }
7527:
1.508 raeburn 7528: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7529:
7530: sub fetch_enrollment_query {
1.511 raeburn 7531: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7532: my $homeserver;
1.547 raeburn 7533: my $maxtries = 1;
1.508 raeburn 7534: if ($context eq 'automated') {
7535: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7536: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7537: } else {
7538: $homeserver = &homeserver($cnum,$dom);
7539: }
1.838 albertel 7540: my $host=&hostname($homeserver);
1.506 raeburn 7541: my $cmd = '';
1.1000 raeburn 7542: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7543: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7544: }
7545: $cmd =~ s/%%$//;
7546: $cmd = &escape($cmd);
7547: my $query = 'fetchenrollment';
1.620 albertel 7548: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7549: unless ($queryid=~/^\Q$host\E\_/) {
7550: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7551: return 'error: '.$queryid;
7552: }
1.506 raeburn 7553: my $reply = &get_query_reply($queryid);
1.547 raeburn 7554: my $tries = 1;
7555: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7556: $reply = &get_query_reply($queryid);
7557: $tries ++;
7558: }
1.526 raeburn 7559: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7560: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7561: } else {
1.901 albertel 7562: my @responses = split(/:/,$reply);
1.515 raeburn 7563: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7564: foreach my $line (@responses) {
7565: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7566: $$replyref{$key} = $value;
7567: }
7568: } else {
1.1117 foxr 7569: my $pathname = LONCAPA::tempdir();
1.800 albertel 7570: foreach my $line (@responses) {
7571: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7572: $$replyref{$key} = $value;
7573: if ($value > 0) {
1.800 albertel 7574: foreach my $item (@{$$affiliatesref{$key}}) {
7575: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7576: my $destname = $pathname.'/'.$filename;
7577: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7578: if ($xml_classlist =~ /^error/) {
7579: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7580: } else {
1.506 raeburn 7581: if ( open(FILE,">$destname") ) {
7582: print FILE &unescape($xml_classlist);
7583: close(FILE);
1.526 raeburn 7584: } else {
7585: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7586: }
7587: }
7588: }
7589: }
7590: }
7591: }
7592: return 'ok';
7593: }
7594: return 'error';
7595: }
7596:
1.242 www 7597: sub get_query_reply {
7598: my $queryid=shift;
1.1117 foxr 7599: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7600: my $reply='';
7601: for (1..100) {
7602: sleep 2;
7603: if (-e $replyfile.'.end') {
1.448 albertel 7604: if (open(my $fh,$replyfile)) {
1.904 albertel 7605: $reply = join('',<$fh>);
7606: close($fh);
1.240 www 7607: } else { return 'error: reply_file_error'; }
1.242 www 7608: return &unescape($reply);
7609: }
1.240 www 7610: }
1.242 www 7611: return 'timeout:'.$queryid;
1.240 www 7612: }
7613:
7614: sub courselog_query {
1.241 www 7615: #
7616: # possible filters:
7617: # url: url or symb
7618: # username
7619: # domain
7620: # action: view, submit, grade
7621: # start: timestamp
7622: # end: timestamp
7623: #
1.240 www 7624: my (%filters)=@_;
1.620 albertel 7625: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7626: if ($filters{'url'}) {
7627: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7628: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7629: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7630: }
1.620 albertel 7631: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7632: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7633: return &log_query($cname,$cdom,'courselog',%filters);
7634: }
7635:
7636: sub userlog_query {
1.858 raeburn 7637: #
7638: # possible filters:
7639: # action: log check role
7640: # start: timestamp
7641: # end: timestamp
7642: #
1.240 www 7643: my ($uname,$udom,%filters)=@_;
7644: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7645: }
7646:
1.506 raeburn 7647: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7648:
7649: sub auto_run {
1.508 raeburn 7650: my ($cnum,$cdom) = @_;
1.876 raeburn 7651: my $response = 0;
7652: my $settings;
7653: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7654: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7655: $settings = $domconfig{'autoenroll'};
7656: if ($settings->{'run'} eq '1') {
7657: $response = 1;
7658: }
7659: } else {
1.934 raeburn 7660: my $homeserver;
7661: if (&is_course($cdom,$cnum)) {
7662: $homeserver = &homeserver($cnum,$cdom);
7663: } else {
7664: $homeserver = &domain($cdom,'primary');
7665: }
7666: if ($homeserver ne 'no_host') {
7667: $response = &reply('autorun:'.$cdom,$homeserver);
7668: }
1.876 raeburn 7669: }
1.506 raeburn 7670: return $response;
7671: }
1.776 albertel 7672:
1.506 raeburn 7673: sub auto_get_sections {
1.508 raeburn 7674: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7675: my $homeserver;
7676: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7677: $homeserver = &homeserver($cnum,$cdom);
7678: }
7679: if (!defined($homeserver)) {
7680: if ($cdom =~ /^$match_domain$/) {
7681: $homeserver = &domain($cdom,'primary');
7682: }
7683: }
7684: my @secs;
7685: if (defined($homeserver)) {
7686: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7687: unless ($response eq 'refused') {
7688: @secs = split(/:/,$response);
7689: }
1.506 raeburn 7690: }
7691: return @secs;
7692: }
1.776 albertel 7693:
1.506 raeburn 7694: sub auto_new_course {
1.1099 raeburn 7695: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7696: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7697: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7698: return $response;
7699: }
1.776 albertel 7700:
1.506 raeburn 7701: sub auto_validate_courseID {
1.508 raeburn 7702: my ($cnum,$cdom,$inst_course_id) = @_;
7703: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7704: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7705: return $response;
7706: }
1.776 albertel 7707:
1.1007 raeburn 7708: sub auto_validate_instcode {
1.1020 raeburn 7709: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7710: my ($homeserver,$response);
7711: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7712: $homeserver = &homeserver($cnum,$cdom);
7713: }
7714: if (!defined($homeserver)) {
7715: if ($cdom =~ /^$match_domain$/) {
7716: $homeserver = &domain($cdom,'primary');
7717: }
7718: }
1.1065 raeburn 7719: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7720: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7721: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7722: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7723: }
7724:
1.506 raeburn 7725: sub auto_create_password {
1.873 raeburn 7726: my ($cnum,$cdom,$authparam,$udom) = @_;
7727: my ($homeserver,$response);
1.506 raeburn 7728: my $create_passwd = 0;
7729: my $authchk = '';
1.873 raeburn 7730: if ($udom =~ /^$match_domain$/) {
7731: $homeserver = &domain($udom,'primary');
7732: }
7733: if ($homeserver eq '') {
7734: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7735: $homeserver = &homeserver($cnum,$cdom);
7736: }
7737: }
7738: if ($homeserver eq '') {
7739: $authchk = 'nodomain';
1.506 raeburn 7740: } else {
1.873 raeburn 7741: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7742: if ($response eq 'refused') {
7743: $authchk = 'refused';
7744: } else {
1.901 albertel 7745: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7746: }
1.506 raeburn 7747: }
7748: return ($authparam,$create_passwd,$authchk);
7749: }
7750:
1.706 raeburn 7751: sub auto_photo_permission {
7752: my ($cnum,$cdom,$students) = @_;
7753: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7754: my ($outcome,$perm_reqd,$conditions) =
7755: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7756: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7757: return (undef,undef);
7758: }
1.706 raeburn 7759: return ($outcome,$perm_reqd,$conditions);
7760: }
7761:
7762: sub auto_checkphotos {
7763: my ($uname,$udom,$pid) = @_;
7764: my $homeserver = &homeserver($uname,$udom);
7765: my ($result,$resulttype);
7766: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7767: &escape($uname).':'.&escape($pid),
7768: $homeserver));
1.709 albertel 7769: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7770: return (undef,undef);
7771: }
1.706 raeburn 7772: if ($outcome) {
7773: ($result,$resulttype) = split(/:/,$outcome);
7774: }
7775: return ($result,$resulttype);
7776: }
7777:
7778: sub auto_photochoice {
7779: my ($cnum,$cdom) = @_;
7780: my $homeserver = &homeserver($cnum,$cdom);
7781: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7782: &escape($cdom),
7783: $homeserver)));
1.709 albertel 7784: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7785: return (undef,undef);
7786: }
1.706 raeburn 7787: return ($update,$comment);
7788: }
7789:
7790: sub auto_photoupdate {
7791: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7792: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7793: my $host=&hostname($homeserver);
1.706 raeburn 7794: my $cmd = '';
7795: my $maxtries = 1;
1.800 albertel 7796: foreach my $affiliate (keys(%{$affiliatesref})) {
7797: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7798: }
7799: $cmd =~ s/%%$//;
7800: $cmd = &escape($cmd);
7801: my $query = 'institutionalphotos';
7802: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7803: unless ($queryid=~/^\Q$host\E\_/) {
7804: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7805: return 'error: '.$queryid;
7806: }
7807: my $reply = &get_query_reply($queryid);
7808: my $tries = 1;
7809: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7810: $reply = &get_query_reply($queryid);
7811: $tries ++;
7812: }
7813: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7814: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7815: } else {
7816: my @responses = split(/:/,$reply);
7817: my $outcome = shift(@responses);
7818: foreach my $item (@responses) {
7819: my ($key,$value) = split(/=/,$item);
7820: $$photo{$key} = $value;
7821: }
7822: return $outcome;
7823: }
7824: return 'error';
7825: }
7826:
1.521 raeburn 7827: sub auto_instcode_format {
1.793 albertel 7828: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7829: $cat_order) = @_;
1.521 raeburn 7830: my $courses = '';
1.772 raeburn 7831: my @homeservers;
1.521 raeburn 7832: if ($caller eq 'global') {
1.841 albertel 7833: my %servers = &get_servers($codedom,'library');
7834: foreach my $tryserver (keys(%servers)) {
7835: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7836: push(@homeservers,$tryserver);
7837: }
1.584 raeburn 7838: }
1.1022 raeburn 7839: } elsif ($caller eq 'requests') {
7840: if ($codedom =~ /^$match_domain$/) {
7841: my $chome = &domain($codedom,'primary');
7842: unless ($chome eq 'no_host') {
7843: push(@homeservers,$chome);
7844: }
7845: }
1.521 raeburn 7846: } else {
1.772 raeburn 7847: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7848: }
1.793 albertel 7849: foreach my $code (keys(%{$instcodes})) {
7850: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7851: }
7852: chop($courses);
1.772 raeburn 7853: my $ok_response = 0;
7854: my $response;
7855: while (@homeservers > 0 && $ok_response == 0) {
7856: my $server = shift(@homeservers);
7857: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7858: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7859: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7860: split(/:/,$response);
1.772 raeburn 7861: %{$codes} = (%{$codes},&str2hash($codes_str));
7862: push(@{$codetitles},&str2array($codetitles_str));
7863: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7864: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7865: $ok_response = 1;
7866: }
7867: }
7868: if ($ok_response) {
1.521 raeburn 7869: return 'ok';
1.772 raeburn 7870: } else {
7871: return $response;
1.521 raeburn 7872: }
7873: }
7874:
1.792 raeburn 7875: sub auto_instcode_defaults {
7876: my ($domain,$returnhash,$code_order) = @_;
7877: my @homeservers;
1.841 albertel 7878:
7879: my %servers = &get_servers($domain,'library');
7880: foreach my $tryserver (keys(%servers)) {
7881: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7882: push(@homeservers,$tryserver);
7883: }
1.792 raeburn 7884: }
1.841 albertel 7885:
1.792 raeburn 7886: my $response;
1.841 albertel 7887: foreach my $server (@homeservers) {
1.792 raeburn 7888: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7889: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7890:
7891: foreach my $pair (split(/\&/,$response)) {
7892: my ($name,$value)=split(/\=/,$pair);
7893: if ($name eq 'code_order') {
7894: @{$code_order} = split(/\&/,&unescape($value));
7895: } else {
7896: $returnhash->{&unescape($name)}=&unescape($value);
7897: }
7898: }
7899: return 'ok';
1.792 raeburn 7900: }
1.841 albertel 7901:
7902: return $response;
1.1003 raeburn 7903: }
7904:
7905: sub auto_possible_instcodes {
1.1007 raeburn 7906: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7907: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7908: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7909: return;
7910: }
1.1003 raeburn 7911: my (@homeservers,$uhome);
7912: if (defined(&domain($domain,'primary'))) {
7913: $uhome=&domain($domain,'primary');
7914: push(@homeservers,&domain($domain,'primary'));
7915: } else {
7916: my %servers = &get_servers($domain,'library');
7917: foreach my $tryserver (keys(%servers)) {
7918: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7919: push(@homeservers,$tryserver);
7920: }
7921: }
7922: }
7923: my $response;
7924: foreach my $server (@homeservers) {
7925: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7926: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7927: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7928: split(':',$response);
7929: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7930: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7931: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7932: my ($name,$value)=split('=',$item);
7933: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7934: }
7935: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7936: my ($name,$value)=split('=',$item);
7937: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7938: }
7939: return 'ok';
7940: }
7941: return $response;
7942: }
1.792 raeburn 7943:
1.1010 raeburn 7944: sub auto_courserequest_checks {
7945: my ($dom) = @_;
1.1020 raeburn 7946: my ($homeserver,%validations);
7947: if ($dom =~ /^$match_domain$/) {
7948: $homeserver = &domain($dom,'primary');
7949: }
7950: unless ($homeserver eq 'no_host') {
7951: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7952: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7953: my @items = split(/&/,$response);
7954: foreach my $item (@items) {
7955: my ($key,$value) = split('=',$item);
7956: $validations{&unescape($key)} = &thaw_unescape($value);
7957: }
7958: }
7959: }
1.1010 raeburn 7960: return %validations;
7961: }
7962:
1.1020 raeburn 7963: sub auto_courserequest_validation {
1.1172.2.43 raeburn 7964: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 7965: my ($homeserver,$response);
7966: if ($dom =~ /^$match_domain$/) {
7967: $homeserver = &domain($dom,'primary');
7968: }
1.1172.2.43 raeburn 7969: unless ($homeserver eq 'no_host') {
7970: my $customdata;
7971: if (ref($custominfo) eq 'HASH') {
7972: $customdata = &freeze_escape($custominfo);
7973: }
1.1020 raeburn 7974: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7975: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 7976: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7977: $customdata,$homeserver));
1.1020 raeburn 7978: }
7979: return $response;
7980: }
7981:
1.777 albertel 7982: sub auto_validate_class_sec {
1.918 raeburn 7983: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7984: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7985: my $ownerlist;
7986: if (ref($owners) eq 'ARRAY') {
7987: $ownerlist = join(',',@{$owners});
7988: } else {
7989: $ownerlist = $owners;
7990: }
1.773 raeburn 7991: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7992: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7993: return $response;
7994: }
7995:
1.1172.2.38 raeburn 7996: sub auto_crsreq_update {
7997: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 7998: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 7999: my ($homeserver,%crsreqresponse);
8000: if ($cdom =~ /^$match_domain$/) {
8001: $homeserver = &domain($cdom,'primary');
8002: }
8003: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8004: my $info;
8005: if (ref($inbound) eq 'HASH') {
8006: $info = &freeze_escape($inbound);
8007: }
8008: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8009: ':'.&escape($action).':'.&escape($ownername).':'.
8010: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8011: &escape($title).':'.&escape($code).':'.
8012: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8013: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8014: my @items = split(/&/,$response);
8015: foreach my $item (@items) {
8016: my ($key,$value) = split('=',$item);
8017: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8018: }
8019: }
8020: }
8021: return \%crsreqresponse;
8022: }
8023:
1.679 raeburn 8024: # ------------------------------------------------------- Course Group routines
8025:
8026: sub get_coursegroups {
1.809 raeburn 8027: my ($cdom,$cnum,$group,$namespace) = @_;
8028: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8029: }
8030:
1.679 raeburn 8031: sub modify_coursegroup {
8032: my ($cdom,$cnum,$groupsettings) = @_;
8033: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8034: }
8035:
1.809 raeburn 8036: sub toggle_coursegroup_status {
8037: my ($cdom,$cnum,$group,$action) = @_;
8038: my ($from_namespace,$to_namespace);
8039: if ($action eq 'delete') {
8040: $from_namespace = 'coursegroups';
8041: $to_namespace = 'deleted_groups';
8042: } else {
8043: $from_namespace = 'deleted_groups';
8044: $to_namespace = 'coursegroups';
8045: }
8046: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8047: if (my $tmp = &error(%curr_group)) {
8048: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8049: return ('read error',$tmp);
8050: } else {
8051: my %savedsettings = %curr_group;
1.809 raeburn 8052: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8053: my $deloutcome;
8054: if ($result eq 'ok') {
1.809 raeburn 8055: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8056: } else {
8057: return ('write error',$result);
8058: }
8059: if ($deloutcome eq 'ok') {
8060: return 'ok';
8061: } else {
8062: return ('delete error',$deloutcome);
8063: }
8064: }
8065: }
8066:
1.679 raeburn 8067: sub modify_group_roles {
1.957 raeburn 8068: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8069: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8070: my $role = 'gr/'.&escape($userprivs);
8071: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8072: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8073: if ($result eq 'ok') {
8074: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8075: }
1.679 raeburn 8076: return $result;
8077: }
8078:
8079: sub modify_coursegroup_membership {
8080: my ($cdom,$cnum,$membership) = @_;
8081: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8082: return $result;
8083: }
8084:
1.682 raeburn 8085: sub get_active_groups {
8086: my ($udom,$uname,$cdom,$cnum) = @_;
8087: my $now = time;
8088: my %groups = ();
8089: foreach my $key (keys(%env)) {
1.811 albertel 8090: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8091: my ($start,$end) = split(/\./,$env{$key});
8092: if (($end!=0) && ($end<$now)) { next; }
8093: if (($start!=0) && ($start>$now)) { next; }
8094: if ($1 eq $cdom && $2 eq $cnum) {
8095: $groups{$3} = $env{$key} ;
8096: }
8097: }
8098: }
8099: return %groups;
8100: }
8101:
1.683 raeburn 8102: sub get_group_membership {
8103: my ($cdom,$cnum,$group) = @_;
8104: return(&dump('groupmembership',$cdom,$cnum,$group));
8105: }
8106:
8107: sub get_users_groups {
8108: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8109: my @usersgroups;
1.683 raeburn 8110: my $cachetime=1800;
8111:
8112: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8113: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8114: if (defined($cached)) {
1.734 albertel 8115: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8116: } else {
8117: $grouplist = '';
1.816 raeburn 8118: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8119: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8120: my $access_end = $env{'course.'.$courseid.
8121: '.default_enrollment_end_date'};
8122: my $now = time;
8123: foreach my $key (keys(%roleshash)) {
8124: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8125: my $group = $1;
8126: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8127: my $start = $2;
8128: my $end = $1;
8129: if ($start == -1) { next; } # deleted from group
8130: if (($start!=0) && ($start>$now)) { next; }
8131: if (($end!=0) && ($end<$now)) {
8132: if ($access_end && $access_end < $now) {
8133: if ($access_end - $end < 86400) {
8134: push(@usersgroups,$group);
1.733 raeburn 8135: }
8136: }
1.817 raeburn 8137: next;
1.733 raeburn 8138: }
1.817 raeburn 8139: push(@usersgroups,$group);
1.683 raeburn 8140: }
8141: }
8142: }
1.817 raeburn 8143: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8144: $grouplist = join(':',@usersgroups);
8145: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8146: }
1.733 raeburn 8147: return @usersgroups;
1.683 raeburn 8148: }
8149:
8150: sub devalidate_getgroups_cache {
8151: my ($udom,$uname,$cdom,$cnum)=@_;
8152: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8153:
1.683 raeburn 8154: my $hashid="$udom:$uname:$courseid";
8155: &devalidate_cache_new('getgroups',$hashid);
8156: }
8157:
1.12 www 8158: # ------------------------------------------------------------------ Plain Text
8159:
8160: sub plaintext {
1.988 raeburn 8161: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8162: if ($short =~ m{^cr/}) {
1.758 albertel 8163: return (split('/',$short))[-1];
8164: }
1.742 raeburn 8165: if (!defined($cid)) {
8166: $cid = $env{'request.course.id'};
8167: }
8168: my %rolenames = (
1.1008 raeburn 8169: Course => 'std',
8170: Community => 'alt1',
1.742 raeburn 8171: );
1.1037 raeburn 8172: if ($cid ne '') {
8173: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8174: unless ($forcedefault) {
8175: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8176: &Apache::lonlocal::mt_escape(\$roletext);
8177: return &Apache::lonlocal::mt($roletext);
8178: }
8179: }
8180: }
8181: if ((defined($type)) && (defined($rolenames{$type})) &&
8182: (defined($rolenames{$type})) &&
8183: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8184: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8185: } elsif ($cid ne '') {
8186: my $crstype = $env{'course.'.$cid.'.type'};
8187: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8188: (defined($prp{$short}{$rolenames{$crstype}}))) {
8189: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8190: }
1.742 raeburn 8191: }
1.1037 raeburn 8192: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8193: }
8194:
8195: # ----------------------------------------------------------------- Assign Role
8196:
8197: sub assignrole {
1.957 raeburn 8198: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8199: $context)=@_;
1.21 www 8200: my $mrole;
8201: if ($role =~ /^cr\//) {
1.393 www 8202: my $cwosec=$url;
1.811 albertel 8203: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8204: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8205: my $refused = 1;
8206: if ($context eq 'requestcourses') {
8207: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8208: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8209: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8210: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8211: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8212: if ($crsenv{'internal.courseowner'} eq
8213: $env{'user.name'}.':'.$env{'user.domain'}) {
8214: $refused = '';
8215: }
8216: }
8217: }
8218: }
8219: }
8220: if ($refused) {
8221: &logthis('Refused custom assignrole: '.
8222: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8223: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8224: return 'refused';
8225: }
1.104 www 8226: }
1.21 www 8227: $mrole='cr';
1.678 raeburn 8228: } elsif ($role =~ /^gr\//) {
8229: my $cwogrp=$url;
1.811 albertel 8230: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8231: unless (&allowed('mdg',$cwogrp)) {
8232: &logthis('Refused group assignrole: '.
8233: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8234: $env{'user.name'}.' at '.$env{'user.domain'});
8235: return 'refused';
8236: }
8237: $mrole='gr';
1.21 www 8238: } else {
1.82 www 8239: my $cwosec=$url;
1.811 albertel 8240: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8241: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8242: my $refused;
8243: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8244: if (!(&allowed('c'.$role,$url))) {
8245: $refused = 1;
8246: }
8247: } else {
8248: $refused = 1;
8249: }
1.947 raeburn 8250: if ($refused) {
1.1045 raeburn 8251: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8252: if (!$selfenroll && $context eq 'course') {
8253: my %crsenv;
8254: if ($role eq 'cc' || $role eq 'co') {
8255: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8256: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8257: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8258: if ($crsenv{'internal.courseowner'} eq
8259: $env{'user.name'}.':'.$env{'user.domain'}) {
8260: $refused = '';
8261: }
8262: }
8263: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8264: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8265: if ($crsenv{'internal.courseowner'} eq
8266: $env{'user.name'}.':'.$env{'user.domain'}) {
8267: $refused = '';
8268: }
8269: }
8270: }
8271: }
8272: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8273: $refused = '';
1.1017 raeburn 8274: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8275: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8276: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8277: my $wrongcc;
8278: if ($cnum =~ /^$match_community$/) {
8279: $wrongcc = 1 if ($role eq 'cc');
8280: } else {
8281: $wrongcc = 1 if ($role eq 'co');
8282: }
8283: unless ($wrongcc) {
8284: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8285: if ($crsenv{'internal.courseowner'} eq
8286: $env{'user.name'}.':'.$env{'user.domain'}) {
8287: $refused = '';
8288: }
1.1017 raeburn 8289: }
8290: }
1.1172.2.9 raeburn 8291: } elsif ($context eq 'requestauthor') {
8292: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8293: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8294: if ($env{'environment.requestauthor'} eq 'automatic') {
8295: $refused = '';
8296: } else {
8297: my %domdefaults = &get_domain_defaults($udom);
8298: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8299: my $checkbystatus;
8300: if ($env{'user.adv'}) {
8301: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8302: if ($disposition eq 'automatic') {
8303: $refused = '';
8304: } elsif ($disposition eq '') {
8305: $checkbystatus = 1;
8306: }
8307: } else {
8308: $checkbystatus = 1;
8309: }
8310: if ($checkbystatus) {
8311: if ($env{'environment.inststatus'}) {
8312: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8313: foreach my $type (@inststatuses) {
8314: if (($type ne '') &&
8315: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8316: $refused = '';
8317: }
8318: }
8319: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8320: $refused = '';
8321: }
8322: }
8323: }
8324: }
8325: }
1.1017 raeburn 8326: }
8327: if ($refused) {
1.947 raeburn 8328: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8329: ' '.$role.' '.$end.' '.$start.' by '.
8330: $env{'user.name'}.' at '.$env{'user.domain'});
8331: return 'refused';
8332: }
1.932 raeburn 8333: }
1.1131 raeburn 8334: } elsif ($role eq 'au') {
8335: if ($url ne '/'.$udom.'/') {
8336: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8337: ' to assign author role for '.$uname.':'.$udom.
8338: ' in domain: '.$url.' refused (wrong domain).');
8339: return 'refused';
8340: }
1.104 www 8341: }
1.21 www 8342: $mrole=$role;
8343: }
1.620 albertel 8344: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8345: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8346: if ($end) { $command.='_'.$end; }
1.21 www 8347: if ($start) {
8348: if ($end) {
1.81 www 8349: $command.='_'.$start;
1.21 www 8350: } else {
1.81 www 8351: $command.='_0_'.$start;
1.21 www 8352: }
8353: }
1.739 raeburn 8354: my $origstart = $start;
8355: my $origend = $end;
1.957 raeburn 8356: my $delflag;
1.357 www 8357: # actually delete
8358: if ($deleteflag) {
1.373 www 8359: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8360: # modify command to delete the role
1.620 albertel 8361: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8362: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8363: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8364: # set start and finish to negative values for userrolelog
8365: $start=-1;
8366: $end=-1;
1.957 raeburn 8367: $delflag = 1;
1.357 www 8368: }
8369: }
8370: # send command
1.349 www 8371: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8372: # log new user role if status is ok
1.349 www 8373: if ($answer eq 'ok') {
1.663 raeburn 8374: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8375: if (($role eq 'cc') || ($role eq 'in') ||
8376: ($role eq 'ep') || ($role eq 'ad') ||
8377: ($role eq 'ta') || ($role eq 'st') ||
8378: ($role=~/^cr/) || ($role eq 'gr') ||
8379: ($role eq 'co')) {
1.1172.2.13 raeburn 8380: # for course roles, perform group memberships changes triggered by role change.
8381: unless ($role =~ /^gr/) {
8382: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8383: $origstart,$selfenroll,$context);
8384: }
1.1172.2.9 raeburn 8385: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8386: $selfenroll,$context);
8387: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8388: ($role eq 'au') || ($role eq 'dc')) {
8389: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8390: $context);
8391: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8392: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8393: $context);
8394: }
1.1053 raeburn 8395: if ($role eq 'cc') {
8396: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8397: }
1.349 www 8398: }
8399: return $answer;
1.169 harris41 8400: }
8401:
1.1053 raeburn 8402: sub autoupdate_coowners {
8403: my ($url,$end,$start,$uname,$udom) = @_;
8404: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8405: if (($cdom ne '') && ($cnum ne '')) {
8406: my $now = time;
8407: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8408: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8409: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8410: my $instcode = $coursehash{'internal.coursecode'};
8411: if ($instcode ne '') {
1.1056 raeburn 8412: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8413: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8414: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8415: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8416: if ($result eq 'valid') {
8417: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8418: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8419: push(@newcoowners,$coowner);
8420: }
8421: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8422: push(@newcoowners,$uname.':'.$udom);
8423: }
8424: @newcoowners = sort(@newcoowners);
8425: } else {
8426: push(@newcoowners,$uname.':'.$udom);
8427: }
8428: } else {
8429: if ($coursehash{'internal.co-owners'}) {
8430: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8431: unless ($coowner eq $uname.':'.$udom) {
8432: push(@newcoowners,$coowner);
8433: }
8434: }
8435: unless (@newcoowners > 0) {
8436: $delcoowners = 1;
8437: $coowners = '';
8438: }
8439: }
8440: }
8441: if (@newcoowners || $delcoowners) {
8442: &store_coowners($cdom,$cnum,$coursehash{'home'},
8443: $delcoowners,@newcoowners);
8444: }
8445: }
8446: }
8447: }
8448: }
8449: }
8450: }
8451:
8452: sub store_coowners {
8453: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8454: my $cid = $cdom.'_'.$cnum;
8455: my ($coowners,$delresult,$putresult);
8456: if (@newcoowners) {
8457: $coowners = join(',',@newcoowners);
8458: my %coownershash = (
8459: 'internal.co-owners' => $coowners,
8460: );
8461: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8462: if ($putresult eq 'ok') {
8463: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8464: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8465: }
8466: }
8467: }
8468: if ($delcoowners) {
8469: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8470: if ($delresult eq 'ok') {
8471: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8472: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8473: }
8474: }
8475: }
8476: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8477: my %crsinfo =
8478: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8479: if (ref($crsinfo{$cid}) eq 'HASH') {
8480: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8481: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8482: }
8483: }
8484: }
8485:
1.169 harris41 8486: # -------------------------------------------------- Modify user authentication
1.197 www 8487: # Overrides without validation
8488:
1.169 harris41 8489: sub modifyuserauth {
8490: my ($udom,$uname,$umode,$upass)=@_;
8491: my $uhome=&homeserver($uname,$udom);
1.197 www 8492: unless (&allowed('mau',$udom)) { return 'refused'; }
8493: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8494: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8495: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8496: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8497: &escape($upass),$uhome);
1.620 albertel 8498: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8499: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8500: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8501: &log($udom,,$uname,$uhome,
1.620 albertel 8502: 'Authentication changed by '.$env{'user.domain'}.', '.
8503: $env{'user.name'}.', '.$umode.
1.197 www 8504: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8505: unless ($reply eq 'ok') {
1.197 www 8506: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8507: return 'error: '.$reply;
8508: }
1.170 harris41 8509: return 'ok';
1.80 www 8510: }
8511:
1.81 www 8512: # --------------------------------------------------------------- Modify a user
1.80 www 8513:
1.81 www 8514: sub modifyuser {
1.206 matthew 8515: my ($udom, $uname, $uid,
8516: $umode, $upass, $first,
8517: $middle, $last, $gene,
1.1058 raeburn 8518: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8519: $udom= &LONCAPA::clean_domain($udom);
8520: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8521: my $showcandelete = 'none';
8522: if (ref($candelete) eq 'ARRAY') {
8523: if (@{$candelete} > 0) {
8524: $showcandelete = join(', ',@{$candelete});
8525: }
8526: }
1.81 www 8527: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8528: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8529: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8530: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8531: ' desiredhome not specified').
1.620 albertel 8532: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8533: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8534: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8535: my $newuser;
8536: if ($uhome eq 'no_host') {
8537: $newuser = 1;
8538: }
1.80 www 8539: # ----------------------------------------------------------------- Create User
1.406 albertel 8540: if (($uhome eq 'no_host') &&
8541: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8542: my $unhome='';
1.844 albertel 8543: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8544: $unhome = $desiredhome;
1.620 albertel 8545: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8546: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8547: } else { # load balancing routine for determining $unhome
1.81 www 8548: my $loadm=10000000;
1.841 albertel 8549: my %servers = &get_servers($udom,'library');
8550: foreach my $tryserver (keys(%servers)) {
8551: my $answer=reply('load',$tryserver);
8552: if (($answer=~/\d+/) && ($answer<$loadm)) {
8553: $loadm=$answer;
8554: $unhome=$tryserver;
8555: }
1.80 www 8556: }
8557: }
8558: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8559: return 'error: unable to find a home server for '.$uname.
8560: ' in domain '.$udom;
1.80 www 8561: }
8562: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8563: &escape($upass),$unhome);
8564: unless ($reply eq 'ok') {
8565: return 'error: '.$reply;
8566: }
1.230 stredwic 8567: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8568: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8569: return 'error: unable verify users home machine.';
1.80 www 8570: }
1.209 matthew 8571: } # End of creation of new user
1.80 www 8572: # ---------------------------------------------------------------------- Add ID
8573: if ($uid) {
8574: $uid=~tr/A-Z/a-z/;
8575: my %uidhash=&idrget($udom,$uname);
1.196 www 8576: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8577: && (!$forceid)) {
1.80 www 8578: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8579: return 'error: user id "'.$uid.'" does not match '.
8580: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8581: }
8582: } else {
8583: &idput($udom,($uname => $uid));
8584: }
8585: }
8586: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8587: my @tmp=&get('environment',
1.899 raeburn 8588: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8589: 'permanentemail','inststatus'],
1.134 albertel 8590: $udom,$uname);
1.1075 raeburn 8591: my (%names,%oldnames);
1.313 matthew 8592: if ($tmp[0] =~ m/^error:.*/) {
8593: %names=();
8594: } else {
8595: %names = @tmp;
1.1075 raeburn 8596: %oldnames = %names;
1.313 matthew 8597: }
1.388 www 8598: #
1.1058 raeburn 8599: # If name, email and/or uid are blank (e.g., because an uploaded file
8600: # of users did not contain them), do not overwrite existing values
8601: # unless field is in $candelete array ref.
8602: #
8603:
8604: my @fields = ('firstname','middlename','lastname','generation',
8605: 'permanentemail','id');
8606: my %newvalues;
8607: if (ref($candelete) eq 'ARRAY') {
8608: foreach my $field (@fields) {
8609: if (grep(/^\Q$field\E$/,@{$candelete})) {
8610: if ($field eq 'firstname') {
8611: $names{$field} = $first;
8612: } elsif ($field eq 'middlename') {
8613: $names{$field} = $middle;
8614: } elsif ($field eq 'lastname') {
8615: $names{$field} = $last;
8616: } elsif ($field eq 'generation') {
8617: $names{$field} = $gene;
8618: } elsif ($field eq 'permanentemail') {
8619: $names{$field} = $email;
8620: } elsif ($field eq 'id') {
8621: $names{$field} = $uid;
8622: }
8623: }
8624: }
8625: }
1.388 www 8626: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8627: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8628: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8629: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8630: if ($email) {
8631: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8632: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8633: }
1.899 raeburn 8634: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8635: if (defined($inststatus)) {
8636: $names{'inststatus'} = '';
8637: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8638: if (ref($usertypes) eq 'HASH') {
8639: my @okstatuses;
8640: foreach my $item (split(/:/,$inststatus)) {
8641: if (defined($usertypes->{$item})) {
8642: push(@okstatuses,$item);
8643: }
8644: }
8645: if (@okstatuses) {
8646: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8647: }
8648: }
8649: }
1.1075 raeburn 8650: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8651: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8652: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8653: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8654: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8655: } else {
8656: $logmsg .= ' during self creation';
8657: }
1.1075 raeburn 8658: my $changed;
8659: if ($newuser) {
8660: $changed = 1;
8661: } else {
8662: foreach my $field (@fields) {
8663: if ($names{$field} ne $oldnames{$field}) {
8664: $changed = 1;
8665: last;
8666: }
8667: }
8668: }
8669: unless ($changed) {
8670: $logmsg = 'No changes in user information needed for: '.$logmsg;
8671: &logthis($logmsg);
8672: return 'ok';
8673: }
8674: my $reply = &put('environment', \%names, $udom,$uname);
8675: if ($reply ne 'ok') {
8676: return 'error: '.$reply;
8677: }
1.1087 raeburn 8678: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8679: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8680: }
1.1075 raeburn 8681: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8682: &devalidate_cache_new('namescache',$uname.':'.$udom);
8683: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8684: &logthis($logmsg);
1.134 albertel 8685: return 'ok';
1.80 www 8686: }
8687:
1.81 www 8688: # -------------------------------------------------------------- Modify student
1.80 www 8689:
1.81 www 8690: sub modifystudent {
8691: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8692: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8693: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8694: if (!$cid) {
1.620 albertel 8695: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8696: return 'not_in_class';
8697: }
1.80 www 8698: }
8699: # --------------------------------------------------------------- Make the user
1.81 www 8700: my $reply=&modifyuser
1.209 matthew 8701: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8702: $desiredhome,$email,$inststatus);
1.80 www 8703: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8704: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8705: # student's environment
1.297 matthew 8706: $uid = undef if (!$forceid);
1.455 albertel 8707: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8708: $gene,$usec,$end,$start,$type,$locktype,
8709: $cid,$selfenroll,$context,$credits);
1.297 matthew 8710: return $reply;
8711: }
8712:
8713: sub modify_student_enrollment {
1.1172.2.23 raeburn 8714: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8715: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8716: my ($cdom,$cnum,$chome);
8717: if (!$cid) {
1.620 albertel 8718: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8719: return 'not_in_class';
8720: }
1.620 albertel 8721: $cdom=$env{'course.'.$cid.'.domain'};
8722: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8723: } else {
8724: ($cdom,$cnum)=split(/_/,$cid);
8725: }
1.620 albertel 8726: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8727: if (!$chome) {
1.457 raeburn 8728: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8729: }
1.455 albertel 8730: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8731: # Make sure the user exists
1.81 www 8732: my $uhome=&homeserver($uname,$udom);
8733: if (($uhome eq '') || ($uhome eq 'no_host')) {
8734: return 'error: no such user';
8735: }
1.297 matthew 8736: # Get student data if we were not given enough information
8737: if (!defined($first) || $first eq '' ||
8738: !defined($last) || $last eq '' ||
8739: !defined($uid) || $uid eq '' ||
8740: !defined($middle) || $middle eq '' ||
8741: !defined($gene) || $gene eq '') {
1.294 matthew 8742: # They did not supply us with enough data to enroll the student, so
8743: # we need to pick up more information.
1.297 matthew 8744: my %tmp = &get('environment',
1.294 matthew 8745: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8746: ,$udom,$uname);
8747:
1.800 albertel 8748: #foreach my $key (keys(%tmp)) {
8749: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8750: #}
1.294 matthew 8751: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8752: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8753: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8754: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8755: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8756: }
1.556 albertel 8757: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8758: my $user = "$uname:$udom";
8759: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8760: my $reply=cput('classlist',
1.1148 raeburn 8761: {$user =>
1.1172.2.19 raeburn 8762: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8763: $cdom,$cnum);
1.1148 raeburn 8764: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8765: &devalidate_getsection_cache($udom,$uname,$cid);
8766: } else {
1.81 www 8767: return 'error: '.$reply;
8768: }
1.297 matthew 8769: # Add student role to user
1.83 www 8770: my $uurl='/'.$cid;
1.81 www 8771: $uurl=~s/\_/\//g;
8772: if ($usec) {
8773: $uurl.='/'.$usec;
8774: }
1.1148 raeburn 8775: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8776: $selfenroll,$context);
8777: if ($result ne 'ok') {
8778: if ($old_entry{$user} ne '') {
8779: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8780: } else {
8781: $reply = &del('classlist',[$user],$cdom,$cnum);
8782: }
8783: }
8784: return $result;
1.21 www 8785: }
8786:
1.556 albertel 8787: sub format_name {
8788: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8789: my $name;
8790: if ($first ne 'lastname') {
8791: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8792: } else {
8793: if ($lastname=~/\S/) {
8794: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8795: $name=~s/\s+,/,/;
8796: } else {
8797: $name.= $firstname.' '.$middlename.' '.$generation;
8798: }
8799: }
8800: $name=~s/^\s+//;
8801: $name=~s/\s+$//;
8802: $name=~s/\s+/ /g;
8803: return $name;
8804: }
8805:
1.84 www 8806: # ------------------------------------------------- Write to course preferences
8807:
8808: sub writecoursepref {
8809: my ($courseid,%prefs)=@_;
8810: $courseid=~s/^\///;
8811: $courseid=~s/\_/\//g;
8812: my ($cdomain,$cnum)=split(/\//,$courseid);
8813: my $chome=homeserver($cnum,$cdomain);
8814: if (($chome eq '') || ($chome eq 'no_host')) {
8815: return 'error: no such course';
8816: }
8817: my $cstring='';
1.800 albertel 8818: foreach my $pref (keys(%prefs)) {
8819: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8820: }
1.84 www 8821: $cstring=~s/\&$//;
8822: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8823: }
8824:
8825: # ---------------------------------------------------------- Make/modify course
8826:
8827: sub createcourse {
1.741 raeburn 8828: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8829: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8830: $url=&declutter($url);
8831: my $cid='';
1.1028 raeburn 8832: if ($context eq 'requestcourses') {
8833: my $can_create = 0;
8834: my ($ownername,$ownerdom) = split(':',$course_owner);
8835: if ($udom eq $ownerdom) {
8836: if (&usertools_access($ownername,$ownerdom,$category,undef,
8837: $context)) {
8838: $can_create = 1;
8839: }
8840: } else {
8841: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8842: $category);
8843: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8844: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8845: if (@curr > 0) {
8846: my @options = qw(approval validate autolimit);
8847: my $optregex = join('|',@options);
8848: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8849: $can_create = 1;
8850: }
8851: }
8852: }
8853: }
8854: if ($can_create) {
8855: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8856: unless (&allowed('ccc',$udom)) {
8857: return 'refused';
8858: }
1.1017 raeburn 8859: }
8860: } else {
8861: return 'refused';
8862: }
1.1028 raeburn 8863: } elsif (!&allowed('ccc',$udom)) {
8864: return 'refused';
1.84 www 8865: }
1.1011 raeburn 8866: # --------------------------------------------------------------- Get Unique ID
8867: my $uname;
8868: if ($cnum =~ /^$match_courseid$/) {
8869: my $chome=&homeserver($cnum,$udom,'true');
8870: if (($chome eq '') || ($chome eq 'no_host')) {
8871: $uname = $cnum;
8872: } else {
1.1038 raeburn 8873: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8874: }
8875: } else {
1.1038 raeburn 8876: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8877: }
8878: return $uname if ($uname =~ /^error/);
8879: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8880: if (!defined($course_server)) {
8881: if (defined(&domain($udom,'primary'))) {
8882: $course_server = &domain($udom,'primary');
8883: } else {
8884: $course_server = $env{'user.home'};
8885: }
8886: }
8887: my %host_servers =
8888: &Apache::lonnet::get_servers($udom,'library');
8889: unless ($host_servers{$course_server}) {
8890: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8891: }
1.84 www 8892: # ------------------------------------------------------------- Make the course
8893: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8894: $course_server);
1.84 www 8895: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8896: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8897: if (($uhome eq '') || ($uhome eq 'no_host')) {
8898: return 'error: no such course';
8899: }
1.271 www 8900: # ----------------------------------------------------------------- Course made
1.516 raeburn 8901: # log existence
1.1029 raeburn 8902: my $now = time;
1.918 raeburn 8903: my $newcourse = {
8904: $udom.'_'.$uname => {
1.921 raeburn 8905: description => $description,
8906: inst_code => $inst_code,
8907: owner => $course_owner,
8908: type => $crstype,
1.1029 raeburn 8909: creator => $env{'user.name'}.':'.
8910: $env{'user.domain'},
8911: created => $now,
8912: context => $context,
1.918 raeburn 8913: },
8914: };
1.921 raeburn 8915: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8916: # set toplevel url
1.271 www 8917: my $topurl=$url;
8918: unless ($nonstandard) {
8919: # ------------------------------------------ For standard courses, make top url
8920: my $mapurl=&clutter($url);
1.278 www 8921: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8922: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8923: <map>
8924: <resource id="1" type="start"></resource>
8925: <resource id="2" src="$mapurl"></resource>
8926: <resource id="3" type="finish"></resource>
8927: <link index="1" from="1" to="2"></link>
8928: <link index="2" from="2" to="3"></link>
8929: </map>
8930: ENDINITMAP
8931: $topurl=&declutter(
1.638 albertel 8932: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8933: );
8934: }
8935: # ----------------------------------------------------------- Write preferences
1.84 www 8936: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8937: ('description' => $description,
8938: 'url' => $topurl,
8939: 'internal.creator' => $env{'user.name'}.':'.
8940: $env{'user.domain'},
8941: 'internal.created' => $now,
8942: 'internal.creationcontext' => $context)
8943: );
1.84 www 8944: return '/'.$udom.'/'.$uname;
8945: }
8946:
1.1011 raeburn 8947: # ------------------------------------------------------------------- Create ID
8948: sub generate_coursenum {
1.1038 raeburn 8949: my ($udom,$crstype) = @_;
1.1011 raeburn 8950: my $domdesc = &domain($udom);
8951: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8952: my $first;
8953: if ($crstype eq 'Community') {
8954: $first = '0';
8955: } else {
8956: $first = int(1+rand(9));
8957: }
8958: my $uname=$first.
1.1011 raeburn 8959: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8960: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8961: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8962: # ----------------------------------------------- Make sure that does not exist
8963: my $uhome=&homeserver($uname,$udom,'true');
8964: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8965: if ($crstype eq 'Community') {
8966: $first = '0';
8967: } else {
8968: $first = int(1+rand(9));
8969: }
8970: $uname=$first.
1.1011 raeburn 8971: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8972: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8973: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8974: $uhome=&homeserver($uname,$udom,'true');
8975: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8976: return 'error: unable to generate unique course-ID';
8977: }
8978: }
8979: return $uname;
8980: }
8981:
1.813 albertel 8982: sub is_course {
1.1167 droeschl 8983: my ($cdom, $cnum) = scalar(@_) == 1 ?
8984: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8985:
8986: return unless $cdom and $cnum;
8987:
8988: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8989: '.');
8990:
1.1172.2.23 raeburn 8991: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8992: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8993: }
8994:
1.1015 raeburn 8995: sub store_userdata {
8996: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8997: my $result;
1.1016 raeburn 8998: if ($datakey ne '') {
1.1013 raeburn 8999: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9000: if ($udom eq '' || $uname eq '') {
9001: $udom = $env{'user.domain'};
9002: $uname = $env{'user.name'};
9003: }
9004: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9005: if (($uhome eq '') || ($uhome eq 'no_host')) {
9006: $result = 'error: no_host';
9007: } else {
9008: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9009: $storehash->{'host'} = $perlvar{'lonHostID'};
9010:
9011: my $namevalue='';
9012: foreach my $key (keys(%{$storehash})) {
9013: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9014: }
9015: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9016: unless ($namespace eq 'courserequests') {
9017: $datakey = &escape($datakey);
9018: }
1.1105 raeburn 9019: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9020: $namevalue,$uhome);
1.1013 raeburn 9021: }
9022: } else {
9023: $result = 'error: data to store was not a hash reference';
9024: }
9025: } else {
9026: $result= 'error: invalid requestkey';
9027: }
9028: return $result;
9029: }
9030:
1.21 www 9031: # ---------------------------------------------------------- Assign Custom Role
9032:
9033: sub assigncustomrole {
1.957 raeburn 9034: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9035: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9036: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9037: }
9038:
9039: # ----------------------------------------------------------------- Revoke Role
9040:
9041: sub revokerole {
1.957 raeburn 9042: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9043: my $now=time;
1.965 raeburn 9044: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9045: }
9046:
9047: # ---------------------------------------------------------- Revoke Custom Role
9048:
9049: sub revokecustomrole {
1.957 raeburn 9050: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9051: my $now=time;
1.357 www 9052: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9053: $deleteflag,$selfenroll,$context);
1.17 www 9054: }
9055:
1.533 banghart 9056: # ------------------------------------------------------------ Disk usage
1.535 albertel 9057: sub diskusage {
1.955 raeburn 9058: my ($udom,$uname,$directorypath,$getpropath)=@_;
9059: $directorypath =~ s/\/$//;
9060: my $listing=&reply('du2:'.&escape($directorypath).':'
9061: .&escape($getpropath).':'.&escape($uname).':'
9062: .&escape($udom),homeserver($uname,$udom));
9063: if ($listing eq 'unknown_cmd') {
9064: if ($getpropath) {
9065: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9066: }
9067: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9068: }
1.514 albertel 9069: return $listing;
1.512 banghart 9070: }
9071:
1.566 banghart 9072: sub is_locked {
1.1096 raeburn 9073: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9074: my @check;
9075: my $is_locked;
1.1093 raeburn 9076: push (@check,$file_name);
1.613 albertel 9077: my %locked = &get('file_permissions',\@check,
1.620 albertel 9078: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9079: my ($tmp)=keys(%locked);
9080: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9081:
1.566 banghart 9082: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9083: $is_locked = 'false';
9084: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9085: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9086: $is_locked = 'true';
1.1096 raeburn 9087: if (ref($which) eq 'ARRAY') {
9088: push(@{$which},$entry);
9089: } else {
9090: last;
9091: }
1.745 raeburn 9092: }
9093: }
1.566 banghart 9094: } else {
9095: $is_locked = 'false';
9096: }
1.1093 raeburn 9097: return $is_locked;
1.566 banghart 9098: }
9099:
1.759 albertel 9100: sub declutter_portfile {
9101: my ($file) = @_;
1.833 albertel 9102: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9103: return $file;
9104: }
9105:
1.559 banghart 9106: # ------------------------------------------------------------- Mark as Read Only
9107:
9108: sub mark_as_readonly {
9109: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9110: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9111: my ($tmp)=keys(%current_permissions);
9112: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9113: foreach my $file (@{$files}) {
1.759 albertel 9114: $file = &declutter_portfile($file);
1.561 banghart 9115: push(@{$current_permissions{$file}},$what);
1.559 banghart 9116: }
1.613 albertel 9117: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9118: return;
9119: }
9120:
1.572 banghart 9121: # ------------------------------------------------------------Save Selected Files
9122:
9123: sub save_selected_files {
9124: my ($user, $path, @files) = @_;
9125: my $filename = $user."savedfiles";
1.573 banghart 9126: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9127: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9128: foreach my $file (@files) {
1.620 albertel 9129: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9130: }
9131: foreach my $file (@other_files) {
1.574 banghart 9132: print (OUT $file."\n");
1.572 banghart 9133: }
1.574 banghart 9134: close (OUT);
1.572 banghart 9135: return 'ok';
9136: }
9137:
1.574 banghart 9138: sub clear_selected_files {
9139: my ($user) = @_;
9140: my $filename = $user."savedfiles";
1.1117 foxr 9141: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9142: print (OUT undef);
9143: close (OUT);
9144: return ("ok");
9145: }
9146:
1.572 banghart 9147: sub files_in_path {
9148: my ($user, $path) = @_;
9149: my $filename = $user."savedfiles";
9150: my %return_files;
1.1117 foxr 9151: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9152: while (my $line_in = <IN>) {
1.574 banghart 9153: chomp ($line_in);
9154: my @paths_and_file = split (m!/!, $line_in);
9155: my $file_part = pop (@paths_and_file);
9156: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9157: $path_part.='/';
9158: my $path_and_file = $path_part.$file_part;
9159: if ($path_part eq $path) {
9160: $return_files{$file_part}= 'selected';
9161: }
9162: }
1.574 banghart 9163: close (IN);
9164: return (\%return_files);
1.572 banghart 9165: }
9166:
9167: # called in portfolio select mode, to show files selected NOT in current directory
9168: sub files_not_in_path {
9169: my ($user, $path) = @_;
9170: my $filename = $user."savedfiles";
9171: my @return_files;
9172: my $path_part;
1.1117 foxr 9173: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9174: while (my $line = <IN>) {
1.572 banghart 9175: #ok, I know it's clunky, but I want it to work
1.800 albertel 9176: my @paths_and_file = split(m|/|, $line);
9177: my $file_part = pop(@paths_and_file);
9178: chomp($file_part);
9179: my $path_part = join('/', @paths_and_file);
1.572 banghart 9180: $path_part .= '/';
9181: my $path_and_file = $path_part.$file_part;
9182: if ($path_part ne $path) {
1.800 albertel 9183: push(@return_files, ($path_and_file));
1.572 banghart 9184: }
9185: }
1.800 albertel 9186: close(OUT);
1.574 banghart 9187: return (@return_files);
1.572 banghart 9188: }
9189:
1.745 raeburn 9190: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9191:
1.745 raeburn 9192: sub get_portfile_permissions {
9193: my ($domain,$user) = @_;
1.613 albertel 9194: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9195: my ($tmp)=keys(%current_permissions);
9196: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9197: return \%current_permissions;
9198: }
9199:
9200: #---------------------------------------------Get portfolio file access controls
9201:
1.749 raeburn 9202: sub get_access_controls {
1.745 raeburn 9203: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9204: my %access;
9205: my $real_file = $file;
9206: $file =~ s/\.meta$//;
1.745 raeburn 9207: if (defined($file)) {
1.749 raeburn 9208: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9209: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9210: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9211: }
9212: }
1.745 raeburn 9213: } else {
1.749 raeburn 9214: foreach my $key (keys(%{$current_permissions})) {
9215: if ($key =~ /\0accesscontrol$/) {
9216: if (defined($group)) {
9217: if ($key !~ m-^\Q$group\E/-) {
9218: next;
9219: }
9220: }
9221: my ($fullpath) = split(/\0/,$key);
9222: if (ref($$current_permissions{$key}) eq 'HASH') {
9223: foreach my $control (keys(%{$$current_permissions{$key}})) {
9224: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9225: }
9226: }
9227: }
9228: }
9229: }
9230: return %access;
9231: }
9232:
9233: sub modify_access_controls {
9234: my ($file_name,$changes,$domain,$user)=@_;
9235: my ($outcome,$deloutcome);
9236: my %store_permissions;
9237: my %new_values;
9238: my %new_control;
9239: my %translation;
9240: my @deletions = ();
9241: my $now = time;
9242: if (exists($$changes{'activate'})) {
9243: if (ref($$changes{'activate'}) eq 'HASH') {
9244: my @newitems = sort(keys(%{$$changes{'activate'}}));
9245: my $numnew = scalar(@newitems);
9246: for (my $i=0; $i<$numnew; $i++) {
9247: my $newkey = $newitems[$i];
9248: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9249: if ($newkey =~ /^\d+:/) {
9250: $newkey =~ s/^(\d+)/$newid/;
9251: $translation{$1} = $newid;
9252: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9253: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9254: $translation{$1} = $newid;
9255: }
1.749 raeburn 9256: $new_values{$file_name."\0".$newkey} =
9257: $$changes{'activate'}{$newitems[$i]};
9258: $new_control{$newkey} = $now;
9259: }
9260: }
9261: }
9262: my %todelete;
9263: my %changed_items;
9264: foreach my $action ('delete','update') {
9265: if (exists($$changes{$action})) {
9266: if (ref($$changes{$action}) eq 'HASH') {
9267: foreach my $key (keys(%{$$changes{$action}})) {
9268: my ($itemnum) = ($key =~ /^([^:]+):/);
9269: if ($action eq 'delete') {
9270: $todelete{$itemnum} = 1;
9271: } else {
9272: $changed_items{$itemnum} = $key;
9273: }
9274: }
1.745 raeburn 9275: }
9276: }
1.749 raeburn 9277: }
9278: # get lock on access controls for file.
9279: my $lockhash = {
9280: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9281: ':'.$env{'user.domain'},
9282: };
9283: my $tries = 0;
9284: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9285:
9286: while (($gotlock ne 'ok') && $tries <3) {
9287: $tries ++;
9288: sleep 1;
9289: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9290: }
9291: if ($gotlock eq 'ok') {
9292: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9293: my ($tmp)=keys(%curr_permissions);
9294: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9295: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9296: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9297: if (ref($curr_controls) eq 'HASH') {
9298: foreach my $control_item (keys(%{$curr_controls})) {
9299: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9300: if (defined($todelete{$itemnum})) {
9301: push(@deletions,$file_name."\0".$control_item);
9302: } else {
9303: if (defined($changed_items{$itemnum})) {
9304: $new_control{$changed_items{$itemnum}} = $now;
9305: push(@deletions,$file_name."\0".$control_item);
9306: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9307: } else {
9308: $new_control{$control_item} = $$curr_controls{$control_item};
9309: }
9310: }
1.745 raeburn 9311: }
9312: }
9313: }
1.970 raeburn 9314: my ($group);
9315: if (&is_course($domain,$user)) {
9316: ($group,my $file) = split(/\//,$file_name,2);
9317: }
1.749 raeburn 9318: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9319: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9320: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9321: # remove lock
9322: my @del_lock = ($file_name."\0".'locked_access_records');
9323: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9324: my $sqlresult =
1.970 raeburn 9325: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9326: $group);
1.749 raeburn 9327: } else {
9328: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9329: }
1.749 raeburn 9330: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9331: }
9332:
1.827 raeburn 9333: sub make_public_indefinitely {
9334: my ($requrl) = @_;
9335: my $now = time;
9336: my $action = 'activate';
9337: my $aclnum = 0;
9338: if (&is_portfolio_url($requrl)) {
9339: my (undef,$udom,$unum,$file_name,$group) =
9340: &parse_portfolio_url($requrl);
9341: my $current_perms = &get_portfile_permissions($udom,$unum);
9342: my %access_controls = &get_access_controls($current_perms,
9343: $group,$file_name);
9344: foreach my $key (keys(%{$access_controls{$file_name}})) {
9345: my ($num,$scope,$end,$start) =
9346: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9347: if ($scope eq 'public') {
9348: if ($start <= $now && $end == 0) {
9349: $action = 'none';
9350: } else {
9351: $action = 'update';
9352: $aclnum = $num;
9353: }
9354: last;
9355: }
9356: }
9357: if ($action eq 'none') {
9358: return 'ok';
9359: } else {
9360: my %changes;
9361: my $newend = 0;
9362: my $newstart = $now;
9363: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9364: $changes{$action}{$newkey} = {
9365: type => 'public',
9366: time => {
9367: start => $newstart,
9368: end => $newend,
9369: },
9370: };
9371: my ($outcome,$deloutcome,$new_values,$translation) =
9372: &modify_access_controls($file_name,\%changes,$udom,$unum);
9373: return $outcome;
9374: }
9375: } else {
9376: return 'invalid';
9377: }
9378: }
9379:
1.745 raeburn 9380: #------------------------------------------------------Get Marked as Read Only
9381:
9382: sub get_marked_as_readonly {
9383: my ($domain,$user,$what,$group) = @_;
9384: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9385: my @readonly_files;
1.629 banghart 9386: my $cmp1=$what;
9387: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9388: while (my ($file_name,$value) = each(%{$current_permissions})) {
9389: if (defined($group)) {
9390: if ($file_name !~ m-^\Q$group\E/-) {
9391: next;
9392: }
9393: }
1.561 banghart 9394: if (ref($value) eq "ARRAY"){
9395: foreach my $stored_what (@{$value}) {
1.629 banghart 9396: my $cmp2=$stored_what;
1.759 albertel 9397: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9398: $cmp2=join('',@{$stored_what});
1.745 raeburn 9399: }
1.629 banghart 9400: if ($cmp1 eq $cmp2) {
1.561 banghart 9401: push(@readonly_files, $file_name);
1.745 raeburn 9402: last;
1.563 banghart 9403: } elsif (!defined($what)) {
9404: push(@readonly_files, $file_name);
1.745 raeburn 9405: last;
1.561 banghart 9406: }
9407: }
1.745 raeburn 9408: }
1.561 banghart 9409: }
9410: return @readonly_files;
9411: }
1.577 banghart 9412: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9413:
1.577 banghart 9414: sub get_marked_as_readonly_hash {
1.745 raeburn 9415: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9416: my %readonly_files;
1.745 raeburn 9417: while (my ($file_name,$value) = each(%{$current_permissions})) {
9418: if (defined($group)) {
9419: if ($file_name !~ m-^\Q$group\E/-) {
9420: next;
9421: }
9422: }
1.577 banghart 9423: if (ref($value) eq "ARRAY"){
9424: foreach my $stored_what (@{$value}) {
1.745 raeburn 9425: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9426: foreach my $lock_descriptor(@{$stored_what}) {
9427: if ($lock_descriptor eq 'graded') {
9428: $readonly_files{$file_name} = 'graded';
9429: } elsif ($lock_descriptor eq 'handback') {
9430: $readonly_files{$file_name} = 'handback';
9431: } else {
9432: if (!exists($readonly_files{$file_name})) {
9433: $readonly_files{$file_name} = 'locked';
9434: }
9435: }
1.745 raeburn 9436: }
1.750 banghart 9437: }
1.577 banghart 9438: }
9439: }
9440: }
9441: return %readonly_files;
9442: }
1.559 banghart 9443: # ------------------------------------------------------------ Unmark as Read Only
9444:
9445: sub unmark_as_readonly {
1.629 banghart 9446: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9447: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9448: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9449: $file_name = &declutter_portfile($file_name);
1.634 albertel 9450: my $symb_crs = $what;
9451: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9452: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9453: my ($tmp)=keys(%current_permissions);
9454: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9455: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9456: foreach my $file (@readonly_files) {
1.759 albertel 9457: my $clean_file = &declutter_portfile($file);
9458: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9459: my $current_locks = $current_permissions{$file};
1.563 banghart 9460: my @new_locks;
9461: my @del_keys;
9462: if (ref($current_locks) eq "ARRAY"){
9463: foreach my $locker (@{$current_locks}) {
1.632 albertel 9464: my $compare=$locker;
1.749 raeburn 9465: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9466: $compare=join('',@{$locker});
1.746 raeburn 9467: if ($compare ne $symb_crs) {
9468: push(@new_locks, $locker);
9469: }
1.563 banghart 9470: }
9471: }
1.650 albertel 9472: if (scalar(@new_locks) > 0) {
1.563 banghart 9473: $current_permissions{$file} = \@new_locks;
9474: } else {
9475: push(@del_keys, $file);
1.613 albertel 9476: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9477: delete($current_permissions{$file});
1.563 banghart 9478: }
9479: }
1.561 banghart 9480: }
1.613 albertel 9481: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9482: return;
9483: }
1.512 banghart 9484:
1.17 www 9485: # ------------------------------------------------------------ Directory lister
9486:
9487: sub dirlist {
1.955 raeburn 9488: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9489: $uri=~s/^\///;
9490: $uri=~s/\/$//;
1.253 stredwic 9491: my ($udom, $uname);
1.955 raeburn 9492: if ($getuserdir) {
1.253 stredwic 9493: $udom = $userdomain;
9494: $uname = $username;
1.955 raeburn 9495: } else {
9496: (undef,$udom,$uname)=split(/\//,$uri);
9497: if(defined($userdomain)) {
9498: $udom = $userdomain;
9499: }
9500: if(defined($username)) {
9501: $uname = $username;
9502: }
1.253 stredwic 9503: }
1.955 raeburn 9504: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9505:
1.955 raeburn 9506: $dirRoot = $perlvar{'lonDocRoot'};
9507: if (defined($getpropath)) {
9508: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9509: $dirRoot =~ s/\/$//;
1.955 raeburn 9510: } elsif (defined($getuserdir)) {
9511: my $subdir=$uname.'__';
9512: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9513: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9514: ."/$udom/$subdir/$uname";
9515: } elsif (defined($alternateRoot)) {
9516: $dirRoot = $alternateRoot;
1.751 banghart 9517: }
1.253 stredwic 9518:
9519: if($udom) {
9520: if($uname) {
1.1135 raeburn 9521: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9522: if ($uhome eq 'no_host') {
9523: return ([],'no_host');
9524: }
1.955 raeburn 9525: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9526: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9527: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9528: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9529: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9530: } else {
9531: @listing_results = map { &unescape($_); } split(/:/,$listing);
9532: }
1.605 matthew 9533: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9534: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9535: @listing_results = split(/:/,$listing);
9536: } else {
9537: @listing_results = map { &unescape($_); } split(/:/,$listing);
9538: }
1.1135 raeburn 9539: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9540: ($listing eq 'rejected') || ($listing eq 'refused') ||
9541: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9542: return ([],$listing);
9543: } else {
9544: return (\@listing_results);
1.1135 raeburn 9545: }
1.955 raeburn 9546: } elsif(!$alternateRoot) {
1.1136 raeburn 9547: my (%allusers,%listerror);
1.841 albertel 9548: my %servers = &get_servers($udom,'library');
1.955 raeburn 9549: foreach my $tryserver (keys(%servers)) {
9550: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9551: &escape($udom),$tryserver);
9552: if ($listing eq 'unknown_cmd') {
9553: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9554: $udom, $tryserver);
9555: } else {
9556: @listing_results = map { &unescape($_); } split(/:/,$listing);
9557: }
1.841 albertel 9558: if ($listing eq 'unknown_cmd') {
9559: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9560: $udom, $tryserver);
9561: @listing_results = split(/:/,$listing);
9562: } else {
9563: @listing_results =
9564: map { &unescape($_); } split(/:/,$listing);
9565: }
1.1136 raeburn 9566: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9567: ($listing eq 'rejected') || ($listing eq 'refused') ||
9568: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9569: $listerror{$tryserver} = $listing;
9570: } else {
1.841 albertel 9571: foreach my $line (@listing_results) {
9572: my ($entry) = split(/&/,$line,2);
9573: $allusers{$entry} = 1;
9574: }
9575: }
1.253 stredwic 9576: }
1.1136 raeburn 9577: my @alluserslist=();
1.800 albertel 9578: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9579: push(@alluserslist,$user.'&user');
1.253 stredwic 9580: }
1.1136 raeburn 9581: return (\@alluserslist);
1.253 stredwic 9582: } else {
1.1136 raeburn 9583: return ([],'missing username');
1.253 stredwic 9584: }
1.955 raeburn 9585: } elsif(!defined($getpropath)) {
1.1136 raeburn 9586: my $path = $perlvar{'lonDocRoot'}.'/res/';
9587: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9588: return (\@all_domains);
1.955 raeburn 9589: } else {
1.1136 raeburn 9590: return ([],'missing domain');
1.275 stredwic 9591: }
9592: }
9593:
9594: # --------------------------------------------- GetFileTimestamp
9595: # This function utilizes dirlist and returns the date stamp for
9596: # when it was last modified. It will also return an error of -1
9597: # if an error occurs
9598:
9599: sub GetFileTimestamp {
1.955 raeburn 9600: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9601: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9602: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9603: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9604: undef,$getuserdir);
9605: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9606: return -1;
9607: }
9608: if (ref($fileref) eq 'ARRAY') {
9609: my @stats = split('&',$fileref->[0]);
1.375 matthew 9610: # @stats contains first the filename, then the stat output
9611: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9612: } else {
9613: return -1;
1.253 stredwic 9614: }
1.26 www 9615: }
9616:
1.712 albertel 9617: sub stat_file {
9618: my ($uri) = @_;
1.787 albertel 9619: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9620:
1.955 raeburn 9621: my ($udom,$uname,$file);
1.712 albertel 9622: if ($uri =~ m-^/(uploaded|editupload)/-) {
9623: ($udom,$uname,$file) =
1.811 albertel 9624: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9625: $file = 'userfiles/'.$file;
9626: }
9627: if ($uri =~ m-^/res/-) {
9628: ($udom,$uname) =
1.807 albertel 9629: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9630: $file = $uri;
9631: }
9632:
9633: if (!$udom || !$uname || !$file) {
9634: # unable to handle the uri
9635: return ();
9636: }
1.956 raeburn 9637: my $getpropath;
9638: if ($file =~ /^userfiles\//) {
9639: $getpropath = 1;
9640: }
1.1136 raeburn 9641: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9642: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9643: return ();
9644: } else {
9645: if (ref($listref) eq 'ARRAY') {
9646: my @stats = split('&',$listref->[0]);
9647: shift(@stats); #filename is first
9648: return @stats;
9649: }
1.712 albertel 9650: }
9651: return ();
9652: }
9653:
1.26 www 9654: # -------------------------------------------------------- Value of a Condition
9655:
1.713 albertel 9656: # gets the value of a specific preevaluated condition
9657: # stored in the string $env{user.state.<cid>}
9658: # or looks up a condition reference in the bighash and if if hasn't
9659: # already been evaluated recurses into docondval to get the value of
9660: # the condition, then memoizing it to
9661: # $env{user.state.<cid>.<condition>}
1.40 www 9662: sub directcondval {
9663: my $number=shift;
1.620 albertel 9664: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9665: &Apache::lonuserstate::evalstate();
9666: }
1.713 albertel 9667: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9668: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9669: } elsif ($number =~ /^_/) {
9670: my $sub_condition;
9671: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9672: &GDBM_READER(),0640)) {
9673: $sub_condition=$bighash{'conditions'.$number};
9674: untie(%bighash);
9675: }
9676: my $value = &docondval($sub_condition);
1.949 raeburn 9677: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9678: return $value;
9679: }
1.620 albertel 9680: if ($env{'user.state.'.$env{'request.course.id'}}) {
9681: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9682: } else {
9683: return 2;
9684: }
9685: }
9686:
1.713 albertel 9687: # get the collection of conditions for this resource
1.26 www 9688: sub condval {
9689: my $condidx=shift;
1.54 www 9690: my $allpathcond='';
1.713 albertel 9691: foreach my $cond (split(/\|/,$condidx)) {
9692: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9693: $allpathcond.=
9694: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9695: }
1.191 harris41 9696: }
1.54 www 9697: $allpathcond=~s/\|$//;
1.713 albertel 9698: return &docondval($allpathcond);
9699: }
9700:
9701: #evaluates an expression of conditions
9702: sub docondval {
9703: my ($allpathcond) = @_;
9704: my $result=0;
9705: if ($env{'request.course.id'}
9706: && defined($allpathcond)) {
9707: my $operand='|';
9708: my @stack;
9709: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9710: if ($chunk eq '(') {
9711: push @stack,($operand,$result);
9712: } elsif ($chunk eq ')') {
9713: my $before=pop @stack;
9714: if (pop @stack eq '&') {
9715: $result=$result>$before?$before:$result;
9716: } else {
9717: $result=$result>$before?$result:$before;
9718: }
9719: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9720: $operand=$chunk;
9721: } else {
9722: my $new=directcondval($chunk);
9723: if ($operand eq '&') {
9724: $result=$result>$new?$new:$result;
9725: } else {
9726: $result=$result>$new?$result:$new;
9727: }
9728: }
9729: }
1.26 www 9730: }
9731: return $result;
1.421 albertel 9732: }
9733:
9734: # ---------------------------------------------------- Devalidate courseresdata
9735:
9736: sub devalidatecourseresdata {
9737: my ($coursenum,$coursedomain)=@_;
9738: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9739: &devalidate_cache_new('courseres',$hashid);
1.28 www 9740: }
9741:
1.763 www 9742:
1.200 www 9743: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9744: #
9745: # Parameters:
9746: # $coursenum - Number of the course.
9747: # $coursedomain - Domain at which the course was created.
9748: # Returns:
9749: # A hash of the course parameters along (I think) with timestamps
9750: # and version info.
1.877 foxr 9751:
1.624 albertel 9752: sub get_courseresdata {
9753: my ($coursenum,$coursedomain)=@_;
1.200 www 9754: my $coursehom=&homeserver($coursenum,$coursedomain);
9755: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9756: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9757: my %dumpreply;
1.417 albertel 9758: unless (defined($cached)) {
1.624 albertel 9759: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9760: $result=\%dumpreply;
1.251 albertel 9761: my ($tmp) = keys(%dumpreply);
9762: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9763: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9764: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9765: return $tmp;
1.416 albertel 9766: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9767: $result=undef;
1.599 albertel 9768: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9769: }
9770: }
1.624 albertel 9771: return $result;
9772: }
9773:
1.633 albertel 9774: sub devalidateuserresdata {
9775: my ($uname,$udom)=@_;
9776: my $hashid="$udom:$uname";
9777: &devalidate_cache_new('userres',$hashid);
9778: }
9779:
1.624 albertel 9780: sub get_userresdata {
9781: my ($uname,$udom)=@_;
9782: #most student don\'t have any data set, check if there is some data
9783: if (&EXT_cache_status($udom,$uname)) { return undef; }
9784:
9785: my $hashid="$udom:$uname";
9786: my ($result,$cached)=&is_cached_new('userres',$hashid);
9787: if (!defined($cached)) {
9788: my %resourcedata=&dump('resourcedata',$udom,$uname);
9789: $result=\%resourcedata;
9790: &do_cache_new('userres',$hashid,$result,600);
9791: }
9792: my ($tmp)=keys(%$result);
9793: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9794: return $result;
9795: }
9796: #error 2 occurs when the .db doesn't exist
9797: if ($tmp!~/error: 2 /) {
1.672 albertel 9798: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9799: " Trying to get resource data for ".
9800: $uname." at ".$udom.": ".
9801: $tmp."</font>");
9802: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9803: #&EXT_cache_set($udom,$uname);
9804: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9805: undef($tmp); # not really an error so don't send it back
1.624 albertel 9806: }
9807: return $tmp;
9808: }
1.879 foxr 9809: #----------------------------------------------- resdata - return resource data
9810: # Purpose:
9811: # Return resource data for either users or for a course.
9812: # Parameters:
9813: # $name - Course/user name.
9814: # $domain - Name of the domain the user/course is registered on.
9815: # $type - Type of thing $name is (must be 'course' or 'user'
9816: # @which - Array of names of resources desired.
9817: # Returns:
9818: # The value of the first reasource in @which that is found in the
9819: # resource hash.
9820: # Exceptional Conditions:
9821: # If the $type passed in is not valid (not the string 'course' or
9822: # 'user', an undefined reference is returned.
9823: # If none of the resources are found, an undef is returned
1.624 albertel 9824: sub resdata {
9825: my ($name,$domain,$type,@which)=@_;
9826: my $result;
9827: if ($type eq 'course') {
9828: $result=&get_courseresdata($name,$domain);
9829: } elsif ($type eq 'user') {
9830: $result=&get_userresdata($name,$domain);
9831: }
9832: if (!ref($result)) { return $result; }
1.251 albertel 9833: foreach my $item (@which) {
1.927 albertel 9834: if (defined($result->{$item->[0]})) {
9835: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9836: }
1.250 albertel 9837: }
1.291 albertel 9838: return undef;
1.200 www 9839: }
9840:
1.1172.2.31 raeburn 9841: sub get_numsuppfiles {
9842: my ($cnum,$cdom,$ignorecache)=@_;
9843: my $hashid=$cnum.':'.$cdom;
9844: my ($suppcount,$cached);
9845: unless ($ignorecache) {
9846: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9847: }
9848: unless (defined($cached)) {
9849: my $chome=&homeserver($cnum,$cdom);
9850: unless ($chome eq 'no_host') {
9851: ($suppcount,my $errors) = (0,0);
9852: my $suppmap = 'supplemental.sequence';
9853: ($suppcount,$errors) =
9854: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9855: }
9856: &do_cache_new('suppcount',$hashid,$suppcount,600);
9857: }
9858: return $suppcount;
9859: }
9860:
1.379 matthew 9861: #
9862: # EXT resource caching routines
9863: #
9864:
9865: sub clear_EXT_cache_status {
1.383 albertel 9866: &delenv('cache.EXT.');
1.379 matthew 9867: }
9868:
9869: sub EXT_cache_status {
9870: my ($target_domain,$target_user) = @_;
1.383 albertel 9871: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9872: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9873: # We know already the user has no data
9874: return 1;
9875: } else {
9876: return 0;
9877: }
9878: }
9879:
9880: sub EXT_cache_set {
9881: my ($target_domain,$target_user) = @_;
1.383 albertel 9882: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9883: #&appenv({$cachename => time});
1.379 matthew 9884: }
9885:
1.28 www 9886: # --------------------------------------------------------- Value of a Variable
1.58 www 9887: sub EXT {
1.715 albertel 9888:
1.1172.2.28 raeburn 9889: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9890: unless ($varname) { return ''; }
1.218 albertel 9891: #get real user name/domain, courseid and symb
9892: my $courseid;
1.359 albertel 9893: my $publicuser;
1.427 www 9894: if ($symbparm) {
9895: $symbparm=&get_symb_from_alias($symbparm);
9896: }
1.218 albertel 9897: if (!($uname && $udom)) {
1.790 albertel 9898: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9899: if (!$symbparm) { $symbparm=$cursymb; }
9900: } else {
1.620 albertel 9901: $courseid=$env{'request.course.id'};
1.218 albertel 9902: }
1.48 www 9903: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9904: my $rest;
1.320 albertel 9905: if (defined($therest[0])) {
1.48 www 9906: $rest=join('.',@therest);
9907: } else {
9908: $rest='';
9909: }
1.320 albertel 9910:
1.57 www 9911: my $qualifierrest=$qualifier;
9912: if ($rest) { $qualifierrest.='.'.$rest; }
9913: my $spacequalifierrest=$space;
9914: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9915: if ($realm eq 'user') {
1.48 www 9916: # --------------------------------------------------------------- user.resource
9917: if ($space eq 'resource') {
1.651 albertel 9918: if ( (defined($Apache::lonhomework::parsing_a_problem)
9919: || defined($Apache::lonhomework::parsing_a_task))
9920: &&
1.744 albertel 9921: ($symbparm eq &symbread()) ) {
9922: # if we are in the middle of processing the resource the
9923: # get the value we are planning on committing
9924: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9925: return $Apache::lonhomework::results{$qualifierrest};
9926: } else {
9927: return $Apache::lonhomework::history{$qualifierrest};
9928: }
1.335 albertel 9929: } else {
1.359 albertel 9930: my %restored;
1.620 albertel 9931: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9932: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9933: } else {
9934: %restored=&restore($symbparm,$courseid,$udom,$uname);
9935: }
1.335 albertel 9936: return $restored{$qualifierrest};
9937: }
1.48 www 9938: # ----------------------------------------------------------------- user.access
9939: } elsif ($space eq 'access') {
1.218 albertel 9940: # FIXME - not supporting calls for a specific user
1.48 www 9941: return &allowed($qualifier,$rest);
9942: # ------------------------------------------ user.preferences, user.environment
9943: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9944: if (($uname eq $env{'user.name'}) &&
9945: ($udom eq $env{'user.domain'})) {
9946: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9947: } else {
1.359 albertel 9948: my %returnhash;
9949: if (!$publicuser) {
9950: %returnhash=&userenvironment($udom,$uname,
9951: $qualifierrest);
9952: }
1.218 albertel 9953: return $returnhash{$qualifierrest};
9954: }
1.48 www 9955: # ----------------------------------------------------------------- user.course
9956: } elsif ($space eq 'course') {
1.218 albertel 9957: # FIXME - not supporting calls for a specific user
1.620 albertel 9958: return $env{join('.',('request.course',$qualifier))};
1.48 www 9959: # ------------------------------------------------------------------- user.role
9960: } elsif ($space eq 'role') {
1.218 albertel 9961: # FIXME - not supporting calls for a specific user
1.620 albertel 9962: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9963: if ($qualifier eq 'value') {
9964: return $role;
9965: } elsif ($qualifier eq 'extent') {
9966: return $where;
9967: }
9968: # ----------------------------------------------------------------- user.domain
9969: } elsif ($space eq 'domain') {
1.218 albertel 9970: return $udom;
1.48 www 9971: # ------------------------------------------------------------------- user.name
9972: } elsif ($space eq 'name') {
1.218 albertel 9973: return $uname;
1.48 www 9974: # ---------------------------------------------------- Any other user namespace
1.29 www 9975: } else {
1.359 albertel 9976: my %reply;
9977: if (!$publicuser) {
9978: %reply=&get($space,[$qualifierrest],$udom,$uname);
9979: }
9980: return $reply{$qualifierrest};
1.48 www 9981: }
1.236 www 9982: } elsif ($realm eq 'query') {
9983: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9984: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9985: [$spacequalifierrest]);
1.620 albertel 9986: return $env{'form.'.$spacequalifierrest};
1.236 www 9987: } elsif ($realm eq 'request') {
1.48 www 9988: # ------------------------------------------------------------- request.browser
9989: if ($space eq 'browser') {
1.1145 bisitz 9990: return $env{'browser.'.$qualifier};
1.57 www 9991: # ------------------------------------------------------------ request.filename
9992: } else {
1.620 albertel 9993: return $env{'request.'.$spacequalifierrest};
1.29 www 9994: }
1.28 www 9995: } elsif ($realm eq 'course') {
1.48 www 9996: # ---------------------------------------------------------- course.description
1.620 albertel 9997: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9998: } elsif ($realm eq 'resource') {
1.165 www 9999:
1.620 albertel 10000: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10001: if (!$symbparm) { $symbparm=&symbread(); }
10002: }
1.693 albertel 10003:
1.1172.2.30 raeburn 10004: if ($qualifier eq '') {
10005: if ($space eq 'title') {
10006: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10007: return &gettitle($symbparm);
10008: }
1.693 albertel 10009:
1.1172.2.30 raeburn 10010: if ($space eq 'map') {
10011: my ($map) = &decode_symb($symbparm);
10012: return &symbread($map);
10013: }
10014: if ($space eq 'maptitle') {
10015: my ($map) = &decode_symb($symbparm);
10016: return &gettitle($map);
10017: }
10018: if ($space eq 'filename') {
10019: if ($symbparm) {
10020: return &clutter((&decode_symb($symbparm))[2]);
10021: }
10022: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10023: }
1.1172.2.30 raeburn 10024:
10025: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10026: if ($space eq 'visibleparts') {
10027: my $navmap = Apache::lonnavmaps::navmap->new();
10028: my $item;
10029: if (ref($navmap)) {
10030: my $res = $navmap->getBySymb($symbparm);
10031: my $parts = $res->parts();
10032: if (ref($parts) eq 'ARRAY') {
10033: $item = join(',',@{$parts});
10034: }
10035: undef($navmap);
10036: }
10037: return $item;
10038: }
10039: }
10040: }
1.693 albertel 10041:
10042: my ($section, $group, @groups);
1.593 albertel 10043: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10044: if (($courseid eq '') && ($cid)) {
10045: $courseid = $cid;
10046: }
10047: if (($symbparm && $courseid) &&
10048: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10049:
1.218 albertel 10050: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10051:
1.60 www 10052: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10053: my $symbp=$symbparm;
1.735 albertel 10054: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10055:
10056: my $symbparm=$symbp.'.'.$spacequalifierrest;
10057: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10058:
1.620 albertel 10059: if (($env{'user.name'} eq $uname) &&
10060: ($env{'user.domain'} eq $udom)) {
10061: $section=$env{'request.course.sec'};
1.733 raeburn 10062: @groups = split(/:/,$env{'request.course.groups'});
10063: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10064: } else {
1.539 albertel 10065: if (! defined($usection)) {
1.551 albertel 10066: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10067: } else {
10068: $section = $usection;
10069: }
1.733 raeburn 10070: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10071: }
10072:
10073: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10074: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10075: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10076:
1.593 albertel 10077: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10078: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10079: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10080:
1.60 www 10081: # ----------------------------------------------------------- first, check user
1.624 albertel 10082:
10083: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10084: ([$courselevelr,'resource'],
10085: [$courselevelm,'map' ],
10086: [$courselevel, 'course' ]));
1.931 albertel 10087: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10088:
1.594 albertel 10089: # ------------------------------------------------ second, check some of course
1.684 raeburn 10090: my $coursereply;
1.691 raeburn 10091: if (@groups > 0) {
10092: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10093: $mapparm,$spacequalifierrest);
1.927 albertel 10094: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10095: }
1.96 www 10096:
1.684 raeburn 10097: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10098: $env{'course.'.$courseid.'.domain'},
10099: 'course',
10100: ([$seclevelr, 'resource'],
10101: [$seclevelm, 'map' ],
10102: [$seclevel, 'course' ],
10103: [$courselevelr,'resource']));
10104: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10105:
1.60 www 10106: # ------------------------------------------------------ third, check map parms
1.218 albertel 10107: my %parmhash=();
10108: my $thisparm='';
10109: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10110: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10111: &GDBM_READER(),0640)) {
1.218 albertel 10112: $thisparm=$parmhash{$symbparm};
10113: untie(%parmhash);
10114: }
1.927 albertel 10115: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10116: }
1.594 albertel 10117: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10118:
1.218 albertel 10119: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10120: my $filename;
10121: if (!$symbparm) { $symbparm=&symbread(); }
10122: if ($symbparm) {
1.409 www 10123: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10124: } else {
1.620 albertel 10125: $filename=$env{'request.filename'};
1.282 albertel 10126: }
10127: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10128: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10129: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10130: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10131:
1.927 albertel 10132: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10133: if ($symbparm && defined($courseid) &&
1.620 albertel 10134: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10135: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10136: $env{'course.'.$courseid.'.domain'},
10137: 'course',
1.927 albertel 10138: ([$courselevelm,'map' ],
10139: [$courselevel, 'course']));
10140: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10141: }
1.145 www 10142: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10143: unless ($space eq '0') {
1.336 albertel 10144: my @parts=split(/_/,$space);
10145: my $id=pop(@parts);
10146: my $part=join('_',@parts);
10147: if ($part eq '') { $part='0'; }
1.927 albertel 10148: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10149: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10150: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10151: }
1.395 albertel 10152: if ($recurse) { return undef; }
10153: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10154: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10155: # ---------------------------------------------------- Any other user namespace
10156: } elsif ($realm eq 'environment') {
10157: # ----------------------------------------------------------------- environment
1.620 albertel 10158: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10159: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10160: } else {
1.770 albertel 10161: if ($uname eq 'anonymous' && $udom eq '') {
10162: return '';
10163: }
1.219 albertel 10164: my %returnhash=&userenvironment($udom,$uname,
10165: $spacequalifierrest);
10166: return $returnhash{$spacequalifierrest};
10167: }
1.28 www 10168: } elsif ($realm eq 'system') {
1.48 www 10169: # ----------------------------------------------------------------- system.time
10170: if ($space eq 'time') {
10171: return time;
10172: }
1.696 albertel 10173: } elsif ($realm eq 'server') {
10174: # ----------------------------------------------------------------- system.time
10175: if ($space eq 'name') {
10176: return $ENV{'SERVER_NAME'};
10177: }
1.28 www 10178: }
1.48 www 10179: return '';
1.61 www 10180: }
10181:
1.927 albertel 10182: sub get_reply {
10183: my ($reply_value) = @_;
1.940 raeburn 10184: if (ref($reply_value) eq 'ARRAY') {
10185: if (wantarray) {
10186: return @$reply_value;
10187: }
10188: return $reply_value->[0];
10189: } else {
10190: return $reply_value;
1.927 albertel 10191: }
10192: }
10193:
1.691 raeburn 10194: sub check_group_parms {
10195: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10196: my @groupitems = ();
10197: my $resultitem;
1.927 albertel 10198: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10199: foreach my $group (@{$groups}) {
10200: foreach my $level (@levels) {
1.927 albertel 10201: my $item = $courseid.'.['.$group.'].'.$level->[0];
10202: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10203: }
10204: }
10205: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10206: $env{'course.'.$courseid.'.domain'},
10207: 'course',@groupitems);
10208: return $coursereply;
10209: }
10210:
10211: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10212: my ($courseid,@groups) = @_;
10213: @groups = sort(@groups);
1.691 raeburn 10214: return @groups;
10215: }
10216:
1.395 albertel 10217: sub packages_tab_default {
10218: my ($uri,$varname)=@_;
10219: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10220:
10221: my (@extension,@specifics,$do_default);
10222: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10223: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10224: if ($pack_type eq 'default') {
10225: $do_default=1;
10226: } elsif ($pack_type eq 'extension') {
10227: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10228: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10229: # only look at packages defaults for packages that this id is
1.738 albertel 10230: push(@specifics,[$package,$pack_type,$pack_part]);
10231: }
10232: }
10233: # first look for a package that matches the requested part id
10234: foreach my $package (@specifics) {
10235: my (undef,$pack_type,$pack_part)=@{$package};
10236: next if ($pack_part ne $part);
10237: if (defined($packagetab{"$pack_type&$name&default"})) {
10238: return $packagetab{"$pack_type&$name&default"};
10239: }
10240: }
10241: # look for any possible matching non extension_ package
10242: foreach my $package (@specifics) {
10243: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10244: if (defined($packagetab{"$pack_type&$name&default"})) {
10245: return $packagetab{"$pack_type&$name&default"};
10246: }
1.585 albertel 10247: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10248: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10249: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10250: }
10251: }
1.738 albertel 10252: # look for any posible extension_ match
10253: foreach my $package (@extension) {
10254: my ($package,$pack_type)=@{$package};
10255: if (defined($packagetab{"$pack_type&$name&default"})) {
10256: return $packagetab{"$pack_type&$name&default"};
10257: }
10258: if (defined($packagetab{$package."&$name&default"})) {
10259: return $packagetab{$package."&$name&default"};
10260: }
10261: }
10262: # look for a global default setting
10263: if ($do_default && defined($packagetab{"default&$name&default"})) {
10264: return $packagetab{"default&$name&default"};
10265: }
1.395 albertel 10266: return undef;
10267: }
10268:
1.334 albertel 10269: sub add_prefix_and_part {
10270: my ($prefix,$part)=@_;
10271: my $keyroot;
10272: if (defined($prefix) && $prefix !~ /^__/) {
10273: # prefix that has a part already
10274: $keyroot=$prefix;
10275: } elsif (defined($prefix)) {
10276: # prefix that is missing a part
10277: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10278: } else {
10279: # no prefix at all
10280: if (defined($part)) { $keyroot='_'.$part; }
10281: }
10282: return $keyroot;
10283: }
10284:
1.71 www 10285: # ---------------------------------------------------------------- Get metadata
10286:
1.599 albertel 10287: my %metaentry;
1.1070 www 10288: my %importedpartids;
1.71 www 10289: sub metadata {
1.176 www 10290: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10291: $uri=&declutter($uri);
1.288 albertel 10292: # if it is a non metadata possible uri return quickly
1.529 albertel 10293: if (($uri eq '') ||
10294: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10295: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10296: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10297: return undef;
10298: }
1.1172.2.49 raeburn 10299: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10300: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10301: return undef;
1.288 albertel 10302: }
1.73 www 10303: my $filename=$uri;
10304: $uri=~s/\.meta$//;
1.172 www 10305: #
10306: # Is the metadata already cached?
1.177 www 10307: # Look at timestamp of caching
1.172 www 10308: # Everything is cached by the main uri, libraries are never directly cached
10309: #
1.428 albertel 10310: if (!defined($liburi)) {
1.599 albertel 10311: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10312: if (defined($cached)) { return $result->{':'.$what}; }
10313: }
10314: {
1.1069 www 10315: # Imported parts would go here
1.1070 www 10316: my %importedids=();
10317: my @origfileimportpartids=();
1.1069 www 10318: my $importedparts=0;
1.172 www 10319: #
10320: # Is this a recursive call for a library?
10321: #
1.599 albertel 10322: # if (! exists($metacache{$uri})) {
10323: # $metacache{$uri}={};
10324: # }
1.924 albertel 10325: my $cachetime = 60*60;
1.171 www 10326: if ($liburi) {
10327: $liburi=&declutter($liburi);
10328: $filename=$liburi;
1.401 bowersj2 10329: } else {
1.599 albertel 10330: &devalidate_cache_new('meta',$uri);
10331: undef(%metaentry);
1.401 bowersj2 10332: }
1.140 www 10333: my %metathesekeys=();
1.73 www 10334: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10335: my $metastring;
1.1140 www 10336: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10337: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10338: $metastring =
1.929 albertel 10339: &Apache::lonnet::ssi_body($which,
1.924 albertel 10340: ('grade_target' => 'meta'));
10341: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10342: } elsif (($uri !~ m -^(editupload)/-) &&
10343: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10344: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10345: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10346: $metastring=&getfile($file);
1.489 albertel 10347: }
1.208 albertel 10348: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10349: my $token;
1.140 www 10350: undef %metathesekeys;
1.71 www 10351: while ($token=$parser->get_token) {
1.339 albertel 10352: if ($token->[0] eq 'S') {
10353: if (defined($token->[2]->{'package'})) {
1.172 www 10354: #
10355: # This is a package - get package info
10356: #
1.339 albertel 10357: my $package=$token->[2]->{'package'};
10358: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10359: if (defined($token->[2]->{'id'})) {
10360: $keyroot.='_'.$token->[2]->{'id'};
10361: }
1.599 albertel 10362: if ($metaentry{':packages'}) {
10363: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10364: } else {
1.599 albertel 10365: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10366: }
1.736 albertel 10367: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10368: my $part=$keyroot;
10369: $part=~s/^\_//;
1.736 albertel 10370: if ($pack_entry=~/^\Q$package\E\&/ ||
10371: $pack_entry=~/^\Q$package\E_0\&/) {
10372: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10373: # ignore package.tab specified default values
10374: # here &package_tab_default() will fetch those
10375: if ($subp eq 'default') { next; }
1.736 albertel 10376: my $value=$packagetab{$pack_entry};
1.432 albertel 10377: my $unikey;
10378: if ($pack =~ /_0$/) {
10379: $unikey='parameter_0_'.$name;
10380: $part=0;
10381: } else {
10382: $unikey='parameter'.$keyroot.'_'.$name;
10383: }
1.339 albertel 10384: if ($subp eq 'display') {
10385: $value.=' [Part: '.$part.']';
10386: }
1.599 albertel 10387: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10388: $metathesekeys{$unikey}=1;
1.599 albertel 10389: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10390: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10391: }
1.599 albertel 10392: if (defined($metaentry{':'.$unikey.'.default'})) {
10393: $metaentry{':'.$unikey}=
10394: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10395: }
1.339 albertel 10396: }
10397: }
10398: } else {
1.172 www 10399: #
10400: # This is not a package - some other kind of start tag
1.339 albertel 10401: #
10402: my $entry=$token->[1];
1.1068 www 10403: my $unikey='';
1.175 www 10404:
1.339 albertel 10405: if ($entry eq 'import') {
1.175 www 10406: #
10407: # Importing a library here
1.339 albertel 10408: #
1.1067 www 10409: my $location=$parser->get_text('/import');
10410: my $dir=$filename;
10411: $dir=~s|[^/]*$||;
10412: $location=&filelocation($dir,$location);
1.1069 www 10413:
1.1068 www 10414: my $importmode=$token->[2]->{'importmode'};
10415: if ($importmode eq 'problem') {
1.1069 www 10416: # Import as problem/response
1.1068 www 10417: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10418: } elsif ($importmode eq 'part') {
10419: # Import as part(s)
1.1069 www 10420: $importedparts=1;
10421: # We need to get the original file and the imported file to get the part order correct
10422: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10423: # Load and inspect original file
1.1070 www 10424: if ($#origfileimportpartids<0) {
10425: undef(%importedpartids);
10426: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10427: my $origfile=&getfile($origfilelocation);
10428: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10429: }
10430:
1.1069 www 10431: # Load and inspect imported file
10432: my $impfile=&getfile($location);
10433: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10434: if ($#impfilepartids>=0) {
10435: # This problem had parts
1.1070 www 10436: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10437: } else {
10438: # Importing by turning a single problem into a problem part
10439: # It gets the import-tags ID as part-ID
10440: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10441: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10442: }
1.1068 www 10443: } else {
10444: # Normal import
10445: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10446: if (defined($token->[2]->{'id'})) {
10447: $unikey.='_'.$token->[2]->{'id'};
10448: }
1.1067 www 10449: }
10450:
1.339 albertel 10451: if ($depthcount<20) {
1.736 albertel 10452: my $metadata =
10453: &metadata($uri,'keys', $location,$unikey,
10454: $depthcount+1);
10455: foreach my $meta (split(',',$metadata)) {
10456: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10457: $metathesekeys{$meta}=1;
1.339 albertel 10458: }
1.1068 www 10459:
10460: }
1.1067 www 10461: } else {
10462: #
10463: # Not importing, some other kind of non-package, non-library start tag
10464: #
10465: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10466: if (defined($token->[2]->{'id'})) {
10467: $unikey.='_'.$token->[2]->{'id'};
10468: }
1.339 albertel 10469: if (defined($token->[2]->{'name'})) {
10470: $unikey.='_'.$token->[2]->{'name'};
10471: }
10472: $metathesekeys{$unikey}=1;
1.736 albertel 10473: foreach my $param (@{$token->[3]}) {
10474: $metaentry{':'.$unikey.'.'.$param} =
10475: $token->[2]->{$param};
1.339 albertel 10476: }
10477: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10478: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10479: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10480: # only ws inside the tag, and not in default, so use default
10481: # as value
1.599 albertel 10482: $metaentry{':'.$unikey}=$default;
1.908 albertel 10483: } elsif ( $internaltext =~ /\S/ ) {
10484: # something interesting inside the tag
10485: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10486: } else {
1.908 albertel 10487: # no interesting values, don't set a default
1.339 albertel 10488: }
1.172 www 10489: # end of not-a-package not-a-library import
1.339 albertel 10490: }
1.172 www 10491: # end of not-a-package start tag
1.339 albertel 10492: }
1.172 www 10493: # the next is the end of "start tag"
1.339 albertel 10494: }
10495: }
1.483 albertel 10496: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10497: $extension = lc($extension);
10498: if ($extension eq 'htm') { $extension='html'; }
10499:
1.737 albertel 10500: foreach my $key (keys(%packagetab)) {
1.483 albertel 10501: #no specific packages #how's our extension
10502: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10503: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10504: \%metathesekeys);
10505: }
1.883 albertel 10506:
10507: if (!exists($metaentry{':packages'})
10508: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10509: foreach my $key (keys(%packagetab)) {
1.483 albertel 10510: #no specific packages well let's get default then
10511: if ($key!~/^default&/) { next; }
1.488 albertel 10512: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10513: \%metathesekeys);
10514: }
10515: }
1.338 www 10516: # are there custom rights to evaluate
1.599 albertel 10517: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10518:
1.338 www 10519: #
10520: # Importing a rights file here
1.339 albertel 10521: #
10522: unless ($depthcount) {
1.599 albertel 10523: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10524: my $dir=$filename;
10525: $dir=~s|[^/]*$||;
10526: $location=&filelocation($dir,$location);
1.736 albertel 10527: my $rights_metadata =
10528: &metadata($uri,'keys',$location,'_rights',
10529: $depthcount+1);
10530: foreach my $rights (split(',',$rights_metadata)) {
10531: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10532: $metathesekeys{$rights}=1;
1.339 albertel 10533: }
10534: }
10535: }
1.737 albertel 10536: # uniqifiy package listing
10537: my %seen;
10538: my @uniq_packages =
10539: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10540: $metaentry{':packages'} = join(',',@uniq_packages);
10541:
1.1070 www 10542: if ($importedparts) {
10543: # We had imported parts and need to rebuild partorder
10544: $metaentry{':partorder'}='';
10545: $metathesekeys{'partorder'}=1;
10546: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10547: if ($origfileimportpartids[$index] eq 'part') {
10548: # original part, part of the problem
10549: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10550: } else {
10551: # we have imported parts at this position
10552: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10553: }
10554: }
10555: $metaentry{':partorder'}=~s/^\,//;
10556: }
10557:
1.737 albertel 10558: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10559: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10560: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10561: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10562: # this is the end of "was not already recently cached
1.71 www 10563: }
1.599 albertel 10564: return $metaentry{':'.$what};
1.261 albertel 10565: }
10566:
1.488 albertel 10567: sub metadata_create_package_def {
1.483 albertel 10568: my ($uri,$key,$package,$metathesekeys)=@_;
10569: my ($pack,$name,$subp)=split(/\&/,$key);
10570: if ($subp eq 'default') { next; }
10571:
1.599 albertel 10572: if (defined($metaentry{':packages'})) {
10573: $metaentry{':packages'}.=','.$package;
1.483 albertel 10574: } else {
1.599 albertel 10575: $metaentry{':packages'}=$package;
1.483 albertel 10576: }
10577: my $value=$packagetab{$key};
10578: my $unikey;
10579: $unikey='parameter_0_'.$name;
1.599 albertel 10580: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10581: $$metathesekeys{$unikey}=1;
1.599 albertel 10582: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10583: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10584: }
1.599 albertel 10585: if (defined($metaentry{':'.$unikey.'.default'})) {
10586: $metaentry{':'.$unikey}=
10587: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10588: }
10589: }
10590:
1.261 albertel 10591: sub metadata_generate_part0 {
10592: my ($metadata,$metacache,$uri) = @_;
10593: my %allnames;
1.737 albertel 10594: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10595: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10596: my $part=$$metacache{':'.$metakey.'.part'};
10597: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10598: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10599: $allnames{$name}=$part;
10600: }
10601: }
10602: }
10603: foreach my $name (keys(%allnames)) {
10604: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10605: my $key=":parameter_0_$name";
1.261 albertel 10606: $$metacache{"$key.part"}='0';
10607: $$metacache{"$key.name"}=$name;
1.428 albertel 10608: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10609: $allnames{$name}.'_'.$name.
10610: '.type'};
1.428 albertel 10611: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10612: '.display'};
1.644 www 10613: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10614: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10615: $$metacache{"$key.display"}=$olddis;
10616: }
1.71 www 10617: }
10618:
1.764 albertel 10619: # ------------------------------------------------------ Devalidate title cache
10620:
10621: sub devalidate_title_cache {
10622: my ($url)=@_;
10623: if (!$env{'request.course.id'}) { return; }
10624: my $symb=&symbread($url);
10625: if (!$symb) { return; }
10626: my $key=$env{'request.course.id'}."\0".$symb;
10627: &devalidate_cache_new('title',$key);
10628: }
10629:
1.1014 droeschl 10630: # ------------------------------------------------- Get the title of a course
10631:
10632: sub current_course_title {
10633: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10634: }
1.301 www 10635: # ------------------------------------------------- Get the title of a resource
10636:
10637: sub gettitle {
10638: my $urlsymb=shift;
10639: my $symb=&symbread($urlsymb);
1.534 albertel 10640: if ($symb) {
1.620 albertel 10641: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10642: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10643: if (defined($cached)) {
10644: return $result;
10645: }
1.534 albertel 10646: my ($map,$resid,$url)=&decode_symb($symb);
10647: my $title='';
1.907 albertel 10648: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10649: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10650: } else {
10651: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10652: &GDBM_READER(),0640)) {
10653: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10654: $title=$bighash{'title_'.$mapid.'.'.$resid};
10655: untie(%bighash);
10656: }
1.534 albertel 10657: }
10658: $title=~s/\&colon\;/\:/gs;
10659: if ($title) {
1.1159 www 10660: # Remember both $symb and $title for dynamic metadata
10661: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10662: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10663: # Cache this title and then return it
1.599 albertel 10664: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10665: }
10666: $urlsymb=$url;
10667: }
10668: my $title=&metadata($urlsymb,'title');
10669: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10670: return $title;
1.301 www 10671: }
1.613 albertel 10672:
1.614 albertel 10673: sub get_slot {
10674: my ($which,$cnum,$cdom)=@_;
10675: if (!$cnum || !$cdom) {
1.790 albertel 10676: (undef,my $courseid)=&whichuser();
1.620 albertel 10677: $cdom=$env{'course.'.$courseid.'.domain'};
10678: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10679: }
1.703 albertel 10680: my $key=join("\0",'slots',$cdom,$cnum,$which);
10681: my %slotinfo;
10682: if (exists($remembered{$key})) {
10683: $slotinfo{$which} = $remembered{$key};
10684: } else {
10685: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10686: &Apache::lonhomework::showhash(%slotinfo);
10687: my ($tmp)=keys(%slotinfo);
10688: if ($tmp=~/^error:/) { return (); }
10689: $remembered{$key} = $slotinfo{$which};
10690: }
1.616 albertel 10691: if (ref($slotinfo{$which}) eq 'HASH') {
10692: return %{$slotinfo{$which}};
10693: }
10694: return $slotinfo{$which};
1.614 albertel 10695: }
1.1150 raeburn 10696:
10697: sub get_reservable_slots {
10698: my ($cnum,$cdom,$uname,$udom) = @_;
10699: my $now = time;
10700: my $reservable_info;
10701: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10702: if (exists($remembered{$key})) {
10703: $reservable_info = $remembered{$key};
10704: } else {
10705: my %resv;
10706: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10707: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10708: $reservable_info = \%resv;
10709: $remembered{$key} = $reservable_info;
10710: }
10711: return $reservable_info;
10712: }
10713:
10714: sub get_course_slots {
10715: my ($cnum,$cdom) = @_;
10716: my $hashid=$cnum.':'.$cdom;
10717: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10718: if (defined($cached)) {
10719: if (ref($result) eq 'HASH') {
10720: return %{$result};
10721: }
10722: } else {
10723: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10724: my ($tmp) = keys(%slots);
10725: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10726: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10727: return %slots;
10728: }
10729: }
10730: return;
10731: }
10732:
10733: sub devalidate_slots_cache {
10734: my ($cnum,$cdom)=@_;
10735: my $hashid=$cnum.':'.$cdom;
10736: &devalidate_cache_new('allslots',$hashid);
10737: }
10738:
1.1172.2.8 raeburn 10739: sub get_coursechange {
10740: my ($cdom,$cnum) = @_;
10741: if ($cdom eq '' || $cnum eq '') {
10742: return unless ($env{'request.course.id'});
10743: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10744: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10745: }
10746: my $hashid=$cdom.'_'.$cnum;
10747: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10748: if ((defined($cached)) && ($change ne '')) {
10749: return $change;
10750: } else {
10751: my %crshash;
10752: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10753: if ($crshash{'internal.contentchange'} eq '') {
10754: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10755: if ($change eq '') {
10756: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10757: $change = $crshash{'internal.created'};
10758: }
10759: } else {
10760: $change = $crshash{'internal.contentchange'};
10761: }
10762: my $cachetime = 600;
10763: &do_cache_new('crschange',$hashid,$change,$cachetime);
10764: }
10765: return $change;
10766: }
10767:
10768: sub devalidate_coursechange_cache {
10769: my ($cnum,$cdom)=@_;
10770: my $hashid=$cnum.':'.$cdom;
10771: &devalidate_cache_new('crschange',$hashid);
10772: }
10773:
1.31 www 10774: # ------------------------------------------------- Update symbolic store links
10775:
10776: sub symblist {
10777: my ($mapname,%newhash)=@_;
1.438 www 10778: $mapname=&deversion(&declutter($mapname));
1.31 www 10779: my %hash;
1.620 albertel 10780: if (($env{'request.course.fn'}) && (%newhash)) {
10781: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10782: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10783: foreach my $url (keys(%newhash)) {
1.711 albertel 10784: next if ($url eq 'last_known'
10785: && $env{'form.no_update_last_known'});
10786: $hash{declutter($url)}=&encode_symb($mapname,
10787: $newhash{$url}->[1],
10788: $newhash{$url}->[0]);
1.191 harris41 10789: }
1.31 www 10790: if (untie(%hash)) {
10791: return 'ok';
10792: }
10793: }
10794: }
10795: return 'error';
1.212 www 10796: }
10797:
10798: # --------------------------------------------------------------- Verify a symb
10799:
10800: sub symbverify {
1.1172.2.11 raeburn 10801: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10802: my $thisfn=$thisurl;
1.439 www 10803: $thisfn=&declutter($thisfn);
1.215 www 10804: # direct jump to resource in page or to a sequence - will construct own symbs
10805: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10806: # check URL part
1.409 www 10807: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10808:
1.431 www 10809: unless ($url eq $thisfn) { return 0; }
1.213 www 10810:
1.216 www 10811: $symb=&symbclean($symb);
1.510 www 10812: $thisurl=&deversion($thisurl);
1.439 www 10813: $thisfn=&deversion($thisfn);
1.213 www 10814:
10815: my %bighash;
10816: my $okay=0;
1.431 www 10817:
1.620 albertel 10818: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10819: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10820: my $noclutter;
1.1032 raeburn 10821: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10822: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10823: if ($map =~ m{^uploaded/.+\.page$}) {
10824: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10825: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10826: $noclutter = 1;
10827: }
10828: }
10829: my $ids;
10830: if ($noclutter) {
10831: $ids=$bighash{'ids_'.$thisurl};
10832: } else {
10833: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10834: }
1.1102 raeburn 10835: unless ($ids) {
1.1172.2.13 raeburn 10836: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10837: $ids=$bighash{$idkey};
1.216 www 10838: }
10839: if ($ids) {
10840: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10841: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10842: $symb =~ s/\?.+$//;
10843: }
1.800 albertel 10844: foreach my $id (split(/\,/,$ids)) {
10845: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10846: if (
10847: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10848: eq $symb) {
1.1172.2.11 raeburn 10849: if (ref($encstate)) {
10850: $$encstate = $bighash{'encrypted_'.$id};
10851: }
1.1172.2.13 raeburn 10852: if (($env{'request.role.adv'}) ||
10853: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10854: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10855: $okay=1;
10856: last;
10857: }
10858: }
10859: }
1.216 www 10860: }
1.213 www 10861: untie(%bighash);
10862: }
10863: return $okay;
1.31 www 10864: }
10865:
1.210 www 10866: # --------------------------------------------------------------- Clean-up symb
10867:
10868: sub symbclean {
10869: my $symb=shift;
1.568 albertel 10870: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10871: # remove version from map
10872: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10873:
1.210 www 10874: # remove version from URL
10875: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10876:
1.507 www 10877: # remove wrapper
10878:
1.510 www 10879: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10880: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10881: return $symb;
1.409 www 10882: }
10883:
10884: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10885:
10886: sub encode_symb {
10887: my ($map,$resid,$url)=@_;
10888: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10889: }
1.409 www 10890:
10891: sub decode_symb {
1.568 albertel 10892: my $symb=shift;
10893: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10894: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10895: return (&fixversion($map),$resid,&fixversion($url));
10896: }
10897:
10898: sub fixversion {
10899: my $fn=shift;
1.609 banghart 10900: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10901: my %bighash;
10902: my $uri=&clutter($fn);
1.620 albertel 10903: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10904: # is this cached?
1.599 albertel 10905: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10906: if (defined($cached)) { return $result; }
10907: # unfortunately not cached, or expired
1.620 albertel 10908: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10909: &GDBM_READER(),0640)) {
10910: if ($bighash{'version_'.$uri}) {
10911: my $version=$bighash{'version_'.$uri};
1.444 www 10912: unless (($version eq 'mostrecent') ||
10913: ($version==&getversion($uri))) {
1.440 www 10914: $uri=~s/\.(\w+)$/\.$version\.$1/;
10915: }
10916: }
10917: untie %bighash;
1.413 www 10918: }
1.599 albertel 10919: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10920: }
10921:
10922: sub deversion {
10923: my $url=shift;
10924: $url=~s/\.\d+\.(\w+)$/\.$1/;
10925: return $url;
1.210 www 10926: }
10927:
1.31 www 10928: # ------------------------------------------------------ Return symb list entry
10929:
10930: sub symbread {
1.249 www 10931: my ($thisfn,$donotrecurse)=@_;
1.1172.2.54 raeburn 10932: my $cache_str='request.symbread.cached.'.$thisfn;
10933: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 10934: # no filename provided? try from environment
1.1172.2.54 raeburn 10935: unless ($thisfn) {
1.620 albertel 10936: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10937: return $env{$cache_str}=&symbclean($env{'request.symb'});
10938: }
10939: $thisfn=$env{'request.filename'};
1.44 www 10940: }
1.569 albertel 10941: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10942: # is that filename actually a symb? Verify, clean, and return
10943: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10944: if (&symbverify($thisfn,$1)) {
1.620 albertel 10945: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10946: }
1.242 www 10947: }
1.44 www 10948: $thisfn=declutter($thisfn);
1.31 www 10949: my %hash;
1.37 www 10950: my %bighash;
10951: my $syval='';
1.620 albertel 10952: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10953: my $targetfn = $thisfn;
1.609 banghart 10954: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10955: $targetfn = 'adm/wrapper/'.$thisfn;
10956: }
1.687 albertel 10957: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10958: $targetfn=$1;
10959: }
1.620 albertel 10960: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10961: &GDBM_READER(),0640)) {
1.481 raeburn 10962: $syval=$hash{$targetfn};
1.37 www 10963: untie(%hash);
10964: }
10965: # ---------------------------------------------------------- There was an entry
10966: if ($syval) {
1.601 albertel 10967: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10968: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10969: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10970: #return $env{$cache_str}='';
1.601 albertel 10971: #}
10972: #$syval.=$1;
10973: #}
1.37 www 10974: } else {
10975: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10976: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10977: &GDBM_READER(),0640)) {
1.37 www 10978: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10979: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10980: unless ($ids) {
10981: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10982: }
10983: unless ($ids) {
10984: # alias?
10985: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10986: }
1.37 www 10987: if ($ids) {
10988: # ------------------------------------------------------------------- Has ID(s)
10989: my @possibilities=split(/\,/,$ids);
1.39 www 10990: if ($#possibilities==0) {
10991: # ----------------------------------------------- There is only one possibility
1.37 www 10992: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10993: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10994: $resid,$thisfn);
1.249 www 10995: } elsif (!$donotrecurse) {
1.39 www 10996: # ------------------------------------------ There is more than one possibility
10997: my $realpossible=0;
1.800 albertel 10998: foreach my $id (@possibilities) {
10999: my $file=$bighash{'src_'.$id};
1.39 www 11000: if (&allowed('bre',$file)) {
1.800 albertel 11001: my ($mapid,$resid)=split(/\./,$id);
1.39 www 11002: if ($bighash{'map_type_'.$mapid} ne 'page') {
11003: $realpossible++;
1.626 albertel 11004: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11005: $resid,$thisfn);
1.39 www 11006: }
11007: }
1.191 harris41 11008: }
1.39 www 11009: if ($realpossible!=1) { $syval=''; }
1.249 www 11010: } else {
11011: $syval='';
1.37 www 11012: }
11013: }
11014: untie(%bighash)
1.481 raeburn 11015: }
1.31 www 11016: }
1.62 www 11017: if ($syval) {
1.620 albertel 11018: return $env{$cache_str}=$syval;
1.62 www 11019: }
1.31 www 11020: }
1.949 raeburn 11021: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11022: return $env{$cache_str}='';
1.31 www 11023: }
11024:
11025: # ---------------------------------------------------------- Return random seed
11026:
1.32 www 11027: sub numval {
11028: my $txt=shift;
11029: $txt=~tr/A-J/0-9/;
11030: $txt=~tr/a-j/0-9/;
11031: $txt=~tr/K-T/0-9/;
11032: $txt=~tr/k-t/0-9/;
11033: $txt=~tr/U-Z/0-5/;
11034: $txt=~tr/u-z/0-5/;
11035: $txt=~s/\D//g;
1.564 albertel 11036: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11037: return int($txt);
1.368 albertel 11038: }
11039:
1.484 albertel 11040: sub numval2 {
11041: my $txt=shift;
11042: $txt=~tr/A-J/0-9/;
11043: $txt=~tr/a-j/0-9/;
11044: $txt=~tr/K-T/0-9/;
11045: $txt=~tr/k-t/0-9/;
11046: $txt=~tr/U-Z/0-5/;
11047: $txt=~tr/u-z/0-5/;
11048: $txt=~s/\D//g;
11049: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11050: my $total;
11051: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11052: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11053: return int($total);
11054: }
11055:
1.575 albertel 11056: sub numval3 {
11057: use integer;
11058: my $txt=shift;
11059: $txt=~tr/A-J/0-9/;
11060: $txt=~tr/a-j/0-9/;
11061: $txt=~tr/K-T/0-9/;
11062: $txt=~tr/k-t/0-9/;
11063: $txt=~tr/U-Z/0-5/;
11064: $txt=~tr/u-z/0-5/;
11065: $txt=~s/\D//g;
11066: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11067: my $total;
11068: foreach my $val (@txts) { $total+=$val; }
11069: if ($_64bit) { $total=(($total<<32)>>32); }
11070: return $total;
11071: }
11072:
1.675 albertel 11073: sub digest {
11074: my ($data)=@_;
11075: my $digest=&Digest::MD5::md5($data);
11076: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11077: my ($e,$f);
11078: {
11079: use integer;
11080: $e=($a+$b);
11081: $f=($c+$d);
11082: if ($_64bit) {
11083: $e=(($e<<32)>>32);
11084: $f=(($f<<32)>>32);
11085: }
11086: }
11087: if (wantarray) {
11088: return ($e,$f);
11089: } else {
11090: my $g;
11091: {
11092: use integer;
11093: $g=($e+$f);
11094: if ($_64bit) {
11095: $g=(($g<<32)>>32);
11096: }
11097: }
11098: return $g;
11099: }
11100: }
11101:
1.368 albertel 11102: sub latest_rnd_algorithm_id {
1.675 albertel 11103: return '64bit5';
1.366 albertel 11104: }
1.32 www 11105:
1.503 albertel 11106: sub get_rand_alg {
11107: my ($courseid)=@_;
1.790 albertel 11108: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11109: if ($courseid) {
1.620 albertel 11110: return $env{"course.$courseid.rndseed"};
1.503 albertel 11111: }
11112: return &latest_rnd_algorithm_id();
11113: }
11114:
1.562 albertel 11115: sub validCODE {
11116: my ($CODE)=@_;
11117: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11118: return 0;
11119: }
11120:
1.491 albertel 11121: sub getCODE {
1.620 albertel 11122: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11123: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11124: defined($Apache::lonhomework::parsing_a_task) ) &&
11125: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11126: return $Apache::lonhomework::history{'resource.CODE'};
11127: }
11128: return undef;
11129: }
1.1133 foxr 11130: #
11131: # Determines the random seed for a specific context:
11132: #
11133: # parameters:
11134: # symb - in course context the symb for the seed.
11135: # course_id - The course id of the form domain_coursenum.
11136: # domain - Domain for the user.
11137: # course - Course for the user.
11138: # cenv - environment of the course.
11139: #
11140: # NOTE:
11141: # All parameters are picked out of the environment if missing
11142: # or not defined.
11143: # If a symb cannot be determined the current time is used instead.
11144: #
11145: # For a given well defined symb, courside, domain, username,
11146: # and course environment, the seed is reproducible.
11147: #
1.31 www 11148: sub rndseed {
1.1133 foxr 11149: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11150: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11151: if (!defined($symb)) {
1.366 albertel 11152: unless ($symb=$wsymb) { return time; }
11153: }
1.1146 foxr 11154: if (!defined $courseid) {
11155: $courseid=$wcourseid;
11156: }
11157: if (!defined $domain) { $domain=$wdomain; }
11158: if (!defined $username) { $username=$wusername }
1.1133 foxr 11159:
11160: my $which;
11161: if (defined($cenv->{'rndseed'})) {
11162: $which = $cenv->{'rndseed'};
11163: } else {
11164: $which =&get_rand_alg($courseid);
11165: }
1.491 albertel 11166: if (defined(&getCODE())) {
1.675 albertel 11167: if ($which eq '64bit5') {
11168: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11169: } elsif ($which eq '64bit4') {
1.575 albertel 11170: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11171: } else {
11172: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11173: }
1.675 albertel 11174: } elsif ($which eq '64bit5') {
11175: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11176: } elsif ($which eq '64bit4') {
11177: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11178: } elsif ($which eq '64bit3') {
11179: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11180: } elsif ($which eq '64bit2') {
11181: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11182: } elsif ($which eq '64bit') {
11183: return &rndseed_64bit($symb,$courseid,$domain,$username);
11184: }
11185: return &rndseed_32bit($symb,$courseid,$domain,$username);
11186: }
11187:
11188: sub rndseed_32bit {
11189: my ($symb,$courseid,$domain,$username)=@_;
11190: {
11191: use integer;
11192: my $symbchck=unpack("%32C*",$symb) << 27;
11193: my $symbseed=numval($symb) << 22;
11194: my $namechck=unpack("%32C*",$username) << 17;
11195: my $nameseed=numval($username) << 12;
11196: my $domainseed=unpack("%32C*",$domain) << 7;
11197: my $courseseed=unpack("%32C*",$courseid);
11198: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11199: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11200: #&logthis("rndseed :$num:$symb");
1.564 albertel 11201: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11202: return $num;
11203: }
11204: }
11205:
11206: sub rndseed_64bit {
11207: my ($symb,$courseid,$domain,$username)=@_;
11208: {
11209: use integer;
11210: my $symbchck=unpack("%32S*",$symb) << 21;
11211: my $symbseed=numval($symb) << 10;
11212: my $namechck=unpack("%32S*",$username);
11213:
11214: my $nameseed=numval($username) << 21;
11215: my $domainseed=unpack("%32S*",$domain) << 10;
11216: my $courseseed=unpack("%32S*",$courseid);
11217:
11218: my $num1=$symbchck+$symbseed+$namechck;
11219: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11220: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11221: #&logthis("rndseed :$num:$symb");
1.564 albertel 11222: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11223: return "$num1,$num2";
1.155 albertel 11224: }
1.366 albertel 11225: }
11226:
1.443 albertel 11227: sub rndseed_64bit2 {
11228: my ($symb,$courseid,$domain,$username)=@_;
11229: {
11230: use integer;
11231: # strings need to be an even # of cahracters long, it it is odd the
11232: # last characters gets thrown away
11233: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11234: my $symbseed=numval($symb) << 10;
11235: my $namechck=unpack("%32S*",$username.' ');
11236:
11237: my $nameseed=numval($username) << 21;
1.501 albertel 11238: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11239: my $courseseed=unpack("%32S*",$courseid.' ');
11240:
11241: my $num1=$symbchck+$symbseed+$namechck;
11242: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11243: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11244: #&logthis("rndseed :$num:$symb");
1.803 albertel 11245: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11246: return "$num1,$num2";
11247: }
11248: }
11249:
11250: sub rndseed_64bit3 {
11251: my ($symb,$courseid,$domain,$username)=@_;
11252: {
11253: use integer;
11254: # strings need to be an even # of cahracters long, it it is odd the
11255: # last characters gets thrown away
11256: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11257: my $symbseed=numval2($symb) << 10;
11258: my $namechck=unpack("%32S*",$username.' ');
11259:
11260: my $nameseed=numval2($username) << 21;
1.443 albertel 11261: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11262: my $courseseed=unpack("%32S*",$courseid.' ');
11263:
11264: my $num1=$symbchck+$symbseed+$namechck;
11265: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11266: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11267: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11268: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11269:
1.503 albertel 11270: return "$num1:$num2";
1.443 albertel 11271: }
11272: }
11273:
1.575 albertel 11274: sub rndseed_64bit4 {
11275: my ($symb,$courseid,$domain,$username)=@_;
11276: {
11277: use integer;
11278: # strings need to be an even # of cahracters long, it it is odd the
11279: # last characters gets thrown away
11280: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11281: my $symbseed=numval3($symb) << 10;
11282: my $namechck=unpack("%32S*",$username.' ');
11283:
11284: my $nameseed=numval3($username) << 21;
11285: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11286: my $courseseed=unpack("%32S*",$courseid.' ');
11287:
11288: my $num1=$symbchck+$symbseed+$namechck;
11289: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11290: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11291: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11292: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11293:
1.575 albertel 11294: return "$num1:$num2";
11295: }
11296: }
11297:
1.675 albertel 11298: sub rndseed_64bit5 {
11299: my ($symb,$courseid,$domain,$username)=@_;
11300: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11301: return "$num1:$num2";
11302: }
11303:
1.366 albertel 11304: sub rndseed_CODE_64bit {
11305: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11306: {
1.366 albertel 11307: use integer;
1.443 albertel 11308: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11309: my $symbseed=numval2($symb);
1.491 albertel 11310: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11311: my $CODEseed=numval(&getCODE());
1.443 albertel 11312: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11313: my $num1=$symbseed+$CODEchck;
11314: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11315: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11316: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11317: if ($_64bit) { $num1=(($num1<<32)>>32); }
11318: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11319: return "$num1:$num2";
1.366 albertel 11320: }
11321: }
11322:
1.575 albertel 11323: sub rndseed_CODE_64bit4 {
11324: my ($symb,$courseid,$domain,$username)=@_;
11325: {
11326: use integer;
11327: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11328: my $symbseed=numval3($symb);
11329: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11330: my $CODEseed=numval3(&getCODE());
11331: my $courseseed=unpack("%32S*",$courseid.' ');
11332: my $num1=$symbseed+$CODEchck;
11333: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11334: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11335: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11336: if ($_64bit) { $num1=(($num1<<32)>>32); }
11337: if ($_64bit) { $num2=(($num2<<32)>>32); }
11338: return "$num1:$num2";
11339: }
11340: }
11341:
1.675 albertel 11342: sub rndseed_CODE_64bit5 {
11343: my ($symb,$courseid,$domain,$username)=@_;
11344: my $code = &getCODE();
11345: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11346: return "$num1:$num2";
11347: }
11348:
1.366 albertel 11349: sub setup_random_from_rndseed {
11350: my ($rndseed)=@_;
1.503 albertel 11351: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11352: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11353: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11354: &Math::Random::random_set_seed_from_phrase($rndseed);
11355: } else {
11356: &Math::Random::random_set_seed($num1,$num2);
11357: }
1.366 albertel 11358: } else {
11359: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11360: }
1.36 albertel 11361: }
11362:
1.474 albertel 11363: sub latest_receipt_algorithm_id {
1.835 albertel 11364: return 'receipt3';
1.474 albertel 11365: }
11366:
1.480 www 11367: sub recunique {
11368: my $fucourseid=shift;
11369: my $unique;
1.835 albertel 11370: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11371: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11372: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11373: } else {
11374: $unique=$perlvar{'lonReceipt'};
11375: }
11376: return unpack("%32C*",$unique);
11377: }
11378:
11379: sub recprefix {
11380: my $fucourseid=shift;
11381: my $prefix;
1.835 albertel 11382: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11383: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11384: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11385: } else {
11386: $prefix=$perlvar{'lonHostID'};
11387: }
11388: return unpack("%32C*",$prefix);
11389: }
11390:
1.76 www 11391: sub ireceipt {
1.474 albertel 11392: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11393:
11394: my $return =&recprefix($fucourseid).'-';
11395:
11396: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11397: $env{'request.state'} eq 'construct') {
11398: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11399: return $return;
11400: }
11401:
1.76 www 11402: my $cuname=unpack("%32C*",$funame);
11403: my $cudom=unpack("%32C*",$fudom);
11404: my $cucourseid=unpack("%32C*",$fucourseid);
11405: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11406: my $cunique=&recunique($fucourseid);
1.474 albertel 11407: my $cpart=unpack("%32S*",$part);
1.835 albertel 11408: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11409:
1.790 albertel 11410: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11411:
11412: $return.= ($cunique%$cuname+
11413: $cunique%$cudom+
11414: $cusymb%$cuname+
11415: $cusymb%$cudom+
11416: $cucourseid%$cuname+
11417: $cucourseid%$cudom+
11418: $cpart%$cuname+
11419: $cpart%$cudom);
11420: } else {
11421: $return.= ($cunique%$cuname+
11422: $cunique%$cudom+
11423: $cusymb%$cuname+
11424: $cusymb%$cudom+
11425: $cucourseid%$cuname+
11426: $cucourseid%$cudom);
11427: }
11428: return $return;
1.76 www 11429: }
11430:
11431: sub receipt {
1.474 albertel 11432: my ($part)=@_;
1.790 albertel 11433: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11434: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11435: }
1.260 ng 11436:
1.790 albertel 11437: sub whichuser {
11438: my ($passedsymb)=@_;
11439: my ($symb,$courseid,$domain,$name,$publicuser);
11440: if (defined($env{'form.grade_symb'})) {
11441: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11442: my $allowed=&allowed('vgr',$tmp_courseid);
11443: if (!$allowed &&
11444: exists($env{'request.course.sec'}) &&
11445: $env{'request.course.sec'} !~ /^\s*$/) {
11446: $allowed=&allowed('vgr',$tmp_courseid.
11447: '/'.$env{'request.course.sec'});
11448: }
11449: if ($allowed) {
11450: ($symb)=&get_env_multiple('form.grade_symb');
11451: $courseid=$tmp_courseid;
11452: ($domain)=&get_env_multiple('form.grade_domain');
11453: ($name)=&get_env_multiple('form.grade_username');
11454: return ($symb,$courseid,$domain,$name,$publicuser);
11455: }
11456: }
11457: if (!$passedsymb) {
11458: $symb=&symbread();
11459: } else {
11460: $symb=$passedsymb;
11461: }
11462: $courseid=$env{'request.course.id'};
11463: $domain=$env{'user.domain'};
11464: $name=$env{'user.name'};
11465: if ($name eq 'public' && $domain eq 'public') {
11466: if (!defined($env{'form.username'})) {
11467: $env{'form.username'}.=time.rand(10000000);
11468: }
11469: $name.=$env{'form.username'};
11470: }
11471: return ($symb,$courseid,$domain,$name,$publicuser);
11472:
11473: }
11474:
1.36 albertel 11475: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11476: # returns either the contents of the file or
11477: # -1 if the file doesn't exist
1.481 raeburn 11478: #
11479: # if the target is a file that was uploaded via DOCS,
11480: # a check will be made to see if a current copy exists on the local server,
11481: # if it does this will be served, otherwise a copy will be retrieved from
11482: # the home server for the course and stored in /home/httpd/html/userfiles on
11483: # the local server.
1.472 albertel 11484:
1.36 albertel 11485: sub getfile {
1.538 albertel 11486: my ($file) = @_;
1.609 banghart 11487: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11488: &repcopy($file);
11489: return &readfile($file);
11490: }
11491:
11492: sub repcopy_userfile {
11493: my ($file)=@_;
1.1142 raeburn 11494: my $londocroot = $perlvar{'lonDocRoot'};
11495: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11496: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11497: my ($cdom,$cnum,$filename) =
1.811 albertel 11498: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11499: my $uri="/uploaded/$cdom/$cnum/$filename";
11500: if (-e "$file") {
1.828 www 11501: # we already have a local copy, check it out
1.538 albertel 11502: my @fileinfo = stat($file);
1.828 www 11503: my $rtncode;
11504: my $info;
1.538 albertel 11505: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11506: if ($lwpresp ne 'ok') {
1.828 www 11507: # there is no such file anymore, even though we had a local copy
1.482 albertel 11508: if ($rtncode eq '404') {
1.538 albertel 11509: unlink($file);
1.482 albertel 11510: }
11511: return -1;
11512: }
11513: if ($info < $fileinfo[9]) {
1.828 www 11514: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11515: return 'ok';
1.828 www 11516: } else {
11517: # the file is outdated, get rid of it
11518: unlink($file);
1.482 albertel 11519: }
1.828 www 11520: }
11521: # one way or the other, at this point, we don't have the file
11522: # construct the correct path for the file
11523: my @parts = ($cdom,$cnum);
11524: if ($filename =~ m|^(.+)/[^/]+$|) {
11525: push @parts, split(/\//,$1);
11526: }
11527: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11528: foreach my $part (@parts) {
11529: $path .= '/'.$part;
11530: if (!-e $path) {
11531: mkdir($path,0770);
1.482 albertel 11532: }
11533: }
1.828 www 11534: # now the path exists for sure
11535: # get a user agent
11536: my $ua=new LWP::UserAgent;
11537: my $transferfile=$file.'.in.transfer';
11538: # FIXME: this should flock
11539: if (-e $transferfile) { return 'ok'; }
11540: my $request;
11541: $uri=~s/^\///;
1.980 raeburn 11542: my $homeserver = &homeserver($cnum,$cdom);
11543: my $protocol = $protocol{$homeserver};
11544: $protocol = 'http' if ($protocol ne 'https');
11545: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11546: my $response=$ua->request($request,$transferfile);
11547: # did it work?
11548: if ($response->is_error()) {
11549: unlink($transferfile);
11550: &logthis("Userfile repcopy failed for $uri");
11551: return -1;
11552: }
11553: # worked, rename the transfer file
11554: rename($transferfile,$file);
1.607 raeburn 11555: return 'ok';
1.481 raeburn 11556: }
11557:
1.517 albertel 11558: sub tokenwrapper {
11559: my $uri=shift;
1.980 raeburn 11560: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11561: $uri=~s|^/||;
1.620 albertel 11562: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11563: my $token=$1;
1.552 albertel 11564: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11565: if ($udom && $uname && $file) {
11566: $file=~s|(\?\.*)*$||;
1.949 raeburn 11567: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11568: my $homeserver = &homeserver($uname,$udom);
11569: my $protocol = $protocol{$homeserver};
11570: $protocol = 'http' if ($protocol ne 'https');
11571: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11572: (($uri=~/\?/)?'&':'?').'token='.$token.
11573: '&tokenissued='.$perlvar{'lonHostID'};
11574: } else {
11575: return '/adm/notfound.html';
11576: }
11577: }
11578:
1.828 www 11579: # call with reqtype HEAD: get last modification time
11580: # call with reqtype GET: get the file contents
11581: # Do not call this with reqtype GET for large files! It loads everything into memory
11582: #
1.481 raeburn 11583: sub getuploaded {
11584: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11585: $uri=~s/^\///;
1.980 raeburn 11586: my $homeserver = &homeserver($cnum,$cdom);
11587: my $protocol = $protocol{$homeserver};
11588: $protocol = 'http' if ($protocol ne 'https');
11589: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11590: my $ua=new LWP::UserAgent;
11591: my $request=new HTTP::Request($reqtype,$uri);
11592: my $response=$ua->request($request);
11593: $$rtncode = $response->code;
1.482 albertel 11594: if (! $response->is_success()) {
11595: return 'failed';
11596: }
11597: if ($reqtype eq 'HEAD') {
1.486 www 11598: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11599: } elsif ($reqtype eq 'GET') {
11600: $$info = $response->content;
1.472 albertel 11601: }
1.482 albertel 11602: return 'ok';
1.36 albertel 11603: }
11604:
1.481 raeburn 11605: sub readfile {
11606: my $file = shift;
11607: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11608: my $fh;
11609: open($fh,"<$file");
11610: my $a='';
1.800 albertel 11611: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11612: return $a;
11613: }
11614:
1.36 albertel 11615: sub filelocation {
1.590 banghart 11616: my ($dir,$file) = @_;
11617: my $location;
11618: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11619:
11620: if ($file =~ m-^/adm/-) {
11621: $file=~s-^/adm/wrapper/-/-;
11622: $file=~s-^/adm/coursedocs/showdoc/-/-;
11623: }
1.882 albertel 11624:
1.1139 www 11625: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11626: $location = $file;
1.609 banghart 11627: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11628: my ($udom,$uname,$filename)=
1.811 albertel 11629: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11630: my $home=&homeserver($uname,$udom);
11631: my $is_me=0;
11632: my @ids=¤t_machine_ids();
11633: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11634: if ($is_me) {
1.1117 foxr 11635: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11636: } else {
11637: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11638: $udom.'/'.$uname.'/'.$filename;
11639: }
1.882 albertel 11640: } elsif ($file =~ m-^/adm/-) {
11641: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11642: } else {
11643: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11644: $file=~s:^/(res|priv)/:/:;
11645: my $space=$1;
1.590 banghart 11646: if ( !( $file =~ m:^/:) ) {
11647: $location = $dir. '/'.$file;
11648: } else {
1.1142 raeburn 11649: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11650: }
1.59 albertel 11651: }
1.590 banghart 11652: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11653: while ($location=~m{/\.\./}) {
11654: if ($location =~ m{/[^/]+/\.\./}) {
11655: $location=~ s{/[^/]+/\.\./}{/}g;
11656: } else {
11657: $location=~ s{/\.\./}{/}g;
11658: }
11659: } #remove dir/..
1.590 banghart 11660: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11661: return $location;
1.46 www 11662: }
1.36 albertel 11663:
1.46 www 11664: sub hreflocation {
11665: my ($dir,$file)=@_;
1.980 raeburn 11666: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11667: $file=filelocation($dir,$file);
1.700 albertel 11668: } elsif ($file=~m-^/adm/-) {
11669: $file=~s-^/adm/wrapper/-/-;
11670: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11671: }
11672: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11673: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11674: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11675: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11676: {/uploaded/$1/$2/}x;
1.46 www 11677: }
1.913 albertel 11678: if ($file=~ m{^/userfiles/}) {
11679: $file =~ s{^/userfiles/}{/uploaded/};
11680: }
1.462 albertel 11681: return $file;
1.465 albertel 11682: }
11683:
1.1139 www 11684:
11685:
11686:
11687:
1.465 albertel 11688: sub current_machine_domains {
1.853 albertel 11689: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11690: }
11691:
11692: sub machine_domains {
11693: my ($hostname) = @_;
1.465 albertel 11694: my @domains;
1.838 albertel 11695: my %hostname = &all_hostnames();
1.465 albertel 11696: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11697: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11698: if ($hostname eq $name) {
1.844 albertel 11699: push(@domains,&host_domain($id));
1.465 albertel 11700: }
11701: }
11702: return @domains;
11703: }
11704:
11705: sub current_machine_ids {
1.853 albertel 11706: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11707: }
11708:
11709: sub machine_ids {
11710: my ($hostname) = @_;
11711: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11712: my @ids;
1.888 albertel 11713: my %name_to_host = &all_names();
1.889 albertel 11714: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11715: return @{ $name_to_host{$hostname} };
11716: }
11717: return;
1.31 www 11718: }
11719:
1.824 raeburn 11720: sub additional_machine_domains {
11721: my @domains;
11722: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11723: while( my $line = <$fh>) {
11724: $line =~ s/\s//g;
11725: push(@domains,$line);
11726: }
11727: return @domains;
11728: }
11729:
11730: sub default_login_domain {
11731: my $domain = $perlvar{'lonDefDomain'};
11732: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11733: foreach my $posdom (¤t_machine_domains(),
11734: &additional_machine_domains()) {
11735: if (lc($posdom) eq lc($testdomain)) {
11736: $domain=$posdom;
11737: last;
11738: }
11739: }
11740: return $domain;
11741: }
11742:
1.31 www 11743: # ------------------------------------------------------------- Declutters URLs
11744:
11745: sub declutter {
11746: my $thisfn=shift;
1.569 albertel 11747: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 11748: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11749: $thisfn=~s{^/home/httpd/html}{};
11750: }
1.31 www 11751: $thisfn=~s/^\///;
1.697 albertel 11752: $thisfn=~s|^adm/wrapper/||;
11753: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11754: $thisfn=~s/^res\///;
1.1172 bisitz 11755: $thisfn=~s/^priv\///;
1.1032 raeburn 11756: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11757: $thisfn=~s/\?.+$//;
11758: }
1.268 www 11759: return $thisfn;
11760: }
11761:
11762: # ------------------------------------------------------------- Clutter up URLs
11763:
11764: sub clutter {
11765: my $thisfn='/'.&declutter(shift);
1.887 albertel 11766: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11767: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11768: $thisfn='/res'.$thisfn;
11769: }
1.1031 raeburn 11770: if ($thisfn !~m|^/adm|) {
11771: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11772: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11773: } else {
11774: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11775: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11776: if ($embstyle eq 'ssi'
11777: || ($embstyle eq 'hdn')
11778: || ($embstyle eq 'rat')
11779: || ($embstyle eq 'prv')
11780: || ($embstyle eq 'ign')) {
11781: #do nothing with these
11782: } elsif (($embstyle eq 'img')
1.695 albertel 11783: || ($embstyle eq 'emb')
11784: || ($embstyle eq 'wrp')) {
11785: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11786: } elsif ($embstyle eq 'unk'
11787: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11788: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11789: } else {
1.718 www 11790: # &logthis("Got a blank emb style");
1.695 albertel 11791: }
1.694 albertel 11792: }
11793: }
1.31 www 11794: return $thisfn;
1.12 www 11795: }
11796:
1.787 albertel 11797: sub clutter_with_no_wrapper {
11798: my $uri = &clutter(shift);
11799: if ($uri =~ m-^/adm/-) {
11800: $uri =~ s-^/adm/wrapper/-/-;
11801: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11802: }
11803: return $uri;
11804: }
11805:
1.557 albertel 11806: sub freeze_escape {
11807: my ($value)=@_;
11808: if (ref($value)) {
11809: $value=&nfreeze($value);
11810: return '__FROZEN__'.&escape($value);
11811: }
11812: return &escape($value);
11813: }
11814:
1.11 www 11815:
1.557 albertel 11816: sub thaw_unescape {
11817: my ($value)=@_;
11818: if ($value =~ /^__FROZEN__/) {
11819: substr($value,0,10,undef);
11820: $value=&unescape($value);
11821: return &thaw($value);
11822: }
11823: return &unescape($value);
11824: }
11825:
1.436 albertel 11826: sub correct_line_ends {
11827: my ($result)=@_;
11828: $$result =~s/\r\n/\n/mg;
11829: $$result =~s/\r/\n/mg;
1.415 albertel 11830: }
1.1 albertel 11831: # ================================================================ Main Program
11832:
1.184 www 11833: sub goodbye {
1.204 albertel 11834: &logthis("Starting Shut down");
1.443 albertel 11835: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11836: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11837: #converted
1.599 albertel 11838: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11839: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11840: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11841: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11842: #1.1 only
1.870 albertel 11843: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11844: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11845: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11846: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11847: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11848: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11849: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11850: &flushcourselogs();
11851: &logthis("Shutting down");
11852: }
11853:
1.852 albertel 11854: sub get_dns {
1.1172.2.17 raeburn 11855: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11856: if (!$ignore_cache) {
11857: my ($content,$cached)=
11858: &Apache::lonnet::is_cached_new('dns',$url);
11859: if ($cached) {
1.1172.2.17 raeburn 11860: &$func($content,$hashref);
1.869 albertel 11861: return;
11862: }
11863: }
11864:
11865: my %alldns;
1.852 albertel 11866: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11867: foreach my $dns (<$config>) {
11868: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11869: my $line = $1;
11870: my ($host,$protocol) = split(/:/,$line);
11871: if ($protocol ne 'https') {
11872: $protocol = 'http';
11873: }
11874: $alldns{$host} = $protocol;
1.869 albertel 11875: }
11876: while (%alldns) {
1.1172.2.52 raeburn 11877: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 11878: my $ua=new LWP::UserAgent;
1.1134 raeburn 11879: $ua->timeout(30);
1.979 raeburn 11880: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11881: my $response=$ua->request($request);
1.979 raeburn 11882: delete($alldns{$dns});
1.852 albertel 11883: next if ($response->is_error());
11884: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11885: unless ($nocache) {
1.1172.2.23 raeburn 11886: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11887: }
11888: &$func(\@content,$hashref);
1.869 albertel 11889: return;
1.852 albertel 11890: }
11891: close($config);
1.871 albertel 11892: my $which = (split('/',$url))[3];
11893: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11894: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11895: my @content = <$config>;
1.1172.2.17 raeburn 11896: &$func(\@content,$hashref);
11897: return;
11898: }
11899:
11900: # ------------------------------------------------------Get DNS checksums file
11901: sub parse_dns_checksums_tab {
11902: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 11903: my $lonhost = $perlvar{'lonHostID'};
11904: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 11905: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 11906: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
11907: my $webconfdir = '/etc/httpd/conf';
11908: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
11909: $webconfdir = '/etc/apache2';
11910: } elsif ($distro =~ /^sles(\d+)$/) {
11911: if ($1 >= 10) {
11912: $webconfdir = '/etc/apache2';
11913: }
11914: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
11915: if ($1 >= 10.0) {
11916: $webconfdir = '/etc/apache2';
11917: }
11918: }
1.1172.2.17 raeburn 11919: my ($release,$timestamp) = split(/\-/,$loncaparev);
11920: my (%chksum,%revnum);
11921: if (ref($lines) eq 'ARRAY') {
11922: chomp(@{$lines});
1.1172.2.34 raeburn 11923: my $version = shift(@{$lines});
11924: if ($version eq $release) {
1.1172.2.17 raeburn 11925: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 11926: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 11927: if ($file =~ m{^/etc/httpd/conf}) {
11928: if ($webconfdir eq '/etc/apache2') {
11929: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
11930: }
11931: }
1.1172.2.34 raeburn 11932: $chksum{$file} = $shasum;
11933: $revnum{$file} = $version;
1.1172.2.17 raeburn 11934: }
11935: if (ref($hashref) eq 'HASH') {
11936: %{$hashref} = (
11937: sums => \%chksum,
11938: versions => \%revnum,
11939: );
11940: }
11941: }
11942: }
1.869 albertel 11943: return;
1.852 albertel 11944: }
1.1172.2.17 raeburn 11945:
11946: sub fetch_dns_checksums {
11947: my %checksums;
1.1172.2.34 raeburn 11948: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 11949: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 11950: my ($release,$timestamp) = split(/\-/,$loncaparev);
11951: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 11952: \%checksums);
11953: return \%checksums;
11954: }
11955:
1.327 albertel 11956: # ------------------------------------------------------------ Read domain file
11957: {
1.852 albertel 11958: my $loaded;
1.846 albertel 11959: my %domain;
11960:
1.852 albertel 11961: sub parse_domain_tab {
11962: my ($lines) = @_;
11963: foreach my $line (@$lines) {
11964: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11965:
1.846 albertel 11966: chomp($line);
1.852 albertel 11967: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11968: my %this_domain;
11969: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11970: 'lang_def', 'city', 'longi', 'lati',
11971: 'primary') {
11972: $this_domain{$field} = shift(@elements);
11973: }
11974: $domain{$name} = \%this_domain;
1.852 albertel 11975: }
11976: }
1.864 albertel 11977:
11978: sub reset_domain_info {
11979: undef($loaded);
11980: undef(%domain);
11981: }
11982:
1.852 albertel 11983: sub load_domain_tab {
1.869 albertel 11984: my ($ignore_cache) = @_;
11985: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11986: my $fh;
11987: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11988: my @lines = <$fh>;
11989: &parse_domain_tab(\@lines);
1.448 albertel 11990: }
1.852 albertel 11991: close($fh);
11992: $loaded = 1;
1.327 albertel 11993: }
1.846 albertel 11994:
11995: sub domain {
1.852 albertel 11996: &load_domain_tab() if (!$loaded);
11997:
1.846 albertel 11998: my ($name,$what) = @_;
11999: return if ( !exists($domain{$name}) );
12000:
12001: if (!$what) {
12002: return $domain{$name}{'description'};
12003: }
12004: return $domain{$name}{$what};
12005: }
1.974 raeburn 12006:
12007: sub domain_info {
12008: &load_domain_tab() if (!$loaded);
12009: return %domain;
12010: }
12011:
1.327 albertel 12012: }
12013:
12014:
1.1 albertel 12015: # ------------------------------------------------------------- Read hosts file
12016: {
1.838 albertel 12017: my %hostname;
1.844 albertel 12018: my %hostdom;
1.845 albertel 12019: my %libserv;
1.852 albertel 12020: my $loaded;
1.888 albertel 12021: my %name_to_host;
1.1074 raeburn 12022: my %internetdom;
1.1107 raeburn 12023: my %LC_dns_serv;
1.852 albertel 12024:
12025: sub parse_hosts_tab {
12026: my ($file) = @_;
12027: foreach my $configline (@$file) {
12028: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12029: chomp($configline);
12030: if ($configline =~ /^\^/) {
12031: if ($configline =~ /^\^([\w.\-]+)/) {
12032: $LC_dns_serv{$1} = 1;
12033: }
12034: next;
12035: }
1.1074 raeburn 12036: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12037: $name=~s/\s//g;
12038: if ($id && $domain && $role && $name) {
12039: $hostname{$id}=$name;
1.888 albertel 12040: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12041: $hostdom{$id}=$domain;
12042: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12043: if (defined($protocol)) {
12044: if ($protocol eq 'https') {
12045: $protocol{$id} = $protocol;
12046: } else {
12047: $protocol{$id} = 'http';
12048: }
1.968 raeburn 12049: } else {
1.969 raeburn 12050: $protocol{$id} = 'http';
1.968 raeburn 12051: }
1.1074 raeburn 12052: if (defined($intdom)) {
12053: $internetdom{$id} = $intdom;
12054: }
1.852 albertel 12055: }
12056: }
12057: }
1.864 albertel 12058:
12059: sub reset_hosts_info {
1.897 albertel 12060: &purge_remembered();
1.864 albertel 12061: &reset_domain_info();
12062: &reset_hosts_ip_info();
1.892 albertel 12063: undef(%name_to_host);
1.864 albertel 12064: undef(%hostname);
12065: undef(%hostdom);
12066: undef(%libserv);
12067: undef($loaded);
12068: }
1.1 albertel 12069:
1.852 albertel 12070: sub load_hosts_tab {
1.869 albertel 12071: my ($ignore_cache) = @_;
12072: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12073: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12074: my @config = <$config>;
12075: &parse_hosts_tab(\@config);
12076: close($config);
12077: $loaded=1;
1.1 albertel 12078: }
1.852 albertel 12079:
1.838 albertel 12080: sub hostname {
1.852 albertel 12081: &load_hosts_tab() if (!$loaded);
12082:
1.838 albertel 12083: my ($lonid) = @_;
12084: return $hostname{$lonid};
12085: }
1.845 albertel 12086:
1.838 albertel 12087: sub all_hostnames {
1.852 albertel 12088: &load_hosts_tab() if (!$loaded);
12089:
1.838 albertel 12090: return %hostname;
12091: }
1.845 albertel 12092:
1.888 albertel 12093: sub all_names {
12094: &load_hosts_tab() if (!$loaded);
12095:
12096: return %name_to_host;
12097: }
12098:
1.974 raeburn 12099: sub all_host_domain {
12100: &load_hosts_tab() if (!$loaded);
12101: return %hostdom;
12102: }
12103:
1.845 albertel 12104: sub is_library {
1.852 albertel 12105: &load_hosts_tab() if (!$loaded);
12106:
1.845 albertel 12107: return exists($libserv{$_[0]});
12108: }
12109:
12110: sub all_library {
1.852 albertel 12111: &load_hosts_tab() if (!$loaded);
12112:
1.845 albertel 12113: return %libserv;
12114: }
12115:
1.1062 droeschl 12116: sub unique_library {
12117: #2x reverse removes all hostnames that appear more than once
12118: my %unique = reverse &all_library();
12119: return reverse %unique;
12120: }
12121:
1.841 albertel 12122: sub get_servers {
1.852 albertel 12123: &load_hosts_tab() if (!$loaded);
12124:
1.841 albertel 12125: my ($domain,$type) = @_;
12126: my %possible_hosts = ($type eq 'library') ? %libserv
12127: : %hostname;
12128: my %result;
1.842 albertel 12129: if (ref($domain) eq 'ARRAY') {
12130: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12131: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12132: $result{$host} = $hostname;
12133: }
12134: }
12135: } else {
12136: while ( my ($host,$hostname) = each(%possible_hosts)) {
12137: if ($hostdom{$host} eq $domain) {
12138: $result{$host} = $hostname;
12139: }
1.841 albertel 12140: }
12141: }
12142: return %result;
12143: }
1.845 albertel 12144:
1.1062 droeschl 12145: sub get_unique_servers {
12146: my %unique = reverse &get_servers(@_);
12147: return reverse %unique;
12148: }
12149:
1.844 albertel 12150: sub host_domain {
1.852 albertel 12151: &load_hosts_tab() if (!$loaded);
12152:
1.844 albertel 12153: my ($lonid) = @_;
12154: return $hostdom{$lonid};
12155: }
12156:
1.841 albertel 12157: sub all_domains {
1.852 albertel 12158: &load_hosts_tab() if (!$loaded);
12159:
1.841 albertel 12160: my %seen;
12161: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12162: return @uniq;
12163: }
1.1074 raeburn 12164:
12165: sub internet_dom {
12166: &load_hosts_tab() if (!$loaded);
12167:
12168: my ($lonid) = @_;
12169: return $internetdom{$lonid};
12170: }
1.1107 raeburn 12171:
12172: sub is_LC_dns {
12173: &load_hosts_tab() if (!$loaded);
12174:
12175: my ($hostname) = @_;
12176: return exists($LC_dns_serv{$hostname});
12177: }
12178:
1.1 albertel 12179: }
12180:
1.847 albertel 12181: {
12182: my %iphost;
1.856 albertel 12183: my %name_to_ip;
12184: my %lonid_to_ip;
1.869 albertel 12185:
1.847 albertel 12186: sub get_hosts_from_ip {
12187: my ($ip) = @_;
12188: my %iphosts = &get_iphost();
12189: if (ref($iphosts{$ip})) {
12190: return @{$iphosts{$ip}};
12191: }
12192: return;
1.839 albertel 12193: }
1.864 albertel 12194:
12195: sub reset_hosts_ip_info {
12196: undef(%iphost);
12197: undef(%name_to_ip);
12198: undef(%lonid_to_ip);
12199: }
1.856 albertel 12200:
12201: sub get_host_ip {
12202: my ($lonid) = @_;
12203: if (exists($lonid_to_ip{$lonid})) {
12204: return $lonid_to_ip{$lonid};
12205: }
12206: my $name=&hostname($lonid);
12207: my $ip = gethostbyname($name);
12208: return if (!$ip || length($ip) ne 4);
12209: $ip=inet_ntoa($ip);
12210: $name_to_ip{$name} = $ip;
12211: $lonid_to_ip{$lonid} = $ip;
12212: return $ip;
12213: }
1.847 albertel 12214:
12215: sub get_iphost {
1.869 albertel 12216: my ($ignore_cache) = @_;
1.894 albertel 12217:
1.869 albertel 12218: if (!$ignore_cache) {
12219: if (%iphost) {
12220: return %iphost;
12221: }
12222: my ($ip_info,$cached)=
12223: &Apache::lonnet::is_cached_new('iphost','iphost');
12224: if ($cached) {
12225: %iphost = %{$ip_info->[0]};
12226: %name_to_ip = %{$ip_info->[1]};
12227: %lonid_to_ip = %{$ip_info->[2]};
12228: return %iphost;
12229: }
12230: }
1.894 albertel 12231:
12232: # get yesterday's info for fallback
12233: my %old_name_to_ip;
12234: my ($ip_info,$cached)=
12235: &Apache::lonnet::is_cached_new('iphost','iphost');
12236: if ($cached) {
12237: %old_name_to_ip = %{$ip_info->[1]};
12238: }
12239:
1.888 albertel 12240: my %name_to_host = &all_names();
12241: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12242: my $ip;
12243: if (!exists($name_to_ip{$name})) {
12244: $ip = gethostbyname($name);
12245: if (!$ip || length($ip) ne 4) {
1.894 albertel 12246: if (defined($old_name_to_ip{$name})) {
12247: $ip = $old_name_to_ip{$name};
12248: &logthis("Can't find $name defaulting to old $ip");
12249: } else {
12250: &logthis("Name $name no IP found");
12251: next;
12252: }
12253: } else {
12254: $ip=inet_ntoa($ip);
1.847 albertel 12255: }
12256: $name_to_ip{$name} = $ip;
12257: } else {
12258: $ip = $name_to_ip{$name};
1.653 albertel 12259: }
1.888 albertel 12260: foreach my $id (@{ $name_to_host{$name} }) {
12261: $lonid_to_ip{$id} = $ip;
12262: }
12263: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12264: }
1.1172.2.23 raeburn 12265: &do_cache_new('iphost','iphost',
12266: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12267: 48*60*60);
1.869 albertel 12268:
1.847 albertel 12269: return %iphost;
1.598 albertel 12270: }
12271:
1.992 raeburn 12272: #
12273: # Given a DNS returns the loncapa host name for that DNS
12274: #
12275: sub host_from_dns {
12276: my ($dns) = @_;
12277: my @hosts;
12278: my $ip;
12279:
1.993 raeburn 12280: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12281: $ip = $name_to_ip{$dns};
12282: }
12283: if (!$ip) {
12284: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12285: if (length($ip) == 4) {
12286: $ip = &IO::Socket::inet_ntoa($ip);
12287: }
12288: }
12289: if ($ip) {
12290: @hosts = get_hosts_from_ip($ip);
12291: return $hosts[0];
12292: }
12293: return undef;
1.986 foxr 12294: }
1.992 raeburn 12295:
1.1074 raeburn 12296: sub get_internet_names {
12297: my ($lonid) = @_;
12298: return if ($lonid eq '');
12299: my ($idnref,$cached)=
12300: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12301: if ($cached) {
12302: return $idnref;
12303: }
12304: my $ip = &get_host_ip($lonid);
12305: my @hosts = &get_hosts_from_ip($ip);
12306: my %iphost = &get_iphost();
12307: my (@idns,%seen);
12308: foreach my $id (@hosts) {
12309: my $dom = &host_domain($id);
12310: my $prim_id = &domain($dom,'primary');
12311: my $prim_ip = &get_host_ip($prim_id);
12312: next if ($seen{$prim_ip});
12313: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12314: foreach my $id (@{$iphost{$prim_ip}}) {
12315: my $intdom = &internet_dom($id);
12316: unless (grep(/^\Q$intdom\E$/,@idns)) {
12317: push(@idns,$intdom);
12318: }
12319: }
12320: }
12321: $seen{$prim_ip} = 1;
12322: }
1.1172.2.23 raeburn 12323: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12324: }
12325:
1.986 foxr 12326: }
12327:
1.1079 raeburn 12328: sub all_loncaparevs {
1.1172.2.39 raeburn 12329: 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 12330: }
12331:
1.1172.2.27 raeburn 12332: # ------------------------------------------------------- Read loncaparev table
12333: {
12334: sub load_loncaparevs {
12335: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12336: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12337: while (my $configline=<$config>) {
12338: chomp($configline);
12339: my ($hostid,$loncaparev)=split(/:/,$configline);
12340: $loncaparevs{$hostid}=$loncaparev;
12341: }
12342: close($config);
12343: }
12344: }
12345: }
12346: }
12347:
12348: # ----------------------------------------------------- Read serverhostID table
12349: {
12350: sub load_serverhomeIDs {
12351: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12352: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12353: while (my $configline=<$config>) {
12354: chomp($configline);
12355: my ($name,$id)=split(/:/,$configline);
12356: $serverhomeIDs{$name}=$id;
12357: }
12358: close($config);
12359: }
12360: }
12361: }
12362: }
12363:
12364:
1.862 albertel 12365: BEGIN {
12366:
12367: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12368: unless ($readit) {
12369: {
12370: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12371: %perlvar = (%perlvar,%{$configvars});
12372: }
12373:
12374:
1.1 albertel 12375: # ------------------------------------------------------ Read spare server file
12376: {
1.448 albertel 12377: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12378:
12379: while (my $configline=<$config>) {
12380: chomp($configline);
1.284 matthew 12381: if ($configline) {
1.784 albertel 12382: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12383: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12384: push(@{ $spareid{$type} }, $host);
1.1 albertel 12385: }
12386: }
1.448 albertel 12387: close($config);
1.1 albertel 12388: }
1.11 www 12389: # ------------------------------------------------------------ Read permissions
12390: {
1.448 albertel 12391: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12392:
12393: while (my $configline=<$config>) {
1.448 albertel 12394: chomp($configline);
12395: if ($configline) {
12396: my ($role,$perm)=split(/ /,$configline);
12397: if ($perm ne '') { $pr{$role}=$perm; }
12398: }
1.11 www 12399: }
1.448 albertel 12400: close($config);
1.11 www 12401: }
12402:
12403: # -------------------------------------------- Read plain texts for permissions
12404: {
1.448 albertel 12405: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12406:
12407: while (my $configline=<$config>) {
1.448 albertel 12408: chomp($configline);
12409: if ($configline) {
1.742 raeburn 12410: my ($short,@plain)=split(/:/,$configline);
12411: %{$prp{$short}} = ();
12412: if (@plain > 0) {
12413: $prp{$short}{'std'} = $plain[0];
12414: for (my $i=1; $i<@plain; $i++) {
12415: $prp{$short}{'alt'.$i} = $plain[$i];
12416: }
12417: }
1.448 albertel 12418: }
1.135 www 12419: }
1.448 albertel 12420: close($config);
1.135 www 12421: }
12422:
12423: # ---------------------------------------------------------- Read package table
12424: {
1.448 albertel 12425: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12426:
12427: while (my $configline=<$config>) {
1.483 albertel 12428: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12429: chomp($configline);
12430: my ($short,$plain)=split(/:/,$configline);
12431: my ($pack,$name)=split(/\&/,$short);
12432: if ($plain ne '') {
12433: $packagetab{$pack.'&'.$name.'&name'}=$name;
12434: $packagetab{$short}=$plain;
12435: }
1.11 www 12436: }
1.448 albertel 12437: close($config);
1.329 matthew 12438: }
12439:
1.1172.2.27 raeburn 12440: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12441:
1.1172.2.27 raeburn 12442: &load_loncaparevs();
12443:
12444: # ------------------------------------------------------- Read serverhostID table
12445:
12446: &load_serverhomeIDs();
1.1074 raeburn 12447:
1.1172.2.27 raeburn 12448: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12449: {
12450: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12451: if (-e $file) {
12452: my $parser = HTML::LCParser->new($file);
12453: while (my $token = $parser->get_token()) {
12454: if ($token->[0] eq 'S') {
12455: my $item = $token->[1];
12456: my $name = $token->[2]{'name'};
12457: my $value = $token->[2]{'value'};
12458: if ($item ne '' && $name ne '' && $value ne '') {
12459: my $release = $parser->get_text();
12460: $release =~ s/(^\s*|\s*$ )//gx;
12461: $needsrelease{$item.':'.$name.':'.$value} = $release;
12462: }
12463: }
12464: }
12465: }
1.1073 raeburn 12466: }
12467:
1.1138 raeburn 12468: # ---------------------------------------------------------- Read managers table
12469: {
12470: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12471: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12472: while (my $configline=<$config>) {
12473: chomp($configline);
12474: next if ($configline =~ /^\#/);
12475: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12476: $managerstab{$configline} = 1;
12477: }
12478: }
12479: close($config);
12480: }
12481: }
12482: }
12483:
1.329 matthew 12484: # ------------- set up temporary directory
12485: {
1.1117 foxr 12486: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12487:
1.11 www 12488: }
12489:
1.794 albertel 12490: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12491: 'compress_threshold'=> 20_000,
12492: });
1.185 www 12493:
1.281 www 12494: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12495: $dumpcount=0;
1.958 www 12496: $locknum=0;
1.22 www 12497:
1.163 harris41 12498: &logtouch();
1.672 albertel 12499: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12500: $readit=1;
1.564 albertel 12501: {
12502: use integer;
12503: my $test=(2**32)+1;
1.568 albertel 12504: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12505: &logthis(" Detected 64bit platform ($_64bit)");
12506: }
1.195 www 12507: }
1.1 albertel 12508: }
1.179 www 12509:
1.1 albertel 12510: 1;
1.191 harris41 12511: __END__
12512:
1.243 albertel 12513: =pod
12514:
1.191 harris41 12515: =head1 NAME
12516:
1.243 albertel 12517: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12518:
12519: =head1 SYNOPSIS
12520:
1.243 albertel 12521: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12522:
12523: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12524:
1.243 albertel 12525: Common parameters:
12526:
12527: =over 4
12528:
12529: =item *
12530:
12531: $uname : an internal username (if $cname expecting a course Id specifically)
12532:
12533: =item *
12534:
12535: $udom : a domain (if $cdom expecting a course's domain specifically)
12536:
12537: =item *
12538:
12539: $symb : a resource instance identifier
12540:
12541: =item *
12542:
12543: $namespace : the name of a .db file that contains the data needed or
12544: being set.
12545:
12546: =back
12547:
1.394 bowersj2 12548: =head1 OVERVIEW
1.191 harris41 12549:
1.394 bowersj2 12550: lonnet provides subroutines which interact with the
12551: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12552: about classes, users, and resources.
1.243 albertel 12553:
12554: For many of these objects you can also use this to store data about
12555: them or modify them in various ways.
1.191 harris41 12556:
1.394 bowersj2 12557: =head2 Symbs
1.191 harris41 12558:
1.394 bowersj2 12559: To identify a specific instance of a resource, LON-CAPA uses symbols
12560: or "symbs"X<symb>. These identifiers are built from the URL of the
12561: map, the resource number of the resource in the map, and the URL of
12562: the resource itself. The latter is somewhat redundant, but might help
12563: if maps change.
12564:
12565: An example is
12566:
12567: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12568:
12569: The respective map entry is
12570:
12571: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12572: title="Problem 2">
12573: </resource>
12574:
12575: Symbs are used by the random number generator, as well as to store and
12576: restore data specific to a certain instance of for example a problem.
12577:
12578: =head2 Storing And Retrieving Data
12579:
12580: X<store()>X<cstore()>X<restore()>Three of the most important functions
12581: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12582: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12583: is is the non-critical message twin of cstore. These functions are for
12584: handlers to store a perl hash to a user's permanent data space in an
12585: easy manner, and to retrieve it again on another call. It is expected
12586: that a handler would use this once at the beginning to retrieve data,
12587: and then again once at the end to send only the new data back.
12588:
12589: The data is stored in the user's data directory on the user's
12590: homeserver under the ID of the course.
12591:
12592: The hash that is returned by restore will have all of the previous
12593: value for all of the elements of the hash.
12594:
12595: Example:
12596:
12597: #creating a hash
12598: my %hash;
12599: $hash{'foo'}='bar';
12600:
12601: #storing it
12602: &Apache::lonnet::cstore(\%hash);
12603:
12604: #changing a value
12605: $hash{'foo'}='notbar';
12606:
12607: #adding a new value
12608: $hash{'bar'}='foo';
12609: &Apache::lonnet::cstore(\%hash);
12610:
12611: #retrieving the hash
12612: my %history=&Apache::lonnet::restore();
12613:
12614: #print the hash
12615: foreach my $key (sort(keys(%history))) {
12616: print("\%history{$key} = $history{$key}");
12617: }
12618:
12619: Will print out:
1.191 harris41 12620:
1.394 bowersj2 12621: %history{1:foo} = bar
12622: %history{1:keys} = foo:timestamp
12623: %history{1:timestamp} = 990455579
12624: %history{2:bar} = foo
12625: %history{2:foo} = notbar
12626: %history{2:keys} = foo:bar:timestamp
12627: %history{2:timestamp} = 990455580
12628: %history{bar} = foo
12629: %history{foo} = notbar
12630: %history{timestamp} = 990455580
12631: %history{version} = 2
12632:
12633: Note that the special hash entries C<keys>, C<version> and
12634: C<timestamp> were added to the hash. C<version> will be equal to the
12635: total number of versions of the data that have been stored. The
12636: C<timestamp> attribute will be the UNIX time the hash was
12637: stored. C<keys> is available in every historical section to list which
12638: keys were added or changed at a specific historical revision of a
12639: hash.
12640:
12641: B<Warning>: do not store the hash that restore returns directly. This
12642: will cause a mess since it will restore the historical keys as if the
12643: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12644:
1.394 bowersj2 12645: Calling convention:
1.191 harris41 12646:
1.1172.2.27 raeburn 12647: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12648: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12649:
1.394 bowersj2 12650: For more detailed information, see lonnet specific documentation.
1.191 harris41 12651:
1.394 bowersj2 12652: =head1 RETURN MESSAGES
1.191 harris41 12653:
1.394 bowersj2 12654: =over 4
1.191 harris41 12655:
1.394 bowersj2 12656: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12657:
1.394 bowersj2 12658: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12659: when the connection is brought back up
1.191 harris41 12660:
1.394 bowersj2 12661: =item * B<con_failed>: unable to contact remote host and unable to save message
12662: for later delivery
1.191 harris41 12663:
1.967 bisitz 12664: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12665:
1.394 bowersj2 12666: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12667: that was requested
1.191 harris41 12668:
1.243 albertel 12669: =back
1.191 harris41 12670:
1.243 albertel 12671: =head1 PUBLIC SUBROUTINES
1.191 harris41 12672:
1.243 albertel 12673: =head2 Session Environment Functions
1.191 harris41 12674:
1.243 albertel 12675: =over 4
1.191 harris41 12676:
1.394 bowersj2 12677: =item *
12678: X<appenv()>
1.949 raeburn 12679: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12680: the user envirnoment file, and will be restored for each access this
1.620 albertel 12681: user makes during this session, also modifies the %env for the current
1.949 raeburn 12682: process. Optional rolesarrayref - if defined contains a reference to an array
12683: of roles which are exempt from the restriction on modifying user.role entries
12684: in the user's environment.db and in %env.
1.191 harris41 12685:
12686: =item *
1.394 bowersj2 12687: X<delenv()>
1.987 raeburn 12688: B<delenv($delthis,$regexp)>: removes all items from the session
12689: environment file that begin with $delthis. If the
12690: optional second arg - $regexp - is true, $delthis is treated as a
12691: regular expression, otherwise \Q$delthis\E is used.
12692: The values are also deleted from the current processes %env.
1.191 harris41 12693:
1.795 albertel 12694: =item * get_env_multiple($name)
12695:
12696: gets $name from the %env hash, it seemlessly handles the cases where multiple
12697: values may be defined and end up as an array ref.
12698:
12699: returns an array of values
12700:
1.243 albertel 12701: =back
12702:
12703: =head2 User Information
1.191 harris41 12704:
1.243 albertel 12705: =over 4
1.191 harris41 12706:
12707: =item *
1.394 bowersj2 12708: X<queryauthenticate()>
12709: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12710: authentication scheme
12711:
12712: =item *
1.394 bowersj2 12713: X<authenticate()>
1.1073 raeburn 12714: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12715: authenticate user from domain's lib servers (first use the current
12716: one). C<$upass> should be the users password.
1.1073 raeburn 12717: $checkdefauth is optional (value is 1 if a check should be made to
12718: authenticate user using default authentication method, and allow
12719: account creation if username does not have account in the domain).
12720: $clientcancheckhost is optional (value is 1 if checking whether the
12721: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12722:
12723: =item *
1.394 bowersj2 12724: X<homeserver()>
12725: B<homeserver($uname,$udom)>: find the server which has
12726: the user's directory and files (there must be only one), this caches
12727: the answer, and also caches if there is a borken connection.
1.191 harris41 12728:
12729: =item *
1.394 bowersj2 12730: X<idget()>
12731: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12732: (IDs are a unique resource in a domain, there must be only 1 ID per
12733: username, and only 1 username per ID in a specific domain) (returns
12734: hash: id=>name,id=>name)
1.191 harris41 12735:
12736: =item *
1.394 bowersj2 12737: X<idrget()>
12738: B<idrget($udom,@unames)>: find the IDs behind a list of
12739: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12740:
12741: =item *
1.394 bowersj2 12742: X<idput()>
12743: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12744:
12745: =item *
1.394 bowersj2 12746: X<rolesinit()>
1.1169 droeschl 12747: B<rolesinit($udom,$username)>: get user privileges.
12748: returns user role, first access and timer interval hashes
1.243 albertel 12749:
12750: =item *
1.1171 droeschl 12751: X<privileged()>
12752: B<privileged($username,$domain)>: returns a true if user has a
12753: privileged and active role (i.e. su or dc), false otherwise.
12754:
12755: =item *
1.551 albertel 12756: X<getsection()>
12757: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12758: course $cname, return section name/number or '' for "not in course"
12759: and '-1' for "no section"
12760:
12761: =item *
1.394 bowersj2 12762: X<userenvironment()>
12763: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12764: passed in @what from the requested user's environment, returns a hash
12765:
1.858 raeburn 12766: =item *
12767: X<userlog_query()>
1.859 albertel 12768: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12769: activity.log file. %filters defines filters applied when parsing the
12770: log file. These can be start or end timestamps, or the type of action
12771: - log to look for Login or Logout events, check for Checkin or
12772: Checkout, role for role selection. The response is in the form
12773: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12774: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12775:
1.243 albertel 12776: =back
12777:
12778: =head2 User Roles
12779:
12780: =over 4
12781:
12782: =item *
12783:
1.810 raeburn 12784: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12785: F: full access
12786: U,I,K: authentication modes (cxx only)
12787: '': forbidden
12788: 1: user needs to choose course
12789: 2: browse allowed
1.766 albertel 12790: A: passphrase authentication needed
1.243 albertel 12791:
12792: =item *
12793:
1.1172.2.13 raeburn 12794: constructaccess($url,$setpriv) : check for access to construction space URL
12795:
12796: See if the owner domain and name in the URL match those in the
12797: expected environment. If so, return three element list
12798: ($ownername,$ownerdomain,$ownerhome).
12799:
12800: Otherwise return the null string.
12801:
12802: If second argument 'setpriv' is true, it assigns the privileges,
12803: and returns the same three element list, unless the owner has
12804: blocked "ad hoc" Domain Coordinator access to the Author Space,
12805: in which case the null string is returned.
12806:
12807: =item *
12808:
1.243 albertel 12809: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12810: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12811: and course level
12812:
12813: =item *
12814:
1.988 raeburn 12815: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12816: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12817: $type is Course (default) or Community.
1.988 raeburn 12818: If $forcedefault evaluates to true, text returned will be default
12819: text for $type. Otherwise, if this is a course, the text returned
12820: will be a custom name for the role (if defined in the course's
12821: environment). If no custom name is defined the default is returned.
12822:
1.832 raeburn 12823: =item *
12824:
1.1172.2.23 raeburn 12825: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12826: All arguments are optional. Returns a hash of a roles, either for
12827: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12828: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12829: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12830: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12831: For each key, value is set to colon-separated start and end times for
12832: the role. If no username and domain are specified, will default to
1.934 raeburn 12833: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12834: of role statuses (active, future or previous), roles
12835: (e.g., cc,in, st etc.) and domains of the roles which can be used
12836: to restrict the list of roles reported. If no array ref is
12837: provided for types, will default to return only active roles.
1.834 albertel 12838:
1.1172.2.13 raeburn 12839: =item *
12840:
12841: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12842: user: $uname:$udom has a role in the course: $cdom_$cnum.
12843:
12844: Additional optional arguments are: $type (if role checking is to be restricted
12845: to certain user status types -- previous (expired roles), active (currently
12846: available roles) or future (roles available in the future), and
12847: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12848: have active Domain Coordinator role in course's domain or in additional
12849: domains (specified in 'Domains to check for privileged users' in course
12850: environment -- set via: Course Settings -> Classlists and staff listing).
12851:
12852: =item *
12853:
12854: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12855: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12856: $possdomains and $possroles are optional array refs -- to domains to check and
12857: roles to check. If $possdomains is not specified, a dump will be done of the
12858: users' roles.db to check for a dc or su role in any domain. This can be
12859: time consuming if &privileged is called repeatedly (e.g., when displaying a
12860: classlist), so in such cases, supplying a $possdomains array is preferred, as
12861: this then allows &privileged_by_domain() to be used, which caches the identity
12862: of privileged users, eliminating the need for repeated calls to &dump().
12863:
12864: =item *
12865:
12866: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12867: where the outer hash keys are domains specified in the $possdomains array ref,
12868: next inner hash keys are privileged roles specified in the $roles array ref,
12869: and the innermost hash contains key = value pairs for username:domain = end:start
12870: for active or future "privileged" users with that role in that domain. To avoid
12871: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12872: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12873:
1.243 albertel 12874: =back
12875:
12876: =head2 User Modification
12877:
12878: =over 4
12879:
12880: =item *
12881:
1.957 raeburn 12882: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12883: user for the level given by URL. Optional start and end dates (leave empty
12884: string or zero for "no date")
1.191 harris41 12885:
12886: =item *
12887:
1.243 albertel 12888: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12889: change a users, password, possible return values are: ok,
12890: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12891: refused
1.191 harris41 12892:
12893: =item *
12894:
1.243 albertel 12895: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12896:
12897: =item *
12898:
1.1058 raeburn 12899: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12900: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12901:
12902: will update user information (firstname,middlename,lastname,generation,
12903: permanentemail), and if forceid is true, student/employee ID also.
12904: A user's institutional affiliation(s) can also be updated.
12905: User information fields will not be overwritten with empty entries
12906: unless the field is included in the $candelete array reference.
12907: This array is included when a single user is modified via "Manage Users",
12908: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12909:
12910: =item *
12911:
1.286 matthew 12912: modifystudent
12913:
1.957 raeburn 12914: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 12915: The course id is resolved based on the current user's environment.
12916: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12917: associated with a course.
12918:
1.297 matthew 12919: This call is essentially a wrapper for lonnet::modifyuser and
12920: lonnet::modify_student_enrollment
1.286 matthew 12921:
12922: Inputs:
12923:
12924: =over 4
12925:
1.957 raeburn 12926: =item B<$udom> Student's loncapa domain
1.286 matthew 12927:
1.957 raeburn 12928: =item B<$uname> Student's loncapa login name
1.286 matthew 12929:
1.964 bisitz 12930: =item B<$uid> Student/Employee ID
1.286 matthew 12931:
1.957 raeburn 12932: =item B<$umode> Student's authentication mode
1.286 matthew 12933:
1.957 raeburn 12934: =item B<$upass> Student's password
1.286 matthew 12935:
1.957 raeburn 12936: =item B<$first> Student's first name
1.286 matthew 12937:
1.957 raeburn 12938: =item B<$middle> Student's middle name
1.286 matthew 12939:
1.957 raeburn 12940: =item B<$last> Student's last name
1.286 matthew 12941:
1.957 raeburn 12942: =item B<$gene> Student's generation
1.286 matthew 12943:
1.957 raeburn 12944: =item B<$usec> Student's section in course
1.286 matthew 12945:
12946: =item B<$end> Unix time of the roles expiration
12947:
12948: =item B<$start> Unix time of the roles start date
12949:
12950: =item B<$forceid> If defined, allow $uid to be changed
12951:
12952: =item B<$desiredhome> server to use as home server for student
12953:
1.957 raeburn 12954: =item B<$email> Student's permanent e-mail address
12955:
12956: =item B<$type> Type of enrollment (auto or manual)
12957:
1.963 raeburn 12958: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12959:
12960: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12961:
1.963 raeburn 12962: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12963:
1.963 raeburn 12964: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12965:
1.1172.2.19 raeburn 12966: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12967:
12968: =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 12969:
1.286 matthew 12970: =back
1.297 matthew 12971:
12972: =item *
12973:
12974: modify_student_enrollment
12975:
1.1172.2.31 raeburn 12976: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12977: 'role.request.course' must be defined for this function to proceed.
12978:
12979: Inputs:
12980:
12981: =over 4
12982:
1.1172.2.31 raeburn 12983: =item $udom, student's domain
1.297 matthew 12984:
1.1172.2.31 raeburn 12985: =item $uname, student's name
1.297 matthew 12986:
1.1172.2.31 raeburn 12987: =item $uid, student's user id
1.297 matthew 12988:
1.1172.2.31 raeburn 12989: =item $first, student's first name
1.297 matthew 12990:
12991: =item $middle
12992:
12993: =item $last
12994:
12995: =item $gene
12996:
12997: =item $usec
12998:
12999: =item $end
13000:
13001: =item $start
13002:
1.957 raeburn 13003: =item $type
13004:
13005: =item $locktype
13006:
13007: =item $cid
13008:
13009: =item $selfenroll
13010:
13011: =item $context
13012:
1.1172.2.19 raeburn 13013: =item $credits, number of credits student will earn from this class
13014:
1.297 matthew 13015: =back
13016:
1.191 harris41 13017:
13018: =item *
13019:
1.243 albertel 13020: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13021: custom role; give a custom role to a user for the level given by URL. Specify
13022: name and domain of role author, and role name
1.191 harris41 13023:
13024: =item *
13025:
1.243 albertel 13026: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13027:
13028: =item *
13029:
1.243 albertel 13030: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13031:
13032: =back
13033:
13034: =head2 Course Infomation
13035:
13036: =over 4
1.191 harris41 13037:
13038: =item *
13039:
1.1118 foxr 13040: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13041: specified course id, including all environment settings for the
13042: course, the description of the course will be in the hash under the
13043: key 'description'
1.191 harris41 13044:
1.1118 foxr 13045: $options is an optional parameter that if supplied is a hash reference that controls
13046: what how this function works. It has the following key/values:
13047:
13048: =over 4
13049:
13050: =item freshen_cache
13051:
13052: If defined, and the environment cache for the course is valid, it is
13053: returned in the returned hash.
13054:
13055: =item one_time
13056:
13057: If defined, the last cache time is set to _now_
13058:
13059: =item user
13060:
13061: If defined, the supplied username is used instead of the current user.
13062:
13063:
13064: =back
13065:
1.191 harris41 13066: =item *
13067:
1.624 albertel 13068: resdata($name,$domain,$type,@which) : request for current parameter
13069: setting for a specific $type, where $type is either 'course' or 'user',
13070: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13071: answers for 10 minutes.
1.243 albertel 13072:
1.877 foxr 13073: =item *
13074:
13075: get_courseresdata($courseid, $domain) : dump the entire course resource
13076: data base, returning a hash that is keyed by the resource name and has
13077: values that are the resource value. I believe that the timestamps and
13078: versions are also returned.
13079:
1.1172.2.31 raeburn 13080: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13081: supplemental content area. This routine caches the number of files for
13082: 10 minutes.
13083:
1.243 albertel 13084: =back
13085:
13086: =head2 Course Modification
13087:
13088: =over 4
1.191 harris41 13089:
13090: =item *
13091:
1.243 albertel 13092: writecoursepref($courseid,%prefs) : write preferences (environment
13093: database) for a course
1.191 harris41 13094:
13095: =item *
13096:
1.1011 raeburn 13097: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13098:
13099: =item *
13100:
1.1038 raeburn 13101: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13102:
1.1167 droeschl 13103: =item *
13104:
13105: is_course($courseid), is_course($cdom, $cnum)
13106:
13107: Accepts either a combined $courseid (in the form of domain_courseid) or the
13108: two component version $cdom, $cnum. It checks if the specified course exists.
13109:
13110: Returns:
13111: undef if the course doesn't exist, otherwise
13112: in scalar context the combined courseid.
13113: in list context the two components of the course identifier, domain and
13114: courseid.
13115:
1.243 albertel 13116: =back
13117:
13118: =head2 Resource Subroutines
13119:
13120: =over 4
1.191 harris41 13121:
13122: =item *
13123:
1.243 albertel 13124: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13125:
13126: =item *
13127:
1.243 albertel 13128: repcopy($filename) : subscribes to the requested file, and attempts to
13129: replicate from the owning library server, Might return
1.607 raeburn 13130: 'unavailable', 'not_found', 'forbidden', 'ok', or
13131: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13132: resource. Expects the local filesystem pathname
13133: (/home/httpd/html/res/....)
13134:
13135: =back
13136:
13137: =head2 Resource Information
13138:
13139: =over 4
1.191 harris41 13140:
13141: =item *
13142:
1.1172.2.28 raeburn 13143: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13144: and returns the value of a variety of different possible values,
13145: $varname should be a request string, and the other parameters can be
13146: used to specify who and what one is asking about. Ordinarily, $cid
13147: does not need to be specified, as it is retrived from
13148: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13149: within lonuserstate::loadmap() when initializing a course, before
13150: $env{'request.course.id'} has been set, so it needs to be provided
13151: in that one case.
1.243 albertel 13152:
13153: Possible values for $varname are environment.lastname (or other item
13154: from the envirnment hash), user.name (or someother aspect about the
13155: user), resource.0.maxtries (or some other part and parameter of a
13156: resource)
1.204 albertel 13157:
13158: =item *
13159:
1.243 albertel 13160: directcondval($number) : get current value of a condition; reads from a state
13161: string
1.204 albertel 13162:
13163: =item *
13164:
1.243 albertel 13165: condval($condidx) : value of condition index based on state
1.204 albertel 13166:
13167: =item *
13168:
1.243 albertel 13169: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13170: resource's metadata, $what should be either a specific key, or either
13171: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13172: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13173:
13174: this function automatically caches all requests
1.191 harris41 13175:
13176: =item *
13177:
1.243 albertel 13178: metadata_query($query,$custom,$customshow) : make a metadata query against the
13179: network of library servers; returns file handle of where SQL and regex results
13180: will be stored for query
1.191 harris41 13181:
13182: =item *
13183:
1.243 albertel 13184: symbread($filename) : return symbolic list entry (filename argument optional);
13185: returns the data handle
1.191 harris41 13186:
13187: =item *
13188:
1.1172.2.17 raeburn 13189: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13190: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13191: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13192: on failure, user must be in a course, as it assumes the existence of
13193: the course initial hash, and uses $env('request.course.id'}. The third
13194: arg is an optional reference to a scalar. If this arg is passed in the
13195: call to symbverify, it will be set to 1 if the symb has been set to be
13196: encrypted; otherwise it will be null.
1.243 albertel 13197:
1.191 harris41 13198: =item *
13199:
1.243 albertel 13200: symbclean($symb) : removes versions numbers from a symb, returns the
13201: cleaned symb
1.191 harris41 13202:
13203: =item *
13204:
1.243 albertel 13205: is_on_map($uri) : checks if the $uri is somewhere on the current
13206: course map, user must be in a course for it to work.
1.191 harris41 13207:
13208: =item *
13209:
1.243 albertel 13210: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13211:
13212: =item *
13213:
1.243 albertel 13214: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13215: a random seed, all arguments are optional, if they aren't sent it uses the
13216: environment to derive them. Note: if symb isn't sent and it can't get one
13217: from &symbread it will use the current time as its return value
1.191 harris41 13218:
13219: =item *
13220:
1.243 albertel 13221: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13222: unfakeable, receipt
1.191 harris41 13223:
13224: =item *
13225:
1.620 albertel 13226: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13227:
13228: =item *
13229:
1.243 albertel 13230: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13231:
13232: =item *
13233:
1.243 albertel 13234: 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 13235:
13236: =item *
13237:
1.243 albertel 13238: 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 13239:
13240: =item *
13241:
1.243 albertel 13242: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13243:
13244: =item *
13245:
1.243 albertel 13246: devalidate($symb) : devalidate temporary spreadsheet calculations,
13247: forcing spreadsheet to reevaluate the resource scores next time.
13248:
1.1172.2.13 raeburn 13249: =item *
13250:
13251: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13252: when viewing in course context.
13253:
13254: input: six args -- filename (decluttered), course number, course domain,
13255: url, symb (if registered) and group (if this is a
13256: group item -- e.g., bulletin board, group page etc.).
13257:
13258: output: array of five scalars --
13259: $cfile -- url for file editing if editable on current server
13260: $home -- homeserver of resource (i.e., for author if published,
13261: or course if uploaded.).
13262: $switchserver -- 1 if server switch will be needed.
13263: $forceedit -- 1 if icon/link should be to go to edit mode
13264: $forceview -- 1 if icon/link should be to go to view mode
13265:
13266: =item *
13267:
13268: is_course_upload($file,$cnum,$cdom)
13269:
13270: Used in course context to determine if current file was uploaded to
13271: the course (i.e., would be found in /userfiles/docs on the course's
13272: homeserver.
13273:
13274: input: 3 args -- filename (decluttered), course number and course domain.
13275: output: boolean -- 1 if file was uploaded.
13276:
1.243 albertel 13277: =back
13278:
13279: =head2 Storing/Retreiving Data
13280:
13281: =over 4
1.191 harris41 13282:
13283: =item *
13284:
1.243 albertel 13285: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13286: for this url; hashref needs to be given and should be a \%hashname; the
13287: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13288: be derived from the env
1.191 harris41 13289:
13290: =item *
13291:
1.243 albertel 13292: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13293: uses critical subroutine
1.191 harris41 13294:
13295: =item *
13296:
1.243 albertel 13297: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13298: all args are optional
1.191 harris41 13299:
13300: =item *
13301:
1.717 albertel 13302: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13303: dumps the complete (or key matching regexp) namespace into a hash
13304: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13305: normally &store()ed into
13306:
13307: $range should be either an integer '100' (give me the first 100
13308: matching records)
13309: or be two integers sperated by a - with no spaces
13310: '30-50' (give me the 30th through the 50th matching
13311: records)
13312:
13313:
13314: =item *
13315:
13316: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13317: replaces a &store() version of data with a replacement set of data
13318: for a particular resource in a namespace passed in the $storehash hash
13319: reference
13320:
13321: =item *
13322:
1.243 albertel 13323: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13324: works very similar to store/cstore, but all data is stored in a
13325: temporary location and can be reset using tmpreset, $storehash should
13326: be a hash reference, returns nothing on success
1.191 harris41 13327:
13328: =item *
13329:
1.243 albertel 13330: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13331: similar to restore, but all data is stored in a temporary location and
13332: can be reset using tmpreset. Returns a hash of values on success,
13333: error string otherwise.
1.191 harris41 13334:
13335: =item *
13336:
1.243 albertel 13337: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13338: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13339:
13340: =item *
13341:
1.243 albertel 13342: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13343: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13344:
13345: =item *
13346:
1.243 albertel 13347: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13348: namesp ($udom and $uname are optional)
1.191 harris41 13349:
13350: =item *
13351:
1.702 albertel 13352: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13353: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13354: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13355:
1.702 albertel 13356: $range should be either an integer '100' (give me the first 100
13357: matching records)
13358: or be two integers sperated by a - with no spaces
13359: '30-50' (give me the 30th through the 50th matching
13360: records)
1.449 matthew 13361: =item *
13362:
13363: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13364: $store can be a scalar, an array reference, or if the amount to be
13365: incremented is > 1, a hash reference.
13366:
13367: ($udom and $uname are optional)
1.191 harris41 13368:
13369: =item *
13370:
1.243 albertel 13371: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13372: ($udom and $uname are optional)
1.191 harris41 13373:
13374: =item *
13375:
1.243 albertel 13376: cput($namespace,$storehash,$udom,$uname) : critical put
13377: ($udom and $uname are optional)
1.191 harris41 13378:
13379: =item *
13380:
1.748 albertel 13381: newput($namespace,$storehash,$udom,$uname) :
13382:
13383: Attempts to store the items in the $storehash, but only if they don't
13384: currently exist, if this succeeds you can be certain that you have
13385: successfully created a new key value pair in the $namespace db.
13386:
13387:
13388: Args:
13389: $namespace: name of database to store values to
13390: $storehash: hashref to store to the db
13391: $udom: (optional) domain of user containing the db
13392: $uname: (optional) name of user caontaining the db
13393:
13394: Returns:
13395: 'ok' -> succeeded in storing all keys of $storehash
13396: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13397: least <key> already existed in the db (other
13398: requested keys may also already exist)
1.967 bisitz 13399: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13400: 'con_lost' -> unable to contact request server
13401: 'refused' -> action was not allowed by remote machine
13402:
13403:
13404: =item *
13405:
1.243 albertel 13406: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13407: reference filled in from namesp (encrypts the return communication)
13408: ($udom and $uname are optional)
1.191 harris41 13409:
13410: =item *
13411:
1.243 albertel 13412: log($udom,$name,$home,$message) : write to permanent log for user; use
13413: critical subroutine
13414:
1.806 raeburn 13415: =item *
13416:
1.860 raeburn 13417: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13418: array reference filled in from namespace found in domain level on either
13419: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13420:
13421: =item *
13422:
1.860 raeburn 13423: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13424: domain level either on specified domain server ($uhome) or primary domain
13425: server ($udom and $uhome are optional)
1.806 raeburn 13426:
1.943 raeburn 13427: =item *
13428:
1.1172.2.35 raeburn 13429: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13430: for: authentication, language, quotas, timezone, date locale, and portal URL in
13431: the target domain.
13432:
13433: May also include additional key => value pairs for the following groups:
13434:
13435: =over
13436:
13437: =item
13438: disk quotas (MB allocated by default to portfolios and authoring spaces).
13439:
13440: =over
13441:
13442: =item defaultquota, authorquota
13443:
13444: =back
13445:
13446: =item
13447: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13448: portfolio for users).
13449:
13450: =over
13451:
13452: =item
13453: aboutme, blog, webdav, portfolio
13454:
13455: =back
13456:
13457: =item
13458: requestcourses: ability to request courses, and how requests are processed.
13459:
13460: =over
13461:
13462: =item
1.1172.2.37 raeburn 13463: official, unofficial, community, textbook
1.1172.2.35 raeburn 13464:
13465: =back
13466:
13467: =item
13468: inststatus: types of institutional affiliation, and order in which they are displayed.
13469:
13470: =over
13471:
13472: =item
1.1172.2.44 raeburn 13473: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13474:
13475: =back
13476:
13477: =item
13478: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13479: for course's uploaded content.
13480:
13481: =over
13482:
13483: =item
1.1172.2.37 raeburn 13484: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35 raeburn 13485:
13486: =back
13487:
13488: =item
13489: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13490: on your servers.
13491:
13492: =over
13493:
13494: =item
13495: remotesessions, hostedsessions
13496:
13497: =back
13498:
13499: =back
13500:
13501: In cases where a domain coordinator has never used the "Set Domain Configuration"
13502: utility to create a configuration.db file on a domain's primary library server
13503: only the following domain defaults: auth_def, auth_arg_def, lang_def
13504: -- corresponding values are authentication type (internal, krb4, krb5,
13505: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13506: will be available. Values are retrieved from cache (if current), unless the
13507: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13508: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13509:
13510: Typical usage:
1.943 raeburn 13511:
1.1172.2.35 raeburn 13512: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13513:
1.243 albertel 13514: =back
13515:
13516: =head2 Network Status Functions
13517:
13518: =over 4
1.191 harris41 13519:
13520: =item *
13521:
1.1137 raeburn 13522: dirlist() : return directory list based on URI (first arg).
13523:
13524: Inputs: 1 required, 5 optional.
13525:
13526: =over
13527:
13528: =item
13529: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13530:
13531: =item
13532: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13533:
13534: =item
13535: $username - username of user/course to be listed. Extracted from $uri if absent.
13536:
13537: =item
13538: $getpropath - boolean: 1 if prepend path using &propath().
13539:
13540: =item
13541: $getuserdir - boolean: 1 if prepend path for "userfiles".
13542:
13543: =item
13544: $alternateRoot - path to prepend in place of path from $uri.
13545:
13546: =back
13547:
13548: Returns: Array of up to two items.
13549:
13550: =over
13551:
13552: a reference to an array of files/subdirectories
13553:
13554: =over
13555:
13556: Each element in the array of files/subdirectories is a & separated list of
13557: item name and the result of running stat on the item. If dirlist was requested
13558: for a file instead of a directory, the item name will be ''. For a directory
13559: listing, if the item is a metadata file, the element will end &N&M
13560: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13561: default copyright set (1).
13562:
13563: =back
13564:
13565: a scalar containing error condition (if encountered).
13566:
13567: =over
13568:
13569: =item
13570: no_host (no homeserver identified for $username:$domain).
13571:
13572: =item
13573: no_such_host (server contacted for listing not identified as valid host).
13574:
13575: =item
13576: con_lost (connection to remote server failed).
13577:
13578: =item
13579: refused (invalid $username:$domain received on lond side).
13580:
13581: =item
13582: no_such_dir (directory at specified path on lond side does not exist).
13583:
13584: =item
13585: empty (directory at specified path on lond side is empty).
13586:
13587: =over
13588:
13589: This is currently not encountered because the &ls3, &ls2,
13590: &ls (_handler) routines on the lond side do not filter out
13591: . and .. from a directory listing.
13592:
13593: =back
13594:
13595: =back
13596:
13597: =back
1.191 harris41 13598:
13599: =item *
13600:
1.243 albertel 13601: spareserver() : find server with least workload from spare.tab
13602:
1.986 foxr 13603:
13604: =item *
13605:
13606: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13607: if there is no corresponding loncapa host.
13608:
1.243 albertel 13609: =back
13610:
1.986 foxr 13611:
1.243 albertel 13612: =head2 Apache Request
13613:
13614: =over 4
1.191 harris41 13615:
13616: =item *
13617:
1.243 albertel 13618: ssi($url,%hash) : server side include, does a complete request cycle on url to
13619: localhost, posts hash
13620:
13621: =back
13622:
13623: =head2 Data to String to Data
13624:
13625: =over 4
1.191 harris41 13626:
13627: =item *
13628:
1.243 albertel 13629: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13630: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13631:
13632: =item *
13633:
1.243 albertel 13634: hashref2str($hashref) : convert a hashref into a string complete with
13635: escaping and '=' and '&' separators, supports elements that are
13636: arrayrefs and hashrefs
1.191 harris41 13637:
13638: =item *
13639:
1.243 albertel 13640: arrayref2str($arrayref) : convert an arrayref into a string complete
13641: with escaping and '&' separators, supports elements that are arrayrefs
13642: and hashrefs
1.191 harris41 13643:
13644: =item *
13645:
1.243 albertel 13646: str2hash($string) : convert string to hash using unescaping and
13647: splitting on '=' and '&', supports elements that are arrayrefs and
13648: hashrefs
1.191 harris41 13649:
13650: =item *
13651:
1.243 albertel 13652: str2array($string) : convert string to hash using unescaping and
13653: splitting on '&', supports elements that are arrayrefs and hashrefs
13654:
13655: =back
13656:
13657: =head2 Logging Routines
13658:
13659:
13660: These routines allow one to make log messages in the lonnet.log and
13661: lonnet.perm logfiles.
1.191 harris41 13662:
1.1119 foxr 13663: =over 4
13664:
1.191 harris41 13665: =item *
13666:
1.243 albertel 13667: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13668:
13669: =item *
13670:
1.243 albertel 13671: logthis() : append message to the normal lonnet.log file, it gets
13672: preiodically rolled over and deleted.
1.191 harris41 13673:
13674: =item *
13675:
1.243 albertel 13676: logperm() : append a permanent message to lonnet.perm.log, this log
13677: file never gets deleted by any automated portion of the system, only
13678: messages of critical importance should go in here.
13679:
1.1119 foxr 13680:
1.243 albertel 13681: =back
13682:
13683: =head2 General File Helper Routines
13684:
13685: =over 4
1.191 harris41 13686:
13687: =item *
13688:
1.481 raeburn 13689: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13690: (a) files in /uploaded
13691: (i) If a local copy of the file exists -
13692: compares modification date of local copy with last-modified date for
13693: definitive version stored on home server for course. If local copy is
13694: stale, requests a new version from the home server and stores it.
13695: If the original has been removed from the home server, then local copy
13696: is unlinked.
13697: (ii) If local copy does not exist -
13698: requests the file from the home server and stores it.
13699:
13700: If $caller is 'uploadrep':
13701: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13702: for request for files originally uploaded via DOCS.
13703: - returns 'ok' if fresh local copy now available, -1 otherwise.
13704:
13705: Otherwise:
13706: This indicates a call from the content generation phase of the request.
13707: - returns the entire contents of the file or -1.
13708:
13709: (b) files in /res
13710: - returns the entire contents of a file or -1;
13711: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13712:
1.712 albertel 13713:
13714: =item *
13715:
13716: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13717: reference
13718:
13719: returns either a stat() list of data about the file or an empty list
13720: if the file doesn't exist or couldn't find out about it (connection
13721: problems or user unknown)
13722:
1.191 harris41 13723: =item *
13724:
1.243 albertel 13725: filelocation($dir,$file) : returns file system location of a file
13726: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13727: directory that relative $file lookups are to looked in ($dir of /a/dir
13728: and a file of ../bob will become /a/bob)
1.191 harris41 13729:
13730: =item *
13731:
13732: hreflocation($dir,$file) : returns file system location or a URL; same as
13733: filelocation except for hrefs
13734:
13735: =item *
13736:
1.1172.2.49 raeburn 13737: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13738: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 13739:
1.243 albertel 13740: =back
13741:
1.608 albertel 13742: =head2 Usererfile file routines (/uploaded*)
13743:
13744: =over 4
13745:
13746: =item *
13747:
13748: userfileupload(): main rotine for putting a file in a user or course's
13749: filespace, arguments are,
13750:
1.620 albertel 13751: formname - required - this is the name of the element in $env where the
1.608 albertel 13752: filename, and the contents of the file to create/modifed exist
1.620 albertel 13753: the filename is in $env{'form.'.$formname.'.filename'} and the
13754: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13755: context - if coursedoc, store the file in the course of the active role
13756: of the current user;
13757: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13758: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13759: subdir - required - subdirectory to put the file in under ../userfiles/
13760: if undefined, it will be placed in "unknown"
13761:
13762: (This routine calls clean_filename() to remove any dangerous
13763: characters from the filename, and then calls finuserfileupload() to
13764: complete the transaction)
13765:
13766: returns either the url of the uploaded file (/uploaded/....) if successful
13767: and /adm/notfound.html if unsuccessful
13768:
13769: =item *
13770:
13771: clean_filename(): routine for cleaing a filename up for storage in
13772: userfile space, argument is:
13773:
13774: filename - proposed filename
13775:
13776: returns: the new clean filename
13777:
13778: =item *
13779:
1.1090 raeburn 13780: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13781: userspace, probably shouldn't be called directly
13782:
13783: docuname: username or courseid of destination for the file
13784: docudom: domain of user/course of destination for the file
13785: formname: same as for userfileupload()
1.1090 raeburn 13786: fname: filename (including subdirectories) for the file
13787: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13788: allfiles: reference to hash used to store objects found by parser
13789: codebase: reference to hash used for codebases of java objects found by parser
13790: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13791: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13792: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13793: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13794: context: if 'overwrite', will move the uploaded file from its temporary location to
13795: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13796: mimetype: reference to scalar to accommodate mime type determined
13797: from File::MMagic if $parser = parse.
1.608 albertel 13798:
13799: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13800: and /adm/notfound.html if unsuccessful (or an error message if context
13801: was 'overwrite').
13802:
1.608 albertel 13803:
13804: =item *
13805:
13806: renameuserfile(): renames an existing userfile to a new name
13807:
13808: Args:
13809: docuname: username or courseid of destination for the file
13810: docudom: domain of user/course of destination for the file
13811: old: current file name (including any subdirs under userfiles)
13812: new: desired file name (including any subdirs under userfiles)
13813:
13814: =item *
13815:
13816: mkdiruserfile(): creates a directory is a userfiles dir
13817:
13818: Args:
13819: docuname: username or courseid of destination for the file
13820: docudom: domain of user/course of destination for the file
13821: dir: dir to create (including any subdirs under userfiles)
13822:
13823: =item *
13824:
13825: removeuserfile(): removes a file that exists in userfiles
13826:
13827: Args:
13828: docuname: username or courseid of destination for the file
13829: docudom: domain of user/course of destination for the file
13830: fname: filname to delete (including any subdirs under userfiles)
13831:
13832: =item *
13833:
13834: removeuploadedurl(): convience function for removeuserfile()
13835:
13836: Args:
13837: url: a full /uploaded/... url to delete
13838:
1.747 albertel 13839: =item *
13840:
13841: get_portfile_permissions():
13842: Args:
13843: domain: domain of user or course contain the portfolio files
13844: user: name of user or num of course contain the portfolio files
13845: Returns:
13846: hashref of a dump of the proper file_permissions.db
13847:
13848:
13849: =item *
13850:
13851: get_access_controls():
13852:
13853: Args:
13854: current_permissions: the hash ref returned from get_portfile_permissions()
13855: group: (optional) the group you want the files associated with
13856: file: (optional) the file you want access info on
13857:
13858: Returns:
1.749 raeburn 13859: a hash (keys are file names) of hashes containing
13860: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13861: values are XML containing access control settings (see below)
1.747 albertel 13862:
13863: Internal notes:
13864:
1.749 raeburn 13865: access controls are stored in file_permissions.db as key=value pairs.
13866: key -> path to file/file_name\0uniqueID:scope_end_start
13867: where scope -> public,guest,course,group,domains or users.
13868: end -> UNIX time for end of access (0 -> no end date)
13869: start -> UNIX time for start of access
13870:
13871: value -> XML description of access control
13872: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13873: <start></start>
13874: <end></end>
13875:
13876: <password></password> for scope type = guest
13877:
13878: <domain></domain> for scope type = course or group
13879: <number></number>
13880: <roles id="">
13881: <role></role>
13882: <access></access>
13883: <section></section>
13884: <group></group>
13885: </roles>
13886:
13887: <dom></dom> for scope type = domains
13888:
13889: <users> for scope type = users
13890: <user>
13891: <uname></uname>
13892: <udom></udom>
13893: </user>
13894: </users>
13895: </scope>
13896:
13897: Access data is also aggregated for each file in an additional key=value pair:
13898: key -> path to file/file_name\0accesscontrol
13899: value -> reference to hash
13900: hash contains key = value pairs
13901: where key = uniqueID:scope_end_start
13902: value = UNIX time record was last updated
13903:
13904: Used to improve speed of look-ups of access controls for each file.
13905:
13906: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13907:
1.1172.2.13 raeburn 13908: =item *
13909:
1.749 raeburn 13910: modify_access_controls():
13911:
13912: Modifies access controls for a portfolio file
13913: Args
13914: 1. file name
13915: 2. reference to hash of required changes,
13916: 3. domain
13917: 4. username
13918: where domain,username are the domain of the portfolio owner
13919: (either a user or a course)
13920:
13921: Returns:
13922: 1. result of additions or updates ('ok' or 'error', with error message).
13923: 2. result of deletions ('ok' or 'error', with error message).
13924: 3. reference to hash of any new or updated access controls.
13925: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13926: key = integer (inbound ID)
1.1172.2.13 raeburn 13927: value = uniqueID
13928:
13929: =item *
13930:
13931: get_timebased_id():
13932:
13933: Attempts to get a unique timestamp-based suffix for use with items added to a
13934: course via the Course Editor (e.g., folders, composite pages,
13935: group bulletin boards).
13936:
13937: Args: (first three required; six others optional)
13938:
13939: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13940: docssequence, or name of group
13941:
13942: 2. keyid (alphanumeric): name of temporary locking key in hash,
13943: e.g., num, boardids
13944:
13945: 3. namespace: name of gdbm file used to store suffixes already assigned;
13946: file will be named nohist_namespace.db
13947:
13948: 4. cdom: domain of course; default is current course domain from %env
13949:
13950: 5. cnum: course number; default is current course number from %env
13951:
13952: 6. idtype: set to concat if an additional digit is to be appended to the
13953: unix timestamp to form the suffix, if the plain timestamp is already
13954: in use. Default is to not do this, but simply increment the unix
13955: timestamp by 1 until a unique key is obtained.
13956:
13957: 7. who: holder of locking key; defaults to user:domain for user.
13958:
13959: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13960: retrying); default is 3.
13961:
13962: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13963:
13964: Returns:
13965:
13966: 1. suffix obtained (numeric)
13967:
13968: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13969:
13970: 3. error: contains (localized) error message if an error occurred.
13971:
1.747 albertel 13972:
1.608 albertel 13973: =back
13974:
1.243 albertel 13975: =head2 HTTP Helper Routines
13976:
13977: =over 4
13978:
1.191 harris41 13979: =item *
13980:
13981: escape() : unpack non-word characters into CGI-compatible hex codes
13982:
13983: =item *
13984:
13985: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13986:
1.243 albertel 13987: =back
13988:
13989: =head1 PRIVATE SUBROUTINES
13990:
13991: =head2 Underlying communication routines (Shouldn't call)
13992:
13993: =over 4
13994:
13995: =item *
13996:
13997: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13998:
13999: =item *
14000:
14001: reply() : uses subreply to send a message to remote machine, logs all failures
14002:
14003: =item *
14004:
14005: critical() : passes a critical message to another server; if cannot
14006: get through then place message in connection buffer directory and
14007: returns con_delayed, if incapable of saving message, returns
14008: con_failed
14009:
14010: =item *
14011:
14012: reconlonc() : tries to reconnect lonc client processes.
14013:
14014: =back
14015:
14016: =head2 Resource Access Logging
14017:
14018: =over 4
14019:
14020: =item *
14021:
14022: flushcourselogs() : flush (save) buffer logs and access logs
14023:
14024: =item *
14025:
14026: courselog($what) : save message for course in hash
14027:
14028: =item *
14029:
14030: courseacclog($what) : save message for course using &courselog(). Perform
14031: special processing for specific resource types (problems, exams, quizzes, etc).
14032:
1.191 harris41 14033: =item *
14034:
14035: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14036: as a PerlChildExitHandler
1.243 albertel 14037:
14038: =back
14039:
14040: =head2 Other
14041:
14042: =over 4
14043:
14044: =item *
14045:
14046: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14047:
14048: =back
14049:
14050: =cut
1.877 foxr 14051:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>