Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.56
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.56! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.55 2014/10/13 15:47:14 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;
1.1172.2.56! raeburn 6066: if ($idtype eq 'addcode') {
! 6067: $newid .= &sixnum_code();
! 6068: }
1.1172.2.13 raeburn 6069: my $idtries = 0;
6070: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6071: if ($idtype eq 'concat') {
6072: $newid = $id.$idtries;
1.1172.2.56! raeburn 6073: } elsif ($idtype eq 'addcode') {
! 6074: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6075: } else {
6076: $newid ++;
6077: }
6078: $idtries ++;
6079: }
6080: if (!exists($inuse{$prefix."\0".$newid})) {
6081: my %new_item = (
6082: $prefix."\0".$newid => $who,
6083: );
6084: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6085: $cdom,$cnum);
6086: if ($putresult ne 'ok') {
6087: undef($newid);
6088: $error = 'error saving new item: '.$putresult;
6089: }
6090: } else {
1.1172.2.56! raeburn 6091: undef($newid);
1.1172.2.13 raeburn 6092: $error = ('error: no unique suffix available for the new item ');
6093: }
6094: # remove lock
6095: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6096: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6097: } else {
6098: $error = "error: could not obtain lockfile\n";
6099: $dellock = 'ok';
6100: }
6101: return ($newid,$dellock,$error);
6102: }
6103:
1.1172.2.56! raeburn 6104: sub sixnum_code {
! 6105: my $code;
! 6106: for (0..6) {
! 6107: $code .= int( rand(9) );
! 6108: }
! 6109: return $code;
! 6110: }
! 6111:
1.765 albertel 6112: # -------------------------------------------------- portfolio access checking
6113:
6114: sub portfolio_access {
1.766 albertel 6115: my ($requrl) = @_;
1.765 albertel 6116: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6117: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6118: if ($result) {
6119: my %setters;
6120: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6121: my ($startblock,$endblock) =
6122: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6123: if ($startblock && $endblock) {
6124: return 'B';
6125: }
6126: } else {
6127: my ($startblock,$endblock) =
6128: &Apache::loncommon::blockcheck(\%setters,'port');
6129: if ($startblock && $endblock) {
6130: return 'B';
6131: }
6132: }
6133: }
1.765 albertel 6134: if ($result eq 'ok') {
1.766 albertel 6135: return 'F';
1.765 albertel 6136: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6137: return 'A';
1.765 albertel 6138: }
1.766 albertel 6139: return '';
1.765 albertel 6140: }
6141:
6142: sub get_portfolio_access {
1.767 albertel 6143: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6144:
6145: if (!ref($access_hash)) {
6146: my $current_perms = &get_portfile_permissions($udom,$unum);
6147: my %access_controls = &get_access_controls($current_perms,$group,
6148: $file_name);
6149: $access_hash = $access_controls{$file_name};
6150: }
6151:
1.765 albertel 6152: my ($public,$guest,@domains,@users,@courses,@groups);
6153: my $now = time;
6154: if (ref($access_hash) eq 'HASH') {
6155: foreach my $key (keys(%{$access_hash})) {
6156: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6157: if ($start > $now) {
6158: next;
6159: }
6160: if ($end && $end<$now) {
6161: next;
6162: }
6163: if ($scope eq 'public') {
6164: $public = $key;
6165: last;
6166: } elsif ($scope eq 'guest') {
6167: $guest = $key;
6168: } elsif ($scope eq 'domains') {
6169: push(@domains,$key);
6170: } elsif ($scope eq 'users') {
6171: push(@users,$key);
6172: } elsif ($scope eq 'course') {
6173: push(@courses,$key);
6174: } elsif ($scope eq 'group') {
6175: push(@groups,$key);
6176: }
6177: }
6178: if ($public) {
6179: return 'ok';
6180: }
6181: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6182: if ($guest) {
6183: return $guest;
6184: }
6185: } else {
6186: if (@domains > 0) {
6187: foreach my $domkey (@domains) {
6188: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6189: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6190: return 'ok';
6191: }
6192: }
6193: }
6194: }
6195: if (@users > 0) {
6196: foreach my $userkey (@users) {
1.865 raeburn 6197: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6198: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6199: if (ref($item) eq 'HASH') {
6200: if (($item->{'uname'} eq $env{'user.name'}) &&
6201: ($item->{'udom'} eq $env{'user.domain'})) {
6202: return 'ok';
6203: }
6204: }
6205: }
6206: }
1.765 albertel 6207: }
6208: }
6209: my %roleshash;
6210: my @courses_and_groups = @courses;
6211: push(@courses_and_groups,@groups);
6212: if (@courses_and_groups > 0) {
6213: my (%allgroups,%allroles);
6214: my ($start,$end,$role,$sec,$group);
6215: foreach my $envkey (%env) {
1.1060 raeburn 6216: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6217: my $cid = $2.'_'.$3;
6218: if ($1 eq 'gr') {
6219: $group = $4;
6220: $allgroups{$cid}{$group} = $env{$envkey};
6221: } else {
6222: if ($4 eq '') {
6223: $sec = 'none';
6224: } else {
6225: $sec = $4;
6226: }
6227: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6228: }
1.811 albertel 6229: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6230: my $cid = $2.'_'.$3;
6231: if ($4 eq '') {
6232: $sec = 'none';
6233: } else {
6234: $sec = $4;
6235: }
6236: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6237: }
6238: }
6239: if (keys(%allroles) == 0) {
6240: return;
6241: }
6242: foreach my $key (@courses_and_groups) {
6243: my %content = %{$$access_hash{$key}};
6244: my $cnum = $content{'number'};
6245: my $cdom = $content{'domain'};
6246: my $cid = $cdom.'_'.$cnum;
6247: if (!exists($allroles{$cid})) {
6248: next;
6249: }
6250: foreach my $role_id (keys(%{$content{'roles'}})) {
6251: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6252: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6253: my @status = @{$content{'roles'}{$role_id}{'access'}};
6254: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6255: foreach my $role (keys(%{$allroles{$cid}})) {
6256: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6257: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6258: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6259: if (grep/^all$/,@sections) {
6260: return 'ok';
6261: } else {
6262: if (grep/^$sec$/,@sections) {
6263: return 'ok';
6264: }
6265: }
6266: }
6267: }
6268: if (keys(%{$allgroups{$cid}}) == 0) {
6269: if (grep/^none$/,@groups) {
6270: return 'ok';
6271: }
6272: } else {
6273: if (grep/^all$/,@groups) {
6274: return 'ok';
6275: }
6276: foreach my $group (keys(%{$allgroups{$cid}})) {
6277: if (grep/^$group$/,@groups) {
6278: return 'ok';
6279: }
6280: }
6281: }
6282: }
6283: }
6284: }
6285: }
6286: }
6287: if ($guest) {
6288: return $guest;
6289: }
6290: }
6291: }
6292: return;
6293: }
6294:
6295: sub course_group_datechecker {
6296: my ($dates,$now,$status) = @_;
6297: my ($start,$end) = split(/\./,$dates);
6298: if (!$start && !$end) {
6299: return 'ok';
6300: }
6301: if (grep/^active$/,@{$status}) {
6302: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6303: return 'ok';
6304: }
6305: }
6306: if (grep/^previous$/,@{$status}) {
6307: if ($end > $now ) {
6308: return 'ok';
6309: }
6310: }
6311: if (grep/^future$/,@{$status}) {
6312: if ($start > $now) {
6313: return 'ok';
6314: }
6315: }
6316: return;
6317: }
6318:
6319: sub parse_portfolio_url {
6320: my ($url) = @_;
6321:
6322: my ($type,$udom,$unum,$group,$file_name);
6323:
1.823 albertel 6324: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6325: $type = 1;
6326: $udom = $1;
6327: $unum = $2;
6328: $file_name = $3;
1.823 albertel 6329: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6330: $type = 2;
6331: $udom = $1;
6332: $unum = $2;
6333: $group = $3;
6334: $file_name = $3.'/'.$4;
6335: }
6336: if (wantarray) {
6337: return ($type,$udom,$unum,$file_name,$group);
6338: }
6339: return $type;
6340: }
6341:
6342: sub is_portfolio_url {
6343: my ($url) = @_;
6344: return scalar(&parse_portfolio_url($url));
6345: }
6346:
1.798 raeburn 6347: sub is_portfolio_file {
6348: my ($file) = @_;
1.820 raeburn 6349: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6350: return 1;
6351: }
6352: return;
6353: }
6354:
1.976 raeburn 6355: sub usertools_access {
1.1084 raeburn 6356: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6357: my ($access,%tools);
6358: if ($context eq '') {
6359: $context = 'tools';
6360: }
6361: if ($context eq 'requestcourses') {
6362: %tools = (
6363: official => 1,
6364: unofficial => 1,
1.1006 raeburn 6365: community => 1,
1.1172.2.37 raeburn 6366: textbook => 1,
1.985 raeburn 6367: );
1.1172.2.9 raeburn 6368: } elsif ($context eq 'requestauthor') {
6369: %tools = (
6370: requestauthor => 1,
6371: );
1.985 raeburn 6372: } else {
6373: %tools = (
6374: aboutme => 1,
6375: blog => 1,
1.1172.2.6 raeburn 6376: webdav => 1,
1.985 raeburn 6377: portfolio => 1,
6378: );
6379: }
1.976 raeburn 6380: return if (!defined($tools{$tool}));
6381:
1.1172.2.35 raeburn 6382: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6383: $udom = $env{'user.domain'};
6384: $uname = $env{'user.name'};
6385: }
6386:
1.978 raeburn 6387: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6388: if ($action ne 'reload') {
1.985 raeburn 6389: if ($context eq 'requestcourses') {
6390: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6391: } elsif ($context eq 'requestauthor') {
6392: return $env{'environment.canrequest.author'};
1.985 raeburn 6393: } else {
6394: return $env{'environment.availabletools.'.$tool};
6395: }
6396: }
1.976 raeburn 6397: }
6398:
1.1172.2.9 raeburn 6399: my ($toolstatus,$inststatus,$envkey);
6400: if ($context eq 'requestauthor') {
6401: $envkey = $context;
6402: } else {
6403: $envkey = $context.'.'.$tool;
6404: }
1.976 raeburn 6405:
1.985 raeburn 6406: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6407: ($action ne 'reload')) {
1.1172.2.9 raeburn 6408: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6409: $inststatus = $env{'environment.inststatus'};
6410: } else {
1.1084 raeburn 6411: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6412: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6413: $inststatus = $userenvref->{'inststatus'};
6414: } else {
1.1172.2.9 raeburn 6415: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6416: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6417: $inststatus = $userenv{'inststatus'};
6418: }
1.976 raeburn 6419: }
6420:
6421: if ($toolstatus ne '') {
6422: if ($toolstatus) {
6423: $access = 1;
6424: } else {
6425: $access = 0;
6426: }
6427: return $access;
6428: }
6429:
1.1084 raeburn 6430: my ($is_adv,%domdef);
6431: if (ref($is_advref) eq 'HASH') {
6432: $is_adv = $is_advref->{'is_adv'};
6433: } else {
6434: $is_adv = &is_advanced_user($udom,$uname);
6435: }
6436: if (ref($domdefref) eq 'HASH') {
6437: %domdef = %{$domdefref};
6438: } else {
6439: %domdef = &get_domain_defaults($udom);
6440: }
1.976 raeburn 6441: if (ref($domdef{$tool}) eq 'HASH') {
6442: if ($is_adv) {
6443: if ($domdef{$tool}{'_LC_adv'} ne '') {
6444: if ($domdef{$tool}{'_LC_adv'}) {
6445: $access = 1;
6446: } else {
6447: $access = 0;
6448: }
6449: return $access;
6450: }
6451: }
6452: if ($inststatus ne '') {
6453: my ($hasaccess,$hasnoaccess);
6454: foreach my $affiliation (split(/:/,$inststatus)) {
6455: if ($domdef{$tool}{$affiliation} ne '') {
6456: if ($domdef{$tool}{$affiliation}) {
6457: $hasaccess = 1;
6458: } else {
6459: $hasnoaccess = 1;
6460: }
6461: }
6462: }
6463: if ($hasaccess || $hasnoaccess) {
6464: if ($hasaccess) {
6465: $access = 1;
6466: } elsif ($hasnoaccess) {
6467: $access = 0;
6468: }
6469: return $access;
6470: }
6471: } else {
6472: if ($domdef{$tool}{'default'} ne '') {
6473: if ($domdef{$tool}{'default'}) {
6474: $access = 1;
6475: } elsif ($domdef{$tool}{'default'} == 0) {
6476: $access = 0;
6477: }
6478: return $access;
6479: }
6480: }
6481: } else {
1.1172.2.6 raeburn 6482: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6483: $access = 1;
6484: } else {
6485: $access = 0;
6486: }
1.976 raeburn 6487: return $access;
6488: }
6489: }
6490:
1.1050 raeburn 6491: sub is_course_owner {
6492: my ($cdom,$cnum,$udom,$uname) = @_;
6493: if (($udom eq '') || ($uname eq '')) {
6494: $udom = $env{'user.domain'};
6495: $uname = $env{'user.name'};
6496: }
6497: unless (($udom eq '') || ($uname eq '')) {
6498: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6499: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6500: return 1;
6501: } else {
6502: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6503: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6504: return 1;
6505: }
6506: }
6507: }
6508: }
6509: return;
6510: }
6511:
1.976 raeburn 6512: sub is_advanced_user {
6513: my ($udom,$uname) = @_;
1.1085 raeburn 6514: if ($udom ne '' && $uname ne '') {
6515: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6516: if (wantarray) {
6517: return ($env{'user.adv'},$env{'user.author'});
6518: } else {
6519: return $env{'user.adv'};
6520: }
1.1085 raeburn 6521: }
6522: }
1.976 raeburn 6523: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6524: my %allroles;
1.1128 raeburn 6525: my ($is_adv,$is_author);
1.976 raeburn 6526: foreach my $role (keys(%roleshash)) {
6527: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6528: my $area = '/'.$tdomain.'/'.$trest;
6529: if ($sec ne '') {
6530: $area .= '/'.$sec;
6531: }
6532: if (($area ne '') && ($trole ne '')) {
6533: my $spec=$trole.'.'.$area;
6534: if ($trole =~ /^cr\//) {
6535: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6536: } elsif ($trole ne 'gr') {
6537: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6538: }
1.1128 raeburn 6539: if ($trole eq 'au') {
6540: $is_author = 1;
6541: }
1.976 raeburn 6542: }
6543: }
6544: foreach my $role (keys(%allroles)) {
6545: last if ($is_adv);
6546: foreach my $item (split(/:/,$allroles{$role})) {
6547: if ($item ne '') {
6548: my ($privilege,$restrictions)=split(/&/,$item);
6549: if ($privilege eq 'adv') {
6550: $is_adv = 1;
6551: last;
6552: }
6553: }
6554: }
6555: }
1.1128 raeburn 6556: if (wantarray) {
6557: return ($is_adv,$is_author);
6558: }
1.976 raeburn 6559: return $is_adv;
6560: }
1.798 raeburn 6561:
1.1035 raeburn 6562: sub check_can_request {
1.1036 raeburn 6563: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6564: my $canreq = 0;
6565: my ($types,$typename) = &Apache::loncommon::course_types();
6566: my @options = ('approval','validate','autolimit');
6567: my $optregex = join('|',@options);
6568: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6569: foreach my $type (@{$types}) {
6570: if (&usertools_access($env{'user.name'},
6571: $env{'user.domain'},
6572: $type,undef,'requestcourses')) {
6573: $canreq ++;
1.1036 raeburn 6574: if (ref($request_domains) eq 'HASH') {
6575: push(@{$request_domains->{$type}},$env{'user.domain'});
6576: }
1.1035 raeburn 6577: if ($dom eq $env{'user.domain'}) {
6578: $can_request->{$type} = 1;
6579: }
6580: }
6581: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6582: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6583: if (@curr > 0) {
1.1036 raeburn 6584: foreach my $item (@curr) {
6585: if (ref($request_domains) eq 'HASH') {
6586: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6587: if ($otherdom ne '') {
6588: if (ref($request_domains->{$type}) eq 'ARRAY') {
6589: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6590: push(@{$request_domains->{$type}},$otherdom);
6591: }
6592: } else {
6593: push(@{$request_domains->{$type}},$otherdom);
6594: }
6595: }
6596: }
6597: }
6598: unless($dom eq $env{'user.domain'}) {
6599: $canreq ++;
1.1035 raeburn 6600: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6601: $can_request->{$type} = 1;
6602: }
6603: }
6604: }
6605: }
6606: }
6607: }
6608: return $canreq;
6609: }
6610:
1.341 www 6611: # ---------------------------------------------- Custom access rule evaluation
6612:
6613: sub customaccess {
6614: my ($priv,$uri)=@_;
1.807 albertel 6615: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6616: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6617: $udom = &LONCAPA::clean_domain($udom);
6618: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6619: my $access=0;
1.800 albertel 6620: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6621: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6622: if ($type eq 'user') {
6623: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6624: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6625: if ($tdom) {
6626: if ($tdom ne $env{'user.domain'}) { next; }
6627: }
1.896 albertel 6628: if ($tuname) {
6629: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6630: }
6631: $access=($effect eq 'allow');
6632: last;
6633: }
6634: } else {
6635: if ($role) {
6636: if ($role ne $urole) { next; }
6637: }
6638: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6639: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6640: if ($tdom) {
6641: if ($tdom ne $udom) { next; }
6642: }
6643: if ($tcrs) {
6644: if ($tcrs ne $ucrs) { next; }
6645: }
6646: if ($tsec) {
6647: if ($tsec ne $usec) { next; }
6648: }
6649: $access=($effect eq 'allow');
6650: last;
6651: }
6652: if ($realm eq '' && $role eq '') {
6653: $access=($effect eq 'allow');
6654: }
1.402 bowersj2 6655: }
1.341 www 6656: }
6657: return $access;
6658: }
6659:
1.103 harris41 6660: # ------------------------------------------------- Check for a user privilege
1.12 www 6661:
6662: sub allowed {
1.810 raeburn 6663: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6664: my $ver_orguri=$uri;
1.439 www 6665: $uri=&deversion($uri);
1.152 www 6666: my $orguri=$uri;
1.52 www 6667: $uri=&declutter($uri);
1.809 raeburn 6668:
1.810 raeburn 6669: if ($priv eq 'evb') {
6670: # Evade communication block restrictions for specified role in a course
6671: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6672: return $1;
6673: } else {
6674: return;
6675: }
6676: }
6677:
1.620 albertel 6678: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6679: # Free bre access to adm and meta resources
1.775 albertel 6680: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6681: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6682: && ($priv eq 'bre')) {
1.14 www 6683: return 'F';
1.159 www 6684: }
6685:
1.545 banghart 6686: # Free bre access to user's own portfolio contents
1.714 raeburn 6687: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6688: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6689: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6690: my %setters;
6691: my ($startblock,$endblock) =
6692: &Apache::loncommon::blockcheck(\%setters,'port');
6693: if ($startblock && $endblock) {
6694: return 'B';
6695: } else {
6696: return 'F';
6697: }
1.545 banghart 6698: }
6699:
1.762 raeburn 6700: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6701: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6702: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6703: if (exists($env{'request.course.id'})) {
6704: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6705: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6706: if (($domain eq $cdom) && ($name eq $cnum)) {
6707: my $courseprivid=$env{'request.course.id'};
6708: $courseprivid=~s/\_/\//;
6709: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6710: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6711: return $1;
1.762 raeburn 6712: } else {
6713: if ($env{'request.course.sec'}) {
6714: $courseprivid.='/'.$env{'request.course.sec'};
6715: }
6716: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6717: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6718: return $2;
6719: }
1.714 raeburn 6720: }
6721: }
6722: }
6723: }
6724:
1.159 www 6725: # Free bre to public access
6726:
6727: if ($priv eq 'bre') {
1.238 www 6728: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6729: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6730: return 'F';
6731: }
1.238 www 6732: if ($copyright eq 'priv') {
6733: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6734: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6735: return '';
6736: }
6737: }
6738: if ($copyright eq 'domain') {
6739: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6740: unless (($env{'user.domain'} eq $1) ||
6741: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6742: return '';
6743: }
1.262 matthew 6744: }
1.620 albertel 6745: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6746: # Library role, so allow browsing of resources in this domain.
6747: return 'F';
1.238 www 6748: }
1.341 www 6749: if ($copyright eq 'custom') {
6750: unless (&customaccess($priv,$uri)) { return ''; }
6751: }
1.14 www 6752: }
1.264 matthew 6753: # Domain coordinator is trying to create a course
1.620 albertel 6754: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6755: # uri is the requested domain in this case.
6756: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6757: # a role of dc for the domain in question.
1.620 albertel 6758: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6759: }
1.29 www 6760:
1.52 www 6761: my $thisallowed='';
6762: my $statecond=0;
6763: my $courseprivid='';
6764:
1.1039 raeburn 6765: my $ownaccess;
1.1043 raeburn 6766: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6767: if (($priv eq 'bro') && ($env{'user.author'})) {
6768: if ($uri eq '') {
6769: $ownaccess = 1;
6770: } else {
6771: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6772: my $udom = $env{'user.domain'};
6773: my $uname = $env{'user.name'};
6774: if ($uri =~ m{^\Q$udom\E/?$}) {
6775: $ownaccess = 1;
1.1040 raeburn 6776: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6777: unless ($uri =~ m{\.\./}) {
6778: $ownaccess = 1;
6779: }
6780: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6781: my $now = time;
6782: if ($uri =~ m{^([^/]+)/?$}) {
6783: my $adom = $1;
6784: foreach my $key (keys(%env)) {
1.1042 raeburn 6785: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6786: my ($start,$end) = split('.',$env{$key});
6787: if (($now >= $start) && (!$end || $end < $now)) {
6788: $ownaccess = 1;
6789: last;
6790: }
6791: }
6792: }
6793: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6794: my $adom = $1;
6795: my $aname = $2;
1.1042 raeburn 6796: foreach my $role ('ca','aa') {
6797: if ($env{"user.role.$role./$adom/$aname"}) {
6798: my ($start,$end) =
6799: split('.',$env{"user.role.$role./$adom/$aname"});
6800: if (($now >= $start) && (!$end || $end < $now)) {
6801: $ownaccess = 1;
6802: last;
6803: }
1.1039 raeburn 6804: }
6805: }
6806: }
6807: }
6808: }
6809: }
6810: }
6811:
1.52 www 6812: # Course
6813:
1.620 albertel 6814: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6815: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6816: $thisallowed.=$1;
6817: }
1.52 www 6818: }
1.29 www 6819:
1.52 www 6820: # Domain
6821:
1.620 albertel 6822: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6823: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6824: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6825: $thisallowed.=$1;
6826: }
1.12 www 6827: }
1.52 www 6828:
1.1141 raeburn 6829: # User who is not author or co-author might still be able to edit
6830: # resource of an author in the domain (e.g., if Domain Coordinator).
6831: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6832: (&allowed('mdc',$env{'request.course.id'}))) {
6833: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6834: $thisallowed.=$1;
6835: }
6836: }
6837:
1.52 www 6838: # Course: uri itself is a course
1.66 www 6839: my $courseuri=$uri;
6840: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6841: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6842:
1.620 albertel 6843: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6844: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6845: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6846: $thisallowed.=$1;
6847: }
1.12 www 6848: }
1.29 www 6849:
1.665 albertel 6850: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6851: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6852: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6853: $thisallowed='';
1.671 raeburn 6854: my ($match)=&is_on_map($uri);
6855: if ($match) {
6856: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6857: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6858: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6859: if (@blockers > 0) {
6860: $thisallowed = 'B';
6861: } else {
6862: $thisallowed.=$1;
6863: }
1.671 raeburn 6864: }
6865: } else {
1.705 albertel 6866: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6867: if ($refuri) {
6868: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6869: $thisallowed='F';
1.671 raeburn 6870: } else {
6871: $refuri=&declutter($refuri);
6872: my ($match) = &is_on_map($refuri);
6873: if ($match) {
1.1162 raeburn 6874: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6875: if (@blockers > 0) {
6876: $thisallowed = 'B';
6877: } else {
6878: $thisallowed='F';
6879: }
1.671 raeburn 6880: }
1.669 raeburn 6881: }
1.671 raeburn 6882: }
6883: }
1.314 www 6884: }
1.492 albertel 6885:
1.766 albertel 6886: if ($priv eq 'bre'
6887: && $thisallowed ne 'F'
6888: && $thisallowed ne '2'
6889: && &is_portfolio_url($uri)) {
6890: $thisallowed = &portfolio_access($uri);
6891: }
6892:
1.52 www 6893: # Full access at system, domain or course-wide level? Exit.
1.29 www 6894: if ($thisallowed=~/F/) {
6895: return 'F';
6896: }
6897:
1.52 www 6898: # If this is generating or modifying users, exit with special codes
1.29 www 6899:
1.643 www 6900: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6901: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6902: my ($audom,$auname)=split('/',$uri);
1.643 www 6903: # no author name given, so this just checks on the general right to make a co-author in this domain
6904: unless ($auname) { return $thisallowed; }
6905: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6906: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6907: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6908: ($audom ne $env{'request.role.domain'}))) { return ''; }
6909: }
1.52 www 6910: return $thisallowed;
6911: }
6912: #
1.103 harris41 6913: # Gathered so far: system, domain and course wide privileges
1.52 www 6914: #
6915: # Course: See if uri or referer is an individual resource that is part of
6916: # the course
6917:
1.620 albertel 6918: if ($env{'request.course.id'}) {
1.232 www 6919:
1.620 albertel 6920: $courseprivid=$env{'request.course.id'};
6921: if ($env{'request.course.sec'}) {
6922: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6923: }
6924: $courseprivid=~s/\_/\//;
6925: my $checkreferer=1;
1.232 www 6926: my ($match,$cond)=&is_on_map($uri);
6927: if ($match) {
6928: $statecond=$cond;
1.620 albertel 6929: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6930: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6931: my $value = $1;
6932: if ($priv eq 'bre') {
6933: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6934: if (@blockers > 0) {
6935: $thisallowed = 'B';
6936: } else {
6937: $thisallowed.=$value;
6938: }
6939: } else {
6940: $thisallowed.=$value;
6941: }
1.52 www 6942: $checkreferer=0;
6943: }
1.29 www 6944: }
1.83 www 6945:
1.148 www 6946: if ($checkreferer) {
1.620 albertel 6947: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6948: unless ($refuri) {
1.800 albertel 6949: foreach my $key (keys(%env)) {
6950: if ($key=~/^httpref\..*\*/) {
6951: my $pattern=$key;
1.156 www 6952: $pattern=~s/^httpref\.\/res\///;
1.148 www 6953: $pattern=~s/\*/\[\^\/\]\+/g;
6954: $pattern=~s/\//\\\//g;
1.152 www 6955: if ($orguri=~/$pattern/) {
1.800 albertel 6956: $refuri=$env{$key};
1.148 www 6957: }
6958: }
1.191 harris41 6959: }
1.148 www 6960: }
1.232 www 6961:
1.148 www 6962: if ($refuri) {
1.152 www 6963: $refuri=&declutter($refuri);
1.232 www 6964: my ($match,$cond)=&is_on_map($refuri);
6965: if ($match) {
6966: my $refstatecond=$cond;
1.620 albertel 6967: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6968: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6969: my $value = $1;
6970: if ($priv eq 'bre') {
6971: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6972: if (@blockers > 0) {
6973: $thisallowed = 'B';
6974: } else {
6975: $thisallowed.=$value;
6976: }
6977: } else {
6978: $thisallowed.=$value;
6979: }
1.53 www 6980: $uri=$refuri;
6981: $statecond=$refstatecond;
1.52 www 6982: }
6983: }
1.148 www 6984: }
1.29 www 6985: }
1.52 www 6986: }
1.29 www 6987:
1.52 www 6988: #
1.103 harris41 6989: # Gathered now: all privileges that could apply, and condition number
1.52 www 6990: #
6991: #
6992: # Full or no access?
6993: #
1.29 www 6994:
1.52 www 6995: if ($thisallowed=~/F/) {
6996: return 'F';
6997: }
1.29 www 6998:
1.52 www 6999: unless ($thisallowed) {
7000: return '';
7001: }
1.29 www 7002:
1.52 www 7003: # Restrictions exist, deal with them
7004: #
7005: # C:according to course preferences
7006: # R:according to resource settings
7007: # L:unless locked
7008: # X:according to user session state
7009: #
7010:
7011: # Possibly locked functionality, check all courses
1.54 www 7012: # Locks might take effect only after 10 minutes cache expiration for other
7013: # courses, and 2 minutes for current course
1.52 www 7014:
7015: my $envkey;
7016: if ($thisallowed=~/L/) {
1.1000 raeburn 7017: foreach $envkey (keys(%env)) {
1.54 www 7018: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7019: my $courseid=$2;
7020: my $roleid=$1.'.'.$2;
1.92 www 7021: $courseid=~s/^\///;
1.54 www 7022: my $expiretime=600;
1.620 albertel 7023: if ($env{'request.role'} eq $roleid) {
1.54 www 7024: $expiretime=120;
7025: }
7026: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7027: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7028: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7029: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7030: }
1.620 albertel 7031: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7032: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7033: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7034: &log($env{'user.domain'},$env{'user.name'},
7035: $env{'user.home'},
1.57 www 7036: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7037: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7038: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7039: return '';
7040: }
7041: }
1.620 albertel 7042: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7043: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7044: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7045: &log($env{'user.domain'},$env{'user.name'},
7046: $env{'user.home'},
1.57 www 7047: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7048: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7049: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7050: return '';
7051: }
7052: }
7053: }
1.29 www 7054: }
1.52 www 7055: }
7056:
7057: #
7058: # Rest of the restrictions depend on selected course
7059: #
7060:
1.620 albertel 7061: unless ($env{'request.course.id'}) {
1.766 albertel 7062: if ($thisallowed eq 'A') {
7063: return 'A';
1.814 raeburn 7064: } elsif ($thisallowed eq 'B') {
7065: return 'B';
1.766 albertel 7066: } else {
7067: return '1';
7068: }
1.52 www 7069: }
1.29 www 7070:
1.52 www 7071: #
7072: # Now user is definitely in a course
7073: #
1.53 www 7074:
7075:
7076: # Course preferences
7077:
7078: if ($thisallowed=~/C/) {
1.620 albertel 7079: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7080: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7081: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7082: =~/\Q$rolecode\E/) {
1.1103 raeburn 7083: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7084: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7085: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7086: $env{'request.course.id'});
7087: }
1.237 www 7088: return '';
7089: }
7090:
1.620 albertel 7091: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7092: =~/\Q$unamedom\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 user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7096: $env{'request.course.id'});
7097: }
1.54 www 7098: return '';
7099: }
1.53 www 7100: }
7101:
7102: # Resource preferences
7103:
7104: if ($thisallowed=~/R/) {
1.620 albertel 7105: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7106: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7107: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7108: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7109: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7110: }
7111: return '';
1.54 www 7112: }
1.53 www 7113: }
1.30 www 7114:
1.246 www 7115: # Restricted by state or randomout?
1.30 www 7116:
1.52 www 7117: if ($thisallowed=~/X/) {
1.620 albertel 7118: if ($env{'acc.randomout'}) {
1.579 albertel 7119: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7120: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7121: return '';
7122: }
1.247 www 7123: }
7124: if (&condval($statecond)) {
1.52 www 7125: return '2';
7126: } else {
7127: return '';
7128: }
7129: }
1.30 www 7130:
1.766 albertel 7131: if ($thisallowed eq 'A') {
7132: return 'A';
1.814 raeburn 7133: } elsif ($thisallowed eq 'B') {
7134: return 'B';
1.766 albertel 7135: }
1.52 www 7136: return 'F';
1.232 www 7137: }
1.1162 raeburn 7138:
1.1172.2.13 raeburn 7139: # ------------------------------------------- Check construction space access
7140:
7141: sub constructaccess {
7142: my ($url,$setpriv)=@_;
7143:
7144: # We do not allow editing of previous versions of files
7145: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7146:
7147: # Get username and domain from URL
7148: my ($ownername,$ownerdomain,$ownerhome);
7149:
7150: ($ownerdomain,$ownername) =
7151: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7152:
7153: # The URL does not really point to any authorspace, forget it
7154: unless (($ownername) && ($ownerdomain)) { return ''; }
7155:
7156: # Now we need to see if the user has access to the authorspace of
7157: # $ownername at $ownerdomain
7158:
7159: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7160: # Real author for this?
7161: $ownerhome = $env{'user.home'};
7162: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7163: return ($ownername,$ownerdomain,$ownerhome);
7164: }
7165: } else {
7166: # Co-author for this?
7167: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7168: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7169: $ownerhome = &homeserver($ownername,$ownerdomain);
7170: return ($ownername,$ownerdomain,$ownerhome);
7171: }
7172: }
7173:
7174: # We don't have any access right now. If we are not possibly going to do anything about this,
7175: # we might as well leave
7176: unless ($setpriv) { return ''; }
7177:
7178: # Backdoor access?
7179: my $allowed=&allowed('eco',$ownerdomain);
7180: # Nope
7181: unless ($allowed) { return ''; }
7182: # Looks like we may have access, but could be locked by the owner of the construction space
7183: if ($allowed eq 'U') {
7184: my %blocked=&get('environment',['domcoord.author'],
7185: $ownerdomain,$ownername);
7186: # Is blocked by owner
7187: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7188: }
7189: if (($allowed eq 'F') || ($allowed eq 'U')) {
7190: # Grant temporary access
7191: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7192: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7193: if (!$update) { $update = $then; }
7194: my $refresh=$env{'user.refresh.time'};
7195: if (!$refresh) { $refresh = $update; }
7196: my $now = time;
7197: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7198: $now,'ca','constructaccess');
7199: $ownerhome = &homeserver($ownername,$ownerdomain);
7200: return($ownername,$ownerdomain,$ownerhome);
7201: }
7202: # No business here
7203: return '';
7204: }
7205:
1.1162 raeburn 7206: sub get_comm_blocks {
7207: my ($cdom,$cnum) = @_;
7208: if ($cdom eq '' || $cnum eq '') {
7209: return unless ($env{'request.course.id'});
7210: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7211: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7212: }
7213: my %commblocks;
7214: my $hashid=$cdom.'_'.$cnum;
7215: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7216: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7217: %commblocks = %{$blocksref};
7218: } else {
7219: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7220: my $cachetime = 600;
7221: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7222: }
7223: return %commblocks;
7224: }
7225:
7226: sub has_comm_blocking {
7227: my ($priv,$symb,$uri,$blocks) = @_;
7228: return unless ($env{'request.course.id'});
7229: return unless ($priv eq 'bre');
7230: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7231: my %commblocks;
7232: if (ref($blocks) eq 'HASH') {
7233: %commblocks = %{$blocks};
7234: } else {
7235: %commblocks = &get_comm_blocks();
7236: }
7237: return unless (keys(%commblocks) > 0);
7238: if (!$symb) { $symb=&symbread($uri,1); }
7239: my ($map,$resid,undef)=&decode_symb($symb);
7240: my %tocheck = (
7241: maps => $map,
7242: resources => $symb,
7243: );
7244: my @blockers;
7245: my $now = time;
1.1163 raeburn 7246: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7247: foreach my $block (keys(%commblocks)) {
7248: if ($block =~ /^(\d+)____(\d+)$/) {
7249: my ($start,$end) = ($1,$2);
7250: if ($start <= $now && $end >= $now) {
7251: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7252: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7253: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7254: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7255: unless (grep(/^\Q$block\E$/,@blockers)) {
7256: push(@blockers,$block);
7257: }
7258: }
7259: }
7260: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7261: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7262: unless (grep(/^\Q$block\E$/,@blockers)) {
7263: push(@blockers,$block);
7264: }
7265: }
7266: }
7267: }
7268: }
7269: }
7270: } elsif ($block =~ /^firstaccess____(.+)$/) {
7271: my $item = $1;
1.1163 raeburn 7272: my @to_test;
1.1162 raeburn 7273: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7274: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7275: my $check_interval;
7276: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7277: my @interval;
7278: my $type = 'map';
7279: if ($item eq 'course') {
7280: $type = 'course';
7281: @interval=&EXT("resource.0.interval");
7282: } else {
7283: if ($item =~ /___\d+___/) {
7284: $type = 'resource';
7285: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7286: if (ref($navmap)) {
7287: my $res = $navmap->getBySymb($item);
7288: push(@to_test,$res);
7289: }
1.1162 raeburn 7290: } else {
7291: my $mapsymb = &symbread($item,1);
7292: if ($mapsymb) {
7293: if (ref($navmap)) {
7294: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7295: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7296: foreach my $res (@to_test) {
1.1162 raeburn 7297: my $symb = $res->symb();
7298: next if ($symb eq $mapsymb);
7299: if ($symb ne '') {
7300: @interval=&EXT("resource.0.interval",$symb);
7301: last;
7302: }
7303: }
7304: }
7305: }
7306: }
7307: }
7308: if ($interval[0] =~ /\d+/) {
7309: my $first_access;
7310: if ($type eq 'resource') {
7311: $first_access=&get_first_access($interval[1],$item);
7312: } elsif ($type eq 'map') {
7313: $first_access=&get_first_access($interval[1],undef,$item);
7314: } else {
7315: $first_access=&get_first_access($interval[1]);
7316: }
7317: if ($first_access) {
7318: my $timesup = $first_access+$interval[0];
7319: if ($timesup > $now) {
1.1163 raeburn 7320: foreach my $res (@to_test) {
7321: if ($res->is_problem()) {
7322: if ($res->completable()) {
7323: unless (grep(/^\Q$block\E$/,@blockers)) {
7324: push(@blockers,$block);
7325: }
7326: last;
7327: }
7328: }
1.1162 raeburn 7329: }
7330: }
7331: }
7332: }
7333: }
7334: }
7335: }
7336: }
7337: }
7338: return @blockers;
7339: }
7340:
7341: sub check_docs_block {
7342: my ($docsblock,$tocheck) =@_;
7343: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7344: return;
7345: }
7346: if (ref($docsblock->{'maps'}) eq 'HASH') {
7347: if ($tocheck->{'maps'}) {
7348: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7349: return 1;
7350: }
7351: }
7352: }
7353: if (ref($docsblock->{'resources'}) eq 'HASH') {
7354: if ($tocheck->{'resources'}) {
7355: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7356: return 1;
7357: }
7358: }
7359: }
7360: return;
7361: }
7362:
1.1133 foxr 7363: #
7364: # Removes the versino from a URI and
7365: # splits it in to its filename and path to the filename.
7366: # Seems like File::Basename could have done this more clearly.
7367: # Parameters:
7368: # $uri - input URI
7369: # Returns:
7370: # Two element list consisting of
7371: # $pathname - the URI up to and excluding the trailing /
7372: # $filename - The part of the URI following the last /
7373: # NOTE:
7374: # Another realization of this is simply:
7375: # use File::Basename;
7376: # ...
7377: # $uri = shift;
7378: # $filename = basename($uri);
7379: # $path = dirname($uri);
7380: # return ($filename, $path);
7381: #
7382: # The implementation below is probably faster however.
7383: #
1.710 albertel 7384: sub split_uri_for_cond {
7385: my $uri=&deversion(&declutter(shift));
7386: my @uriparts=split(/\//,$uri);
7387: my $filename=pop(@uriparts);
7388: my $pathname=join('/',@uriparts);
7389: return ($pathname,$filename);
7390: }
1.232 www 7391: # --------------------------------------------------- Is a resource on the map?
7392:
7393: sub is_on_map {
1.710 albertel 7394: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7395: #Trying to find the conditional for the file
1.620 albertel 7396: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7397: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7398: if ($match) {
1.289 bowersj2 7399: return (1,$1);
7400: } else {
1.434 www 7401: return (0,0);
1.289 bowersj2 7402: }
1.12 www 7403: }
7404:
1.427 www 7405: # --------------------------------------------------------- Get symb from alias
7406:
7407: sub get_symb_from_alias {
7408: my $symb=shift;
7409: my ($map,$resid,$url)=&decode_symb($symb);
7410: # Already is a symb
7411: if ($url) { return $symb; }
7412: # Must be an alias
7413: my $aliassymb='';
7414: my %bighash;
1.620 albertel 7415: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7416: &GDBM_READER(),0640)) {
7417: my $rid=$bighash{'mapalias_'.$symb};
7418: if ($rid) {
7419: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7420: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7421: $resid,$bighash{'src_'.$rid});
1.427 www 7422: }
7423: untie %bighash;
7424: }
7425: return $aliassymb;
7426: }
7427:
1.12 www 7428: # ----------------------------------------------------------------- Define Role
7429:
7430: sub definerole {
7431: if (allowed('mcr','/')) {
7432: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7433: foreach my $role (split(':',$sysrole)) {
7434: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7435: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7436: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7437: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7438: return "refused:s:$crole&$cqual";
7439: }
7440: }
1.191 harris41 7441: }
1.800 albertel 7442: foreach my $role (split(':',$domrole)) {
7443: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7444: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7445: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7446: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7447: return "refused:d:$crole&$cqual";
7448: }
7449: }
1.191 harris41 7450: }
1.800 albertel 7451: foreach my $role (split(':',$courole)) {
7452: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7453: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7454: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7455: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7456: return "refused:c:$crole&$cqual";
7457: }
7458: }
1.191 harris41 7459: }
1.620 albertel 7460: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7461: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7462: "rolesdef_$rolename=".
7463: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7464: return reply($command,$env{'user.home'});
1.12 www 7465: } else {
7466: return 'refused';
7467: }
1.105 harris41 7468: }
7469:
7470: # ---------------- Make a metadata query against the network of library servers
7471:
7472: sub metadata_query {
1.1172.2.33 raeburn 7473: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7474: my %rhash;
1.845 albertel 7475: my %libserv = &all_library();
1.244 matthew 7476: my @server_list = (defined($server_array) ? @$server_array
7477: : keys(%libserv) );
7478: for my $server (@server_list) {
1.1172.2.33 raeburn 7479: my $domains = '';
7480: if (ref($domains_hash) eq 'HASH') {
7481: $domains = $domains_hash->{$server};
7482: }
1.118 harris41 7483: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7484: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7485: $rhash{$server}=$reply;
7486: }
7487: else {
7488: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7489: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7490: $server);
7491: $rhash{$server}=$reply;
7492: }
1.112 harris41 7493: }
1.118 harris41 7494: return \%rhash;
1.240 www 7495: }
7496:
7497: # ----------------------------------------- Send log queries and wait for reply
7498:
7499: sub log_query {
7500: my ($uname,$udom,$query,%filters)=@_;
7501: my $uhome=&homeserver($uname,$udom);
7502: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7503: my $uhost=&hostname($uhome);
1.800 albertel 7504: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7505: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7506: $uhome);
1.479 albertel 7507: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7508: return get_query_reply($queryid);
7509: }
7510:
1.818 raeburn 7511: # -------------------------- Update MySQL table for portfolio file
7512:
7513: sub update_portfolio_table {
1.821 raeburn 7514: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7515: if ($group ne '') {
7516: $file_name =~s /^\Q$group\E//;
7517: }
1.818 raeburn 7518: my $homeserver = &homeserver($uname,$udom);
7519: my $queryid=
1.821 raeburn 7520: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7521: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7522: my $reply = &get_query_reply($queryid);
7523: return $reply;
7524: }
7525:
1.899 raeburn 7526: # -------------------------- Update MySQL allusers table
7527:
7528: sub update_allusers_table {
7529: my ($uname,$udom,$names) = @_;
7530: my $homeserver = &homeserver($uname,$udom);
7531: my $queryid=
7532: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7533: 'lastname='.&escape($names->{'lastname'}).'%%'.
7534: 'firstname='.&escape($names->{'firstname'}).'%%'.
7535: 'middlename='.&escape($names->{'middlename'}).'%%'.
7536: 'generation='.&escape($names->{'generation'}).'%%'.
7537: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7538: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7539: return;
1.899 raeburn 7540: }
7541:
1.508 raeburn 7542: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7543:
7544: sub fetch_enrollment_query {
1.511 raeburn 7545: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7546: my $homeserver;
1.547 raeburn 7547: my $maxtries = 1;
1.508 raeburn 7548: if ($context eq 'automated') {
7549: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7550: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7551: } else {
7552: $homeserver = &homeserver($cnum,$dom);
7553: }
1.838 albertel 7554: my $host=&hostname($homeserver);
1.506 raeburn 7555: my $cmd = '';
1.1000 raeburn 7556: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7557: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7558: }
7559: $cmd =~ s/%%$//;
7560: $cmd = &escape($cmd);
7561: my $query = 'fetchenrollment';
1.620 albertel 7562: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7563: unless ($queryid=~/^\Q$host\E\_/) {
7564: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7565: return 'error: '.$queryid;
7566: }
1.506 raeburn 7567: my $reply = &get_query_reply($queryid);
1.547 raeburn 7568: my $tries = 1;
7569: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7570: $reply = &get_query_reply($queryid);
7571: $tries ++;
7572: }
1.526 raeburn 7573: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7574: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7575: } else {
1.901 albertel 7576: my @responses = split(/:/,$reply);
1.515 raeburn 7577: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7578: foreach my $line (@responses) {
7579: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7580: $$replyref{$key} = $value;
7581: }
7582: } else {
1.1117 foxr 7583: my $pathname = LONCAPA::tempdir();
1.800 albertel 7584: foreach my $line (@responses) {
7585: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7586: $$replyref{$key} = $value;
7587: if ($value > 0) {
1.800 albertel 7588: foreach my $item (@{$$affiliatesref{$key}}) {
7589: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7590: my $destname = $pathname.'/'.$filename;
7591: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7592: if ($xml_classlist =~ /^error/) {
7593: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7594: } else {
1.506 raeburn 7595: if ( open(FILE,">$destname") ) {
7596: print FILE &unescape($xml_classlist);
7597: close(FILE);
1.526 raeburn 7598: } else {
7599: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7600: }
7601: }
7602: }
7603: }
7604: }
7605: }
7606: return 'ok';
7607: }
7608: return 'error';
7609: }
7610:
1.242 www 7611: sub get_query_reply {
7612: my $queryid=shift;
1.1117 foxr 7613: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7614: my $reply='';
7615: for (1..100) {
7616: sleep 2;
7617: if (-e $replyfile.'.end') {
1.448 albertel 7618: if (open(my $fh,$replyfile)) {
1.904 albertel 7619: $reply = join('',<$fh>);
7620: close($fh);
1.240 www 7621: } else { return 'error: reply_file_error'; }
1.242 www 7622: return &unescape($reply);
7623: }
1.240 www 7624: }
1.242 www 7625: return 'timeout:'.$queryid;
1.240 www 7626: }
7627:
7628: sub courselog_query {
1.241 www 7629: #
7630: # possible filters:
7631: # url: url or symb
7632: # username
7633: # domain
7634: # action: view, submit, grade
7635: # start: timestamp
7636: # end: timestamp
7637: #
1.240 www 7638: my (%filters)=@_;
1.620 albertel 7639: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7640: if ($filters{'url'}) {
7641: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7642: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7643: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7644: }
1.620 albertel 7645: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7646: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7647: return &log_query($cname,$cdom,'courselog',%filters);
7648: }
7649:
7650: sub userlog_query {
1.858 raeburn 7651: #
7652: # possible filters:
7653: # action: log check role
7654: # start: timestamp
7655: # end: timestamp
7656: #
1.240 www 7657: my ($uname,$udom,%filters)=@_;
7658: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7659: }
7660:
1.506 raeburn 7661: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7662:
7663: sub auto_run {
1.508 raeburn 7664: my ($cnum,$cdom) = @_;
1.876 raeburn 7665: my $response = 0;
7666: my $settings;
7667: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7668: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7669: $settings = $domconfig{'autoenroll'};
7670: if ($settings->{'run'} eq '1') {
7671: $response = 1;
7672: }
7673: } else {
1.934 raeburn 7674: my $homeserver;
7675: if (&is_course($cdom,$cnum)) {
7676: $homeserver = &homeserver($cnum,$cdom);
7677: } else {
7678: $homeserver = &domain($cdom,'primary');
7679: }
7680: if ($homeserver ne 'no_host') {
7681: $response = &reply('autorun:'.$cdom,$homeserver);
7682: }
1.876 raeburn 7683: }
1.506 raeburn 7684: return $response;
7685: }
1.776 albertel 7686:
1.506 raeburn 7687: sub auto_get_sections {
1.508 raeburn 7688: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7689: my $homeserver;
7690: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7691: $homeserver = &homeserver($cnum,$cdom);
7692: }
7693: if (!defined($homeserver)) {
7694: if ($cdom =~ /^$match_domain$/) {
7695: $homeserver = &domain($cdom,'primary');
7696: }
7697: }
7698: my @secs;
7699: if (defined($homeserver)) {
7700: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7701: unless ($response eq 'refused') {
7702: @secs = split(/:/,$response);
7703: }
1.506 raeburn 7704: }
7705: return @secs;
7706: }
1.776 albertel 7707:
1.506 raeburn 7708: sub auto_new_course {
1.1099 raeburn 7709: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7710: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7711: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7712: return $response;
7713: }
1.776 albertel 7714:
1.506 raeburn 7715: sub auto_validate_courseID {
1.508 raeburn 7716: my ($cnum,$cdom,$inst_course_id) = @_;
7717: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7718: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7719: return $response;
7720: }
1.776 albertel 7721:
1.1007 raeburn 7722: sub auto_validate_instcode {
1.1020 raeburn 7723: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7724: my ($homeserver,$response);
7725: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7726: $homeserver = &homeserver($cnum,$cdom);
7727: }
7728: if (!defined($homeserver)) {
7729: if ($cdom =~ /^$match_domain$/) {
7730: $homeserver = &domain($cdom,'primary');
7731: }
7732: }
1.1065 raeburn 7733: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7734: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7735: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7736: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7737: }
7738:
1.506 raeburn 7739: sub auto_create_password {
1.873 raeburn 7740: my ($cnum,$cdom,$authparam,$udom) = @_;
7741: my ($homeserver,$response);
1.506 raeburn 7742: my $create_passwd = 0;
7743: my $authchk = '';
1.873 raeburn 7744: if ($udom =~ /^$match_domain$/) {
7745: $homeserver = &domain($udom,'primary');
7746: }
7747: if ($homeserver eq '') {
7748: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7749: $homeserver = &homeserver($cnum,$cdom);
7750: }
7751: }
7752: if ($homeserver eq '') {
7753: $authchk = 'nodomain';
1.506 raeburn 7754: } else {
1.873 raeburn 7755: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7756: if ($response eq 'refused') {
7757: $authchk = 'refused';
7758: } else {
1.901 albertel 7759: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7760: }
1.506 raeburn 7761: }
7762: return ($authparam,$create_passwd,$authchk);
7763: }
7764:
1.706 raeburn 7765: sub auto_photo_permission {
7766: my ($cnum,$cdom,$students) = @_;
7767: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7768: my ($outcome,$perm_reqd,$conditions) =
7769: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7770: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7771: return (undef,undef);
7772: }
1.706 raeburn 7773: return ($outcome,$perm_reqd,$conditions);
7774: }
7775:
7776: sub auto_checkphotos {
7777: my ($uname,$udom,$pid) = @_;
7778: my $homeserver = &homeserver($uname,$udom);
7779: my ($result,$resulttype);
7780: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7781: &escape($uname).':'.&escape($pid),
7782: $homeserver));
1.709 albertel 7783: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7784: return (undef,undef);
7785: }
1.706 raeburn 7786: if ($outcome) {
7787: ($result,$resulttype) = split(/:/,$outcome);
7788: }
7789: return ($result,$resulttype);
7790: }
7791:
7792: sub auto_photochoice {
7793: my ($cnum,$cdom) = @_;
7794: my $homeserver = &homeserver($cnum,$cdom);
7795: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7796: &escape($cdom),
7797: $homeserver)));
1.709 albertel 7798: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7799: return (undef,undef);
7800: }
1.706 raeburn 7801: return ($update,$comment);
7802: }
7803:
7804: sub auto_photoupdate {
7805: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7806: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7807: my $host=&hostname($homeserver);
1.706 raeburn 7808: my $cmd = '';
7809: my $maxtries = 1;
1.800 albertel 7810: foreach my $affiliate (keys(%{$affiliatesref})) {
7811: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7812: }
7813: $cmd =~ s/%%$//;
7814: $cmd = &escape($cmd);
7815: my $query = 'institutionalphotos';
7816: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7817: unless ($queryid=~/^\Q$host\E\_/) {
7818: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7819: return 'error: '.$queryid;
7820: }
7821: my $reply = &get_query_reply($queryid);
7822: my $tries = 1;
7823: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7824: $reply = &get_query_reply($queryid);
7825: $tries ++;
7826: }
7827: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7828: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7829: } else {
7830: my @responses = split(/:/,$reply);
7831: my $outcome = shift(@responses);
7832: foreach my $item (@responses) {
7833: my ($key,$value) = split(/=/,$item);
7834: $$photo{$key} = $value;
7835: }
7836: return $outcome;
7837: }
7838: return 'error';
7839: }
7840:
1.521 raeburn 7841: sub auto_instcode_format {
1.793 albertel 7842: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7843: $cat_order) = @_;
1.521 raeburn 7844: my $courses = '';
1.772 raeburn 7845: my @homeservers;
1.521 raeburn 7846: if ($caller eq 'global') {
1.841 albertel 7847: my %servers = &get_servers($codedom,'library');
7848: foreach my $tryserver (keys(%servers)) {
7849: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7850: push(@homeservers,$tryserver);
7851: }
1.584 raeburn 7852: }
1.1022 raeburn 7853: } elsif ($caller eq 'requests') {
7854: if ($codedom =~ /^$match_domain$/) {
7855: my $chome = &domain($codedom,'primary');
7856: unless ($chome eq 'no_host') {
7857: push(@homeservers,$chome);
7858: }
7859: }
1.521 raeburn 7860: } else {
1.772 raeburn 7861: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7862: }
1.793 albertel 7863: foreach my $code (keys(%{$instcodes})) {
7864: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7865: }
7866: chop($courses);
1.772 raeburn 7867: my $ok_response = 0;
7868: my $response;
7869: while (@homeservers > 0 && $ok_response == 0) {
7870: my $server = shift(@homeservers);
7871: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7872: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7873: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7874: split(/:/,$response);
1.772 raeburn 7875: %{$codes} = (%{$codes},&str2hash($codes_str));
7876: push(@{$codetitles},&str2array($codetitles_str));
7877: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7878: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7879: $ok_response = 1;
7880: }
7881: }
7882: if ($ok_response) {
1.521 raeburn 7883: return 'ok';
1.772 raeburn 7884: } else {
7885: return $response;
1.521 raeburn 7886: }
7887: }
7888:
1.792 raeburn 7889: sub auto_instcode_defaults {
7890: my ($domain,$returnhash,$code_order) = @_;
7891: my @homeservers;
1.841 albertel 7892:
7893: my %servers = &get_servers($domain,'library');
7894: foreach my $tryserver (keys(%servers)) {
7895: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7896: push(@homeservers,$tryserver);
7897: }
1.792 raeburn 7898: }
1.841 albertel 7899:
1.792 raeburn 7900: my $response;
1.841 albertel 7901: foreach my $server (@homeservers) {
1.792 raeburn 7902: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7903: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7904:
7905: foreach my $pair (split(/\&/,$response)) {
7906: my ($name,$value)=split(/\=/,$pair);
7907: if ($name eq 'code_order') {
7908: @{$code_order} = split(/\&/,&unescape($value));
7909: } else {
7910: $returnhash->{&unescape($name)}=&unescape($value);
7911: }
7912: }
7913: return 'ok';
1.792 raeburn 7914: }
1.841 albertel 7915:
7916: return $response;
1.1003 raeburn 7917: }
7918:
7919: sub auto_possible_instcodes {
1.1007 raeburn 7920: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7921: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7922: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7923: return;
7924: }
1.1003 raeburn 7925: my (@homeservers,$uhome);
7926: if (defined(&domain($domain,'primary'))) {
7927: $uhome=&domain($domain,'primary');
7928: push(@homeservers,&domain($domain,'primary'));
7929: } else {
7930: my %servers = &get_servers($domain,'library');
7931: foreach my $tryserver (keys(%servers)) {
7932: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7933: push(@homeservers,$tryserver);
7934: }
7935: }
7936: }
7937: my $response;
7938: foreach my $server (@homeservers) {
7939: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7940: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7941: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7942: split(':',$response);
7943: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7944: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7945: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7946: my ($name,$value)=split('=',$item);
7947: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7948: }
7949: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7950: my ($name,$value)=split('=',$item);
7951: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7952: }
7953: return 'ok';
7954: }
7955: return $response;
7956: }
1.792 raeburn 7957:
1.1010 raeburn 7958: sub auto_courserequest_checks {
7959: my ($dom) = @_;
1.1020 raeburn 7960: my ($homeserver,%validations);
7961: if ($dom =~ /^$match_domain$/) {
7962: $homeserver = &domain($dom,'primary');
7963: }
7964: unless ($homeserver eq 'no_host') {
7965: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7966: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7967: my @items = split(/&/,$response);
7968: foreach my $item (@items) {
7969: my ($key,$value) = split('=',$item);
7970: $validations{&unescape($key)} = &thaw_unescape($value);
7971: }
7972: }
7973: }
1.1010 raeburn 7974: return %validations;
7975: }
7976:
1.1020 raeburn 7977: sub auto_courserequest_validation {
1.1172.2.43 raeburn 7978: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 7979: my ($homeserver,$response);
7980: if ($dom =~ /^$match_domain$/) {
7981: $homeserver = &domain($dom,'primary');
7982: }
1.1172.2.43 raeburn 7983: unless ($homeserver eq 'no_host') {
7984: my $customdata;
7985: if (ref($custominfo) eq 'HASH') {
7986: $customdata = &freeze_escape($custominfo);
7987: }
1.1020 raeburn 7988: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7989: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 7990: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7991: $customdata,$homeserver));
1.1020 raeburn 7992: }
7993: return $response;
7994: }
7995:
1.777 albertel 7996: sub auto_validate_class_sec {
1.918 raeburn 7997: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7998: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7999: my $ownerlist;
8000: if (ref($owners) eq 'ARRAY') {
8001: $ownerlist = join(',',@{$owners});
8002: } else {
8003: $ownerlist = $owners;
8004: }
1.773 raeburn 8005: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8006: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8007: return $response;
8008: }
8009:
1.1172.2.38 raeburn 8010: sub auto_crsreq_update {
8011: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8012: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8013: my ($homeserver,%crsreqresponse);
8014: if ($cdom =~ /^$match_domain$/) {
8015: $homeserver = &domain($cdom,'primary');
8016: }
8017: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8018: my $info;
8019: if (ref($inbound) eq 'HASH') {
8020: $info = &freeze_escape($inbound);
8021: }
8022: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8023: ':'.&escape($action).':'.&escape($ownername).':'.
8024: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8025: &escape($title).':'.&escape($code).':'.
8026: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8027: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8028: my @items = split(/&/,$response);
8029: foreach my $item (@items) {
8030: my ($key,$value) = split('=',$item);
8031: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8032: }
8033: }
8034: }
8035: return \%crsreqresponse;
8036: }
8037:
1.679 raeburn 8038: # ------------------------------------------------------- Course Group routines
8039:
8040: sub get_coursegroups {
1.809 raeburn 8041: my ($cdom,$cnum,$group,$namespace) = @_;
8042: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8043: }
8044:
1.679 raeburn 8045: sub modify_coursegroup {
8046: my ($cdom,$cnum,$groupsettings) = @_;
8047: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8048: }
8049:
1.809 raeburn 8050: sub toggle_coursegroup_status {
8051: my ($cdom,$cnum,$group,$action) = @_;
8052: my ($from_namespace,$to_namespace);
8053: if ($action eq 'delete') {
8054: $from_namespace = 'coursegroups';
8055: $to_namespace = 'deleted_groups';
8056: } else {
8057: $from_namespace = 'deleted_groups';
8058: $to_namespace = 'coursegroups';
8059: }
8060: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8061: if (my $tmp = &error(%curr_group)) {
8062: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8063: return ('read error',$tmp);
8064: } else {
8065: my %savedsettings = %curr_group;
1.809 raeburn 8066: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8067: my $deloutcome;
8068: if ($result eq 'ok') {
1.809 raeburn 8069: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8070: } else {
8071: return ('write error',$result);
8072: }
8073: if ($deloutcome eq 'ok') {
8074: return 'ok';
8075: } else {
8076: return ('delete error',$deloutcome);
8077: }
8078: }
8079: }
8080:
1.679 raeburn 8081: sub modify_group_roles {
1.957 raeburn 8082: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8083: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8084: my $role = 'gr/'.&escape($userprivs);
8085: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8086: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8087: if ($result eq 'ok') {
8088: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8089: }
1.679 raeburn 8090: return $result;
8091: }
8092:
8093: sub modify_coursegroup_membership {
8094: my ($cdom,$cnum,$membership) = @_;
8095: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8096: return $result;
8097: }
8098:
1.682 raeburn 8099: sub get_active_groups {
8100: my ($udom,$uname,$cdom,$cnum) = @_;
8101: my $now = time;
8102: my %groups = ();
8103: foreach my $key (keys(%env)) {
1.811 albertel 8104: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8105: my ($start,$end) = split(/\./,$env{$key});
8106: if (($end!=0) && ($end<$now)) { next; }
8107: if (($start!=0) && ($start>$now)) { next; }
8108: if ($1 eq $cdom && $2 eq $cnum) {
8109: $groups{$3} = $env{$key} ;
8110: }
8111: }
8112: }
8113: return %groups;
8114: }
8115:
1.683 raeburn 8116: sub get_group_membership {
8117: my ($cdom,$cnum,$group) = @_;
8118: return(&dump('groupmembership',$cdom,$cnum,$group));
8119: }
8120:
8121: sub get_users_groups {
8122: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8123: my @usersgroups;
1.683 raeburn 8124: my $cachetime=1800;
8125:
8126: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8127: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8128: if (defined($cached)) {
1.734 albertel 8129: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8130: } else {
8131: $grouplist = '';
1.816 raeburn 8132: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8133: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8134: my $access_end = $env{'course.'.$courseid.
8135: '.default_enrollment_end_date'};
8136: my $now = time;
8137: foreach my $key (keys(%roleshash)) {
8138: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8139: my $group = $1;
8140: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8141: my $start = $2;
8142: my $end = $1;
8143: if ($start == -1) { next; } # deleted from group
8144: if (($start!=0) && ($start>$now)) { next; }
8145: if (($end!=0) && ($end<$now)) {
8146: if ($access_end && $access_end < $now) {
8147: if ($access_end - $end < 86400) {
8148: push(@usersgroups,$group);
1.733 raeburn 8149: }
8150: }
1.817 raeburn 8151: next;
1.733 raeburn 8152: }
1.817 raeburn 8153: push(@usersgroups,$group);
1.683 raeburn 8154: }
8155: }
8156: }
1.817 raeburn 8157: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8158: $grouplist = join(':',@usersgroups);
8159: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8160: }
1.733 raeburn 8161: return @usersgroups;
1.683 raeburn 8162: }
8163:
8164: sub devalidate_getgroups_cache {
8165: my ($udom,$uname,$cdom,$cnum)=@_;
8166: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8167:
1.683 raeburn 8168: my $hashid="$udom:$uname:$courseid";
8169: &devalidate_cache_new('getgroups',$hashid);
8170: }
8171:
1.12 www 8172: # ------------------------------------------------------------------ Plain Text
8173:
8174: sub plaintext {
1.988 raeburn 8175: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8176: if ($short =~ m{^cr/}) {
1.758 albertel 8177: return (split('/',$short))[-1];
8178: }
1.742 raeburn 8179: if (!defined($cid)) {
8180: $cid = $env{'request.course.id'};
8181: }
8182: my %rolenames = (
1.1008 raeburn 8183: Course => 'std',
8184: Community => 'alt1',
1.742 raeburn 8185: );
1.1037 raeburn 8186: if ($cid ne '') {
8187: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8188: unless ($forcedefault) {
8189: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8190: &Apache::lonlocal::mt_escape(\$roletext);
8191: return &Apache::lonlocal::mt($roletext);
8192: }
8193: }
8194: }
8195: if ((defined($type)) && (defined($rolenames{$type})) &&
8196: (defined($rolenames{$type})) &&
8197: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8198: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8199: } elsif ($cid ne '') {
8200: my $crstype = $env{'course.'.$cid.'.type'};
8201: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8202: (defined($prp{$short}{$rolenames{$crstype}}))) {
8203: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8204: }
1.742 raeburn 8205: }
1.1037 raeburn 8206: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8207: }
8208:
8209: # ----------------------------------------------------------------- Assign Role
8210:
8211: sub assignrole {
1.957 raeburn 8212: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8213: $context)=@_;
1.21 www 8214: my $mrole;
8215: if ($role =~ /^cr\//) {
1.393 www 8216: my $cwosec=$url;
1.811 albertel 8217: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8218: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8219: my $refused = 1;
8220: if ($context eq 'requestcourses') {
8221: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8222: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8223: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8224: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8225: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8226: if ($crsenv{'internal.courseowner'} eq
8227: $env{'user.name'}.':'.$env{'user.domain'}) {
8228: $refused = '';
8229: }
8230: }
8231: }
8232: }
8233: }
8234: if ($refused) {
8235: &logthis('Refused custom assignrole: '.
8236: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8237: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8238: return 'refused';
8239: }
1.104 www 8240: }
1.21 www 8241: $mrole='cr';
1.678 raeburn 8242: } elsif ($role =~ /^gr\//) {
8243: my $cwogrp=$url;
1.811 albertel 8244: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8245: unless (&allowed('mdg',$cwogrp)) {
8246: &logthis('Refused group assignrole: '.
8247: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8248: $env{'user.name'}.' at '.$env{'user.domain'});
8249: return 'refused';
8250: }
8251: $mrole='gr';
1.21 www 8252: } else {
1.82 www 8253: my $cwosec=$url;
1.811 albertel 8254: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8255: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8256: my $refused;
8257: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8258: if (!(&allowed('c'.$role,$url))) {
8259: $refused = 1;
8260: }
8261: } else {
8262: $refused = 1;
8263: }
1.947 raeburn 8264: if ($refused) {
1.1045 raeburn 8265: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8266: if (!$selfenroll && $context eq 'course') {
8267: my %crsenv;
8268: if ($role eq 'cc' || $role eq 'co') {
8269: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8270: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8271: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8272: if ($crsenv{'internal.courseowner'} eq
8273: $env{'user.name'}.':'.$env{'user.domain'}) {
8274: $refused = '';
8275: }
8276: }
8277: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8278: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8279: if ($crsenv{'internal.courseowner'} eq
8280: $env{'user.name'}.':'.$env{'user.domain'}) {
8281: $refused = '';
8282: }
8283: }
8284: }
8285: }
8286: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8287: $refused = '';
1.1017 raeburn 8288: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8289: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8290: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8291: my $wrongcc;
8292: if ($cnum =~ /^$match_community$/) {
8293: $wrongcc = 1 if ($role eq 'cc');
8294: } else {
8295: $wrongcc = 1 if ($role eq 'co');
8296: }
8297: unless ($wrongcc) {
8298: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8299: if ($crsenv{'internal.courseowner'} eq
8300: $env{'user.name'}.':'.$env{'user.domain'}) {
8301: $refused = '';
8302: }
1.1017 raeburn 8303: }
8304: }
1.1172.2.9 raeburn 8305: } elsif ($context eq 'requestauthor') {
8306: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8307: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8308: if ($env{'environment.requestauthor'} eq 'automatic') {
8309: $refused = '';
8310: } else {
8311: my %domdefaults = &get_domain_defaults($udom);
8312: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8313: my $checkbystatus;
8314: if ($env{'user.adv'}) {
8315: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8316: if ($disposition eq 'automatic') {
8317: $refused = '';
8318: } elsif ($disposition eq '') {
8319: $checkbystatus = 1;
8320: }
8321: } else {
8322: $checkbystatus = 1;
8323: }
8324: if ($checkbystatus) {
8325: if ($env{'environment.inststatus'}) {
8326: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8327: foreach my $type (@inststatuses) {
8328: if (($type ne '') &&
8329: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8330: $refused = '';
8331: }
8332: }
8333: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8334: $refused = '';
8335: }
8336: }
8337: }
8338: }
8339: }
1.1017 raeburn 8340: }
8341: if ($refused) {
1.947 raeburn 8342: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8343: ' '.$role.' '.$end.' '.$start.' by '.
8344: $env{'user.name'}.' at '.$env{'user.domain'});
8345: return 'refused';
8346: }
1.932 raeburn 8347: }
1.1131 raeburn 8348: } elsif ($role eq 'au') {
8349: if ($url ne '/'.$udom.'/') {
8350: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8351: ' to assign author role for '.$uname.':'.$udom.
8352: ' in domain: '.$url.' refused (wrong domain).');
8353: return 'refused';
8354: }
1.104 www 8355: }
1.21 www 8356: $mrole=$role;
8357: }
1.620 albertel 8358: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8359: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8360: if ($end) { $command.='_'.$end; }
1.21 www 8361: if ($start) {
8362: if ($end) {
1.81 www 8363: $command.='_'.$start;
1.21 www 8364: } else {
1.81 www 8365: $command.='_0_'.$start;
1.21 www 8366: }
8367: }
1.739 raeburn 8368: my $origstart = $start;
8369: my $origend = $end;
1.957 raeburn 8370: my $delflag;
1.357 www 8371: # actually delete
8372: if ($deleteflag) {
1.373 www 8373: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8374: # modify command to delete the role
1.620 albertel 8375: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8376: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8377: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8378: # set start and finish to negative values for userrolelog
8379: $start=-1;
8380: $end=-1;
1.957 raeburn 8381: $delflag = 1;
1.357 www 8382: }
8383: }
8384: # send command
1.349 www 8385: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8386: # log new user role if status is ok
1.349 www 8387: if ($answer eq 'ok') {
1.663 raeburn 8388: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8389: if (($role eq 'cc') || ($role eq 'in') ||
8390: ($role eq 'ep') || ($role eq 'ad') ||
8391: ($role eq 'ta') || ($role eq 'st') ||
8392: ($role=~/^cr/) || ($role eq 'gr') ||
8393: ($role eq 'co')) {
1.1172.2.13 raeburn 8394: # for course roles, perform group memberships changes triggered by role change.
8395: unless ($role =~ /^gr/) {
8396: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8397: $origstart,$selfenroll,$context);
8398: }
1.1172.2.9 raeburn 8399: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8400: $selfenroll,$context);
8401: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8402: ($role eq 'au') || ($role eq 'dc')) {
8403: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8404: $context);
8405: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8406: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8407: $context);
8408: }
1.1053 raeburn 8409: if ($role eq 'cc') {
8410: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8411: }
1.349 www 8412: }
8413: return $answer;
1.169 harris41 8414: }
8415:
1.1053 raeburn 8416: sub autoupdate_coowners {
8417: my ($url,$end,$start,$uname,$udom) = @_;
8418: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8419: if (($cdom ne '') && ($cnum ne '')) {
8420: my $now = time;
8421: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8422: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8423: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8424: my $instcode = $coursehash{'internal.coursecode'};
8425: if ($instcode ne '') {
1.1056 raeburn 8426: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8427: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8428: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8429: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8430: if ($result eq 'valid') {
8431: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8432: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8433: push(@newcoowners,$coowner);
8434: }
8435: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8436: push(@newcoowners,$uname.':'.$udom);
8437: }
8438: @newcoowners = sort(@newcoowners);
8439: } else {
8440: push(@newcoowners,$uname.':'.$udom);
8441: }
8442: } else {
8443: if ($coursehash{'internal.co-owners'}) {
8444: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8445: unless ($coowner eq $uname.':'.$udom) {
8446: push(@newcoowners,$coowner);
8447: }
8448: }
8449: unless (@newcoowners > 0) {
8450: $delcoowners = 1;
8451: $coowners = '';
8452: }
8453: }
8454: }
8455: if (@newcoowners || $delcoowners) {
8456: &store_coowners($cdom,$cnum,$coursehash{'home'},
8457: $delcoowners,@newcoowners);
8458: }
8459: }
8460: }
8461: }
8462: }
8463: }
8464: }
8465:
8466: sub store_coowners {
8467: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8468: my $cid = $cdom.'_'.$cnum;
8469: my ($coowners,$delresult,$putresult);
8470: if (@newcoowners) {
8471: $coowners = join(',',@newcoowners);
8472: my %coownershash = (
8473: 'internal.co-owners' => $coowners,
8474: );
8475: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8476: if ($putresult eq 'ok') {
8477: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8478: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8479: }
8480: }
8481: }
8482: if ($delcoowners) {
8483: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8484: if ($delresult eq 'ok') {
8485: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8486: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8487: }
8488: }
8489: }
8490: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8491: my %crsinfo =
8492: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8493: if (ref($crsinfo{$cid}) eq 'HASH') {
8494: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8495: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8496: }
8497: }
8498: }
8499:
1.169 harris41 8500: # -------------------------------------------------- Modify user authentication
1.197 www 8501: # Overrides without validation
8502:
1.169 harris41 8503: sub modifyuserauth {
8504: my ($udom,$uname,$umode,$upass)=@_;
8505: my $uhome=&homeserver($uname,$udom);
1.197 www 8506: unless (&allowed('mau',$udom)) { return 'refused'; }
8507: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8508: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8509: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8510: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8511: &escape($upass),$uhome);
1.620 albertel 8512: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8513: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8514: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8515: &log($udom,,$uname,$uhome,
1.620 albertel 8516: 'Authentication changed by '.$env{'user.domain'}.', '.
8517: $env{'user.name'}.', '.$umode.
1.197 www 8518: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8519: unless ($reply eq 'ok') {
1.197 www 8520: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8521: return 'error: '.$reply;
8522: }
1.170 harris41 8523: return 'ok';
1.80 www 8524: }
8525:
1.81 www 8526: # --------------------------------------------------------------- Modify a user
1.80 www 8527:
1.81 www 8528: sub modifyuser {
1.206 matthew 8529: my ($udom, $uname, $uid,
8530: $umode, $upass, $first,
8531: $middle, $last, $gene,
1.1058 raeburn 8532: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8533: $udom= &LONCAPA::clean_domain($udom);
8534: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8535: my $showcandelete = 'none';
8536: if (ref($candelete) eq 'ARRAY') {
8537: if (@{$candelete} > 0) {
8538: $showcandelete = join(', ',@{$candelete});
8539: }
8540: }
1.81 www 8541: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8542: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8543: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8544: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8545: ' desiredhome not specified').
1.620 albertel 8546: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8547: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8548: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8549: my $newuser;
8550: if ($uhome eq 'no_host') {
8551: $newuser = 1;
8552: }
1.80 www 8553: # ----------------------------------------------------------------- Create User
1.406 albertel 8554: if (($uhome eq 'no_host') &&
8555: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8556: my $unhome='';
1.844 albertel 8557: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8558: $unhome = $desiredhome;
1.620 albertel 8559: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8560: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8561: } else { # load balancing routine for determining $unhome
1.81 www 8562: my $loadm=10000000;
1.841 albertel 8563: my %servers = &get_servers($udom,'library');
8564: foreach my $tryserver (keys(%servers)) {
8565: my $answer=reply('load',$tryserver);
8566: if (($answer=~/\d+/) && ($answer<$loadm)) {
8567: $loadm=$answer;
8568: $unhome=$tryserver;
8569: }
1.80 www 8570: }
8571: }
8572: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8573: return 'error: unable to find a home server for '.$uname.
8574: ' in domain '.$udom;
1.80 www 8575: }
8576: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8577: &escape($upass),$unhome);
8578: unless ($reply eq 'ok') {
8579: return 'error: '.$reply;
8580: }
1.230 stredwic 8581: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8582: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8583: return 'error: unable verify users home machine.';
1.80 www 8584: }
1.209 matthew 8585: } # End of creation of new user
1.80 www 8586: # ---------------------------------------------------------------------- Add ID
8587: if ($uid) {
8588: $uid=~tr/A-Z/a-z/;
8589: my %uidhash=&idrget($udom,$uname);
1.196 www 8590: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8591: && (!$forceid)) {
1.80 www 8592: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8593: return 'error: user id "'.$uid.'" does not match '.
8594: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8595: }
8596: } else {
8597: &idput($udom,($uname => $uid));
8598: }
8599: }
8600: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8601: my @tmp=&get('environment',
1.899 raeburn 8602: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8603: 'permanentemail','inststatus'],
1.134 albertel 8604: $udom,$uname);
1.1075 raeburn 8605: my (%names,%oldnames);
1.313 matthew 8606: if ($tmp[0] =~ m/^error:.*/) {
8607: %names=();
8608: } else {
8609: %names = @tmp;
1.1075 raeburn 8610: %oldnames = %names;
1.313 matthew 8611: }
1.388 www 8612: #
1.1058 raeburn 8613: # If name, email and/or uid are blank (e.g., because an uploaded file
8614: # of users did not contain them), do not overwrite existing values
8615: # unless field is in $candelete array ref.
8616: #
8617:
8618: my @fields = ('firstname','middlename','lastname','generation',
8619: 'permanentemail','id');
8620: my %newvalues;
8621: if (ref($candelete) eq 'ARRAY') {
8622: foreach my $field (@fields) {
8623: if (grep(/^\Q$field\E$/,@{$candelete})) {
8624: if ($field eq 'firstname') {
8625: $names{$field} = $first;
8626: } elsif ($field eq 'middlename') {
8627: $names{$field} = $middle;
8628: } elsif ($field eq 'lastname') {
8629: $names{$field} = $last;
8630: } elsif ($field eq 'generation') {
8631: $names{$field} = $gene;
8632: } elsif ($field eq 'permanentemail') {
8633: $names{$field} = $email;
8634: } elsif ($field eq 'id') {
8635: $names{$field} = $uid;
8636: }
8637: }
8638: }
8639: }
1.388 www 8640: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8641: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8642: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8643: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8644: if ($email) {
8645: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8646: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8647: }
1.899 raeburn 8648: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8649: if (defined($inststatus)) {
8650: $names{'inststatus'} = '';
8651: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8652: if (ref($usertypes) eq 'HASH') {
8653: my @okstatuses;
8654: foreach my $item (split(/:/,$inststatus)) {
8655: if (defined($usertypes->{$item})) {
8656: push(@okstatuses,$item);
8657: }
8658: }
8659: if (@okstatuses) {
8660: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8661: }
8662: }
8663: }
1.1075 raeburn 8664: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8665: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8666: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8667: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8668: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8669: } else {
8670: $logmsg .= ' during self creation';
8671: }
1.1075 raeburn 8672: my $changed;
8673: if ($newuser) {
8674: $changed = 1;
8675: } else {
8676: foreach my $field (@fields) {
8677: if ($names{$field} ne $oldnames{$field}) {
8678: $changed = 1;
8679: last;
8680: }
8681: }
8682: }
8683: unless ($changed) {
8684: $logmsg = 'No changes in user information needed for: '.$logmsg;
8685: &logthis($logmsg);
8686: return 'ok';
8687: }
8688: my $reply = &put('environment', \%names, $udom,$uname);
8689: if ($reply ne 'ok') {
8690: return 'error: '.$reply;
8691: }
1.1087 raeburn 8692: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8693: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8694: }
1.1075 raeburn 8695: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8696: &devalidate_cache_new('namescache',$uname.':'.$udom);
8697: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8698: &logthis($logmsg);
1.134 albertel 8699: return 'ok';
1.80 www 8700: }
8701:
1.81 www 8702: # -------------------------------------------------------------- Modify student
1.80 www 8703:
1.81 www 8704: sub modifystudent {
8705: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8706: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8707: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8708: if (!$cid) {
1.620 albertel 8709: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8710: return 'not_in_class';
8711: }
1.80 www 8712: }
8713: # --------------------------------------------------------------- Make the user
1.81 www 8714: my $reply=&modifyuser
1.209 matthew 8715: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8716: $desiredhome,$email,$inststatus);
1.80 www 8717: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8718: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8719: # student's environment
1.297 matthew 8720: $uid = undef if (!$forceid);
1.455 albertel 8721: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8722: $gene,$usec,$end,$start,$type,$locktype,
8723: $cid,$selfenroll,$context,$credits);
1.297 matthew 8724: return $reply;
8725: }
8726:
8727: sub modify_student_enrollment {
1.1172.2.23 raeburn 8728: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8729: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8730: my ($cdom,$cnum,$chome);
8731: if (!$cid) {
1.620 albertel 8732: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8733: return 'not_in_class';
8734: }
1.620 albertel 8735: $cdom=$env{'course.'.$cid.'.domain'};
8736: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8737: } else {
8738: ($cdom,$cnum)=split(/_/,$cid);
8739: }
1.620 albertel 8740: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8741: if (!$chome) {
1.457 raeburn 8742: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8743: }
1.455 albertel 8744: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8745: # Make sure the user exists
1.81 www 8746: my $uhome=&homeserver($uname,$udom);
8747: if (($uhome eq '') || ($uhome eq 'no_host')) {
8748: return 'error: no such user';
8749: }
1.297 matthew 8750: # Get student data if we were not given enough information
8751: if (!defined($first) || $first eq '' ||
8752: !defined($last) || $last eq '' ||
8753: !defined($uid) || $uid eq '' ||
8754: !defined($middle) || $middle eq '' ||
8755: !defined($gene) || $gene eq '') {
1.294 matthew 8756: # They did not supply us with enough data to enroll the student, so
8757: # we need to pick up more information.
1.297 matthew 8758: my %tmp = &get('environment',
1.294 matthew 8759: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8760: ,$udom,$uname);
8761:
1.800 albertel 8762: #foreach my $key (keys(%tmp)) {
8763: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8764: #}
1.294 matthew 8765: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8766: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8767: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8768: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8769: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8770: }
1.556 albertel 8771: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8772: my $user = "$uname:$udom";
8773: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8774: my $reply=cput('classlist',
1.1148 raeburn 8775: {$user =>
1.1172.2.19 raeburn 8776: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8777: $cdom,$cnum);
1.1148 raeburn 8778: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8779: &devalidate_getsection_cache($udom,$uname,$cid);
8780: } else {
1.81 www 8781: return 'error: '.$reply;
8782: }
1.297 matthew 8783: # Add student role to user
1.83 www 8784: my $uurl='/'.$cid;
1.81 www 8785: $uurl=~s/\_/\//g;
8786: if ($usec) {
8787: $uurl.='/'.$usec;
8788: }
1.1148 raeburn 8789: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8790: $selfenroll,$context);
8791: if ($result ne 'ok') {
8792: if ($old_entry{$user} ne '') {
8793: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8794: } else {
8795: $reply = &del('classlist',[$user],$cdom,$cnum);
8796: }
8797: }
8798: return $result;
1.21 www 8799: }
8800:
1.556 albertel 8801: sub format_name {
8802: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8803: my $name;
8804: if ($first ne 'lastname') {
8805: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8806: } else {
8807: if ($lastname=~/\S/) {
8808: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8809: $name=~s/\s+,/,/;
8810: } else {
8811: $name.= $firstname.' '.$middlename.' '.$generation;
8812: }
8813: }
8814: $name=~s/^\s+//;
8815: $name=~s/\s+$//;
8816: $name=~s/\s+/ /g;
8817: return $name;
8818: }
8819:
1.84 www 8820: # ------------------------------------------------- Write to course preferences
8821:
8822: sub writecoursepref {
8823: my ($courseid,%prefs)=@_;
8824: $courseid=~s/^\///;
8825: $courseid=~s/\_/\//g;
8826: my ($cdomain,$cnum)=split(/\//,$courseid);
8827: my $chome=homeserver($cnum,$cdomain);
8828: if (($chome eq '') || ($chome eq 'no_host')) {
8829: return 'error: no such course';
8830: }
8831: my $cstring='';
1.800 albertel 8832: foreach my $pref (keys(%prefs)) {
8833: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8834: }
1.84 www 8835: $cstring=~s/\&$//;
8836: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8837: }
8838:
8839: # ---------------------------------------------------------- Make/modify course
8840:
8841: sub createcourse {
1.741 raeburn 8842: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8843: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8844: $url=&declutter($url);
8845: my $cid='';
1.1028 raeburn 8846: if ($context eq 'requestcourses') {
8847: my $can_create = 0;
8848: my ($ownername,$ownerdom) = split(':',$course_owner);
8849: if ($udom eq $ownerdom) {
8850: if (&usertools_access($ownername,$ownerdom,$category,undef,
8851: $context)) {
8852: $can_create = 1;
8853: }
8854: } else {
8855: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8856: $category);
8857: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8858: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8859: if (@curr > 0) {
8860: my @options = qw(approval validate autolimit);
8861: my $optregex = join('|',@options);
8862: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8863: $can_create = 1;
8864: }
8865: }
8866: }
8867: }
8868: if ($can_create) {
8869: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8870: unless (&allowed('ccc',$udom)) {
8871: return 'refused';
8872: }
1.1017 raeburn 8873: }
8874: } else {
8875: return 'refused';
8876: }
1.1028 raeburn 8877: } elsif (!&allowed('ccc',$udom)) {
8878: return 'refused';
1.84 www 8879: }
1.1011 raeburn 8880: # --------------------------------------------------------------- Get Unique ID
8881: my $uname;
8882: if ($cnum =~ /^$match_courseid$/) {
8883: my $chome=&homeserver($cnum,$udom,'true');
8884: if (($chome eq '') || ($chome eq 'no_host')) {
8885: $uname = $cnum;
8886: } else {
1.1038 raeburn 8887: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8888: }
8889: } else {
1.1038 raeburn 8890: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8891: }
8892: return $uname if ($uname =~ /^error/);
8893: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8894: if (!defined($course_server)) {
8895: if (defined(&domain($udom,'primary'))) {
8896: $course_server = &domain($udom,'primary');
8897: } else {
8898: $course_server = $env{'user.home'};
8899: }
8900: }
8901: my %host_servers =
8902: &Apache::lonnet::get_servers($udom,'library');
8903: unless ($host_servers{$course_server}) {
8904: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8905: }
1.84 www 8906: # ------------------------------------------------------------- Make the course
8907: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8908: $course_server);
1.84 www 8909: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8910: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8911: if (($uhome eq '') || ($uhome eq 'no_host')) {
8912: return 'error: no such course';
8913: }
1.271 www 8914: # ----------------------------------------------------------------- Course made
1.516 raeburn 8915: # log existence
1.1029 raeburn 8916: my $now = time;
1.918 raeburn 8917: my $newcourse = {
8918: $udom.'_'.$uname => {
1.921 raeburn 8919: description => $description,
8920: inst_code => $inst_code,
8921: owner => $course_owner,
8922: type => $crstype,
1.1029 raeburn 8923: creator => $env{'user.name'}.':'.
8924: $env{'user.domain'},
8925: created => $now,
8926: context => $context,
1.918 raeburn 8927: },
8928: };
1.921 raeburn 8929: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8930: # set toplevel url
1.271 www 8931: my $topurl=$url;
8932: unless ($nonstandard) {
8933: # ------------------------------------------ For standard courses, make top url
8934: my $mapurl=&clutter($url);
1.278 www 8935: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8936: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8937: <map>
8938: <resource id="1" type="start"></resource>
8939: <resource id="2" src="$mapurl"></resource>
8940: <resource id="3" type="finish"></resource>
8941: <link index="1" from="1" to="2"></link>
8942: <link index="2" from="2" to="3"></link>
8943: </map>
8944: ENDINITMAP
8945: $topurl=&declutter(
1.638 albertel 8946: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8947: );
8948: }
8949: # ----------------------------------------------------------- Write preferences
1.84 www 8950: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8951: ('description' => $description,
8952: 'url' => $topurl,
8953: 'internal.creator' => $env{'user.name'}.':'.
8954: $env{'user.domain'},
8955: 'internal.created' => $now,
8956: 'internal.creationcontext' => $context)
8957: );
1.84 www 8958: return '/'.$udom.'/'.$uname;
8959: }
8960:
1.1011 raeburn 8961: # ------------------------------------------------------------------- Create ID
8962: sub generate_coursenum {
1.1038 raeburn 8963: my ($udom,$crstype) = @_;
1.1011 raeburn 8964: my $domdesc = &domain($udom);
8965: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8966: my $first;
8967: if ($crstype eq 'Community') {
8968: $first = '0';
8969: } else {
8970: $first = int(1+rand(9));
8971: }
8972: my $uname=$first.
1.1011 raeburn 8973: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8974: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8975: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8976: # ----------------------------------------------- Make sure that does not exist
8977: my $uhome=&homeserver($uname,$udom,'true');
8978: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8979: if ($crstype eq 'Community') {
8980: $first = '0';
8981: } else {
8982: $first = int(1+rand(9));
8983: }
8984: $uname=$first.
1.1011 raeburn 8985: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8986: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8987: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8988: $uhome=&homeserver($uname,$udom,'true');
8989: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8990: return 'error: unable to generate unique course-ID';
8991: }
8992: }
8993: return $uname;
8994: }
8995:
1.813 albertel 8996: sub is_course {
1.1167 droeschl 8997: my ($cdom, $cnum) = scalar(@_) == 1 ?
8998: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8999:
9000: return unless $cdom and $cnum;
9001:
9002: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9003: '.');
9004:
1.1172.2.23 raeburn 9005: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9006: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9007: }
9008:
1.1015 raeburn 9009: sub store_userdata {
9010: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9011: my $result;
1.1016 raeburn 9012: if ($datakey ne '') {
1.1013 raeburn 9013: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9014: if ($udom eq '' || $uname eq '') {
9015: $udom = $env{'user.domain'};
9016: $uname = $env{'user.name'};
9017: }
9018: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9019: if (($uhome eq '') || ($uhome eq 'no_host')) {
9020: $result = 'error: no_host';
9021: } else {
9022: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9023: $storehash->{'host'} = $perlvar{'lonHostID'};
9024:
9025: my $namevalue='';
9026: foreach my $key (keys(%{$storehash})) {
9027: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9028: }
9029: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9030: unless ($namespace eq 'courserequests') {
9031: $datakey = &escape($datakey);
9032: }
1.1105 raeburn 9033: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9034: $namevalue,$uhome);
1.1013 raeburn 9035: }
9036: } else {
9037: $result = 'error: data to store was not a hash reference';
9038: }
9039: } else {
9040: $result= 'error: invalid requestkey';
9041: }
9042: return $result;
9043: }
9044:
1.21 www 9045: # ---------------------------------------------------------- Assign Custom Role
9046:
9047: sub assigncustomrole {
1.957 raeburn 9048: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9049: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9050: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9051: }
9052:
9053: # ----------------------------------------------------------------- Revoke Role
9054:
9055: sub revokerole {
1.957 raeburn 9056: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9057: my $now=time;
1.965 raeburn 9058: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9059: }
9060:
9061: # ---------------------------------------------------------- Revoke Custom Role
9062:
9063: sub revokecustomrole {
1.957 raeburn 9064: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9065: my $now=time;
1.357 www 9066: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9067: $deleteflag,$selfenroll,$context);
1.17 www 9068: }
9069:
1.533 banghart 9070: # ------------------------------------------------------------ Disk usage
1.535 albertel 9071: sub diskusage {
1.955 raeburn 9072: my ($udom,$uname,$directorypath,$getpropath)=@_;
9073: $directorypath =~ s/\/$//;
9074: my $listing=&reply('du2:'.&escape($directorypath).':'
9075: .&escape($getpropath).':'.&escape($uname).':'
9076: .&escape($udom),homeserver($uname,$udom));
9077: if ($listing eq 'unknown_cmd') {
9078: if ($getpropath) {
9079: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9080: }
9081: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9082: }
1.514 albertel 9083: return $listing;
1.512 banghart 9084: }
9085:
1.566 banghart 9086: sub is_locked {
1.1096 raeburn 9087: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9088: my @check;
9089: my $is_locked;
1.1093 raeburn 9090: push (@check,$file_name);
1.613 albertel 9091: my %locked = &get('file_permissions',\@check,
1.620 albertel 9092: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9093: my ($tmp)=keys(%locked);
9094: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9095:
1.566 banghart 9096: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9097: $is_locked = 'false';
9098: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9099: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9100: $is_locked = 'true';
1.1096 raeburn 9101: if (ref($which) eq 'ARRAY') {
9102: push(@{$which},$entry);
9103: } else {
9104: last;
9105: }
1.745 raeburn 9106: }
9107: }
1.566 banghart 9108: } else {
9109: $is_locked = 'false';
9110: }
1.1093 raeburn 9111: return $is_locked;
1.566 banghart 9112: }
9113:
1.759 albertel 9114: sub declutter_portfile {
9115: my ($file) = @_;
1.833 albertel 9116: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9117: return $file;
9118: }
9119:
1.559 banghart 9120: # ------------------------------------------------------------- Mark as Read Only
9121:
9122: sub mark_as_readonly {
9123: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9124: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9125: my ($tmp)=keys(%current_permissions);
9126: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9127: foreach my $file (@{$files}) {
1.759 albertel 9128: $file = &declutter_portfile($file);
1.561 banghart 9129: push(@{$current_permissions{$file}},$what);
1.559 banghart 9130: }
1.613 albertel 9131: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9132: return;
9133: }
9134:
1.572 banghart 9135: # ------------------------------------------------------------Save Selected Files
9136:
9137: sub save_selected_files {
9138: my ($user, $path, @files) = @_;
9139: my $filename = $user."savedfiles";
1.573 banghart 9140: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9141: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9142: foreach my $file (@files) {
1.620 albertel 9143: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9144: }
9145: foreach my $file (@other_files) {
1.574 banghart 9146: print (OUT $file."\n");
1.572 banghart 9147: }
1.574 banghart 9148: close (OUT);
1.572 banghart 9149: return 'ok';
9150: }
9151:
1.574 banghart 9152: sub clear_selected_files {
9153: my ($user) = @_;
9154: my $filename = $user."savedfiles";
1.1117 foxr 9155: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9156: print (OUT undef);
9157: close (OUT);
9158: return ("ok");
9159: }
9160:
1.572 banghart 9161: sub files_in_path {
9162: my ($user, $path) = @_;
9163: my $filename = $user."savedfiles";
9164: my %return_files;
1.1117 foxr 9165: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9166: while (my $line_in = <IN>) {
1.574 banghart 9167: chomp ($line_in);
9168: my @paths_and_file = split (m!/!, $line_in);
9169: my $file_part = pop (@paths_and_file);
9170: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9171: $path_part.='/';
9172: my $path_and_file = $path_part.$file_part;
9173: if ($path_part eq $path) {
9174: $return_files{$file_part}= 'selected';
9175: }
9176: }
1.574 banghart 9177: close (IN);
9178: return (\%return_files);
1.572 banghart 9179: }
9180:
9181: # called in portfolio select mode, to show files selected NOT in current directory
9182: sub files_not_in_path {
9183: my ($user, $path) = @_;
9184: my $filename = $user."savedfiles";
9185: my @return_files;
9186: my $path_part;
1.1117 foxr 9187: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9188: while (my $line = <IN>) {
1.572 banghart 9189: #ok, I know it's clunky, but I want it to work
1.800 albertel 9190: my @paths_and_file = split(m|/|, $line);
9191: my $file_part = pop(@paths_and_file);
9192: chomp($file_part);
9193: my $path_part = join('/', @paths_and_file);
1.572 banghart 9194: $path_part .= '/';
9195: my $path_and_file = $path_part.$file_part;
9196: if ($path_part ne $path) {
1.800 albertel 9197: push(@return_files, ($path_and_file));
1.572 banghart 9198: }
9199: }
1.800 albertel 9200: close(OUT);
1.574 banghart 9201: return (@return_files);
1.572 banghart 9202: }
9203:
1.745 raeburn 9204: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9205:
1.745 raeburn 9206: sub get_portfile_permissions {
9207: my ($domain,$user) = @_;
1.613 albertel 9208: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9209: my ($tmp)=keys(%current_permissions);
9210: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9211: return \%current_permissions;
9212: }
9213:
9214: #---------------------------------------------Get portfolio file access controls
9215:
1.749 raeburn 9216: sub get_access_controls {
1.745 raeburn 9217: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9218: my %access;
9219: my $real_file = $file;
9220: $file =~ s/\.meta$//;
1.745 raeburn 9221: if (defined($file)) {
1.749 raeburn 9222: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9223: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9224: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9225: }
9226: }
1.745 raeburn 9227: } else {
1.749 raeburn 9228: foreach my $key (keys(%{$current_permissions})) {
9229: if ($key =~ /\0accesscontrol$/) {
9230: if (defined($group)) {
9231: if ($key !~ m-^\Q$group\E/-) {
9232: next;
9233: }
9234: }
9235: my ($fullpath) = split(/\0/,$key);
9236: if (ref($$current_permissions{$key}) eq 'HASH') {
9237: foreach my $control (keys(%{$$current_permissions{$key}})) {
9238: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9239: }
9240: }
9241: }
9242: }
9243: }
9244: return %access;
9245: }
9246:
9247: sub modify_access_controls {
9248: my ($file_name,$changes,$domain,$user)=@_;
9249: my ($outcome,$deloutcome);
9250: my %store_permissions;
9251: my %new_values;
9252: my %new_control;
9253: my %translation;
9254: my @deletions = ();
9255: my $now = time;
9256: if (exists($$changes{'activate'})) {
9257: if (ref($$changes{'activate'}) eq 'HASH') {
9258: my @newitems = sort(keys(%{$$changes{'activate'}}));
9259: my $numnew = scalar(@newitems);
9260: for (my $i=0; $i<$numnew; $i++) {
9261: my $newkey = $newitems[$i];
9262: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9263: if ($newkey =~ /^\d+:/) {
9264: $newkey =~ s/^(\d+)/$newid/;
9265: $translation{$1} = $newid;
9266: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9267: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9268: $translation{$1} = $newid;
9269: }
1.749 raeburn 9270: $new_values{$file_name."\0".$newkey} =
9271: $$changes{'activate'}{$newitems[$i]};
9272: $new_control{$newkey} = $now;
9273: }
9274: }
9275: }
9276: my %todelete;
9277: my %changed_items;
9278: foreach my $action ('delete','update') {
9279: if (exists($$changes{$action})) {
9280: if (ref($$changes{$action}) eq 'HASH') {
9281: foreach my $key (keys(%{$$changes{$action}})) {
9282: my ($itemnum) = ($key =~ /^([^:]+):/);
9283: if ($action eq 'delete') {
9284: $todelete{$itemnum} = 1;
9285: } else {
9286: $changed_items{$itemnum} = $key;
9287: }
9288: }
1.745 raeburn 9289: }
9290: }
1.749 raeburn 9291: }
9292: # get lock on access controls for file.
9293: my $lockhash = {
9294: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9295: ':'.$env{'user.domain'},
9296: };
9297: my $tries = 0;
9298: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9299:
9300: while (($gotlock ne 'ok') && $tries <3) {
9301: $tries ++;
9302: sleep 1;
9303: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9304: }
9305: if ($gotlock eq 'ok') {
9306: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9307: my ($tmp)=keys(%curr_permissions);
9308: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9309: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9310: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9311: if (ref($curr_controls) eq 'HASH') {
9312: foreach my $control_item (keys(%{$curr_controls})) {
9313: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9314: if (defined($todelete{$itemnum})) {
9315: push(@deletions,$file_name."\0".$control_item);
9316: } else {
9317: if (defined($changed_items{$itemnum})) {
9318: $new_control{$changed_items{$itemnum}} = $now;
9319: push(@deletions,$file_name."\0".$control_item);
9320: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9321: } else {
9322: $new_control{$control_item} = $$curr_controls{$control_item};
9323: }
9324: }
1.745 raeburn 9325: }
9326: }
9327: }
1.970 raeburn 9328: my ($group);
9329: if (&is_course($domain,$user)) {
9330: ($group,my $file) = split(/\//,$file_name,2);
9331: }
1.749 raeburn 9332: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9333: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9334: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9335: # remove lock
9336: my @del_lock = ($file_name."\0".'locked_access_records');
9337: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9338: my $sqlresult =
1.970 raeburn 9339: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9340: $group);
1.749 raeburn 9341: } else {
9342: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9343: }
1.749 raeburn 9344: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9345: }
9346:
1.827 raeburn 9347: sub make_public_indefinitely {
9348: my ($requrl) = @_;
9349: my $now = time;
9350: my $action = 'activate';
9351: my $aclnum = 0;
9352: if (&is_portfolio_url($requrl)) {
9353: my (undef,$udom,$unum,$file_name,$group) =
9354: &parse_portfolio_url($requrl);
9355: my $current_perms = &get_portfile_permissions($udom,$unum);
9356: my %access_controls = &get_access_controls($current_perms,
9357: $group,$file_name);
9358: foreach my $key (keys(%{$access_controls{$file_name}})) {
9359: my ($num,$scope,$end,$start) =
9360: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9361: if ($scope eq 'public') {
9362: if ($start <= $now && $end == 0) {
9363: $action = 'none';
9364: } else {
9365: $action = 'update';
9366: $aclnum = $num;
9367: }
9368: last;
9369: }
9370: }
9371: if ($action eq 'none') {
9372: return 'ok';
9373: } else {
9374: my %changes;
9375: my $newend = 0;
9376: my $newstart = $now;
9377: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9378: $changes{$action}{$newkey} = {
9379: type => 'public',
9380: time => {
9381: start => $newstart,
9382: end => $newend,
9383: },
9384: };
9385: my ($outcome,$deloutcome,$new_values,$translation) =
9386: &modify_access_controls($file_name,\%changes,$udom,$unum);
9387: return $outcome;
9388: }
9389: } else {
9390: return 'invalid';
9391: }
9392: }
9393:
1.745 raeburn 9394: #------------------------------------------------------Get Marked as Read Only
9395:
9396: sub get_marked_as_readonly {
9397: my ($domain,$user,$what,$group) = @_;
9398: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9399: my @readonly_files;
1.629 banghart 9400: my $cmp1=$what;
9401: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9402: while (my ($file_name,$value) = each(%{$current_permissions})) {
9403: if (defined($group)) {
9404: if ($file_name !~ m-^\Q$group\E/-) {
9405: next;
9406: }
9407: }
1.561 banghart 9408: if (ref($value) eq "ARRAY"){
9409: foreach my $stored_what (@{$value}) {
1.629 banghart 9410: my $cmp2=$stored_what;
1.759 albertel 9411: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9412: $cmp2=join('',@{$stored_what});
1.745 raeburn 9413: }
1.629 banghart 9414: if ($cmp1 eq $cmp2) {
1.561 banghart 9415: push(@readonly_files, $file_name);
1.745 raeburn 9416: last;
1.563 banghart 9417: } elsif (!defined($what)) {
9418: push(@readonly_files, $file_name);
1.745 raeburn 9419: last;
1.561 banghart 9420: }
9421: }
1.745 raeburn 9422: }
1.561 banghart 9423: }
9424: return @readonly_files;
9425: }
1.577 banghart 9426: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9427:
1.577 banghart 9428: sub get_marked_as_readonly_hash {
1.745 raeburn 9429: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9430: my %readonly_files;
1.745 raeburn 9431: while (my ($file_name,$value) = each(%{$current_permissions})) {
9432: if (defined($group)) {
9433: if ($file_name !~ m-^\Q$group\E/-) {
9434: next;
9435: }
9436: }
1.577 banghart 9437: if (ref($value) eq "ARRAY"){
9438: foreach my $stored_what (@{$value}) {
1.745 raeburn 9439: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9440: foreach my $lock_descriptor(@{$stored_what}) {
9441: if ($lock_descriptor eq 'graded') {
9442: $readonly_files{$file_name} = 'graded';
9443: } elsif ($lock_descriptor eq 'handback') {
9444: $readonly_files{$file_name} = 'handback';
9445: } else {
9446: if (!exists($readonly_files{$file_name})) {
9447: $readonly_files{$file_name} = 'locked';
9448: }
9449: }
1.745 raeburn 9450: }
1.750 banghart 9451: }
1.577 banghart 9452: }
9453: }
9454: }
9455: return %readonly_files;
9456: }
1.559 banghart 9457: # ------------------------------------------------------------ Unmark as Read Only
9458:
9459: sub unmark_as_readonly {
1.629 banghart 9460: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9461: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9462: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9463: $file_name = &declutter_portfile($file_name);
1.634 albertel 9464: my $symb_crs = $what;
9465: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9466: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9467: my ($tmp)=keys(%current_permissions);
9468: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9469: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9470: foreach my $file (@readonly_files) {
1.759 albertel 9471: my $clean_file = &declutter_portfile($file);
9472: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9473: my $current_locks = $current_permissions{$file};
1.563 banghart 9474: my @new_locks;
9475: my @del_keys;
9476: if (ref($current_locks) eq "ARRAY"){
9477: foreach my $locker (@{$current_locks}) {
1.632 albertel 9478: my $compare=$locker;
1.749 raeburn 9479: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9480: $compare=join('',@{$locker});
1.746 raeburn 9481: if ($compare ne $symb_crs) {
9482: push(@new_locks, $locker);
9483: }
1.563 banghart 9484: }
9485: }
1.650 albertel 9486: if (scalar(@new_locks) > 0) {
1.563 banghart 9487: $current_permissions{$file} = \@new_locks;
9488: } else {
9489: push(@del_keys, $file);
1.613 albertel 9490: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9491: delete($current_permissions{$file});
1.563 banghart 9492: }
9493: }
1.561 banghart 9494: }
1.613 albertel 9495: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9496: return;
9497: }
1.512 banghart 9498:
1.17 www 9499: # ------------------------------------------------------------ Directory lister
9500:
9501: sub dirlist {
1.955 raeburn 9502: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9503: $uri=~s/^\///;
9504: $uri=~s/\/$//;
1.253 stredwic 9505: my ($udom, $uname);
1.955 raeburn 9506: if ($getuserdir) {
1.253 stredwic 9507: $udom = $userdomain;
9508: $uname = $username;
1.955 raeburn 9509: } else {
9510: (undef,$udom,$uname)=split(/\//,$uri);
9511: if(defined($userdomain)) {
9512: $udom = $userdomain;
9513: }
9514: if(defined($username)) {
9515: $uname = $username;
9516: }
1.253 stredwic 9517: }
1.955 raeburn 9518: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9519:
1.955 raeburn 9520: $dirRoot = $perlvar{'lonDocRoot'};
9521: if (defined($getpropath)) {
9522: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9523: $dirRoot =~ s/\/$//;
1.955 raeburn 9524: } elsif (defined($getuserdir)) {
9525: my $subdir=$uname.'__';
9526: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9527: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9528: ."/$udom/$subdir/$uname";
9529: } elsif (defined($alternateRoot)) {
9530: $dirRoot = $alternateRoot;
1.751 banghart 9531: }
1.253 stredwic 9532:
9533: if($udom) {
9534: if($uname) {
1.1135 raeburn 9535: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9536: if ($uhome eq 'no_host') {
9537: return ([],'no_host');
9538: }
1.955 raeburn 9539: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9540: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9541: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9542: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9543: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9544: } else {
9545: @listing_results = map { &unescape($_); } split(/:/,$listing);
9546: }
1.605 matthew 9547: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9548: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9549: @listing_results = split(/:/,$listing);
9550: } else {
9551: @listing_results = map { &unescape($_); } split(/:/,$listing);
9552: }
1.1135 raeburn 9553: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9554: ($listing eq 'rejected') || ($listing eq 'refused') ||
9555: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9556: return ([],$listing);
9557: } else {
9558: return (\@listing_results);
1.1135 raeburn 9559: }
1.955 raeburn 9560: } elsif(!$alternateRoot) {
1.1136 raeburn 9561: my (%allusers,%listerror);
1.841 albertel 9562: my %servers = &get_servers($udom,'library');
1.955 raeburn 9563: foreach my $tryserver (keys(%servers)) {
9564: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9565: &escape($udom),$tryserver);
9566: if ($listing eq 'unknown_cmd') {
9567: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9568: $udom, $tryserver);
9569: } else {
9570: @listing_results = map { &unescape($_); } split(/:/,$listing);
9571: }
1.841 albertel 9572: if ($listing eq 'unknown_cmd') {
9573: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9574: $udom, $tryserver);
9575: @listing_results = split(/:/,$listing);
9576: } else {
9577: @listing_results =
9578: map { &unescape($_); } split(/:/,$listing);
9579: }
1.1136 raeburn 9580: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9581: ($listing eq 'rejected') || ($listing eq 'refused') ||
9582: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9583: $listerror{$tryserver} = $listing;
9584: } else {
1.841 albertel 9585: foreach my $line (@listing_results) {
9586: my ($entry) = split(/&/,$line,2);
9587: $allusers{$entry} = 1;
9588: }
9589: }
1.253 stredwic 9590: }
1.1136 raeburn 9591: my @alluserslist=();
1.800 albertel 9592: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9593: push(@alluserslist,$user.'&user');
1.253 stredwic 9594: }
1.1136 raeburn 9595: return (\@alluserslist);
1.253 stredwic 9596: } else {
1.1136 raeburn 9597: return ([],'missing username');
1.253 stredwic 9598: }
1.955 raeburn 9599: } elsif(!defined($getpropath)) {
1.1136 raeburn 9600: my $path = $perlvar{'lonDocRoot'}.'/res/';
9601: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9602: return (\@all_domains);
1.955 raeburn 9603: } else {
1.1136 raeburn 9604: return ([],'missing domain');
1.275 stredwic 9605: }
9606: }
9607:
9608: # --------------------------------------------- GetFileTimestamp
9609: # This function utilizes dirlist and returns the date stamp for
9610: # when it was last modified. It will also return an error of -1
9611: # if an error occurs
9612:
9613: sub GetFileTimestamp {
1.955 raeburn 9614: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9615: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9616: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9617: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9618: undef,$getuserdir);
9619: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9620: return -1;
9621: }
9622: if (ref($fileref) eq 'ARRAY') {
9623: my @stats = split('&',$fileref->[0]);
1.375 matthew 9624: # @stats contains first the filename, then the stat output
9625: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9626: } else {
9627: return -1;
1.253 stredwic 9628: }
1.26 www 9629: }
9630:
1.712 albertel 9631: sub stat_file {
9632: my ($uri) = @_;
1.787 albertel 9633: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9634:
1.955 raeburn 9635: my ($udom,$uname,$file);
1.712 albertel 9636: if ($uri =~ m-^/(uploaded|editupload)/-) {
9637: ($udom,$uname,$file) =
1.811 albertel 9638: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9639: $file = 'userfiles/'.$file;
9640: }
9641: if ($uri =~ m-^/res/-) {
9642: ($udom,$uname) =
1.807 albertel 9643: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9644: $file = $uri;
9645: }
9646:
9647: if (!$udom || !$uname || !$file) {
9648: # unable to handle the uri
9649: return ();
9650: }
1.956 raeburn 9651: my $getpropath;
9652: if ($file =~ /^userfiles\//) {
9653: $getpropath = 1;
9654: }
1.1136 raeburn 9655: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9656: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9657: return ();
9658: } else {
9659: if (ref($listref) eq 'ARRAY') {
9660: my @stats = split('&',$listref->[0]);
9661: shift(@stats); #filename is first
9662: return @stats;
9663: }
1.712 albertel 9664: }
9665: return ();
9666: }
9667:
1.26 www 9668: # -------------------------------------------------------- Value of a Condition
9669:
1.713 albertel 9670: # gets the value of a specific preevaluated condition
9671: # stored in the string $env{user.state.<cid>}
9672: # or looks up a condition reference in the bighash and if if hasn't
9673: # already been evaluated recurses into docondval to get the value of
9674: # the condition, then memoizing it to
9675: # $env{user.state.<cid>.<condition>}
1.40 www 9676: sub directcondval {
9677: my $number=shift;
1.620 albertel 9678: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9679: &Apache::lonuserstate::evalstate();
9680: }
1.713 albertel 9681: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9682: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9683: } elsif ($number =~ /^_/) {
9684: my $sub_condition;
9685: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9686: &GDBM_READER(),0640)) {
9687: $sub_condition=$bighash{'conditions'.$number};
9688: untie(%bighash);
9689: }
9690: my $value = &docondval($sub_condition);
1.949 raeburn 9691: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9692: return $value;
9693: }
1.620 albertel 9694: if ($env{'user.state.'.$env{'request.course.id'}}) {
9695: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9696: } else {
9697: return 2;
9698: }
9699: }
9700:
1.713 albertel 9701: # get the collection of conditions for this resource
1.26 www 9702: sub condval {
9703: my $condidx=shift;
1.54 www 9704: my $allpathcond='';
1.713 albertel 9705: foreach my $cond (split(/\|/,$condidx)) {
9706: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9707: $allpathcond.=
9708: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9709: }
1.191 harris41 9710: }
1.54 www 9711: $allpathcond=~s/\|$//;
1.713 albertel 9712: return &docondval($allpathcond);
9713: }
9714:
9715: #evaluates an expression of conditions
9716: sub docondval {
9717: my ($allpathcond) = @_;
9718: my $result=0;
9719: if ($env{'request.course.id'}
9720: && defined($allpathcond)) {
9721: my $operand='|';
9722: my @stack;
9723: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9724: if ($chunk eq '(') {
9725: push @stack,($operand,$result);
9726: } elsif ($chunk eq ')') {
9727: my $before=pop @stack;
9728: if (pop @stack eq '&') {
9729: $result=$result>$before?$before:$result;
9730: } else {
9731: $result=$result>$before?$result:$before;
9732: }
9733: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9734: $operand=$chunk;
9735: } else {
9736: my $new=directcondval($chunk);
9737: if ($operand eq '&') {
9738: $result=$result>$new?$new:$result;
9739: } else {
9740: $result=$result>$new?$result:$new;
9741: }
9742: }
9743: }
1.26 www 9744: }
9745: return $result;
1.421 albertel 9746: }
9747:
9748: # ---------------------------------------------------- Devalidate courseresdata
9749:
9750: sub devalidatecourseresdata {
9751: my ($coursenum,$coursedomain)=@_;
9752: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9753: &devalidate_cache_new('courseres',$hashid);
1.28 www 9754: }
9755:
1.763 www 9756:
1.200 www 9757: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9758: #
9759: # Parameters:
9760: # $coursenum - Number of the course.
9761: # $coursedomain - Domain at which the course was created.
9762: # Returns:
9763: # A hash of the course parameters along (I think) with timestamps
9764: # and version info.
1.877 foxr 9765:
1.624 albertel 9766: sub get_courseresdata {
9767: my ($coursenum,$coursedomain)=@_;
1.200 www 9768: my $coursehom=&homeserver($coursenum,$coursedomain);
9769: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9770: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9771: my %dumpreply;
1.417 albertel 9772: unless (defined($cached)) {
1.624 albertel 9773: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9774: $result=\%dumpreply;
1.251 albertel 9775: my ($tmp) = keys(%dumpreply);
9776: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9777: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9778: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9779: return $tmp;
1.416 albertel 9780: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9781: $result=undef;
1.599 albertel 9782: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9783: }
9784: }
1.624 albertel 9785: return $result;
9786: }
9787:
1.633 albertel 9788: sub devalidateuserresdata {
9789: my ($uname,$udom)=@_;
9790: my $hashid="$udom:$uname";
9791: &devalidate_cache_new('userres',$hashid);
9792: }
9793:
1.624 albertel 9794: sub get_userresdata {
9795: my ($uname,$udom)=@_;
9796: #most student don\'t have any data set, check if there is some data
9797: if (&EXT_cache_status($udom,$uname)) { return undef; }
9798:
9799: my $hashid="$udom:$uname";
9800: my ($result,$cached)=&is_cached_new('userres',$hashid);
9801: if (!defined($cached)) {
9802: my %resourcedata=&dump('resourcedata',$udom,$uname);
9803: $result=\%resourcedata;
9804: &do_cache_new('userres',$hashid,$result,600);
9805: }
9806: my ($tmp)=keys(%$result);
9807: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9808: return $result;
9809: }
9810: #error 2 occurs when the .db doesn't exist
9811: if ($tmp!~/error: 2 /) {
1.672 albertel 9812: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9813: " Trying to get resource data for ".
9814: $uname." at ".$udom.": ".
9815: $tmp."</font>");
9816: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9817: #&EXT_cache_set($udom,$uname);
9818: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9819: undef($tmp); # not really an error so don't send it back
1.624 albertel 9820: }
9821: return $tmp;
9822: }
1.879 foxr 9823: #----------------------------------------------- resdata - return resource data
9824: # Purpose:
9825: # Return resource data for either users or for a course.
9826: # Parameters:
9827: # $name - Course/user name.
9828: # $domain - Name of the domain the user/course is registered on.
9829: # $type - Type of thing $name is (must be 'course' or 'user'
9830: # @which - Array of names of resources desired.
9831: # Returns:
9832: # The value of the first reasource in @which that is found in the
9833: # resource hash.
9834: # Exceptional Conditions:
9835: # If the $type passed in is not valid (not the string 'course' or
9836: # 'user', an undefined reference is returned.
9837: # If none of the resources are found, an undef is returned
1.624 albertel 9838: sub resdata {
9839: my ($name,$domain,$type,@which)=@_;
9840: my $result;
9841: if ($type eq 'course') {
9842: $result=&get_courseresdata($name,$domain);
9843: } elsif ($type eq 'user') {
9844: $result=&get_userresdata($name,$domain);
9845: }
9846: if (!ref($result)) { return $result; }
1.251 albertel 9847: foreach my $item (@which) {
1.927 albertel 9848: if (defined($result->{$item->[0]})) {
9849: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9850: }
1.250 albertel 9851: }
1.291 albertel 9852: return undef;
1.200 www 9853: }
9854:
1.1172.2.31 raeburn 9855: sub get_numsuppfiles {
9856: my ($cnum,$cdom,$ignorecache)=@_;
9857: my $hashid=$cnum.':'.$cdom;
9858: my ($suppcount,$cached);
9859: unless ($ignorecache) {
9860: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9861: }
9862: unless (defined($cached)) {
9863: my $chome=&homeserver($cnum,$cdom);
9864: unless ($chome eq 'no_host') {
9865: ($suppcount,my $errors) = (0,0);
9866: my $suppmap = 'supplemental.sequence';
9867: ($suppcount,$errors) =
9868: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9869: }
9870: &do_cache_new('suppcount',$hashid,$suppcount,600);
9871: }
9872: return $suppcount;
9873: }
9874:
1.379 matthew 9875: #
9876: # EXT resource caching routines
9877: #
9878:
9879: sub clear_EXT_cache_status {
1.383 albertel 9880: &delenv('cache.EXT.');
1.379 matthew 9881: }
9882:
9883: sub EXT_cache_status {
9884: my ($target_domain,$target_user) = @_;
1.383 albertel 9885: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9886: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9887: # We know already the user has no data
9888: return 1;
9889: } else {
9890: return 0;
9891: }
9892: }
9893:
9894: sub EXT_cache_set {
9895: my ($target_domain,$target_user) = @_;
1.383 albertel 9896: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9897: #&appenv({$cachename => time});
1.379 matthew 9898: }
9899:
1.28 www 9900: # --------------------------------------------------------- Value of a Variable
1.58 www 9901: sub EXT {
1.715 albertel 9902:
1.1172.2.28 raeburn 9903: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9904: unless ($varname) { return ''; }
1.218 albertel 9905: #get real user name/domain, courseid and symb
9906: my $courseid;
1.359 albertel 9907: my $publicuser;
1.427 www 9908: if ($symbparm) {
9909: $symbparm=&get_symb_from_alias($symbparm);
9910: }
1.218 albertel 9911: if (!($uname && $udom)) {
1.790 albertel 9912: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9913: if (!$symbparm) { $symbparm=$cursymb; }
9914: } else {
1.620 albertel 9915: $courseid=$env{'request.course.id'};
1.218 albertel 9916: }
1.48 www 9917: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9918: my $rest;
1.320 albertel 9919: if (defined($therest[0])) {
1.48 www 9920: $rest=join('.',@therest);
9921: } else {
9922: $rest='';
9923: }
1.320 albertel 9924:
1.57 www 9925: my $qualifierrest=$qualifier;
9926: if ($rest) { $qualifierrest.='.'.$rest; }
9927: my $spacequalifierrest=$space;
9928: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9929: if ($realm eq 'user') {
1.48 www 9930: # --------------------------------------------------------------- user.resource
9931: if ($space eq 'resource') {
1.651 albertel 9932: if ( (defined($Apache::lonhomework::parsing_a_problem)
9933: || defined($Apache::lonhomework::parsing_a_task))
9934: &&
1.744 albertel 9935: ($symbparm eq &symbread()) ) {
9936: # if we are in the middle of processing the resource the
9937: # get the value we are planning on committing
9938: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9939: return $Apache::lonhomework::results{$qualifierrest};
9940: } else {
9941: return $Apache::lonhomework::history{$qualifierrest};
9942: }
1.335 albertel 9943: } else {
1.359 albertel 9944: my %restored;
1.620 albertel 9945: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9946: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9947: } else {
9948: %restored=&restore($symbparm,$courseid,$udom,$uname);
9949: }
1.335 albertel 9950: return $restored{$qualifierrest};
9951: }
1.48 www 9952: # ----------------------------------------------------------------- user.access
9953: } elsif ($space eq 'access') {
1.218 albertel 9954: # FIXME - not supporting calls for a specific user
1.48 www 9955: return &allowed($qualifier,$rest);
9956: # ------------------------------------------ user.preferences, user.environment
9957: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9958: if (($uname eq $env{'user.name'}) &&
9959: ($udom eq $env{'user.domain'})) {
9960: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9961: } else {
1.359 albertel 9962: my %returnhash;
9963: if (!$publicuser) {
9964: %returnhash=&userenvironment($udom,$uname,
9965: $qualifierrest);
9966: }
1.218 albertel 9967: return $returnhash{$qualifierrest};
9968: }
1.48 www 9969: # ----------------------------------------------------------------- user.course
9970: } elsif ($space eq 'course') {
1.218 albertel 9971: # FIXME - not supporting calls for a specific user
1.620 albertel 9972: return $env{join('.',('request.course',$qualifier))};
1.48 www 9973: # ------------------------------------------------------------------- user.role
9974: } elsif ($space eq 'role') {
1.218 albertel 9975: # FIXME - not supporting calls for a specific user
1.620 albertel 9976: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9977: if ($qualifier eq 'value') {
9978: return $role;
9979: } elsif ($qualifier eq 'extent') {
9980: return $where;
9981: }
9982: # ----------------------------------------------------------------- user.domain
9983: } elsif ($space eq 'domain') {
1.218 albertel 9984: return $udom;
1.48 www 9985: # ------------------------------------------------------------------- user.name
9986: } elsif ($space eq 'name') {
1.218 albertel 9987: return $uname;
1.48 www 9988: # ---------------------------------------------------- Any other user namespace
1.29 www 9989: } else {
1.359 albertel 9990: my %reply;
9991: if (!$publicuser) {
9992: %reply=&get($space,[$qualifierrest],$udom,$uname);
9993: }
9994: return $reply{$qualifierrest};
1.48 www 9995: }
1.236 www 9996: } elsif ($realm eq 'query') {
9997: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9998: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9999: [$spacequalifierrest]);
1.620 albertel 10000: return $env{'form.'.$spacequalifierrest};
1.236 www 10001: } elsif ($realm eq 'request') {
1.48 www 10002: # ------------------------------------------------------------- request.browser
10003: if ($space eq 'browser') {
1.1145 bisitz 10004: return $env{'browser.'.$qualifier};
1.57 www 10005: # ------------------------------------------------------------ request.filename
10006: } else {
1.620 albertel 10007: return $env{'request.'.$spacequalifierrest};
1.29 www 10008: }
1.28 www 10009: } elsif ($realm eq 'course') {
1.48 www 10010: # ---------------------------------------------------------- course.description
1.620 albertel 10011: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10012: } elsif ($realm eq 'resource') {
1.165 www 10013:
1.620 albertel 10014: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10015: if (!$symbparm) { $symbparm=&symbread(); }
10016: }
1.693 albertel 10017:
1.1172.2.30 raeburn 10018: if ($qualifier eq '') {
10019: if ($space eq 'title') {
10020: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10021: return &gettitle($symbparm);
10022: }
1.693 albertel 10023:
1.1172.2.30 raeburn 10024: if ($space eq 'map') {
10025: my ($map) = &decode_symb($symbparm);
10026: return &symbread($map);
10027: }
10028: if ($space eq 'maptitle') {
10029: my ($map) = &decode_symb($symbparm);
10030: return &gettitle($map);
10031: }
10032: if ($space eq 'filename') {
10033: if ($symbparm) {
10034: return &clutter((&decode_symb($symbparm))[2]);
10035: }
10036: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10037: }
1.1172.2.30 raeburn 10038:
10039: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10040: if ($space eq 'visibleparts') {
10041: my $navmap = Apache::lonnavmaps::navmap->new();
10042: my $item;
10043: if (ref($navmap)) {
10044: my $res = $navmap->getBySymb($symbparm);
10045: my $parts = $res->parts();
10046: if (ref($parts) eq 'ARRAY') {
10047: $item = join(',',@{$parts});
10048: }
10049: undef($navmap);
10050: }
10051: return $item;
10052: }
10053: }
10054: }
1.693 albertel 10055:
10056: my ($section, $group, @groups);
1.593 albertel 10057: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10058: if (($courseid eq '') && ($cid)) {
10059: $courseid = $cid;
10060: }
10061: if (($symbparm && $courseid) &&
10062: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10063:
1.218 albertel 10064: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10065:
1.60 www 10066: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10067: my $symbp=$symbparm;
1.735 albertel 10068: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10069:
10070: my $symbparm=$symbp.'.'.$spacequalifierrest;
10071: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10072:
1.620 albertel 10073: if (($env{'user.name'} eq $uname) &&
10074: ($env{'user.domain'} eq $udom)) {
10075: $section=$env{'request.course.sec'};
1.733 raeburn 10076: @groups = split(/:/,$env{'request.course.groups'});
10077: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10078: } else {
1.539 albertel 10079: if (! defined($usection)) {
1.551 albertel 10080: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10081: } else {
10082: $section = $usection;
10083: }
1.733 raeburn 10084: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10085: }
10086:
10087: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10088: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10089: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10090:
1.593 albertel 10091: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10092: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10093: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10094:
1.60 www 10095: # ----------------------------------------------------------- first, check user
1.624 albertel 10096:
10097: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10098: ([$courselevelr,'resource'],
10099: [$courselevelm,'map' ],
10100: [$courselevel, 'course' ]));
1.931 albertel 10101: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10102:
1.594 albertel 10103: # ------------------------------------------------ second, check some of course
1.684 raeburn 10104: my $coursereply;
1.691 raeburn 10105: if (@groups > 0) {
10106: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10107: $mapparm,$spacequalifierrest);
1.927 albertel 10108: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10109: }
1.96 www 10110:
1.684 raeburn 10111: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10112: $env{'course.'.$courseid.'.domain'},
10113: 'course',
10114: ([$seclevelr, 'resource'],
10115: [$seclevelm, 'map' ],
10116: [$seclevel, 'course' ],
10117: [$courselevelr,'resource']));
10118: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10119:
1.60 www 10120: # ------------------------------------------------------ third, check map parms
1.218 albertel 10121: my %parmhash=();
10122: my $thisparm='';
10123: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10124: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10125: &GDBM_READER(),0640)) {
1.218 albertel 10126: $thisparm=$parmhash{$symbparm};
10127: untie(%parmhash);
10128: }
1.927 albertel 10129: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10130: }
1.594 albertel 10131: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10132:
1.218 albertel 10133: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10134: my $filename;
10135: if (!$symbparm) { $symbparm=&symbread(); }
10136: if ($symbparm) {
1.409 www 10137: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10138: } else {
1.620 albertel 10139: $filename=$env{'request.filename'};
1.282 albertel 10140: }
10141: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10142: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10143: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10144: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10145:
1.927 albertel 10146: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10147: if ($symbparm && defined($courseid) &&
1.620 albertel 10148: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10149: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10150: $env{'course.'.$courseid.'.domain'},
10151: 'course',
1.927 albertel 10152: ([$courselevelm,'map' ],
10153: [$courselevel, 'course']));
10154: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10155: }
1.145 www 10156: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10157: unless ($space eq '0') {
1.336 albertel 10158: my @parts=split(/_/,$space);
10159: my $id=pop(@parts);
10160: my $part=join('_',@parts);
10161: if ($part eq '') { $part='0'; }
1.927 albertel 10162: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10163: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10164: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10165: }
1.395 albertel 10166: if ($recurse) { return undef; }
10167: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10168: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10169: # ---------------------------------------------------- Any other user namespace
10170: } elsif ($realm eq 'environment') {
10171: # ----------------------------------------------------------------- environment
1.620 albertel 10172: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10173: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10174: } else {
1.770 albertel 10175: if ($uname eq 'anonymous' && $udom eq '') {
10176: return '';
10177: }
1.219 albertel 10178: my %returnhash=&userenvironment($udom,$uname,
10179: $spacequalifierrest);
10180: return $returnhash{$spacequalifierrest};
10181: }
1.28 www 10182: } elsif ($realm eq 'system') {
1.48 www 10183: # ----------------------------------------------------------------- system.time
10184: if ($space eq 'time') {
10185: return time;
10186: }
1.696 albertel 10187: } elsif ($realm eq 'server') {
10188: # ----------------------------------------------------------------- system.time
10189: if ($space eq 'name') {
10190: return $ENV{'SERVER_NAME'};
10191: }
1.28 www 10192: }
1.48 www 10193: return '';
1.61 www 10194: }
10195:
1.927 albertel 10196: sub get_reply {
10197: my ($reply_value) = @_;
1.940 raeburn 10198: if (ref($reply_value) eq 'ARRAY') {
10199: if (wantarray) {
10200: return @$reply_value;
10201: }
10202: return $reply_value->[0];
10203: } else {
10204: return $reply_value;
1.927 albertel 10205: }
10206: }
10207:
1.691 raeburn 10208: sub check_group_parms {
10209: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10210: my @groupitems = ();
10211: my $resultitem;
1.927 albertel 10212: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10213: foreach my $group (@{$groups}) {
10214: foreach my $level (@levels) {
1.927 albertel 10215: my $item = $courseid.'.['.$group.'].'.$level->[0];
10216: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10217: }
10218: }
10219: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10220: $env{'course.'.$courseid.'.domain'},
10221: 'course',@groupitems);
10222: return $coursereply;
10223: }
10224:
10225: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10226: my ($courseid,@groups) = @_;
10227: @groups = sort(@groups);
1.691 raeburn 10228: return @groups;
10229: }
10230:
1.395 albertel 10231: sub packages_tab_default {
10232: my ($uri,$varname)=@_;
10233: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10234:
10235: my (@extension,@specifics,$do_default);
10236: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10237: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10238: if ($pack_type eq 'default') {
10239: $do_default=1;
10240: } elsif ($pack_type eq 'extension') {
10241: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10242: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10243: # only look at packages defaults for packages that this id is
1.738 albertel 10244: push(@specifics,[$package,$pack_type,$pack_part]);
10245: }
10246: }
10247: # first look for a package that matches the requested part id
10248: foreach my $package (@specifics) {
10249: my (undef,$pack_type,$pack_part)=@{$package};
10250: next if ($pack_part ne $part);
10251: if (defined($packagetab{"$pack_type&$name&default"})) {
10252: return $packagetab{"$pack_type&$name&default"};
10253: }
10254: }
10255: # look for any possible matching non extension_ package
10256: foreach my $package (@specifics) {
10257: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10258: if (defined($packagetab{"$pack_type&$name&default"})) {
10259: return $packagetab{"$pack_type&$name&default"};
10260: }
1.585 albertel 10261: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10262: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10263: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10264: }
10265: }
1.738 albertel 10266: # look for any posible extension_ match
10267: foreach my $package (@extension) {
10268: my ($package,$pack_type)=@{$package};
10269: if (defined($packagetab{"$pack_type&$name&default"})) {
10270: return $packagetab{"$pack_type&$name&default"};
10271: }
10272: if (defined($packagetab{$package."&$name&default"})) {
10273: return $packagetab{$package."&$name&default"};
10274: }
10275: }
10276: # look for a global default setting
10277: if ($do_default && defined($packagetab{"default&$name&default"})) {
10278: return $packagetab{"default&$name&default"};
10279: }
1.395 albertel 10280: return undef;
10281: }
10282:
1.334 albertel 10283: sub add_prefix_and_part {
10284: my ($prefix,$part)=@_;
10285: my $keyroot;
10286: if (defined($prefix) && $prefix !~ /^__/) {
10287: # prefix that has a part already
10288: $keyroot=$prefix;
10289: } elsif (defined($prefix)) {
10290: # prefix that is missing a part
10291: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10292: } else {
10293: # no prefix at all
10294: if (defined($part)) { $keyroot='_'.$part; }
10295: }
10296: return $keyroot;
10297: }
10298:
1.71 www 10299: # ---------------------------------------------------------------- Get metadata
10300:
1.599 albertel 10301: my %metaentry;
1.1070 www 10302: my %importedpartids;
1.71 www 10303: sub metadata {
1.176 www 10304: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10305: $uri=&declutter($uri);
1.288 albertel 10306: # if it is a non metadata possible uri return quickly
1.529 albertel 10307: if (($uri eq '') ||
10308: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10309: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10310: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10311: return undef;
10312: }
1.1172.2.49 raeburn 10313: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10314: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10315: return undef;
1.288 albertel 10316: }
1.73 www 10317: my $filename=$uri;
10318: $uri=~s/\.meta$//;
1.172 www 10319: #
10320: # Is the metadata already cached?
1.177 www 10321: # Look at timestamp of caching
1.172 www 10322: # Everything is cached by the main uri, libraries are never directly cached
10323: #
1.428 albertel 10324: if (!defined($liburi)) {
1.599 albertel 10325: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10326: if (defined($cached)) { return $result->{':'.$what}; }
10327: }
10328: {
1.1069 www 10329: # Imported parts would go here
1.1070 www 10330: my %importedids=();
10331: my @origfileimportpartids=();
1.1069 www 10332: my $importedparts=0;
1.172 www 10333: #
10334: # Is this a recursive call for a library?
10335: #
1.599 albertel 10336: # if (! exists($metacache{$uri})) {
10337: # $metacache{$uri}={};
10338: # }
1.924 albertel 10339: my $cachetime = 60*60;
1.171 www 10340: if ($liburi) {
10341: $liburi=&declutter($liburi);
10342: $filename=$liburi;
1.401 bowersj2 10343: } else {
1.599 albertel 10344: &devalidate_cache_new('meta',$uri);
10345: undef(%metaentry);
1.401 bowersj2 10346: }
1.140 www 10347: my %metathesekeys=();
1.73 www 10348: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10349: my $metastring;
1.1140 www 10350: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10351: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10352: $metastring =
1.929 albertel 10353: &Apache::lonnet::ssi_body($which,
1.924 albertel 10354: ('grade_target' => 'meta'));
10355: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10356: } elsif (($uri !~ m -^(editupload)/-) &&
10357: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10358: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10359: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10360: $metastring=&getfile($file);
1.489 albertel 10361: }
1.208 albertel 10362: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10363: my $token;
1.140 www 10364: undef %metathesekeys;
1.71 www 10365: while ($token=$parser->get_token) {
1.339 albertel 10366: if ($token->[0] eq 'S') {
10367: if (defined($token->[2]->{'package'})) {
1.172 www 10368: #
10369: # This is a package - get package info
10370: #
1.339 albertel 10371: my $package=$token->[2]->{'package'};
10372: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10373: if (defined($token->[2]->{'id'})) {
10374: $keyroot.='_'.$token->[2]->{'id'};
10375: }
1.599 albertel 10376: if ($metaentry{':packages'}) {
10377: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10378: } else {
1.599 albertel 10379: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10380: }
1.736 albertel 10381: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10382: my $part=$keyroot;
10383: $part=~s/^\_//;
1.736 albertel 10384: if ($pack_entry=~/^\Q$package\E\&/ ||
10385: $pack_entry=~/^\Q$package\E_0\&/) {
10386: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10387: # ignore package.tab specified default values
10388: # here &package_tab_default() will fetch those
10389: if ($subp eq 'default') { next; }
1.736 albertel 10390: my $value=$packagetab{$pack_entry};
1.432 albertel 10391: my $unikey;
10392: if ($pack =~ /_0$/) {
10393: $unikey='parameter_0_'.$name;
10394: $part=0;
10395: } else {
10396: $unikey='parameter'.$keyroot.'_'.$name;
10397: }
1.339 albertel 10398: if ($subp eq 'display') {
10399: $value.=' [Part: '.$part.']';
10400: }
1.599 albertel 10401: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10402: $metathesekeys{$unikey}=1;
1.599 albertel 10403: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10404: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10405: }
1.599 albertel 10406: if (defined($metaentry{':'.$unikey.'.default'})) {
10407: $metaentry{':'.$unikey}=
10408: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10409: }
1.339 albertel 10410: }
10411: }
10412: } else {
1.172 www 10413: #
10414: # This is not a package - some other kind of start tag
1.339 albertel 10415: #
10416: my $entry=$token->[1];
1.1068 www 10417: my $unikey='';
1.175 www 10418:
1.339 albertel 10419: if ($entry eq 'import') {
1.175 www 10420: #
10421: # Importing a library here
1.339 albertel 10422: #
1.1067 www 10423: my $location=$parser->get_text('/import');
10424: my $dir=$filename;
10425: $dir=~s|[^/]*$||;
10426: $location=&filelocation($dir,$location);
1.1069 www 10427:
1.1068 www 10428: my $importmode=$token->[2]->{'importmode'};
10429: if ($importmode eq 'problem') {
1.1069 www 10430: # Import as problem/response
1.1068 www 10431: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10432: } elsif ($importmode eq 'part') {
10433: # Import as part(s)
1.1069 www 10434: $importedparts=1;
10435: # We need to get the original file and the imported file to get the part order correct
10436: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10437: # Load and inspect original file
1.1070 www 10438: if ($#origfileimportpartids<0) {
10439: undef(%importedpartids);
10440: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10441: my $origfile=&getfile($origfilelocation);
10442: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10443: }
10444:
1.1069 www 10445: # Load and inspect imported file
10446: my $impfile=&getfile($location);
10447: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10448: if ($#impfilepartids>=0) {
10449: # This problem had parts
1.1070 www 10450: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10451: } else {
10452: # Importing by turning a single problem into a problem part
10453: # It gets the import-tags ID as part-ID
10454: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10455: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10456: }
1.1068 www 10457: } else {
10458: # Normal import
10459: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10460: if (defined($token->[2]->{'id'})) {
10461: $unikey.='_'.$token->[2]->{'id'};
10462: }
1.1067 www 10463: }
10464:
1.339 albertel 10465: if ($depthcount<20) {
1.736 albertel 10466: my $metadata =
10467: &metadata($uri,'keys', $location,$unikey,
10468: $depthcount+1);
10469: foreach my $meta (split(',',$metadata)) {
10470: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10471: $metathesekeys{$meta}=1;
1.339 albertel 10472: }
1.1068 www 10473:
10474: }
1.1067 www 10475: } else {
10476: #
10477: # Not importing, some other kind of non-package, non-library start tag
10478: #
10479: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10480: if (defined($token->[2]->{'id'})) {
10481: $unikey.='_'.$token->[2]->{'id'};
10482: }
1.339 albertel 10483: if (defined($token->[2]->{'name'})) {
10484: $unikey.='_'.$token->[2]->{'name'};
10485: }
10486: $metathesekeys{$unikey}=1;
1.736 albertel 10487: foreach my $param (@{$token->[3]}) {
10488: $metaentry{':'.$unikey.'.'.$param} =
10489: $token->[2]->{$param};
1.339 albertel 10490: }
10491: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10492: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10493: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10494: # only ws inside the tag, and not in default, so use default
10495: # as value
1.599 albertel 10496: $metaentry{':'.$unikey}=$default;
1.908 albertel 10497: } elsif ( $internaltext =~ /\S/ ) {
10498: # something interesting inside the tag
10499: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10500: } else {
1.908 albertel 10501: # no interesting values, don't set a default
1.339 albertel 10502: }
1.172 www 10503: # end of not-a-package not-a-library import
1.339 albertel 10504: }
1.172 www 10505: # end of not-a-package start tag
1.339 albertel 10506: }
1.172 www 10507: # the next is the end of "start tag"
1.339 albertel 10508: }
10509: }
1.483 albertel 10510: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10511: $extension = lc($extension);
10512: if ($extension eq 'htm') { $extension='html'; }
10513:
1.737 albertel 10514: foreach my $key (keys(%packagetab)) {
1.483 albertel 10515: #no specific packages #how's our extension
10516: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10517: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10518: \%metathesekeys);
10519: }
1.883 albertel 10520:
10521: if (!exists($metaentry{':packages'})
10522: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10523: foreach my $key (keys(%packagetab)) {
1.483 albertel 10524: #no specific packages well let's get default then
10525: if ($key!~/^default&/) { next; }
1.488 albertel 10526: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10527: \%metathesekeys);
10528: }
10529: }
1.338 www 10530: # are there custom rights to evaluate
1.599 albertel 10531: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10532:
1.338 www 10533: #
10534: # Importing a rights file here
1.339 albertel 10535: #
10536: unless ($depthcount) {
1.599 albertel 10537: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10538: my $dir=$filename;
10539: $dir=~s|[^/]*$||;
10540: $location=&filelocation($dir,$location);
1.736 albertel 10541: my $rights_metadata =
10542: &metadata($uri,'keys',$location,'_rights',
10543: $depthcount+1);
10544: foreach my $rights (split(',',$rights_metadata)) {
10545: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10546: $metathesekeys{$rights}=1;
1.339 albertel 10547: }
10548: }
10549: }
1.737 albertel 10550: # uniqifiy package listing
10551: my %seen;
10552: my @uniq_packages =
10553: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10554: $metaentry{':packages'} = join(',',@uniq_packages);
10555:
1.1070 www 10556: if ($importedparts) {
10557: # We had imported parts and need to rebuild partorder
10558: $metaentry{':partorder'}='';
10559: $metathesekeys{'partorder'}=1;
10560: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10561: if ($origfileimportpartids[$index] eq 'part') {
10562: # original part, part of the problem
10563: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10564: } else {
10565: # we have imported parts at this position
10566: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10567: }
10568: }
10569: $metaentry{':partorder'}=~s/^\,//;
10570: }
10571:
1.737 albertel 10572: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10573: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10574: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10575: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10576: # this is the end of "was not already recently cached
1.71 www 10577: }
1.599 albertel 10578: return $metaentry{':'.$what};
1.261 albertel 10579: }
10580:
1.488 albertel 10581: sub metadata_create_package_def {
1.483 albertel 10582: my ($uri,$key,$package,$metathesekeys)=@_;
10583: my ($pack,$name,$subp)=split(/\&/,$key);
10584: if ($subp eq 'default') { next; }
10585:
1.599 albertel 10586: if (defined($metaentry{':packages'})) {
10587: $metaentry{':packages'}.=','.$package;
1.483 albertel 10588: } else {
1.599 albertel 10589: $metaentry{':packages'}=$package;
1.483 albertel 10590: }
10591: my $value=$packagetab{$key};
10592: my $unikey;
10593: $unikey='parameter_0_'.$name;
1.599 albertel 10594: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10595: $$metathesekeys{$unikey}=1;
1.599 albertel 10596: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10597: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10598: }
1.599 albertel 10599: if (defined($metaentry{':'.$unikey.'.default'})) {
10600: $metaentry{':'.$unikey}=
10601: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10602: }
10603: }
10604:
1.261 albertel 10605: sub metadata_generate_part0 {
10606: my ($metadata,$metacache,$uri) = @_;
10607: my %allnames;
1.737 albertel 10608: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10609: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10610: my $part=$$metacache{':'.$metakey.'.part'};
10611: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10612: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10613: $allnames{$name}=$part;
10614: }
10615: }
10616: }
10617: foreach my $name (keys(%allnames)) {
10618: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10619: my $key=":parameter_0_$name";
1.261 albertel 10620: $$metacache{"$key.part"}='0';
10621: $$metacache{"$key.name"}=$name;
1.428 albertel 10622: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10623: $allnames{$name}.'_'.$name.
10624: '.type'};
1.428 albertel 10625: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10626: '.display'};
1.644 www 10627: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10628: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10629: $$metacache{"$key.display"}=$olddis;
10630: }
1.71 www 10631: }
10632:
1.764 albertel 10633: # ------------------------------------------------------ Devalidate title cache
10634:
10635: sub devalidate_title_cache {
10636: my ($url)=@_;
10637: if (!$env{'request.course.id'}) { return; }
10638: my $symb=&symbread($url);
10639: if (!$symb) { return; }
10640: my $key=$env{'request.course.id'}."\0".$symb;
10641: &devalidate_cache_new('title',$key);
10642: }
10643:
1.1014 droeschl 10644: # ------------------------------------------------- Get the title of a course
10645:
10646: sub current_course_title {
10647: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10648: }
1.301 www 10649: # ------------------------------------------------- Get the title of a resource
10650:
10651: sub gettitle {
10652: my $urlsymb=shift;
10653: my $symb=&symbread($urlsymb);
1.534 albertel 10654: if ($symb) {
1.620 albertel 10655: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10656: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10657: if (defined($cached)) {
10658: return $result;
10659: }
1.534 albertel 10660: my ($map,$resid,$url)=&decode_symb($symb);
10661: my $title='';
1.907 albertel 10662: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10663: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10664: } else {
10665: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10666: &GDBM_READER(),0640)) {
10667: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10668: $title=$bighash{'title_'.$mapid.'.'.$resid};
10669: untie(%bighash);
10670: }
1.534 albertel 10671: }
10672: $title=~s/\&colon\;/\:/gs;
10673: if ($title) {
1.1159 www 10674: # Remember both $symb and $title for dynamic metadata
10675: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10676: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10677: # Cache this title and then return it
1.599 albertel 10678: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10679: }
10680: $urlsymb=$url;
10681: }
10682: my $title=&metadata($urlsymb,'title');
10683: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10684: return $title;
1.301 www 10685: }
1.613 albertel 10686:
1.614 albertel 10687: sub get_slot {
10688: my ($which,$cnum,$cdom)=@_;
10689: if (!$cnum || !$cdom) {
1.790 albertel 10690: (undef,my $courseid)=&whichuser();
1.620 albertel 10691: $cdom=$env{'course.'.$courseid.'.domain'};
10692: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10693: }
1.703 albertel 10694: my $key=join("\0",'slots',$cdom,$cnum,$which);
10695: my %slotinfo;
10696: if (exists($remembered{$key})) {
10697: $slotinfo{$which} = $remembered{$key};
10698: } else {
10699: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10700: &Apache::lonhomework::showhash(%slotinfo);
10701: my ($tmp)=keys(%slotinfo);
10702: if ($tmp=~/^error:/) { return (); }
10703: $remembered{$key} = $slotinfo{$which};
10704: }
1.616 albertel 10705: if (ref($slotinfo{$which}) eq 'HASH') {
10706: return %{$slotinfo{$which}};
10707: }
10708: return $slotinfo{$which};
1.614 albertel 10709: }
1.1150 raeburn 10710:
10711: sub get_reservable_slots {
10712: my ($cnum,$cdom,$uname,$udom) = @_;
10713: my $now = time;
10714: my $reservable_info;
10715: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10716: if (exists($remembered{$key})) {
10717: $reservable_info = $remembered{$key};
10718: } else {
10719: my %resv;
10720: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10721: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10722: $reservable_info = \%resv;
10723: $remembered{$key} = $reservable_info;
10724: }
10725: return $reservable_info;
10726: }
10727:
10728: sub get_course_slots {
10729: my ($cnum,$cdom) = @_;
10730: my $hashid=$cnum.':'.$cdom;
10731: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10732: if (defined($cached)) {
10733: if (ref($result) eq 'HASH') {
10734: return %{$result};
10735: }
10736: } else {
10737: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10738: my ($tmp) = keys(%slots);
10739: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10740: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10741: return %slots;
10742: }
10743: }
10744: return;
10745: }
10746:
10747: sub devalidate_slots_cache {
10748: my ($cnum,$cdom)=@_;
10749: my $hashid=$cnum.':'.$cdom;
10750: &devalidate_cache_new('allslots',$hashid);
10751: }
10752:
1.1172.2.8 raeburn 10753: sub get_coursechange {
10754: my ($cdom,$cnum) = @_;
10755: if ($cdom eq '' || $cnum eq '') {
10756: return unless ($env{'request.course.id'});
10757: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10758: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10759: }
10760: my $hashid=$cdom.'_'.$cnum;
10761: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10762: if ((defined($cached)) && ($change ne '')) {
10763: return $change;
10764: } else {
10765: my %crshash;
10766: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10767: if ($crshash{'internal.contentchange'} eq '') {
10768: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10769: if ($change eq '') {
10770: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10771: $change = $crshash{'internal.created'};
10772: }
10773: } else {
10774: $change = $crshash{'internal.contentchange'};
10775: }
10776: my $cachetime = 600;
10777: &do_cache_new('crschange',$hashid,$change,$cachetime);
10778: }
10779: return $change;
10780: }
10781:
10782: sub devalidate_coursechange_cache {
10783: my ($cnum,$cdom)=@_;
10784: my $hashid=$cnum.':'.$cdom;
10785: &devalidate_cache_new('crschange',$hashid);
10786: }
10787:
1.31 www 10788: # ------------------------------------------------- Update symbolic store links
10789:
10790: sub symblist {
10791: my ($mapname,%newhash)=@_;
1.438 www 10792: $mapname=&deversion(&declutter($mapname));
1.31 www 10793: my %hash;
1.620 albertel 10794: if (($env{'request.course.fn'}) && (%newhash)) {
10795: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10796: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10797: foreach my $url (keys(%newhash)) {
1.711 albertel 10798: next if ($url eq 'last_known'
10799: && $env{'form.no_update_last_known'});
10800: $hash{declutter($url)}=&encode_symb($mapname,
10801: $newhash{$url}->[1],
10802: $newhash{$url}->[0]);
1.191 harris41 10803: }
1.31 www 10804: if (untie(%hash)) {
10805: return 'ok';
10806: }
10807: }
10808: }
10809: return 'error';
1.212 www 10810: }
10811:
10812: # --------------------------------------------------------------- Verify a symb
10813:
10814: sub symbverify {
1.1172.2.11 raeburn 10815: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10816: my $thisfn=$thisurl;
1.439 www 10817: $thisfn=&declutter($thisfn);
1.215 www 10818: # direct jump to resource in page or to a sequence - will construct own symbs
10819: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10820: # check URL part
1.409 www 10821: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10822:
1.431 www 10823: unless ($url eq $thisfn) { return 0; }
1.213 www 10824:
1.216 www 10825: $symb=&symbclean($symb);
1.510 www 10826: $thisurl=&deversion($thisurl);
1.439 www 10827: $thisfn=&deversion($thisfn);
1.213 www 10828:
10829: my %bighash;
10830: my $okay=0;
1.431 www 10831:
1.620 albertel 10832: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10833: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10834: my $noclutter;
1.1032 raeburn 10835: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10836: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10837: if ($map =~ m{^uploaded/.+\.page$}) {
10838: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10839: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10840: $noclutter = 1;
10841: }
10842: }
10843: my $ids;
10844: if ($noclutter) {
10845: $ids=$bighash{'ids_'.$thisurl};
10846: } else {
10847: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10848: }
1.1102 raeburn 10849: unless ($ids) {
1.1172.2.13 raeburn 10850: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10851: $ids=$bighash{$idkey};
1.216 www 10852: }
10853: if ($ids) {
10854: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10855: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10856: $symb =~ s/\?.+$//;
10857: }
1.800 albertel 10858: foreach my $id (split(/\,/,$ids)) {
10859: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10860: if (
10861: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10862: eq $symb) {
1.1172.2.11 raeburn 10863: if (ref($encstate)) {
10864: $$encstate = $bighash{'encrypted_'.$id};
10865: }
1.1172.2.13 raeburn 10866: if (($env{'request.role.adv'}) ||
10867: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10868: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10869: $okay=1;
10870: last;
10871: }
10872: }
10873: }
1.216 www 10874: }
1.213 www 10875: untie(%bighash);
10876: }
10877: return $okay;
1.31 www 10878: }
10879:
1.210 www 10880: # --------------------------------------------------------------- Clean-up symb
10881:
10882: sub symbclean {
10883: my $symb=shift;
1.568 albertel 10884: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10885: # remove version from map
10886: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10887:
1.210 www 10888: # remove version from URL
10889: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10890:
1.507 www 10891: # remove wrapper
10892:
1.510 www 10893: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10894: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10895: return $symb;
1.409 www 10896: }
10897:
10898: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10899:
10900: sub encode_symb {
10901: my ($map,$resid,$url)=@_;
10902: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10903: }
1.409 www 10904:
10905: sub decode_symb {
1.568 albertel 10906: my $symb=shift;
10907: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10908: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10909: return (&fixversion($map),$resid,&fixversion($url));
10910: }
10911:
10912: sub fixversion {
10913: my $fn=shift;
1.609 banghart 10914: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10915: my %bighash;
10916: my $uri=&clutter($fn);
1.620 albertel 10917: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10918: # is this cached?
1.599 albertel 10919: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10920: if (defined($cached)) { return $result; }
10921: # unfortunately not cached, or expired
1.620 albertel 10922: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10923: &GDBM_READER(),0640)) {
10924: if ($bighash{'version_'.$uri}) {
10925: my $version=$bighash{'version_'.$uri};
1.444 www 10926: unless (($version eq 'mostrecent') ||
10927: ($version==&getversion($uri))) {
1.440 www 10928: $uri=~s/\.(\w+)$/\.$version\.$1/;
10929: }
10930: }
10931: untie %bighash;
1.413 www 10932: }
1.599 albertel 10933: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10934: }
10935:
10936: sub deversion {
10937: my $url=shift;
10938: $url=~s/\.\d+\.(\w+)$/\.$1/;
10939: return $url;
1.210 www 10940: }
10941:
1.31 www 10942: # ------------------------------------------------------ Return symb list entry
10943:
10944: sub symbread {
1.249 www 10945: my ($thisfn,$donotrecurse)=@_;
1.1172.2.54 raeburn 10946: my $cache_str='request.symbread.cached.'.$thisfn;
10947: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 10948: # no filename provided? try from environment
1.1172.2.54 raeburn 10949: unless ($thisfn) {
1.620 albertel 10950: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10951: return $env{$cache_str}=&symbclean($env{'request.symb'});
10952: }
10953: $thisfn=$env{'request.filename'};
1.44 www 10954: }
1.569 albertel 10955: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10956: # is that filename actually a symb? Verify, clean, and return
10957: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10958: if (&symbverify($thisfn,$1)) {
1.620 albertel 10959: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10960: }
1.242 www 10961: }
1.44 www 10962: $thisfn=declutter($thisfn);
1.31 www 10963: my %hash;
1.37 www 10964: my %bighash;
10965: my $syval='';
1.620 albertel 10966: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10967: my $targetfn = $thisfn;
1.609 banghart 10968: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10969: $targetfn = 'adm/wrapper/'.$thisfn;
10970: }
1.687 albertel 10971: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10972: $targetfn=$1;
10973: }
1.620 albertel 10974: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10975: &GDBM_READER(),0640)) {
1.481 raeburn 10976: $syval=$hash{$targetfn};
1.37 www 10977: untie(%hash);
10978: }
10979: # ---------------------------------------------------------- There was an entry
10980: if ($syval) {
1.601 albertel 10981: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10982: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10983: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10984: #return $env{$cache_str}='';
1.601 albertel 10985: #}
10986: #$syval.=$1;
10987: #}
1.37 www 10988: } else {
10989: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10990: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10991: &GDBM_READER(),0640)) {
1.37 www 10992: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10993: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10994: unless ($ids) {
10995: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10996: }
10997: unless ($ids) {
10998: # alias?
10999: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11000: }
1.37 www 11001: if ($ids) {
11002: # ------------------------------------------------------------------- Has ID(s)
11003: my @possibilities=split(/\,/,$ids);
1.39 www 11004: if ($#possibilities==0) {
11005: # ----------------------------------------------- There is only one possibility
1.37 www 11006: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11007: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11008: $resid,$thisfn);
1.249 www 11009: } elsif (!$donotrecurse) {
1.39 www 11010: # ------------------------------------------ There is more than one possibility
11011: my $realpossible=0;
1.800 albertel 11012: foreach my $id (@possibilities) {
11013: my $file=$bighash{'src_'.$id};
1.39 www 11014: if (&allowed('bre',$file)) {
1.800 albertel 11015: my ($mapid,$resid)=split(/\./,$id);
1.39 www 11016: if ($bighash{'map_type_'.$mapid} ne 'page') {
11017: $realpossible++;
1.626 albertel 11018: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11019: $resid,$thisfn);
1.39 www 11020: }
11021: }
1.191 harris41 11022: }
1.39 www 11023: if ($realpossible!=1) { $syval=''; }
1.249 www 11024: } else {
11025: $syval='';
1.37 www 11026: }
11027: }
11028: untie(%bighash)
1.481 raeburn 11029: }
1.31 www 11030: }
1.62 www 11031: if ($syval) {
1.620 albertel 11032: return $env{$cache_str}=$syval;
1.62 www 11033: }
1.31 www 11034: }
1.949 raeburn 11035: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11036: return $env{$cache_str}='';
1.31 www 11037: }
11038:
11039: # ---------------------------------------------------------- Return random seed
11040:
1.32 www 11041: sub numval {
11042: my $txt=shift;
11043: $txt=~tr/A-J/0-9/;
11044: $txt=~tr/a-j/0-9/;
11045: $txt=~tr/K-T/0-9/;
11046: $txt=~tr/k-t/0-9/;
11047: $txt=~tr/U-Z/0-5/;
11048: $txt=~tr/u-z/0-5/;
11049: $txt=~s/\D//g;
1.564 albertel 11050: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11051: return int($txt);
1.368 albertel 11052: }
11053:
1.484 albertel 11054: sub numval2 {
11055: my $txt=shift;
11056: $txt=~tr/A-J/0-9/;
11057: $txt=~tr/a-j/0-9/;
11058: $txt=~tr/K-T/0-9/;
11059: $txt=~tr/k-t/0-9/;
11060: $txt=~tr/U-Z/0-5/;
11061: $txt=~tr/u-z/0-5/;
11062: $txt=~s/\D//g;
11063: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11064: my $total;
11065: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11066: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11067: return int($total);
11068: }
11069:
1.575 albertel 11070: sub numval3 {
11071: use integer;
11072: my $txt=shift;
11073: $txt=~tr/A-J/0-9/;
11074: $txt=~tr/a-j/0-9/;
11075: $txt=~tr/K-T/0-9/;
11076: $txt=~tr/k-t/0-9/;
11077: $txt=~tr/U-Z/0-5/;
11078: $txt=~tr/u-z/0-5/;
11079: $txt=~s/\D//g;
11080: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11081: my $total;
11082: foreach my $val (@txts) { $total+=$val; }
11083: if ($_64bit) { $total=(($total<<32)>>32); }
11084: return $total;
11085: }
11086:
1.675 albertel 11087: sub digest {
11088: my ($data)=@_;
11089: my $digest=&Digest::MD5::md5($data);
11090: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11091: my ($e,$f);
11092: {
11093: use integer;
11094: $e=($a+$b);
11095: $f=($c+$d);
11096: if ($_64bit) {
11097: $e=(($e<<32)>>32);
11098: $f=(($f<<32)>>32);
11099: }
11100: }
11101: if (wantarray) {
11102: return ($e,$f);
11103: } else {
11104: my $g;
11105: {
11106: use integer;
11107: $g=($e+$f);
11108: if ($_64bit) {
11109: $g=(($g<<32)>>32);
11110: }
11111: }
11112: return $g;
11113: }
11114: }
11115:
1.368 albertel 11116: sub latest_rnd_algorithm_id {
1.675 albertel 11117: return '64bit5';
1.366 albertel 11118: }
1.32 www 11119:
1.503 albertel 11120: sub get_rand_alg {
11121: my ($courseid)=@_;
1.790 albertel 11122: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11123: if ($courseid) {
1.620 albertel 11124: return $env{"course.$courseid.rndseed"};
1.503 albertel 11125: }
11126: return &latest_rnd_algorithm_id();
11127: }
11128:
1.562 albertel 11129: sub validCODE {
11130: my ($CODE)=@_;
11131: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11132: return 0;
11133: }
11134:
1.491 albertel 11135: sub getCODE {
1.620 albertel 11136: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11137: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11138: defined($Apache::lonhomework::parsing_a_task) ) &&
11139: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11140: return $Apache::lonhomework::history{'resource.CODE'};
11141: }
11142: return undef;
11143: }
1.1133 foxr 11144: #
11145: # Determines the random seed for a specific context:
11146: #
11147: # parameters:
11148: # symb - in course context the symb for the seed.
11149: # course_id - The course id of the form domain_coursenum.
11150: # domain - Domain for the user.
11151: # course - Course for the user.
11152: # cenv - environment of the course.
11153: #
11154: # NOTE:
11155: # All parameters are picked out of the environment if missing
11156: # or not defined.
11157: # If a symb cannot be determined the current time is used instead.
11158: #
11159: # For a given well defined symb, courside, domain, username,
11160: # and course environment, the seed is reproducible.
11161: #
1.31 www 11162: sub rndseed {
1.1133 foxr 11163: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11164: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11165: if (!defined($symb)) {
1.366 albertel 11166: unless ($symb=$wsymb) { return time; }
11167: }
1.1146 foxr 11168: if (!defined $courseid) {
11169: $courseid=$wcourseid;
11170: }
11171: if (!defined $domain) { $domain=$wdomain; }
11172: if (!defined $username) { $username=$wusername }
1.1133 foxr 11173:
11174: my $which;
11175: if (defined($cenv->{'rndseed'})) {
11176: $which = $cenv->{'rndseed'};
11177: } else {
11178: $which =&get_rand_alg($courseid);
11179: }
1.491 albertel 11180: if (defined(&getCODE())) {
1.675 albertel 11181: if ($which eq '64bit5') {
11182: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11183: } elsif ($which eq '64bit4') {
1.575 albertel 11184: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11185: } else {
11186: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11187: }
1.675 albertel 11188: } elsif ($which eq '64bit5') {
11189: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11190: } elsif ($which eq '64bit4') {
11191: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11192: } elsif ($which eq '64bit3') {
11193: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11194: } elsif ($which eq '64bit2') {
11195: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11196: } elsif ($which eq '64bit') {
11197: return &rndseed_64bit($symb,$courseid,$domain,$username);
11198: }
11199: return &rndseed_32bit($symb,$courseid,$domain,$username);
11200: }
11201:
11202: sub rndseed_32bit {
11203: my ($symb,$courseid,$domain,$username)=@_;
11204: {
11205: use integer;
11206: my $symbchck=unpack("%32C*",$symb) << 27;
11207: my $symbseed=numval($symb) << 22;
11208: my $namechck=unpack("%32C*",$username) << 17;
11209: my $nameseed=numval($username) << 12;
11210: my $domainseed=unpack("%32C*",$domain) << 7;
11211: my $courseseed=unpack("%32C*",$courseid);
11212: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11213: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11214: #&logthis("rndseed :$num:$symb");
1.564 albertel 11215: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11216: return $num;
11217: }
11218: }
11219:
11220: sub rndseed_64bit {
11221: my ($symb,$courseid,$domain,$username)=@_;
11222: {
11223: use integer;
11224: my $symbchck=unpack("%32S*",$symb) << 21;
11225: my $symbseed=numval($symb) << 10;
11226: my $namechck=unpack("%32S*",$username);
11227:
11228: my $nameseed=numval($username) << 21;
11229: my $domainseed=unpack("%32S*",$domain) << 10;
11230: my $courseseed=unpack("%32S*",$courseid);
11231:
11232: my $num1=$symbchck+$symbseed+$namechck;
11233: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11234: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11235: #&logthis("rndseed :$num:$symb");
1.564 albertel 11236: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11237: return "$num1,$num2";
1.155 albertel 11238: }
1.366 albertel 11239: }
11240:
1.443 albertel 11241: sub rndseed_64bit2 {
11242: my ($symb,$courseid,$domain,$username)=@_;
11243: {
11244: use integer;
11245: # strings need to be an even # of cahracters long, it it is odd the
11246: # last characters gets thrown away
11247: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11248: my $symbseed=numval($symb) << 10;
11249: my $namechck=unpack("%32S*",$username.' ');
11250:
11251: my $nameseed=numval($username) << 21;
1.501 albertel 11252: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11253: my $courseseed=unpack("%32S*",$courseid.' ');
11254:
11255: my $num1=$symbchck+$symbseed+$namechck;
11256: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11257: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11258: #&logthis("rndseed :$num:$symb");
1.803 albertel 11259: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11260: return "$num1,$num2";
11261: }
11262: }
11263:
11264: sub rndseed_64bit3 {
11265: my ($symb,$courseid,$domain,$username)=@_;
11266: {
11267: use integer;
11268: # strings need to be an even # of cahracters long, it it is odd the
11269: # last characters gets thrown away
11270: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11271: my $symbseed=numval2($symb) << 10;
11272: my $namechck=unpack("%32S*",$username.' ');
11273:
11274: my $nameseed=numval2($username) << 21;
1.443 albertel 11275: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11276: my $courseseed=unpack("%32S*",$courseid.' ');
11277:
11278: my $num1=$symbchck+$symbseed+$namechck;
11279: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11280: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11281: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11282: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11283:
1.503 albertel 11284: return "$num1:$num2";
1.443 albertel 11285: }
11286: }
11287:
1.575 albertel 11288: sub rndseed_64bit4 {
11289: my ($symb,$courseid,$domain,$username)=@_;
11290: {
11291: use integer;
11292: # strings need to be an even # of cahracters long, it it is odd the
11293: # last characters gets thrown away
11294: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11295: my $symbseed=numval3($symb) << 10;
11296: my $namechck=unpack("%32S*",$username.' ');
11297:
11298: my $nameseed=numval3($username) << 21;
11299: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11300: my $courseseed=unpack("%32S*",$courseid.' ');
11301:
11302: my $num1=$symbchck+$symbseed+$namechck;
11303: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11304: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11305: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11306: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11307:
1.575 albertel 11308: return "$num1:$num2";
11309: }
11310: }
11311:
1.675 albertel 11312: sub rndseed_64bit5 {
11313: my ($symb,$courseid,$domain,$username)=@_;
11314: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11315: return "$num1:$num2";
11316: }
11317:
1.366 albertel 11318: sub rndseed_CODE_64bit {
11319: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11320: {
1.366 albertel 11321: use integer;
1.443 albertel 11322: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11323: my $symbseed=numval2($symb);
1.491 albertel 11324: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11325: my $CODEseed=numval(&getCODE());
1.443 albertel 11326: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11327: my $num1=$symbseed+$CODEchck;
11328: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11329: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11330: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11331: if ($_64bit) { $num1=(($num1<<32)>>32); }
11332: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11333: return "$num1:$num2";
1.366 albertel 11334: }
11335: }
11336:
1.575 albertel 11337: sub rndseed_CODE_64bit4 {
11338: my ($symb,$courseid,$domain,$username)=@_;
11339: {
11340: use integer;
11341: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11342: my $symbseed=numval3($symb);
11343: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11344: my $CODEseed=numval3(&getCODE());
11345: my $courseseed=unpack("%32S*",$courseid.' ');
11346: my $num1=$symbseed+$CODEchck;
11347: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11348: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11349: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11350: if ($_64bit) { $num1=(($num1<<32)>>32); }
11351: if ($_64bit) { $num2=(($num2<<32)>>32); }
11352: return "$num1:$num2";
11353: }
11354: }
11355:
1.675 albertel 11356: sub rndseed_CODE_64bit5 {
11357: my ($symb,$courseid,$domain,$username)=@_;
11358: my $code = &getCODE();
11359: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11360: return "$num1:$num2";
11361: }
11362:
1.366 albertel 11363: sub setup_random_from_rndseed {
11364: my ($rndseed)=@_;
1.503 albertel 11365: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11366: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11367: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11368: &Math::Random::random_set_seed_from_phrase($rndseed);
11369: } else {
11370: &Math::Random::random_set_seed($num1,$num2);
11371: }
1.366 albertel 11372: } else {
11373: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11374: }
1.36 albertel 11375: }
11376:
1.474 albertel 11377: sub latest_receipt_algorithm_id {
1.835 albertel 11378: return 'receipt3';
1.474 albertel 11379: }
11380:
1.480 www 11381: sub recunique {
11382: my $fucourseid=shift;
11383: my $unique;
1.835 albertel 11384: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11385: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11386: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11387: } else {
11388: $unique=$perlvar{'lonReceipt'};
11389: }
11390: return unpack("%32C*",$unique);
11391: }
11392:
11393: sub recprefix {
11394: my $fucourseid=shift;
11395: my $prefix;
1.835 albertel 11396: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11397: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11398: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11399: } else {
11400: $prefix=$perlvar{'lonHostID'};
11401: }
11402: return unpack("%32C*",$prefix);
11403: }
11404:
1.76 www 11405: sub ireceipt {
1.474 albertel 11406: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11407:
11408: my $return =&recprefix($fucourseid).'-';
11409:
11410: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11411: $env{'request.state'} eq 'construct') {
11412: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11413: return $return;
11414: }
11415:
1.76 www 11416: my $cuname=unpack("%32C*",$funame);
11417: my $cudom=unpack("%32C*",$fudom);
11418: my $cucourseid=unpack("%32C*",$fucourseid);
11419: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11420: my $cunique=&recunique($fucourseid);
1.474 albertel 11421: my $cpart=unpack("%32S*",$part);
1.835 albertel 11422: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11423:
1.790 albertel 11424: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11425:
11426: $return.= ($cunique%$cuname+
11427: $cunique%$cudom+
11428: $cusymb%$cuname+
11429: $cusymb%$cudom+
11430: $cucourseid%$cuname+
11431: $cucourseid%$cudom+
11432: $cpart%$cuname+
11433: $cpart%$cudom);
11434: } else {
11435: $return.= ($cunique%$cuname+
11436: $cunique%$cudom+
11437: $cusymb%$cuname+
11438: $cusymb%$cudom+
11439: $cucourseid%$cuname+
11440: $cucourseid%$cudom);
11441: }
11442: return $return;
1.76 www 11443: }
11444:
11445: sub receipt {
1.474 albertel 11446: my ($part)=@_;
1.790 albertel 11447: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11448: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11449: }
1.260 ng 11450:
1.790 albertel 11451: sub whichuser {
11452: my ($passedsymb)=@_;
11453: my ($symb,$courseid,$domain,$name,$publicuser);
11454: if (defined($env{'form.grade_symb'})) {
11455: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11456: my $allowed=&allowed('vgr',$tmp_courseid);
11457: if (!$allowed &&
11458: exists($env{'request.course.sec'}) &&
11459: $env{'request.course.sec'} !~ /^\s*$/) {
11460: $allowed=&allowed('vgr',$tmp_courseid.
11461: '/'.$env{'request.course.sec'});
11462: }
11463: if ($allowed) {
11464: ($symb)=&get_env_multiple('form.grade_symb');
11465: $courseid=$tmp_courseid;
11466: ($domain)=&get_env_multiple('form.grade_domain');
11467: ($name)=&get_env_multiple('form.grade_username');
11468: return ($symb,$courseid,$domain,$name,$publicuser);
11469: }
11470: }
11471: if (!$passedsymb) {
11472: $symb=&symbread();
11473: } else {
11474: $symb=$passedsymb;
11475: }
11476: $courseid=$env{'request.course.id'};
11477: $domain=$env{'user.domain'};
11478: $name=$env{'user.name'};
11479: if ($name eq 'public' && $domain eq 'public') {
11480: if (!defined($env{'form.username'})) {
11481: $env{'form.username'}.=time.rand(10000000);
11482: }
11483: $name.=$env{'form.username'};
11484: }
11485: return ($symb,$courseid,$domain,$name,$publicuser);
11486:
11487: }
11488:
1.36 albertel 11489: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11490: # returns either the contents of the file or
11491: # -1 if the file doesn't exist
1.481 raeburn 11492: #
11493: # if the target is a file that was uploaded via DOCS,
11494: # a check will be made to see if a current copy exists on the local server,
11495: # if it does this will be served, otherwise a copy will be retrieved from
11496: # the home server for the course and stored in /home/httpd/html/userfiles on
11497: # the local server.
1.472 albertel 11498:
1.36 albertel 11499: sub getfile {
1.538 albertel 11500: my ($file) = @_;
1.609 banghart 11501: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11502: &repcopy($file);
11503: return &readfile($file);
11504: }
11505:
11506: sub repcopy_userfile {
11507: my ($file)=@_;
1.1142 raeburn 11508: my $londocroot = $perlvar{'lonDocRoot'};
11509: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11510: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11511: my ($cdom,$cnum,$filename) =
1.811 albertel 11512: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11513: my $uri="/uploaded/$cdom/$cnum/$filename";
11514: if (-e "$file") {
1.828 www 11515: # we already have a local copy, check it out
1.538 albertel 11516: my @fileinfo = stat($file);
1.828 www 11517: my $rtncode;
11518: my $info;
1.538 albertel 11519: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11520: if ($lwpresp ne 'ok') {
1.828 www 11521: # there is no such file anymore, even though we had a local copy
1.482 albertel 11522: if ($rtncode eq '404') {
1.538 albertel 11523: unlink($file);
1.482 albertel 11524: }
11525: return -1;
11526: }
11527: if ($info < $fileinfo[9]) {
1.828 www 11528: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11529: return 'ok';
1.828 www 11530: } else {
11531: # the file is outdated, get rid of it
11532: unlink($file);
1.482 albertel 11533: }
1.828 www 11534: }
11535: # one way or the other, at this point, we don't have the file
11536: # construct the correct path for the file
11537: my @parts = ($cdom,$cnum);
11538: if ($filename =~ m|^(.+)/[^/]+$|) {
11539: push @parts, split(/\//,$1);
11540: }
11541: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11542: foreach my $part (@parts) {
11543: $path .= '/'.$part;
11544: if (!-e $path) {
11545: mkdir($path,0770);
1.482 albertel 11546: }
11547: }
1.828 www 11548: # now the path exists for sure
11549: # get a user agent
11550: my $ua=new LWP::UserAgent;
11551: my $transferfile=$file.'.in.transfer';
11552: # FIXME: this should flock
11553: if (-e $transferfile) { return 'ok'; }
11554: my $request;
11555: $uri=~s/^\///;
1.980 raeburn 11556: my $homeserver = &homeserver($cnum,$cdom);
11557: my $protocol = $protocol{$homeserver};
11558: $protocol = 'http' if ($protocol ne 'https');
11559: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11560: my $response=$ua->request($request,$transferfile);
11561: # did it work?
11562: if ($response->is_error()) {
11563: unlink($transferfile);
11564: &logthis("Userfile repcopy failed for $uri");
11565: return -1;
11566: }
11567: # worked, rename the transfer file
11568: rename($transferfile,$file);
1.607 raeburn 11569: return 'ok';
1.481 raeburn 11570: }
11571:
1.517 albertel 11572: sub tokenwrapper {
11573: my $uri=shift;
1.980 raeburn 11574: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11575: $uri=~s|^/||;
1.620 albertel 11576: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11577: my $token=$1;
1.552 albertel 11578: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11579: if ($udom && $uname && $file) {
11580: $file=~s|(\?\.*)*$||;
1.949 raeburn 11581: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11582: my $homeserver = &homeserver($uname,$udom);
11583: my $protocol = $protocol{$homeserver};
11584: $protocol = 'http' if ($protocol ne 'https');
11585: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11586: (($uri=~/\?/)?'&':'?').'token='.$token.
11587: '&tokenissued='.$perlvar{'lonHostID'};
11588: } else {
11589: return '/adm/notfound.html';
11590: }
11591: }
11592:
1.828 www 11593: # call with reqtype HEAD: get last modification time
11594: # call with reqtype GET: get the file contents
11595: # Do not call this with reqtype GET for large files! It loads everything into memory
11596: #
1.481 raeburn 11597: sub getuploaded {
11598: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11599: $uri=~s/^\///;
1.980 raeburn 11600: my $homeserver = &homeserver($cnum,$cdom);
11601: my $protocol = $protocol{$homeserver};
11602: $protocol = 'http' if ($protocol ne 'https');
11603: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11604: my $ua=new LWP::UserAgent;
11605: my $request=new HTTP::Request($reqtype,$uri);
11606: my $response=$ua->request($request);
11607: $$rtncode = $response->code;
1.482 albertel 11608: if (! $response->is_success()) {
11609: return 'failed';
11610: }
11611: if ($reqtype eq 'HEAD') {
1.486 www 11612: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11613: } elsif ($reqtype eq 'GET') {
11614: $$info = $response->content;
1.472 albertel 11615: }
1.482 albertel 11616: return 'ok';
1.36 albertel 11617: }
11618:
1.481 raeburn 11619: sub readfile {
11620: my $file = shift;
11621: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11622: my $fh;
11623: open($fh,"<$file");
11624: my $a='';
1.800 albertel 11625: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11626: return $a;
11627: }
11628:
1.36 albertel 11629: sub filelocation {
1.590 banghart 11630: my ($dir,$file) = @_;
11631: my $location;
11632: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11633:
11634: if ($file =~ m-^/adm/-) {
11635: $file=~s-^/adm/wrapper/-/-;
11636: $file=~s-^/adm/coursedocs/showdoc/-/-;
11637: }
1.882 albertel 11638:
1.1139 www 11639: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11640: $location = $file;
1.609 banghart 11641: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11642: my ($udom,$uname,$filename)=
1.811 albertel 11643: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11644: my $home=&homeserver($uname,$udom);
11645: my $is_me=0;
11646: my @ids=¤t_machine_ids();
11647: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11648: if ($is_me) {
1.1117 foxr 11649: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11650: } else {
11651: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11652: $udom.'/'.$uname.'/'.$filename;
11653: }
1.882 albertel 11654: } elsif ($file =~ m-^/adm/-) {
11655: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11656: } else {
11657: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11658: $file=~s:^/(res|priv)/:/:;
11659: my $space=$1;
1.590 banghart 11660: if ( !( $file =~ m:^/:) ) {
11661: $location = $dir. '/'.$file;
11662: } else {
1.1142 raeburn 11663: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11664: }
1.59 albertel 11665: }
1.590 banghart 11666: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11667: while ($location=~m{/\.\./}) {
11668: if ($location =~ m{/[^/]+/\.\./}) {
11669: $location=~ s{/[^/]+/\.\./}{/}g;
11670: } else {
11671: $location=~ s{/\.\./}{/}g;
11672: }
11673: } #remove dir/..
1.590 banghart 11674: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11675: return $location;
1.46 www 11676: }
1.36 albertel 11677:
1.46 www 11678: sub hreflocation {
11679: my ($dir,$file)=@_;
1.980 raeburn 11680: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11681: $file=filelocation($dir,$file);
1.700 albertel 11682: } elsif ($file=~m-^/adm/-) {
11683: $file=~s-^/adm/wrapper/-/-;
11684: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11685: }
11686: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11687: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11688: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11689: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11690: {/uploaded/$1/$2/}x;
1.46 www 11691: }
1.913 albertel 11692: if ($file=~ m{^/userfiles/}) {
11693: $file =~ s{^/userfiles/}{/uploaded/};
11694: }
1.462 albertel 11695: return $file;
1.465 albertel 11696: }
11697:
1.1139 www 11698:
11699:
11700:
11701:
1.465 albertel 11702: sub current_machine_domains {
1.853 albertel 11703: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11704: }
11705:
11706: sub machine_domains {
11707: my ($hostname) = @_;
1.465 albertel 11708: my @domains;
1.838 albertel 11709: my %hostname = &all_hostnames();
1.465 albertel 11710: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11711: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11712: if ($hostname eq $name) {
1.844 albertel 11713: push(@domains,&host_domain($id));
1.465 albertel 11714: }
11715: }
11716: return @domains;
11717: }
11718:
11719: sub current_machine_ids {
1.853 albertel 11720: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11721: }
11722:
11723: sub machine_ids {
11724: my ($hostname) = @_;
11725: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11726: my @ids;
1.888 albertel 11727: my %name_to_host = &all_names();
1.889 albertel 11728: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11729: return @{ $name_to_host{$hostname} };
11730: }
11731: return;
1.31 www 11732: }
11733:
1.824 raeburn 11734: sub additional_machine_domains {
11735: my @domains;
11736: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11737: while( my $line = <$fh>) {
11738: $line =~ s/\s//g;
11739: push(@domains,$line);
11740: }
11741: return @domains;
11742: }
11743:
11744: sub default_login_domain {
11745: my $domain = $perlvar{'lonDefDomain'};
11746: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11747: foreach my $posdom (¤t_machine_domains(),
11748: &additional_machine_domains()) {
11749: if (lc($posdom) eq lc($testdomain)) {
11750: $domain=$posdom;
11751: last;
11752: }
11753: }
11754: return $domain;
11755: }
11756:
1.31 www 11757: # ------------------------------------------------------------- Declutters URLs
11758:
11759: sub declutter {
11760: my $thisfn=shift;
1.569 albertel 11761: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 11762: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11763: $thisfn=~s{^/home/httpd/html}{};
11764: }
1.31 www 11765: $thisfn=~s/^\///;
1.697 albertel 11766: $thisfn=~s|^adm/wrapper/||;
11767: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11768: $thisfn=~s/^res\///;
1.1172 bisitz 11769: $thisfn=~s/^priv\///;
1.1032 raeburn 11770: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11771: $thisfn=~s/\?.+$//;
11772: }
1.268 www 11773: return $thisfn;
11774: }
11775:
11776: # ------------------------------------------------------------- Clutter up URLs
11777:
11778: sub clutter {
11779: my $thisfn='/'.&declutter(shift);
1.887 albertel 11780: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11781: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11782: $thisfn='/res'.$thisfn;
11783: }
1.1031 raeburn 11784: if ($thisfn !~m|^/adm|) {
11785: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11786: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11787: } else {
11788: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11789: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11790: if ($embstyle eq 'ssi'
11791: || ($embstyle eq 'hdn')
11792: || ($embstyle eq 'rat')
11793: || ($embstyle eq 'prv')
11794: || ($embstyle eq 'ign')) {
11795: #do nothing with these
11796: } elsif (($embstyle eq 'img')
1.695 albertel 11797: || ($embstyle eq 'emb')
11798: || ($embstyle eq 'wrp')) {
11799: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11800: } elsif ($embstyle eq 'unk'
11801: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11802: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11803: } else {
1.718 www 11804: # &logthis("Got a blank emb style");
1.695 albertel 11805: }
1.694 albertel 11806: }
11807: }
1.31 www 11808: return $thisfn;
1.12 www 11809: }
11810:
1.787 albertel 11811: sub clutter_with_no_wrapper {
11812: my $uri = &clutter(shift);
11813: if ($uri =~ m-^/adm/-) {
11814: $uri =~ s-^/adm/wrapper/-/-;
11815: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11816: }
11817: return $uri;
11818: }
11819:
1.557 albertel 11820: sub freeze_escape {
11821: my ($value)=@_;
11822: if (ref($value)) {
11823: $value=&nfreeze($value);
11824: return '__FROZEN__'.&escape($value);
11825: }
11826: return &escape($value);
11827: }
11828:
1.11 www 11829:
1.557 albertel 11830: sub thaw_unescape {
11831: my ($value)=@_;
11832: if ($value =~ /^__FROZEN__/) {
11833: substr($value,0,10,undef);
11834: $value=&unescape($value);
11835: return &thaw($value);
11836: }
11837: return &unescape($value);
11838: }
11839:
1.436 albertel 11840: sub correct_line_ends {
11841: my ($result)=@_;
11842: $$result =~s/\r\n/\n/mg;
11843: $$result =~s/\r/\n/mg;
1.415 albertel 11844: }
1.1 albertel 11845: # ================================================================ Main Program
11846:
1.184 www 11847: sub goodbye {
1.204 albertel 11848: &logthis("Starting Shut down");
1.443 albertel 11849: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11850: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11851: #converted
1.599 albertel 11852: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11853: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11854: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11855: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11856: #1.1 only
1.870 albertel 11857: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11858: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11859: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11860: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11861: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11862: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11863: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11864: &flushcourselogs();
11865: &logthis("Shutting down");
11866: }
11867:
1.852 albertel 11868: sub get_dns {
1.1172.2.17 raeburn 11869: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11870: if (!$ignore_cache) {
11871: my ($content,$cached)=
11872: &Apache::lonnet::is_cached_new('dns',$url);
11873: if ($cached) {
1.1172.2.17 raeburn 11874: &$func($content,$hashref);
1.869 albertel 11875: return;
11876: }
11877: }
11878:
11879: my %alldns;
1.852 albertel 11880: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11881: foreach my $dns (<$config>) {
11882: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11883: my $line = $1;
11884: my ($host,$protocol) = split(/:/,$line);
11885: if ($protocol ne 'https') {
11886: $protocol = 'http';
11887: }
11888: $alldns{$host} = $protocol;
1.869 albertel 11889: }
11890: while (%alldns) {
1.1172.2.52 raeburn 11891: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 11892: my $ua=new LWP::UserAgent;
1.1134 raeburn 11893: $ua->timeout(30);
1.979 raeburn 11894: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11895: my $response=$ua->request($request);
1.979 raeburn 11896: delete($alldns{$dns});
1.852 albertel 11897: next if ($response->is_error());
11898: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11899: unless ($nocache) {
1.1172.2.23 raeburn 11900: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11901: }
11902: &$func(\@content,$hashref);
1.869 albertel 11903: return;
1.852 albertel 11904: }
11905: close($config);
1.871 albertel 11906: my $which = (split('/',$url))[3];
11907: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11908: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11909: my @content = <$config>;
1.1172.2.17 raeburn 11910: &$func(\@content,$hashref);
11911: return;
11912: }
11913:
11914: # ------------------------------------------------------Get DNS checksums file
11915: sub parse_dns_checksums_tab {
11916: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 11917: my $lonhost = $perlvar{'lonHostID'};
11918: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 11919: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 11920: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
11921: my $webconfdir = '/etc/httpd/conf';
11922: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
11923: $webconfdir = '/etc/apache2';
11924: } elsif ($distro =~ /^sles(\d+)$/) {
11925: if ($1 >= 10) {
11926: $webconfdir = '/etc/apache2';
11927: }
11928: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
11929: if ($1 >= 10.0) {
11930: $webconfdir = '/etc/apache2';
11931: }
11932: }
1.1172.2.17 raeburn 11933: my ($release,$timestamp) = split(/\-/,$loncaparev);
11934: my (%chksum,%revnum);
11935: if (ref($lines) eq 'ARRAY') {
11936: chomp(@{$lines});
1.1172.2.34 raeburn 11937: my $version = shift(@{$lines});
11938: if ($version eq $release) {
1.1172.2.17 raeburn 11939: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 11940: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 11941: if ($file =~ m{^/etc/httpd/conf}) {
11942: if ($webconfdir eq '/etc/apache2') {
11943: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
11944: }
11945: }
1.1172.2.34 raeburn 11946: $chksum{$file} = $shasum;
11947: $revnum{$file} = $version;
1.1172.2.17 raeburn 11948: }
11949: if (ref($hashref) eq 'HASH') {
11950: %{$hashref} = (
11951: sums => \%chksum,
11952: versions => \%revnum,
11953: );
11954: }
11955: }
11956: }
1.869 albertel 11957: return;
1.852 albertel 11958: }
1.1172.2.17 raeburn 11959:
11960: sub fetch_dns_checksums {
11961: my %checksums;
1.1172.2.34 raeburn 11962: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 11963: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 11964: my ($release,$timestamp) = split(/\-/,$loncaparev);
11965: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 11966: \%checksums);
11967: return \%checksums;
11968: }
11969:
1.327 albertel 11970: # ------------------------------------------------------------ Read domain file
11971: {
1.852 albertel 11972: my $loaded;
1.846 albertel 11973: my %domain;
11974:
1.852 albertel 11975: sub parse_domain_tab {
11976: my ($lines) = @_;
11977: foreach my $line (@$lines) {
11978: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11979:
1.846 albertel 11980: chomp($line);
1.852 albertel 11981: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11982: my %this_domain;
11983: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11984: 'lang_def', 'city', 'longi', 'lati',
11985: 'primary') {
11986: $this_domain{$field} = shift(@elements);
11987: }
11988: $domain{$name} = \%this_domain;
1.852 albertel 11989: }
11990: }
1.864 albertel 11991:
11992: sub reset_domain_info {
11993: undef($loaded);
11994: undef(%domain);
11995: }
11996:
1.852 albertel 11997: sub load_domain_tab {
1.869 albertel 11998: my ($ignore_cache) = @_;
11999: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 12000: my $fh;
12001: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12002: my @lines = <$fh>;
12003: &parse_domain_tab(\@lines);
1.448 albertel 12004: }
1.852 albertel 12005: close($fh);
12006: $loaded = 1;
1.327 albertel 12007: }
1.846 albertel 12008:
12009: sub domain {
1.852 albertel 12010: &load_domain_tab() if (!$loaded);
12011:
1.846 albertel 12012: my ($name,$what) = @_;
12013: return if ( !exists($domain{$name}) );
12014:
12015: if (!$what) {
12016: return $domain{$name}{'description'};
12017: }
12018: return $domain{$name}{$what};
12019: }
1.974 raeburn 12020:
12021: sub domain_info {
12022: &load_domain_tab() if (!$loaded);
12023: return %domain;
12024: }
12025:
1.327 albertel 12026: }
12027:
12028:
1.1 albertel 12029: # ------------------------------------------------------------- Read hosts file
12030: {
1.838 albertel 12031: my %hostname;
1.844 albertel 12032: my %hostdom;
1.845 albertel 12033: my %libserv;
1.852 albertel 12034: my $loaded;
1.888 albertel 12035: my %name_to_host;
1.1074 raeburn 12036: my %internetdom;
1.1107 raeburn 12037: my %LC_dns_serv;
1.852 albertel 12038:
12039: sub parse_hosts_tab {
12040: my ($file) = @_;
12041: foreach my $configline (@$file) {
12042: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12043: chomp($configline);
12044: if ($configline =~ /^\^/) {
12045: if ($configline =~ /^\^([\w.\-]+)/) {
12046: $LC_dns_serv{$1} = 1;
12047: }
12048: next;
12049: }
1.1074 raeburn 12050: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12051: $name=~s/\s//g;
12052: if ($id && $domain && $role && $name) {
12053: $hostname{$id}=$name;
1.888 albertel 12054: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12055: $hostdom{$id}=$domain;
12056: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12057: if (defined($protocol)) {
12058: if ($protocol eq 'https') {
12059: $protocol{$id} = $protocol;
12060: } else {
12061: $protocol{$id} = 'http';
12062: }
1.968 raeburn 12063: } else {
1.969 raeburn 12064: $protocol{$id} = 'http';
1.968 raeburn 12065: }
1.1074 raeburn 12066: if (defined($intdom)) {
12067: $internetdom{$id} = $intdom;
12068: }
1.852 albertel 12069: }
12070: }
12071: }
1.864 albertel 12072:
12073: sub reset_hosts_info {
1.897 albertel 12074: &purge_remembered();
1.864 albertel 12075: &reset_domain_info();
12076: &reset_hosts_ip_info();
1.892 albertel 12077: undef(%name_to_host);
1.864 albertel 12078: undef(%hostname);
12079: undef(%hostdom);
12080: undef(%libserv);
12081: undef($loaded);
12082: }
1.1 albertel 12083:
1.852 albertel 12084: sub load_hosts_tab {
1.869 albertel 12085: my ($ignore_cache) = @_;
12086: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12087: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12088: my @config = <$config>;
12089: &parse_hosts_tab(\@config);
12090: close($config);
12091: $loaded=1;
1.1 albertel 12092: }
1.852 albertel 12093:
1.838 albertel 12094: sub hostname {
1.852 albertel 12095: &load_hosts_tab() if (!$loaded);
12096:
1.838 albertel 12097: my ($lonid) = @_;
12098: return $hostname{$lonid};
12099: }
1.845 albertel 12100:
1.838 albertel 12101: sub all_hostnames {
1.852 albertel 12102: &load_hosts_tab() if (!$loaded);
12103:
1.838 albertel 12104: return %hostname;
12105: }
1.845 albertel 12106:
1.888 albertel 12107: sub all_names {
12108: &load_hosts_tab() if (!$loaded);
12109:
12110: return %name_to_host;
12111: }
12112:
1.974 raeburn 12113: sub all_host_domain {
12114: &load_hosts_tab() if (!$loaded);
12115: return %hostdom;
12116: }
12117:
1.845 albertel 12118: sub is_library {
1.852 albertel 12119: &load_hosts_tab() if (!$loaded);
12120:
1.845 albertel 12121: return exists($libserv{$_[0]});
12122: }
12123:
12124: sub all_library {
1.852 albertel 12125: &load_hosts_tab() if (!$loaded);
12126:
1.845 albertel 12127: return %libserv;
12128: }
12129:
1.1062 droeschl 12130: sub unique_library {
12131: #2x reverse removes all hostnames that appear more than once
12132: my %unique = reverse &all_library();
12133: return reverse %unique;
12134: }
12135:
1.841 albertel 12136: sub get_servers {
1.852 albertel 12137: &load_hosts_tab() if (!$loaded);
12138:
1.841 albertel 12139: my ($domain,$type) = @_;
12140: my %possible_hosts = ($type eq 'library') ? %libserv
12141: : %hostname;
12142: my %result;
1.842 albertel 12143: if (ref($domain) eq 'ARRAY') {
12144: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12145: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12146: $result{$host} = $hostname;
12147: }
12148: }
12149: } else {
12150: while ( my ($host,$hostname) = each(%possible_hosts)) {
12151: if ($hostdom{$host} eq $domain) {
12152: $result{$host} = $hostname;
12153: }
1.841 albertel 12154: }
12155: }
12156: return %result;
12157: }
1.845 albertel 12158:
1.1062 droeschl 12159: sub get_unique_servers {
12160: my %unique = reverse &get_servers(@_);
12161: return reverse %unique;
12162: }
12163:
1.844 albertel 12164: sub host_domain {
1.852 albertel 12165: &load_hosts_tab() if (!$loaded);
12166:
1.844 albertel 12167: my ($lonid) = @_;
12168: return $hostdom{$lonid};
12169: }
12170:
1.841 albertel 12171: sub all_domains {
1.852 albertel 12172: &load_hosts_tab() if (!$loaded);
12173:
1.841 albertel 12174: my %seen;
12175: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12176: return @uniq;
12177: }
1.1074 raeburn 12178:
12179: sub internet_dom {
12180: &load_hosts_tab() if (!$loaded);
12181:
12182: my ($lonid) = @_;
12183: return $internetdom{$lonid};
12184: }
1.1107 raeburn 12185:
12186: sub is_LC_dns {
12187: &load_hosts_tab() if (!$loaded);
12188:
12189: my ($hostname) = @_;
12190: return exists($LC_dns_serv{$hostname});
12191: }
12192:
1.1 albertel 12193: }
12194:
1.847 albertel 12195: {
12196: my %iphost;
1.856 albertel 12197: my %name_to_ip;
12198: my %lonid_to_ip;
1.869 albertel 12199:
1.847 albertel 12200: sub get_hosts_from_ip {
12201: my ($ip) = @_;
12202: my %iphosts = &get_iphost();
12203: if (ref($iphosts{$ip})) {
12204: return @{$iphosts{$ip}};
12205: }
12206: return;
1.839 albertel 12207: }
1.864 albertel 12208:
12209: sub reset_hosts_ip_info {
12210: undef(%iphost);
12211: undef(%name_to_ip);
12212: undef(%lonid_to_ip);
12213: }
1.856 albertel 12214:
12215: sub get_host_ip {
12216: my ($lonid) = @_;
12217: if (exists($lonid_to_ip{$lonid})) {
12218: return $lonid_to_ip{$lonid};
12219: }
12220: my $name=&hostname($lonid);
12221: my $ip = gethostbyname($name);
12222: return if (!$ip || length($ip) ne 4);
12223: $ip=inet_ntoa($ip);
12224: $name_to_ip{$name} = $ip;
12225: $lonid_to_ip{$lonid} = $ip;
12226: return $ip;
12227: }
1.847 albertel 12228:
12229: sub get_iphost {
1.869 albertel 12230: my ($ignore_cache) = @_;
1.894 albertel 12231:
1.869 albertel 12232: if (!$ignore_cache) {
12233: if (%iphost) {
12234: return %iphost;
12235: }
12236: my ($ip_info,$cached)=
12237: &Apache::lonnet::is_cached_new('iphost','iphost');
12238: if ($cached) {
12239: %iphost = %{$ip_info->[0]};
12240: %name_to_ip = %{$ip_info->[1]};
12241: %lonid_to_ip = %{$ip_info->[2]};
12242: return %iphost;
12243: }
12244: }
1.894 albertel 12245:
12246: # get yesterday's info for fallback
12247: my %old_name_to_ip;
12248: my ($ip_info,$cached)=
12249: &Apache::lonnet::is_cached_new('iphost','iphost');
12250: if ($cached) {
12251: %old_name_to_ip = %{$ip_info->[1]};
12252: }
12253:
1.888 albertel 12254: my %name_to_host = &all_names();
12255: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12256: my $ip;
12257: if (!exists($name_to_ip{$name})) {
12258: $ip = gethostbyname($name);
12259: if (!$ip || length($ip) ne 4) {
1.894 albertel 12260: if (defined($old_name_to_ip{$name})) {
12261: $ip = $old_name_to_ip{$name};
12262: &logthis("Can't find $name defaulting to old $ip");
12263: } else {
12264: &logthis("Name $name no IP found");
12265: next;
12266: }
12267: } else {
12268: $ip=inet_ntoa($ip);
1.847 albertel 12269: }
12270: $name_to_ip{$name} = $ip;
12271: } else {
12272: $ip = $name_to_ip{$name};
1.653 albertel 12273: }
1.888 albertel 12274: foreach my $id (@{ $name_to_host{$name} }) {
12275: $lonid_to_ip{$id} = $ip;
12276: }
12277: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12278: }
1.1172.2.23 raeburn 12279: &do_cache_new('iphost','iphost',
12280: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12281: 48*60*60);
1.869 albertel 12282:
1.847 albertel 12283: return %iphost;
1.598 albertel 12284: }
12285:
1.992 raeburn 12286: #
12287: # Given a DNS returns the loncapa host name for that DNS
12288: #
12289: sub host_from_dns {
12290: my ($dns) = @_;
12291: my @hosts;
12292: my $ip;
12293:
1.993 raeburn 12294: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12295: $ip = $name_to_ip{$dns};
12296: }
12297: if (!$ip) {
12298: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12299: if (length($ip) == 4) {
12300: $ip = &IO::Socket::inet_ntoa($ip);
12301: }
12302: }
12303: if ($ip) {
12304: @hosts = get_hosts_from_ip($ip);
12305: return $hosts[0];
12306: }
12307: return undef;
1.986 foxr 12308: }
1.992 raeburn 12309:
1.1074 raeburn 12310: sub get_internet_names {
12311: my ($lonid) = @_;
12312: return if ($lonid eq '');
12313: my ($idnref,$cached)=
12314: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12315: if ($cached) {
12316: return $idnref;
12317: }
12318: my $ip = &get_host_ip($lonid);
12319: my @hosts = &get_hosts_from_ip($ip);
12320: my %iphost = &get_iphost();
12321: my (@idns,%seen);
12322: foreach my $id (@hosts) {
12323: my $dom = &host_domain($id);
12324: my $prim_id = &domain($dom,'primary');
12325: my $prim_ip = &get_host_ip($prim_id);
12326: next if ($seen{$prim_ip});
12327: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12328: foreach my $id (@{$iphost{$prim_ip}}) {
12329: my $intdom = &internet_dom($id);
12330: unless (grep(/^\Q$intdom\E$/,@idns)) {
12331: push(@idns,$intdom);
12332: }
12333: }
12334: }
12335: $seen{$prim_ip} = 1;
12336: }
1.1172.2.23 raeburn 12337: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12338: }
12339:
1.986 foxr 12340: }
12341:
1.1079 raeburn 12342: sub all_loncaparevs {
1.1172.2.39 raeburn 12343: 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 12344: }
12345:
1.1172.2.27 raeburn 12346: # ------------------------------------------------------- Read loncaparev table
12347: {
12348: sub load_loncaparevs {
12349: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12350: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12351: while (my $configline=<$config>) {
12352: chomp($configline);
12353: my ($hostid,$loncaparev)=split(/:/,$configline);
12354: $loncaparevs{$hostid}=$loncaparev;
12355: }
12356: close($config);
12357: }
12358: }
12359: }
12360: }
12361:
12362: # ----------------------------------------------------- Read serverhostID table
12363: {
12364: sub load_serverhomeIDs {
12365: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12366: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12367: while (my $configline=<$config>) {
12368: chomp($configline);
12369: my ($name,$id)=split(/:/,$configline);
12370: $serverhomeIDs{$name}=$id;
12371: }
12372: close($config);
12373: }
12374: }
12375: }
12376: }
12377:
12378:
1.862 albertel 12379: BEGIN {
12380:
12381: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12382: unless ($readit) {
12383: {
12384: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12385: %perlvar = (%perlvar,%{$configvars});
12386: }
12387:
12388:
1.1 albertel 12389: # ------------------------------------------------------ Read spare server file
12390: {
1.448 albertel 12391: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12392:
12393: while (my $configline=<$config>) {
12394: chomp($configline);
1.284 matthew 12395: if ($configline) {
1.784 albertel 12396: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12397: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12398: push(@{ $spareid{$type} }, $host);
1.1 albertel 12399: }
12400: }
1.448 albertel 12401: close($config);
1.1 albertel 12402: }
1.11 www 12403: # ------------------------------------------------------------ Read permissions
12404: {
1.448 albertel 12405: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12406:
12407: while (my $configline=<$config>) {
1.448 albertel 12408: chomp($configline);
12409: if ($configline) {
12410: my ($role,$perm)=split(/ /,$configline);
12411: if ($perm ne '') { $pr{$role}=$perm; }
12412: }
1.11 www 12413: }
1.448 albertel 12414: close($config);
1.11 www 12415: }
12416:
12417: # -------------------------------------------- Read plain texts for permissions
12418: {
1.448 albertel 12419: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12420:
12421: while (my $configline=<$config>) {
1.448 albertel 12422: chomp($configline);
12423: if ($configline) {
1.742 raeburn 12424: my ($short,@plain)=split(/:/,$configline);
12425: %{$prp{$short}} = ();
12426: if (@plain > 0) {
12427: $prp{$short}{'std'} = $plain[0];
12428: for (my $i=1; $i<@plain; $i++) {
12429: $prp{$short}{'alt'.$i} = $plain[$i];
12430: }
12431: }
1.448 albertel 12432: }
1.135 www 12433: }
1.448 albertel 12434: close($config);
1.135 www 12435: }
12436:
12437: # ---------------------------------------------------------- Read package table
12438: {
1.448 albertel 12439: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12440:
12441: while (my $configline=<$config>) {
1.483 albertel 12442: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12443: chomp($configline);
12444: my ($short,$plain)=split(/:/,$configline);
12445: my ($pack,$name)=split(/\&/,$short);
12446: if ($plain ne '') {
12447: $packagetab{$pack.'&'.$name.'&name'}=$name;
12448: $packagetab{$short}=$plain;
12449: }
1.11 www 12450: }
1.448 albertel 12451: close($config);
1.329 matthew 12452: }
12453:
1.1172.2.27 raeburn 12454: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12455:
1.1172.2.27 raeburn 12456: &load_loncaparevs();
12457:
12458: # ------------------------------------------------------- Read serverhostID table
12459:
12460: &load_serverhomeIDs();
1.1074 raeburn 12461:
1.1172.2.27 raeburn 12462: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12463: {
12464: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12465: if (-e $file) {
12466: my $parser = HTML::LCParser->new($file);
12467: while (my $token = $parser->get_token()) {
12468: if ($token->[0] eq 'S') {
12469: my $item = $token->[1];
12470: my $name = $token->[2]{'name'};
12471: my $value = $token->[2]{'value'};
12472: if ($item ne '' && $name ne '' && $value ne '') {
12473: my $release = $parser->get_text();
12474: $release =~ s/(^\s*|\s*$ )//gx;
12475: $needsrelease{$item.':'.$name.':'.$value} = $release;
12476: }
12477: }
12478: }
12479: }
1.1073 raeburn 12480: }
12481:
1.1138 raeburn 12482: # ---------------------------------------------------------- Read managers table
12483: {
12484: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12485: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12486: while (my $configline=<$config>) {
12487: chomp($configline);
12488: next if ($configline =~ /^\#/);
12489: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12490: $managerstab{$configline} = 1;
12491: }
12492: }
12493: close($config);
12494: }
12495: }
12496: }
12497:
1.329 matthew 12498: # ------------- set up temporary directory
12499: {
1.1117 foxr 12500: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12501:
1.11 www 12502: }
12503:
1.794 albertel 12504: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12505: 'compress_threshold'=> 20_000,
12506: });
1.185 www 12507:
1.281 www 12508: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12509: $dumpcount=0;
1.958 www 12510: $locknum=0;
1.22 www 12511:
1.163 harris41 12512: &logtouch();
1.672 albertel 12513: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12514: $readit=1;
1.564 albertel 12515: {
12516: use integer;
12517: my $test=(2**32)+1;
1.568 albertel 12518: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12519: &logthis(" Detected 64bit platform ($_64bit)");
12520: }
1.195 www 12521: }
1.1 albertel 12522: }
1.179 www 12523:
1.1 albertel 12524: 1;
1.191 harris41 12525: __END__
12526:
1.243 albertel 12527: =pod
12528:
1.191 harris41 12529: =head1 NAME
12530:
1.243 albertel 12531: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12532:
12533: =head1 SYNOPSIS
12534:
1.243 albertel 12535: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12536:
12537: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12538:
1.243 albertel 12539: Common parameters:
12540:
12541: =over 4
12542:
12543: =item *
12544:
12545: $uname : an internal username (if $cname expecting a course Id specifically)
12546:
12547: =item *
12548:
12549: $udom : a domain (if $cdom expecting a course's domain specifically)
12550:
12551: =item *
12552:
12553: $symb : a resource instance identifier
12554:
12555: =item *
12556:
12557: $namespace : the name of a .db file that contains the data needed or
12558: being set.
12559:
12560: =back
12561:
1.394 bowersj2 12562: =head1 OVERVIEW
1.191 harris41 12563:
1.394 bowersj2 12564: lonnet provides subroutines which interact with the
12565: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12566: about classes, users, and resources.
1.243 albertel 12567:
12568: For many of these objects you can also use this to store data about
12569: them or modify them in various ways.
1.191 harris41 12570:
1.394 bowersj2 12571: =head2 Symbs
1.191 harris41 12572:
1.394 bowersj2 12573: To identify a specific instance of a resource, LON-CAPA uses symbols
12574: or "symbs"X<symb>. These identifiers are built from the URL of the
12575: map, the resource number of the resource in the map, and the URL of
12576: the resource itself. The latter is somewhat redundant, but might help
12577: if maps change.
12578:
12579: An example is
12580:
12581: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12582:
12583: The respective map entry is
12584:
12585: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12586: title="Problem 2">
12587: </resource>
12588:
12589: Symbs are used by the random number generator, as well as to store and
12590: restore data specific to a certain instance of for example a problem.
12591:
12592: =head2 Storing And Retrieving Data
12593:
12594: X<store()>X<cstore()>X<restore()>Three of the most important functions
12595: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12596: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12597: is is the non-critical message twin of cstore. These functions are for
12598: handlers to store a perl hash to a user's permanent data space in an
12599: easy manner, and to retrieve it again on another call. It is expected
12600: that a handler would use this once at the beginning to retrieve data,
12601: and then again once at the end to send only the new data back.
12602:
12603: The data is stored in the user's data directory on the user's
12604: homeserver under the ID of the course.
12605:
12606: The hash that is returned by restore will have all of the previous
12607: value for all of the elements of the hash.
12608:
12609: Example:
12610:
12611: #creating a hash
12612: my %hash;
12613: $hash{'foo'}='bar';
12614:
12615: #storing it
12616: &Apache::lonnet::cstore(\%hash);
12617:
12618: #changing a value
12619: $hash{'foo'}='notbar';
12620:
12621: #adding a new value
12622: $hash{'bar'}='foo';
12623: &Apache::lonnet::cstore(\%hash);
12624:
12625: #retrieving the hash
12626: my %history=&Apache::lonnet::restore();
12627:
12628: #print the hash
12629: foreach my $key (sort(keys(%history))) {
12630: print("\%history{$key} = $history{$key}");
12631: }
12632:
12633: Will print out:
1.191 harris41 12634:
1.394 bowersj2 12635: %history{1:foo} = bar
12636: %history{1:keys} = foo:timestamp
12637: %history{1:timestamp} = 990455579
12638: %history{2:bar} = foo
12639: %history{2:foo} = notbar
12640: %history{2:keys} = foo:bar:timestamp
12641: %history{2:timestamp} = 990455580
12642: %history{bar} = foo
12643: %history{foo} = notbar
12644: %history{timestamp} = 990455580
12645: %history{version} = 2
12646:
12647: Note that the special hash entries C<keys>, C<version> and
12648: C<timestamp> were added to the hash. C<version> will be equal to the
12649: total number of versions of the data that have been stored. The
12650: C<timestamp> attribute will be the UNIX time the hash was
12651: stored. C<keys> is available in every historical section to list which
12652: keys were added or changed at a specific historical revision of a
12653: hash.
12654:
12655: B<Warning>: do not store the hash that restore returns directly. This
12656: will cause a mess since it will restore the historical keys as if the
12657: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12658:
1.394 bowersj2 12659: Calling convention:
1.191 harris41 12660:
1.1172.2.27 raeburn 12661: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12662: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12663:
1.394 bowersj2 12664: For more detailed information, see lonnet specific documentation.
1.191 harris41 12665:
1.394 bowersj2 12666: =head1 RETURN MESSAGES
1.191 harris41 12667:
1.394 bowersj2 12668: =over 4
1.191 harris41 12669:
1.394 bowersj2 12670: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12671:
1.394 bowersj2 12672: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12673: when the connection is brought back up
1.191 harris41 12674:
1.394 bowersj2 12675: =item * B<con_failed>: unable to contact remote host and unable to save message
12676: for later delivery
1.191 harris41 12677:
1.967 bisitz 12678: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12679:
1.394 bowersj2 12680: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12681: that was requested
1.191 harris41 12682:
1.243 albertel 12683: =back
1.191 harris41 12684:
1.243 albertel 12685: =head1 PUBLIC SUBROUTINES
1.191 harris41 12686:
1.243 albertel 12687: =head2 Session Environment Functions
1.191 harris41 12688:
1.243 albertel 12689: =over 4
1.191 harris41 12690:
1.394 bowersj2 12691: =item *
12692: X<appenv()>
1.949 raeburn 12693: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12694: the user envirnoment file, and will be restored for each access this
1.620 albertel 12695: user makes during this session, also modifies the %env for the current
1.949 raeburn 12696: process. Optional rolesarrayref - if defined contains a reference to an array
12697: of roles which are exempt from the restriction on modifying user.role entries
12698: in the user's environment.db and in %env.
1.191 harris41 12699:
12700: =item *
1.394 bowersj2 12701: X<delenv()>
1.987 raeburn 12702: B<delenv($delthis,$regexp)>: removes all items from the session
12703: environment file that begin with $delthis. If the
12704: optional second arg - $regexp - is true, $delthis is treated as a
12705: regular expression, otherwise \Q$delthis\E is used.
12706: The values are also deleted from the current processes %env.
1.191 harris41 12707:
1.795 albertel 12708: =item * get_env_multiple($name)
12709:
12710: gets $name from the %env hash, it seemlessly handles the cases where multiple
12711: values may be defined and end up as an array ref.
12712:
12713: returns an array of values
12714:
1.243 albertel 12715: =back
12716:
12717: =head2 User Information
1.191 harris41 12718:
1.243 albertel 12719: =over 4
1.191 harris41 12720:
12721: =item *
1.394 bowersj2 12722: X<queryauthenticate()>
12723: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12724: authentication scheme
12725:
12726: =item *
1.394 bowersj2 12727: X<authenticate()>
1.1073 raeburn 12728: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12729: authenticate user from domain's lib servers (first use the current
12730: one). C<$upass> should be the users password.
1.1073 raeburn 12731: $checkdefauth is optional (value is 1 if a check should be made to
12732: authenticate user using default authentication method, and allow
12733: account creation if username does not have account in the domain).
12734: $clientcancheckhost is optional (value is 1 if checking whether the
12735: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12736:
12737: =item *
1.394 bowersj2 12738: X<homeserver()>
12739: B<homeserver($uname,$udom)>: find the server which has
12740: the user's directory and files (there must be only one), this caches
12741: the answer, and also caches if there is a borken connection.
1.191 harris41 12742:
12743: =item *
1.394 bowersj2 12744: X<idget()>
12745: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12746: (IDs are a unique resource in a domain, there must be only 1 ID per
12747: username, and only 1 username per ID in a specific domain) (returns
12748: hash: id=>name,id=>name)
1.191 harris41 12749:
12750: =item *
1.394 bowersj2 12751: X<idrget()>
12752: B<idrget($udom,@unames)>: find the IDs behind a list of
12753: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12754:
12755: =item *
1.394 bowersj2 12756: X<idput()>
12757: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12758:
12759: =item *
1.394 bowersj2 12760: X<rolesinit()>
1.1169 droeschl 12761: B<rolesinit($udom,$username)>: get user privileges.
12762: returns user role, first access and timer interval hashes
1.243 albertel 12763:
12764: =item *
1.1171 droeschl 12765: X<privileged()>
12766: B<privileged($username,$domain)>: returns a true if user has a
12767: privileged and active role (i.e. su or dc), false otherwise.
12768:
12769: =item *
1.551 albertel 12770: X<getsection()>
12771: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12772: course $cname, return section name/number or '' for "not in course"
12773: and '-1' for "no section"
12774:
12775: =item *
1.394 bowersj2 12776: X<userenvironment()>
12777: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12778: passed in @what from the requested user's environment, returns a hash
12779:
1.858 raeburn 12780: =item *
12781: X<userlog_query()>
1.859 albertel 12782: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12783: activity.log file. %filters defines filters applied when parsing the
12784: log file. These can be start or end timestamps, or the type of action
12785: - log to look for Login or Logout events, check for Checkin or
12786: Checkout, role for role selection. The response is in the form
12787: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12788: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12789:
1.243 albertel 12790: =back
12791:
12792: =head2 User Roles
12793:
12794: =over 4
12795:
12796: =item *
12797:
1.810 raeburn 12798: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12799: F: full access
12800: U,I,K: authentication modes (cxx only)
12801: '': forbidden
12802: 1: user needs to choose course
12803: 2: browse allowed
1.766 albertel 12804: A: passphrase authentication needed
1.243 albertel 12805:
12806: =item *
12807:
1.1172.2.13 raeburn 12808: constructaccess($url,$setpriv) : check for access to construction space URL
12809:
12810: See if the owner domain and name in the URL match those in the
12811: expected environment. If so, return three element list
12812: ($ownername,$ownerdomain,$ownerhome).
12813:
12814: Otherwise return the null string.
12815:
12816: If second argument 'setpriv' is true, it assigns the privileges,
12817: and returns the same three element list, unless the owner has
12818: blocked "ad hoc" Domain Coordinator access to the Author Space,
12819: in which case the null string is returned.
12820:
12821: =item *
12822:
1.243 albertel 12823: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12824: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12825: and course level
12826:
12827: =item *
12828:
1.988 raeburn 12829: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12830: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12831: $type is Course (default) or Community.
1.988 raeburn 12832: If $forcedefault evaluates to true, text returned will be default
12833: text for $type. Otherwise, if this is a course, the text returned
12834: will be a custom name for the role (if defined in the course's
12835: environment). If no custom name is defined the default is returned.
12836:
1.832 raeburn 12837: =item *
12838:
1.1172.2.23 raeburn 12839: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12840: All arguments are optional. Returns a hash of a roles, either for
12841: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12842: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12843: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12844: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12845: For each key, value is set to colon-separated start and end times for
12846: the role. If no username and domain are specified, will default to
1.934 raeburn 12847: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12848: of role statuses (active, future or previous), roles
12849: (e.g., cc,in, st etc.) and domains of the roles which can be used
12850: to restrict the list of roles reported. If no array ref is
12851: provided for types, will default to return only active roles.
1.834 albertel 12852:
1.1172.2.13 raeburn 12853: =item *
12854:
12855: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12856: user: $uname:$udom has a role in the course: $cdom_$cnum.
12857:
12858: Additional optional arguments are: $type (if role checking is to be restricted
12859: to certain user status types -- previous (expired roles), active (currently
12860: available roles) or future (roles available in the future), and
12861: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12862: have active Domain Coordinator role in course's domain or in additional
12863: domains (specified in 'Domains to check for privileged users' in course
12864: environment -- set via: Course Settings -> Classlists and staff listing).
12865:
12866: =item *
12867:
12868: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12869: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12870: $possdomains and $possroles are optional array refs -- to domains to check and
12871: roles to check. If $possdomains is not specified, a dump will be done of the
12872: users' roles.db to check for a dc or su role in any domain. This can be
12873: time consuming if &privileged is called repeatedly (e.g., when displaying a
12874: classlist), so in such cases, supplying a $possdomains array is preferred, as
12875: this then allows &privileged_by_domain() to be used, which caches the identity
12876: of privileged users, eliminating the need for repeated calls to &dump().
12877:
12878: =item *
12879:
12880: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12881: where the outer hash keys are domains specified in the $possdomains array ref,
12882: next inner hash keys are privileged roles specified in the $roles array ref,
12883: and the innermost hash contains key = value pairs for username:domain = end:start
12884: for active or future "privileged" users with that role in that domain. To avoid
12885: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12886: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12887:
1.243 albertel 12888: =back
12889:
12890: =head2 User Modification
12891:
12892: =over 4
12893:
12894: =item *
12895:
1.957 raeburn 12896: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12897: user for the level given by URL. Optional start and end dates (leave empty
12898: string or zero for "no date")
1.191 harris41 12899:
12900: =item *
12901:
1.243 albertel 12902: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12903: change a users, password, possible return values are: ok,
12904: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12905: refused
1.191 harris41 12906:
12907: =item *
12908:
1.243 albertel 12909: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12910:
12911: =item *
12912:
1.1058 raeburn 12913: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12914: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12915:
12916: will update user information (firstname,middlename,lastname,generation,
12917: permanentemail), and if forceid is true, student/employee ID also.
12918: A user's institutional affiliation(s) can also be updated.
12919: User information fields will not be overwritten with empty entries
12920: unless the field is included in the $candelete array reference.
12921: This array is included when a single user is modified via "Manage Users",
12922: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12923:
12924: =item *
12925:
1.286 matthew 12926: modifystudent
12927:
1.957 raeburn 12928: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 12929: The course id is resolved based on the current user's environment.
12930: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12931: associated with a course.
12932:
1.297 matthew 12933: This call is essentially a wrapper for lonnet::modifyuser and
12934: lonnet::modify_student_enrollment
1.286 matthew 12935:
12936: Inputs:
12937:
12938: =over 4
12939:
1.957 raeburn 12940: =item B<$udom> Student's loncapa domain
1.286 matthew 12941:
1.957 raeburn 12942: =item B<$uname> Student's loncapa login name
1.286 matthew 12943:
1.964 bisitz 12944: =item B<$uid> Student/Employee ID
1.286 matthew 12945:
1.957 raeburn 12946: =item B<$umode> Student's authentication mode
1.286 matthew 12947:
1.957 raeburn 12948: =item B<$upass> Student's password
1.286 matthew 12949:
1.957 raeburn 12950: =item B<$first> Student's first name
1.286 matthew 12951:
1.957 raeburn 12952: =item B<$middle> Student's middle name
1.286 matthew 12953:
1.957 raeburn 12954: =item B<$last> Student's last name
1.286 matthew 12955:
1.957 raeburn 12956: =item B<$gene> Student's generation
1.286 matthew 12957:
1.957 raeburn 12958: =item B<$usec> Student's section in course
1.286 matthew 12959:
12960: =item B<$end> Unix time of the roles expiration
12961:
12962: =item B<$start> Unix time of the roles start date
12963:
12964: =item B<$forceid> If defined, allow $uid to be changed
12965:
12966: =item B<$desiredhome> server to use as home server for student
12967:
1.957 raeburn 12968: =item B<$email> Student's permanent e-mail address
12969:
12970: =item B<$type> Type of enrollment (auto or manual)
12971:
1.963 raeburn 12972: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12973:
12974: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12975:
1.963 raeburn 12976: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12977:
1.963 raeburn 12978: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12979:
1.1172.2.19 raeburn 12980: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12981:
12982: =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 12983:
1.286 matthew 12984: =back
1.297 matthew 12985:
12986: =item *
12987:
12988: modify_student_enrollment
12989:
1.1172.2.31 raeburn 12990: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12991: 'role.request.course' must be defined for this function to proceed.
12992:
12993: Inputs:
12994:
12995: =over 4
12996:
1.1172.2.31 raeburn 12997: =item $udom, student's domain
1.297 matthew 12998:
1.1172.2.31 raeburn 12999: =item $uname, student's name
1.297 matthew 13000:
1.1172.2.31 raeburn 13001: =item $uid, student's user id
1.297 matthew 13002:
1.1172.2.31 raeburn 13003: =item $first, student's first name
1.297 matthew 13004:
13005: =item $middle
13006:
13007: =item $last
13008:
13009: =item $gene
13010:
13011: =item $usec
13012:
13013: =item $end
13014:
13015: =item $start
13016:
1.957 raeburn 13017: =item $type
13018:
13019: =item $locktype
13020:
13021: =item $cid
13022:
13023: =item $selfenroll
13024:
13025: =item $context
13026:
1.1172.2.19 raeburn 13027: =item $credits, number of credits student will earn from this class
13028:
1.297 matthew 13029: =back
13030:
1.191 harris41 13031:
13032: =item *
13033:
1.243 albertel 13034: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13035: custom role; give a custom role to a user for the level given by URL. Specify
13036: name and domain of role author, and role name
1.191 harris41 13037:
13038: =item *
13039:
1.243 albertel 13040: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13041:
13042: =item *
13043:
1.243 albertel 13044: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13045:
13046: =back
13047:
13048: =head2 Course Infomation
13049:
13050: =over 4
1.191 harris41 13051:
13052: =item *
13053:
1.1118 foxr 13054: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13055: specified course id, including all environment settings for the
13056: course, the description of the course will be in the hash under the
13057: key 'description'
1.191 harris41 13058:
1.1118 foxr 13059: $options is an optional parameter that if supplied is a hash reference that controls
13060: what how this function works. It has the following key/values:
13061:
13062: =over 4
13063:
13064: =item freshen_cache
13065:
13066: If defined, and the environment cache for the course is valid, it is
13067: returned in the returned hash.
13068:
13069: =item one_time
13070:
13071: If defined, the last cache time is set to _now_
13072:
13073: =item user
13074:
13075: If defined, the supplied username is used instead of the current user.
13076:
13077:
13078: =back
13079:
1.191 harris41 13080: =item *
13081:
1.624 albertel 13082: resdata($name,$domain,$type,@which) : request for current parameter
13083: setting for a specific $type, where $type is either 'course' or 'user',
13084: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13085: answers for 10 minutes.
1.243 albertel 13086:
1.877 foxr 13087: =item *
13088:
13089: get_courseresdata($courseid, $domain) : dump the entire course resource
13090: data base, returning a hash that is keyed by the resource name and has
13091: values that are the resource value. I believe that the timestamps and
13092: versions are also returned.
13093:
1.1172.2.31 raeburn 13094: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13095: supplemental content area. This routine caches the number of files for
13096: 10 minutes.
13097:
1.243 albertel 13098: =back
13099:
13100: =head2 Course Modification
13101:
13102: =over 4
1.191 harris41 13103:
13104: =item *
13105:
1.243 albertel 13106: writecoursepref($courseid,%prefs) : write preferences (environment
13107: database) for a course
1.191 harris41 13108:
13109: =item *
13110:
1.1011 raeburn 13111: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13112:
13113: =item *
13114:
1.1038 raeburn 13115: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13116:
1.1167 droeschl 13117: =item *
13118:
13119: is_course($courseid), is_course($cdom, $cnum)
13120:
13121: Accepts either a combined $courseid (in the form of domain_courseid) or the
13122: two component version $cdom, $cnum. It checks if the specified course exists.
13123:
13124: Returns:
13125: undef if the course doesn't exist, otherwise
13126: in scalar context the combined courseid.
13127: in list context the two components of the course identifier, domain and
13128: courseid.
13129:
1.243 albertel 13130: =back
13131:
13132: =head2 Resource Subroutines
13133:
13134: =over 4
1.191 harris41 13135:
13136: =item *
13137:
1.243 albertel 13138: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13139:
13140: =item *
13141:
1.243 albertel 13142: repcopy($filename) : subscribes to the requested file, and attempts to
13143: replicate from the owning library server, Might return
1.607 raeburn 13144: 'unavailable', 'not_found', 'forbidden', 'ok', or
13145: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13146: resource. Expects the local filesystem pathname
13147: (/home/httpd/html/res/....)
13148:
13149: =back
13150:
13151: =head2 Resource Information
13152:
13153: =over 4
1.191 harris41 13154:
13155: =item *
13156:
1.1172.2.28 raeburn 13157: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13158: and returns the value of a variety of different possible values,
13159: $varname should be a request string, and the other parameters can be
13160: used to specify who and what one is asking about. Ordinarily, $cid
13161: does not need to be specified, as it is retrived from
13162: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13163: within lonuserstate::loadmap() when initializing a course, before
13164: $env{'request.course.id'} has been set, so it needs to be provided
13165: in that one case.
1.243 albertel 13166:
13167: Possible values for $varname are environment.lastname (or other item
13168: from the envirnment hash), user.name (or someother aspect about the
13169: user), resource.0.maxtries (or some other part and parameter of a
13170: resource)
1.204 albertel 13171:
13172: =item *
13173:
1.243 albertel 13174: directcondval($number) : get current value of a condition; reads from a state
13175: string
1.204 albertel 13176:
13177: =item *
13178:
1.243 albertel 13179: condval($condidx) : value of condition index based on state
1.204 albertel 13180:
13181: =item *
13182:
1.243 albertel 13183: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13184: resource's metadata, $what should be either a specific key, or either
13185: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13186: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13187:
13188: this function automatically caches all requests
1.191 harris41 13189:
13190: =item *
13191:
1.243 albertel 13192: metadata_query($query,$custom,$customshow) : make a metadata query against the
13193: network of library servers; returns file handle of where SQL and regex results
13194: will be stored for query
1.191 harris41 13195:
13196: =item *
13197:
1.243 albertel 13198: symbread($filename) : return symbolic list entry (filename argument optional);
13199: returns the data handle
1.191 harris41 13200:
13201: =item *
13202:
1.1172.2.17 raeburn 13203: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13204: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13205: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13206: on failure, user must be in a course, as it assumes the existence of
13207: the course initial hash, and uses $env('request.course.id'}. The third
13208: arg is an optional reference to a scalar. If this arg is passed in the
13209: call to symbverify, it will be set to 1 if the symb has been set to be
13210: encrypted; otherwise it will be null.
1.243 albertel 13211:
1.191 harris41 13212: =item *
13213:
1.243 albertel 13214: symbclean($symb) : removes versions numbers from a symb, returns the
13215: cleaned symb
1.191 harris41 13216:
13217: =item *
13218:
1.243 albertel 13219: is_on_map($uri) : checks if the $uri is somewhere on the current
13220: course map, user must be in a course for it to work.
1.191 harris41 13221:
13222: =item *
13223:
1.243 albertel 13224: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13225:
13226: =item *
13227:
1.243 albertel 13228: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13229: a random seed, all arguments are optional, if they aren't sent it uses the
13230: environment to derive them. Note: if symb isn't sent and it can't get one
13231: from &symbread it will use the current time as its return value
1.191 harris41 13232:
13233: =item *
13234:
1.243 albertel 13235: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13236: unfakeable, receipt
1.191 harris41 13237:
13238: =item *
13239:
1.620 albertel 13240: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13241:
13242: =item *
13243:
1.243 albertel 13244: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13245:
13246: =item *
13247:
1.243 albertel 13248: 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 13249:
13250: =item *
13251:
1.243 albertel 13252: 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 13253:
13254: =item *
13255:
1.243 albertel 13256: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13257:
13258: =item *
13259:
1.243 albertel 13260: devalidate($symb) : devalidate temporary spreadsheet calculations,
13261: forcing spreadsheet to reevaluate the resource scores next time.
13262:
1.1172.2.13 raeburn 13263: =item *
13264:
13265: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13266: when viewing in course context.
13267:
13268: input: six args -- filename (decluttered), course number, course domain,
13269: url, symb (if registered) and group (if this is a
13270: group item -- e.g., bulletin board, group page etc.).
13271:
13272: output: array of five scalars --
13273: $cfile -- url for file editing if editable on current server
13274: $home -- homeserver of resource (i.e., for author if published,
13275: or course if uploaded.).
13276: $switchserver -- 1 if server switch will be needed.
13277: $forceedit -- 1 if icon/link should be to go to edit mode
13278: $forceview -- 1 if icon/link should be to go to view mode
13279:
13280: =item *
13281:
13282: is_course_upload($file,$cnum,$cdom)
13283:
13284: Used in course context to determine if current file was uploaded to
13285: the course (i.e., would be found in /userfiles/docs on the course's
13286: homeserver.
13287:
13288: input: 3 args -- filename (decluttered), course number and course domain.
13289: output: boolean -- 1 if file was uploaded.
13290:
1.243 albertel 13291: =back
13292:
13293: =head2 Storing/Retreiving Data
13294:
13295: =over 4
1.191 harris41 13296:
13297: =item *
13298:
1.243 albertel 13299: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13300: for this url; hashref needs to be given and should be a \%hashname; the
13301: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13302: be derived from the env
1.191 harris41 13303:
13304: =item *
13305:
1.243 albertel 13306: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13307: uses critical subroutine
1.191 harris41 13308:
13309: =item *
13310:
1.243 albertel 13311: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13312: all args are optional
1.191 harris41 13313:
13314: =item *
13315:
1.717 albertel 13316: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13317: dumps the complete (or key matching regexp) namespace into a hash
13318: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13319: normally &store()ed into
13320:
13321: $range should be either an integer '100' (give me the first 100
13322: matching records)
13323: or be two integers sperated by a - with no spaces
13324: '30-50' (give me the 30th through the 50th matching
13325: records)
13326:
13327:
13328: =item *
13329:
13330: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13331: replaces a &store() version of data with a replacement set of data
13332: for a particular resource in a namespace passed in the $storehash hash
13333: reference
13334:
13335: =item *
13336:
1.243 albertel 13337: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13338: works very similar to store/cstore, but all data is stored in a
13339: temporary location and can be reset using tmpreset, $storehash should
13340: be a hash reference, returns nothing on success
1.191 harris41 13341:
13342: =item *
13343:
1.243 albertel 13344: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13345: similar to restore, but all data is stored in a temporary location and
13346: can be reset using tmpreset. Returns a hash of values on success,
13347: error string otherwise.
1.191 harris41 13348:
13349: =item *
13350:
1.243 albertel 13351: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13352: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13353:
13354: =item *
13355:
1.243 albertel 13356: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13357: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13358:
13359: =item *
13360:
1.243 albertel 13361: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13362: namesp ($udom and $uname are optional)
1.191 harris41 13363:
13364: =item *
13365:
1.702 albertel 13366: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13367: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13368: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13369:
1.702 albertel 13370: $range should be either an integer '100' (give me the first 100
13371: matching records)
13372: or be two integers sperated by a - with no spaces
13373: '30-50' (give me the 30th through the 50th matching
13374: records)
1.449 matthew 13375: =item *
13376:
13377: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13378: $store can be a scalar, an array reference, or if the amount to be
13379: incremented is > 1, a hash reference.
13380:
13381: ($udom and $uname are optional)
1.191 harris41 13382:
13383: =item *
13384:
1.243 albertel 13385: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13386: ($udom and $uname are optional)
1.191 harris41 13387:
13388: =item *
13389:
1.243 albertel 13390: cput($namespace,$storehash,$udom,$uname) : critical put
13391: ($udom and $uname are optional)
1.191 harris41 13392:
13393: =item *
13394:
1.748 albertel 13395: newput($namespace,$storehash,$udom,$uname) :
13396:
13397: Attempts to store the items in the $storehash, but only if they don't
13398: currently exist, if this succeeds you can be certain that you have
13399: successfully created a new key value pair in the $namespace db.
13400:
13401:
13402: Args:
13403: $namespace: name of database to store values to
13404: $storehash: hashref to store to the db
13405: $udom: (optional) domain of user containing the db
13406: $uname: (optional) name of user caontaining the db
13407:
13408: Returns:
13409: 'ok' -> succeeded in storing all keys of $storehash
13410: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13411: least <key> already existed in the db (other
13412: requested keys may also already exist)
1.967 bisitz 13413: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13414: 'con_lost' -> unable to contact request server
13415: 'refused' -> action was not allowed by remote machine
13416:
13417:
13418: =item *
13419:
1.243 albertel 13420: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13421: reference filled in from namesp (encrypts the return communication)
13422: ($udom and $uname are optional)
1.191 harris41 13423:
13424: =item *
13425:
1.243 albertel 13426: log($udom,$name,$home,$message) : write to permanent log for user; use
13427: critical subroutine
13428:
1.806 raeburn 13429: =item *
13430:
1.860 raeburn 13431: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13432: array reference filled in from namespace found in domain level on either
13433: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13434:
13435: =item *
13436:
1.860 raeburn 13437: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13438: domain level either on specified domain server ($uhome) or primary domain
13439: server ($udom and $uhome are optional)
1.806 raeburn 13440:
1.943 raeburn 13441: =item *
13442:
1.1172.2.35 raeburn 13443: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13444: for: authentication, language, quotas, timezone, date locale, and portal URL in
13445: the target domain.
13446:
13447: May also include additional key => value pairs for the following groups:
13448:
13449: =over
13450:
13451: =item
13452: disk quotas (MB allocated by default to portfolios and authoring spaces).
13453:
13454: =over
13455:
13456: =item defaultquota, authorquota
13457:
13458: =back
13459:
13460: =item
13461: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13462: portfolio for users).
13463:
13464: =over
13465:
13466: =item
13467: aboutme, blog, webdav, portfolio
13468:
13469: =back
13470:
13471: =item
13472: requestcourses: ability to request courses, and how requests are processed.
13473:
13474: =over
13475:
13476: =item
1.1172.2.37 raeburn 13477: official, unofficial, community, textbook
1.1172.2.35 raeburn 13478:
13479: =back
13480:
13481: =item
13482: inststatus: types of institutional affiliation, and order in which they are displayed.
13483:
13484: =over
13485:
13486: =item
1.1172.2.44 raeburn 13487: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13488:
13489: =back
13490:
13491: =item
13492: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13493: for course's uploaded content.
13494:
13495: =over
13496:
13497: =item
1.1172.2.37 raeburn 13498: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35 raeburn 13499:
13500: =back
13501:
13502: =item
13503: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13504: on your servers.
13505:
13506: =over
13507:
13508: =item
13509: remotesessions, hostedsessions
13510:
13511: =back
13512:
13513: =back
13514:
13515: In cases where a domain coordinator has never used the "Set Domain Configuration"
13516: utility to create a configuration.db file on a domain's primary library server
13517: only the following domain defaults: auth_def, auth_arg_def, lang_def
13518: -- corresponding values are authentication type (internal, krb4, krb5,
13519: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13520: will be available. Values are retrieved from cache (if current), unless the
13521: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13522: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13523:
13524: Typical usage:
1.943 raeburn 13525:
1.1172.2.35 raeburn 13526: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13527:
1.243 albertel 13528: =back
13529:
13530: =head2 Network Status Functions
13531:
13532: =over 4
1.191 harris41 13533:
13534: =item *
13535:
1.1137 raeburn 13536: dirlist() : return directory list based on URI (first arg).
13537:
13538: Inputs: 1 required, 5 optional.
13539:
13540: =over
13541:
13542: =item
13543: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13544:
13545: =item
13546: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13547:
13548: =item
13549: $username - username of user/course to be listed. Extracted from $uri if absent.
13550:
13551: =item
13552: $getpropath - boolean: 1 if prepend path using &propath().
13553:
13554: =item
13555: $getuserdir - boolean: 1 if prepend path for "userfiles".
13556:
13557: =item
13558: $alternateRoot - path to prepend in place of path from $uri.
13559:
13560: =back
13561:
13562: Returns: Array of up to two items.
13563:
13564: =over
13565:
13566: a reference to an array of files/subdirectories
13567:
13568: =over
13569:
13570: Each element in the array of files/subdirectories is a & separated list of
13571: item name and the result of running stat on the item. If dirlist was requested
13572: for a file instead of a directory, the item name will be ''. For a directory
13573: listing, if the item is a metadata file, the element will end &N&M
13574: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13575: default copyright set (1).
13576:
13577: =back
13578:
13579: a scalar containing error condition (if encountered).
13580:
13581: =over
13582:
13583: =item
13584: no_host (no homeserver identified for $username:$domain).
13585:
13586: =item
13587: no_such_host (server contacted for listing not identified as valid host).
13588:
13589: =item
13590: con_lost (connection to remote server failed).
13591:
13592: =item
13593: refused (invalid $username:$domain received on lond side).
13594:
13595: =item
13596: no_such_dir (directory at specified path on lond side does not exist).
13597:
13598: =item
13599: empty (directory at specified path on lond side is empty).
13600:
13601: =over
13602:
13603: This is currently not encountered because the &ls3, &ls2,
13604: &ls (_handler) routines on the lond side do not filter out
13605: . and .. from a directory listing.
13606:
13607: =back
13608:
13609: =back
13610:
13611: =back
1.191 harris41 13612:
13613: =item *
13614:
1.243 albertel 13615: spareserver() : find server with least workload from spare.tab
13616:
1.986 foxr 13617:
13618: =item *
13619:
13620: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13621: if there is no corresponding loncapa host.
13622:
1.243 albertel 13623: =back
13624:
1.986 foxr 13625:
1.243 albertel 13626: =head2 Apache Request
13627:
13628: =over 4
1.191 harris41 13629:
13630: =item *
13631:
1.243 albertel 13632: ssi($url,%hash) : server side include, does a complete request cycle on url to
13633: localhost, posts hash
13634:
13635: =back
13636:
13637: =head2 Data to String to Data
13638:
13639: =over 4
1.191 harris41 13640:
13641: =item *
13642:
1.243 albertel 13643: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13644: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13645:
13646: =item *
13647:
1.243 albertel 13648: hashref2str($hashref) : convert a hashref into a string complete with
13649: escaping and '=' and '&' separators, supports elements that are
13650: arrayrefs and hashrefs
1.191 harris41 13651:
13652: =item *
13653:
1.243 albertel 13654: arrayref2str($arrayref) : convert an arrayref into a string complete
13655: with escaping and '&' separators, supports elements that are arrayrefs
13656: and hashrefs
1.191 harris41 13657:
13658: =item *
13659:
1.243 albertel 13660: str2hash($string) : convert string to hash using unescaping and
13661: splitting on '=' and '&', supports elements that are arrayrefs and
13662: hashrefs
1.191 harris41 13663:
13664: =item *
13665:
1.243 albertel 13666: str2array($string) : convert string to hash using unescaping and
13667: splitting on '&', supports elements that are arrayrefs and hashrefs
13668:
13669: =back
13670:
13671: =head2 Logging Routines
13672:
13673:
13674: These routines allow one to make log messages in the lonnet.log and
13675: lonnet.perm logfiles.
1.191 harris41 13676:
1.1119 foxr 13677: =over 4
13678:
1.191 harris41 13679: =item *
13680:
1.243 albertel 13681: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13682:
13683: =item *
13684:
1.243 albertel 13685: logthis() : append message to the normal lonnet.log file, it gets
13686: preiodically rolled over and deleted.
1.191 harris41 13687:
13688: =item *
13689:
1.243 albertel 13690: logperm() : append a permanent message to lonnet.perm.log, this log
13691: file never gets deleted by any automated portion of the system, only
13692: messages of critical importance should go in here.
13693:
1.1119 foxr 13694:
1.243 albertel 13695: =back
13696:
13697: =head2 General File Helper Routines
13698:
13699: =over 4
1.191 harris41 13700:
13701: =item *
13702:
1.481 raeburn 13703: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13704: (a) files in /uploaded
13705: (i) If a local copy of the file exists -
13706: compares modification date of local copy with last-modified date for
13707: definitive version stored on home server for course. If local copy is
13708: stale, requests a new version from the home server and stores it.
13709: If the original has been removed from the home server, then local copy
13710: is unlinked.
13711: (ii) If local copy does not exist -
13712: requests the file from the home server and stores it.
13713:
13714: If $caller is 'uploadrep':
13715: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13716: for request for files originally uploaded via DOCS.
13717: - returns 'ok' if fresh local copy now available, -1 otherwise.
13718:
13719: Otherwise:
13720: This indicates a call from the content generation phase of the request.
13721: - returns the entire contents of the file or -1.
13722:
13723: (b) files in /res
13724: - returns the entire contents of a file or -1;
13725: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13726:
1.712 albertel 13727:
13728: =item *
13729:
13730: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13731: reference
13732:
13733: returns either a stat() list of data about the file or an empty list
13734: if the file doesn't exist or couldn't find out about it (connection
13735: problems or user unknown)
13736:
1.191 harris41 13737: =item *
13738:
1.243 albertel 13739: filelocation($dir,$file) : returns file system location of a file
13740: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13741: directory that relative $file lookups are to looked in ($dir of /a/dir
13742: and a file of ../bob will become /a/bob)
1.191 harris41 13743:
13744: =item *
13745:
13746: hreflocation($dir,$file) : returns file system location or a URL; same as
13747: filelocation except for hrefs
13748:
13749: =item *
13750:
1.1172.2.49 raeburn 13751: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13752: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 13753:
1.243 albertel 13754: =back
13755:
1.608 albertel 13756: =head2 Usererfile file routines (/uploaded*)
13757:
13758: =over 4
13759:
13760: =item *
13761:
13762: userfileupload(): main rotine for putting a file in a user or course's
13763: filespace, arguments are,
13764:
1.620 albertel 13765: formname - required - this is the name of the element in $env where the
1.608 albertel 13766: filename, and the contents of the file to create/modifed exist
1.620 albertel 13767: the filename is in $env{'form.'.$formname.'.filename'} and the
13768: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13769: context - if coursedoc, store the file in the course of the active role
13770: of the current user;
13771: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13772: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13773: subdir - required - subdirectory to put the file in under ../userfiles/
13774: if undefined, it will be placed in "unknown"
13775:
13776: (This routine calls clean_filename() to remove any dangerous
13777: characters from the filename, and then calls finuserfileupload() to
13778: complete the transaction)
13779:
13780: returns either the url of the uploaded file (/uploaded/....) if successful
13781: and /adm/notfound.html if unsuccessful
13782:
13783: =item *
13784:
13785: clean_filename(): routine for cleaing a filename up for storage in
13786: userfile space, argument is:
13787:
13788: filename - proposed filename
13789:
13790: returns: the new clean filename
13791:
13792: =item *
13793:
1.1090 raeburn 13794: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13795: userspace, probably shouldn't be called directly
13796:
13797: docuname: username or courseid of destination for the file
13798: docudom: domain of user/course of destination for the file
13799: formname: same as for userfileupload()
1.1090 raeburn 13800: fname: filename (including subdirectories) for the file
13801: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13802: allfiles: reference to hash used to store objects found by parser
13803: codebase: reference to hash used for codebases of java objects found by parser
13804: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13805: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13806: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13807: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13808: context: if 'overwrite', will move the uploaded file from its temporary location to
13809: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13810: mimetype: reference to scalar to accommodate mime type determined
13811: from File::MMagic if $parser = parse.
1.608 albertel 13812:
13813: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13814: and /adm/notfound.html if unsuccessful (or an error message if context
13815: was 'overwrite').
13816:
1.608 albertel 13817:
13818: =item *
13819:
13820: renameuserfile(): renames an existing userfile to a new name
13821:
13822: Args:
13823: docuname: username or courseid of destination for the file
13824: docudom: domain of user/course of destination for the file
13825: old: current file name (including any subdirs under userfiles)
13826: new: desired file name (including any subdirs under userfiles)
13827:
13828: =item *
13829:
13830: mkdiruserfile(): creates a directory is a userfiles dir
13831:
13832: Args:
13833: docuname: username or courseid of destination for the file
13834: docudom: domain of user/course of destination for the file
13835: dir: dir to create (including any subdirs under userfiles)
13836:
13837: =item *
13838:
13839: removeuserfile(): removes a file that exists in userfiles
13840:
13841: Args:
13842: docuname: username or courseid of destination for the file
13843: docudom: domain of user/course of destination for the file
13844: fname: filname to delete (including any subdirs under userfiles)
13845:
13846: =item *
13847:
13848: removeuploadedurl(): convience function for removeuserfile()
13849:
13850: Args:
13851: url: a full /uploaded/... url to delete
13852:
1.747 albertel 13853: =item *
13854:
13855: get_portfile_permissions():
13856: Args:
13857: domain: domain of user or course contain the portfolio files
13858: user: name of user or num of course contain the portfolio files
13859: Returns:
13860: hashref of a dump of the proper file_permissions.db
13861:
13862:
13863: =item *
13864:
13865: get_access_controls():
13866:
13867: Args:
13868: current_permissions: the hash ref returned from get_portfile_permissions()
13869: group: (optional) the group you want the files associated with
13870: file: (optional) the file you want access info on
13871:
13872: Returns:
1.749 raeburn 13873: a hash (keys are file names) of hashes containing
13874: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13875: values are XML containing access control settings (see below)
1.747 albertel 13876:
13877: Internal notes:
13878:
1.749 raeburn 13879: access controls are stored in file_permissions.db as key=value pairs.
13880: key -> path to file/file_name\0uniqueID:scope_end_start
13881: where scope -> public,guest,course,group,domains or users.
13882: end -> UNIX time for end of access (0 -> no end date)
13883: start -> UNIX time for start of access
13884:
13885: value -> XML description of access control
13886: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13887: <start></start>
13888: <end></end>
13889:
13890: <password></password> for scope type = guest
13891:
13892: <domain></domain> for scope type = course or group
13893: <number></number>
13894: <roles id="">
13895: <role></role>
13896: <access></access>
13897: <section></section>
13898: <group></group>
13899: </roles>
13900:
13901: <dom></dom> for scope type = domains
13902:
13903: <users> for scope type = users
13904: <user>
13905: <uname></uname>
13906: <udom></udom>
13907: </user>
13908: </users>
13909: </scope>
13910:
13911: Access data is also aggregated for each file in an additional key=value pair:
13912: key -> path to file/file_name\0accesscontrol
13913: value -> reference to hash
13914: hash contains key = value pairs
13915: where key = uniqueID:scope_end_start
13916: value = UNIX time record was last updated
13917:
13918: Used to improve speed of look-ups of access controls for each file.
13919:
13920: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13921:
1.1172.2.13 raeburn 13922: =item *
13923:
1.749 raeburn 13924: modify_access_controls():
13925:
13926: Modifies access controls for a portfolio file
13927: Args
13928: 1. file name
13929: 2. reference to hash of required changes,
13930: 3. domain
13931: 4. username
13932: where domain,username are the domain of the portfolio owner
13933: (either a user or a course)
13934:
13935: Returns:
13936: 1. result of additions or updates ('ok' or 'error', with error message).
13937: 2. result of deletions ('ok' or 'error', with error message).
13938: 3. reference to hash of any new or updated access controls.
13939: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13940: key = integer (inbound ID)
1.1172.2.13 raeburn 13941: value = uniqueID
13942:
13943: =item *
13944:
13945: get_timebased_id():
13946:
13947: Attempts to get a unique timestamp-based suffix for use with items added to a
13948: course via the Course Editor (e.g., folders, composite pages,
13949: group bulletin boards).
13950:
13951: Args: (first three required; six others optional)
13952:
13953: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13954: docssequence, or name of group
13955:
13956: 2. keyid (alphanumeric): name of temporary locking key in hash,
13957: e.g., num, boardids
13958:
13959: 3. namespace: name of gdbm file used to store suffixes already assigned;
13960: file will be named nohist_namespace.db
13961:
13962: 4. cdom: domain of course; default is current course domain from %env
13963:
13964: 5. cnum: course number; default is current course number from %env
13965:
13966: 6. idtype: set to concat if an additional digit is to be appended to the
13967: unix timestamp to form the suffix, if the plain timestamp is already
13968: in use. Default is to not do this, but simply increment the unix
13969: timestamp by 1 until a unique key is obtained.
13970:
13971: 7. who: holder of locking key; defaults to user:domain for user.
13972:
13973: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13974: retrying); default is 3.
13975:
13976: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13977:
13978: Returns:
13979:
13980: 1. suffix obtained (numeric)
13981:
13982: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13983:
13984: 3. error: contains (localized) error message if an error occurred.
13985:
1.747 albertel 13986:
1.608 albertel 13987: =back
13988:
1.243 albertel 13989: =head2 HTTP Helper Routines
13990:
13991: =over 4
13992:
1.191 harris41 13993: =item *
13994:
13995: escape() : unpack non-word characters into CGI-compatible hex codes
13996:
13997: =item *
13998:
13999: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14000:
1.243 albertel 14001: =back
14002:
14003: =head1 PRIVATE SUBROUTINES
14004:
14005: =head2 Underlying communication routines (Shouldn't call)
14006:
14007: =over 4
14008:
14009: =item *
14010:
14011: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14012:
14013: =item *
14014:
14015: reply() : uses subreply to send a message to remote machine, logs all failures
14016:
14017: =item *
14018:
14019: critical() : passes a critical message to another server; if cannot
14020: get through then place message in connection buffer directory and
14021: returns con_delayed, if incapable of saving message, returns
14022: con_failed
14023:
14024: =item *
14025:
14026: reconlonc() : tries to reconnect lonc client processes.
14027:
14028: =back
14029:
14030: =head2 Resource Access Logging
14031:
14032: =over 4
14033:
14034: =item *
14035:
14036: flushcourselogs() : flush (save) buffer logs and access logs
14037:
14038: =item *
14039:
14040: courselog($what) : save message for course in hash
14041:
14042: =item *
14043:
14044: courseacclog($what) : save message for course using &courselog(). Perform
14045: special processing for specific resource types (problems, exams, quizzes, etc).
14046:
1.191 harris41 14047: =item *
14048:
14049: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14050: as a PerlChildExitHandler
1.243 albertel 14051:
14052: =back
14053:
14054: =head2 Other
14055:
14056: =over 4
14057:
14058: =item *
14059:
14060: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14061:
14062: =back
14063:
14064: =cut
1.877 foxr 14065:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>