Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.61
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.61! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.60 2015/03/11 04:21:21 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;
1.1172.2.61! raeburn 1177: my $internet_names = &get_internet_names($try_server);
1.1083 raeburn 1178: if (ref($internet_names) eq 'ARRAY') {
1179: @intdoms = @{$internet_names};
1180: }
1181: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.1172.2.61! raeburn 1182: my $try_server_hostname = &hostname($try_server);
! 1183: my $serverhomeID = &get_server_homeID($try_server_hostname);
! 1184: my $serverhomedom = &host_domain($serverhomeID);
! 1185: my %defdomdefaults = &get_domain_defaults($serverhomedom);
! 1186: my $remoterev = &get_server_loncaparev(undef,$try_server);
1.1083 raeburn 1187: $canhost = &can_host_session($udom,$try_server,$remoterev,
1188: $remotesessions,
1189: $defdomdefaults{'hostedsessions'});
1190: }
1191: return $canhost;
1192: }
1193:
1.1123 raeburn 1194: sub this_host_spares {
1195: my ($dom) = @_;
1.1126 raeburn 1196: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1197: my @hosts = ¤t_machine_ids();
1198: foreach my $lonhost (@hosts) {
1199: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1200: $dom_in_use = $dom;
1201: $lonhost_in_use = $lonhost;
1.1123 raeburn 1202: last;
1203: }
1204: }
1.1126 raeburn 1205: if ($dom_in_use ne '') {
1206: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1207: }
1208: if (ref($result) ne 'HASH') {
1209: $lonhost_in_use = $perlvar{'lonHostID'};
1210: $dom_in_use = &host_domain($lonhost_in_use);
1211: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1212: if (ref($result) ne 'HASH') {
1213: $result = \%spareid;
1214: }
1215: }
1216: return $result;
1217: }
1218:
1219: sub spares_for_offload {
1220: my ($dom_in_use,$lonhost_in_use) = @_;
1221: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1222: if (defined($cached)) {
1223: return $result;
1224: } else {
1.1126 raeburn 1225: my $cachetime = 60*60*24;
1226: my %domconfig =
1227: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1228: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1229: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1230: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1231: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1232: }
1233: }
1234: }
1235: }
1.1126 raeburn 1236: return;
1.1123 raeburn 1237: }
1238:
1.1129 raeburn 1239: sub get_lonbalancer_config {
1240: my ($servers) = @_;
1241: my ($currbalancer,$currtargets);
1242: if (ref($servers) eq 'HASH') {
1243: foreach my $server (keys(%{$servers})) {
1244: my %what = (
1245: spareid => 1,
1246: perlvar => 1,
1247: );
1248: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1249: if ($result eq 'ok') {
1250: if (ref($returnhash) eq 'HASH') {
1251: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1252: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1253: $currbalancer = $server;
1254: $currtargets = {};
1255: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1256: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1257: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1258: }
1259: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1260: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1261: }
1262: }
1263: last;
1264: }
1265: }
1266: }
1267: }
1268: }
1269: }
1270: return ($currbalancer,$currtargets);
1271: }
1272:
1273: sub check_loadbalancing {
1274: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1275: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1276: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1277: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1278: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1279: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1280: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1281: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1282: my $serverhomedom = &host_domain($lonhost);
1283:
1284: my $cachetime = 60*60*24;
1285:
1286: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1287: $dom_in_use = $udom;
1288: $homeintdom = 1;
1289: } else {
1290: $dom_in_use = $serverhomedom;
1291: }
1292: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1293: unless (defined($cached)) {
1294: my %domconfig =
1295: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1296: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1297: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1298: }
1299: }
1300: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1301: ($is_balancer,$currtargets,$currrules) =
1302: &check_balancer_result($result,@hosts);
1.1129 raeburn 1303: if ($is_balancer) {
1304: if (ref($currrules) eq 'HASH') {
1305: if ($homeintdom) {
1306: if ($uname ne '') {
1307: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1308: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1309: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1310: $rule_in_effect = $currrules->{'_LC_author'};
1311: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1312: $rule_in_effect = $currrules->{'_LC_adv'}
1313: }
1314: }
1315: if ($rule_in_effect eq '') {
1316: my %userenv = &userenvironment($udom,$uname,'inststatus');
1317: if ($userenv{'inststatus'} ne '') {
1318: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1319: my ($othertitle,$usertypes,$types) =
1320: &Apache::loncommon::sorted_inst_types($udom);
1321: if (ref($types) eq 'ARRAY') {
1322: foreach my $type (@{$types}) {
1323: if (grep(/^\Q$type\E$/,@statuses)) {
1324: if (exists($currrules->{$type})) {
1325: $rule_in_effect = $currrules->{$type};
1326: }
1327: }
1328: }
1329: }
1330: } else {
1331: if (exists($currrules->{'default'})) {
1332: $rule_in_effect = $currrules->{'default'};
1333: }
1334: }
1335: }
1336: } else {
1337: if (exists($currrules->{'default'})) {
1338: $rule_in_effect = $currrules->{'default'};
1339: }
1340: }
1341: } else {
1342: if ($currrules->{'_LC_external'} ne '') {
1343: $rule_in_effect = $currrules->{'_LC_external'};
1344: }
1345: }
1346: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1347: $uname,$udom);
1348: }
1349: }
1350: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1351: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1352: unless (defined($cached)) {
1353: my %domconfig =
1354: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1355: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1356: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1357: }
1358: }
1359: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1360: ($is_balancer,$currtargets,$currrules) =
1361: &check_balancer_result($result,@hosts);
1362: if ($is_balancer) {
1.1129 raeburn 1363: if (ref($currrules) eq 'HASH') {
1364: if ($currrules->{'_LC_internetdom'} ne '') {
1365: $rule_in_effect = $currrules->{'_LC_internetdom'};
1366: }
1367: }
1368: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1369: $uname,$udom);
1370: }
1371: } else {
1372: if ($perlvar{'lonBalancer'} eq 'yes') {
1373: $is_balancer = 1;
1374: $offloadto = &this_host_spares($dom_in_use);
1375: }
1376: }
1377: } else {
1378: if ($perlvar{'lonBalancer'} eq 'yes') {
1379: $is_balancer = 1;
1380: $offloadto = &this_host_spares($dom_in_use);
1381: }
1382: }
1.1172.2.5 raeburn 1383: if ($is_balancer) {
1384: my $lowest_load = 30000;
1385: if (ref($offloadto) eq 'HASH') {
1386: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1387: foreach my $try_server (@{$offloadto->{'primary'}}) {
1388: ($otherserver,$lowest_load) =
1389: &compare_server_load($try_server,$otherserver,$lowest_load);
1390: }
1.1129 raeburn 1391: }
1.1172.2.5 raeburn 1392: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1393:
1.1172.2.5 raeburn 1394: if (!$found_server) {
1395: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1396: foreach my $try_server (@{$offloadto->{'default'}}) {
1397: ($otherserver,$lowest_load) =
1398: &compare_server_load($try_server,$otherserver,$lowest_load);
1399: }
1400: }
1401: }
1402: } elsif (ref($offloadto) eq 'ARRAY') {
1403: if (@{$offloadto} == 1) {
1404: $otherserver = $offloadto->[0];
1405: } elsif (@{$offloadto} > 1) {
1406: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1407: ($otherserver,$lowest_load) =
1408: &compare_server_load($try_server,$otherserver,$lowest_load);
1409: }
1410: }
1411: }
1.1172.2.5 raeburn 1412: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1413: $is_balancer = 0;
1414: if ($uname ne '' && $udom ne '') {
1415: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1416:
1417: &appenv({'user.loadbalexempt' => $lonhost,
1418: 'user.loadbalcheck.time' => time});
1419: }
1.1129 raeburn 1420: }
1421: }
1422: }
1423: return ($is_balancer,$otherserver);
1424: }
1425:
1.1172.2.12 raeburn 1426: sub check_balancer_result {
1427: my ($result,@hosts) = @_;
1428: my ($is_balancer,$currtargets,$currrules);
1429: if (ref($result) eq 'HASH') {
1430: if ($result->{'lonhost'} ne '') {
1431: my $currbalancer = $result->{'lonhost'};
1432: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1433: $is_balancer = 1;
1434: $currtargets = $result->{'targets'};
1435: $currrules = $result->{'rules'};
1436: }
1437: } else {
1438: foreach my $key (keys(%{$result})) {
1439: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1440: (ref($result->{$key}) eq 'HASH')) {
1441: $is_balancer = 1;
1442: $currrules = $result->{$key}{'rules'};
1443: $currtargets = $result->{$key}{'targets'};
1444: last;
1445: }
1446: }
1447: }
1448: }
1449: return ($is_balancer,$currtargets,$currrules);
1450: }
1451:
1.1129 raeburn 1452: sub get_loadbalancer_targets {
1453: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1454: my $offloadto;
1.1172.2.4 raeburn 1455: if ($rule_in_effect eq 'none') {
1456: return [$perlvar{'lonHostID'}];
1457: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1458: $offloadto = $currtargets;
1459: } else {
1460: if ($rule_in_effect eq 'homeserver') {
1461: my $homeserver = &homeserver($uname,$udom);
1462: if ($homeserver ne 'no_host') {
1463: $offloadto = [$homeserver];
1464: }
1465: } elsif ($rule_in_effect eq 'externalbalancer') {
1466: my %domconfig =
1467: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1468: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1469: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1470: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1471: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1472: }
1473: }
1474: } else {
1.1172.2.7 raeburn 1475: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1476: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1477: if (&hostname($remotebalancer) ne '') {
1478: $offloadto = [$remotebalancer];
1479: }
1480: }
1481: } elsif (&hostname($rule_in_effect) ne '') {
1482: $offloadto = [$rule_in_effect];
1483: }
1484: }
1485: return $offloadto;
1486: }
1487:
1.1127 raeburn 1488: sub internet_dom_servers {
1489: my ($dom) = @_;
1490: my (%uniqservers,%servers);
1491: my $primaryserver = &hostname(&domain($dom,'primary'));
1492: my @machinedoms = &machine_domains($primaryserver);
1493: foreach my $mdom (@machinedoms) {
1494: my %currservers = %servers;
1495: my %server = &get_servers($mdom);
1496: %servers = (%currservers,%server);
1497: }
1498: my %by_hostname;
1499: foreach my $id (keys(%servers)) {
1500: push(@{$by_hostname{$servers{$id}}},$id);
1501: }
1502: foreach my $hostname (sort(keys(%by_hostname))) {
1503: if (@{$by_hostname{$hostname}} > 1) {
1504: my $match = 0;
1505: foreach my $id (@{$by_hostname{$hostname}}) {
1506: if (&host_domain($id) eq $dom) {
1507: $uniqservers{$id} = $hostname;
1508: $match = 1;
1509: }
1510: }
1511: unless ($match) {
1512: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1513: }
1514: } else {
1515: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1516: }
1517: }
1518: return %uniqservers;
1519: }
1520:
1.1 albertel 1521: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1522:
1.599 albertel 1523: my %homecache;
1.1 albertel 1524: sub homeserver {
1.230 stredwic 1525: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1526: my $index="$uname:$udom";
1.426 albertel 1527:
1.599 albertel 1528: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1529:
1530: my %servers = &get_servers($udom,'library');
1531: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1532: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1533: exists($badServerCache{$tryserver}));
1.841 albertel 1534:
1535: my $answer=reply("home:$udom:$uname",$tryserver);
1536: if ($answer eq 'found') {
1537: delete($badServerCache{$tryserver});
1538: return $homecache{$index}=$tryserver;
1539: } elsif ($answer eq 'no_host') {
1540: $badServerCache{$tryserver}=1;
1541: }
1.1 albertel 1542: }
1543: return 'no_host';
1.70 www 1544: }
1545:
1546: # ------------------------------------- Find the usernames behind a list of IDs
1547:
1548: sub idget {
1549: my ($udom,@ids)=@_;
1550: my %returnhash=();
1551:
1.841 albertel 1552: my %servers = &get_servers($udom,'library');
1553: foreach my $tryserver (keys(%servers)) {
1554: my $idlist=join('&',@ids);
1555: $idlist=~tr/A-Z/a-z/;
1556: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1557: my @answer=();
1558: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1559: @answer=split(/\&/,$reply);
1560: } ;
1561: my $i;
1562: for ($i=0;$i<=$#ids;$i++) {
1563: if ($answer[$i]) {
1564: $returnhash{$ids[$i]}=$answer[$i];
1565: }
1566: }
1567: }
1.70 www 1568: return %returnhash;
1569: }
1570:
1571: # ------------------------------------- Find the IDs behind a list of usernames
1572:
1573: sub idrget {
1574: my ($udom,@unames)=@_;
1575: my %returnhash=();
1.800 albertel 1576: foreach my $uname (@unames) {
1577: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1578: }
1.70 www 1579: return %returnhash;
1580: }
1581:
1582: # ------------------------------- Store away a list of names and associated IDs
1583:
1584: sub idput {
1585: my ($udom,%ids)=@_;
1586: my %servers=();
1.800 albertel 1587: foreach my $uname (keys(%ids)) {
1588: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1589: my $uhom=&homeserver($uname,$udom);
1.70 www 1590: if ($uhom ne 'no_host') {
1.800 albertel 1591: my $id=&escape($ids{$uname});
1.70 www 1592: $id=~tr/A-Z/a-z/;
1.800 albertel 1593: my $esc_unam=&escape($uname);
1.70 www 1594: if ($servers{$uhom}) {
1.800 albertel 1595: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1596: } else {
1.800 albertel 1597: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1598: }
1599: }
1.191 harris41 1600: }
1.800 albertel 1601: foreach my $server (keys(%servers)) {
1602: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1603: }
1.344 www 1604: }
1605:
1.1172.2.30 raeburn 1606: # ---------------------------------------- Delete unwanted IDs from ids.db file
1607:
1608: sub iddel {
1609: my ($udom,$idshashref,$uhome)=@_;
1610: my %result=();
1611: unless (ref($idshashref) eq 'HASH') {
1612: return %result;
1613: }
1614: my %servers=();
1615: while (my ($id,$uname) = each(%{$idshashref})) {
1616: my $uhom;
1617: if ($uhome) {
1618: $uhom = $uhome;
1619: } else {
1620: $uhom=&homeserver($uname,$udom);
1621: }
1622: if ($uhom ne 'no_host') {
1623: if ($servers{$uhom}) {
1624: $servers{$uhom}.='&'.&escape($id);
1625: } else {
1626: $servers{$uhom}=&escape($id);
1627: }
1628: }
1629: }
1630: foreach my $server (keys(%servers)) {
1631: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1632: }
1633: return %result;
1634: }
1635:
1.1023 raeburn 1636: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1637: sub dump_dom {
1.1165 droeschl 1638: my ($namespace, $udom, $regexp) = @_;
1639:
1640: $udom ||= $env{'user.domain'};
1641:
1642: return () unless $udom;
1643:
1644: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1645: }
1646:
1.1023 raeburn 1647: # ------------------------------------------ get items from domain db files
1.806 raeburn 1648:
1649: sub get_dom {
1.860 raeburn 1650: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1651: return if ($udom eq 'public');
1.806 raeburn 1652: my $items='';
1653: foreach my $item (@$storearr) {
1654: $items.=&escape($item).'&';
1655: }
1656: $items=~s/\&$//;
1.860 raeburn 1657: if (!$udom) {
1658: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1659: return if ($udom eq 'public');
1.860 raeburn 1660: if (defined(&domain($udom,'primary'))) {
1661: $uhome=&domain($udom,'primary');
1662: } else {
1.874 albertel 1663: undef($uhome);
1.860 raeburn 1664: }
1665: } else {
1666: if (!$uhome) {
1667: if (defined(&domain($udom,'primary'))) {
1668: $uhome=&domain($udom,'primary');
1669: }
1670: }
1671: }
1672: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1673: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1674: my %returnhash;
1.875 albertel 1675: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1676: return %returnhash;
1677: }
1.806 raeburn 1678: my @pairs=split(/\&/,$rep);
1679: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1680: return @pairs;
1681: }
1682: my $i=0;
1683: foreach my $item (@$storearr) {
1684: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1685: $i++;
1686: }
1687: return %returnhash;
1688: } else {
1.880 banghart 1689: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1690: }
1691: }
1692:
1693: # -------------------------------------------- put items in domain db files
1694:
1695: sub put_dom {
1.860 raeburn 1696: my ($namespace,$storehash,$udom,$uhome)=@_;
1697: if (!$udom) {
1698: $udom=$env{'user.domain'};
1699: if (defined(&domain($udom,'primary'))) {
1700: $uhome=&domain($udom,'primary');
1701: } else {
1.874 albertel 1702: undef($uhome);
1.860 raeburn 1703: }
1704: } else {
1705: if (!$uhome) {
1706: if (defined(&domain($udom,'primary'))) {
1707: $uhome=&domain($udom,'primary');
1708: }
1709: }
1710: }
1711: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1712: my $items='';
1713: foreach my $item (keys(%$storehash)) {
1714: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1715: }
1716: $items=~s/\&$//;
1717: return &reply("putdom:$udom:$namespace:$items",$uhome);
1718: } else {
1.860 raeburn 1719: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1720: }
1721: }
1722:
1.1023 raeburn 1723: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1724: sub newput_dom {
1.1023 raeburn 1725: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1726: my $result;
1727: if (!$udom) {
1728: $udom=$env{'user.domain'};
1729: }
1.1023 raeburn 1730: if ($udom) {
1731: my $uname = &get_domainconfiguser($udom);
1732: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1733: }
1734: return $result;
1735: }
1736:
1.1023 raeburn 1737: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1738: sub del_dom {
1.1023 raeburn 1739: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1740: if (ref($storearr) eq 'ARRAY') {
1741: if (!$udom) {
1742: $udom=$env{'user.domain'};
1743: }
1.1023 raeburn 1744: if ($udom) {
1745: my $uname = &get_domainconfiguser($udom);
1746: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1747: }
1748: }
1749: }
1750:
1.1023 raeburn 1751: # ----------------------------------construct domainconfig user for a domain
1752: sub get_domainconfiguser {
1753: my ($udom) = @_;
1754: return $udom.'-domainconfig';
1755: }
1756:
1.837 raeburn 1757: sub retrieve_inst_usertypes {
1758: my ($udom) = @_;
1759: my (%returnhash,@order);
1.989 raeburn 1760: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1761: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1762: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1763: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1764: } else {
1765: if (defined(&domain($udom,'primary'))) {
1766: my $uhome=&domain($udom,'primary');
1767: my $rep=&reply("inst_usertypes:$udom",$uhome);
1768: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1769: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1770: return (\%returnhash,\@order);
1771: }
1772: my ($hashitems,$orderitems) = split(/:/,$rep);
1773: my @pairs=split(/\&/,$hashitems);
1774: foreach my $item (@pairs) {
1775: my ($key,$value)=split(/=/,$item,2);
1776: $key = &unescape($key);
1777: next if ($key =~ /^error: 2 /);
1778: $returnhash{$key}=&thaw_unescape($value);
1779: }
1780: my @esc_order = split(/\&/,$orderitems);
1781: foreach my $item (@esc_order) {
1782: push(@order,&unescape($item));
1783: }
1784: } else {
1.1172.2.44 raeburn 1785: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1786: }
1.1172.2.44 raeburn 1787: return (\%returnhash,\@order);
1.837 raeburn 1788: }
1789: }
1790:
1.868 raeburn 1791: sub is_domainimage {
1792: my ($url) = @_;
1793: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1794: if (&domain($1) ne '') {
1795: return '1';
1796: }
1797: }
1798: return;
1799: }
1800:
1.899 raeburn 1801: sub inst_directory_query {
1802: my ($srch) = @_;
1803: my $udom = $srch->{'srchdomain'};
1804: my %results;
1805: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1806: my $outcome;
1.899 raeburn 1807: if ($homeserver ne '') {
1.904 albertel 1808: my $queryid=&reply("querysend:instdirsearch:".
1809: &escape($srch->{'srchby'}).':'.
1810: &escape($srch->{'srchterm'}).':'.
1811: &escape($srch->{'srchtype'}),$homeserver);
1812: my $host=&hostname($homeserver);
1813: if ($queryid !~/^\Q$host\E\_/) {
1814: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1815: return;
1816: }
1817: my $response = &get_query_reply($queryid);
1818: my $maxtries = 5;
1819: my $tries = 1;
1820: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1821: $response = &get_query_reply($queryid);
1822: $tries ++;
1823: }
1824:
1825: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1826: if ($response eq 'unavailable') {
1827: $outcome = $response;
1828: } else {
1829: $outcome = 'ok';
1830: my @matches = split(/\n/,$response);
1831: foreach my $match (@matches) {
1832: my ($key,$value) = split(/=/,$match);
1833: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1834: }
1.899 raeburn 1835: }
1836: }
1837: }
1.909 raeburn 1838: return ($outcome,%results);
1.899 raeburn 1839: }
1840:
1841: sub usersearch {
1842: my ($srch) = @_;
1843: my $dom = $srch->{'srchdomain'};
1844: my %results;
1845: my %libserv = &all_library();
1846: my $query = 'usersearch';
1847: foreach my $tryserver (keys(%libserv)) {
1848: if (&host_domain($tryserver) eq $dom) {
1849: my $host=&hostname($tryserver);
1850: my $queryid=
1.911 raeburn 1851: &reply("querysend:".&escape($query).':'.
1852: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1853: &escape($srch->{'srchtype'}).':'.
1854: &escape($srch->{'srchterm'}),$tryserver);
1855: if ($queryid !~/^\Q$host\E\_/) {
1856: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1857: next;
1.899 raeburn 1858: }
1859: my $reply = &get_query_reply($queryid);
1860: my $maxtries = 1;
1861: my $tries = 1;
1862: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1863: $reply = &get_query_reply($queryid);
1864: $tries ++;
1865: }
1866: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1867: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1868: } else {
1.911 raeburn 1869: my @matches;
1870: if ($reply =~ /\n/) {
1871: @matches = split(/\n/,$reply);
1872: } else {
1873: @matches = split(/\&/,$reply);
1874: }
1.899 raeburn 1875: foreach my $match (@matches) {
1876: my ($uname,$udom,%userhash);
1.911 raeburn 1877: foreach my $entry (split(/:/,$match)) {
1878: my ($key,$value) =
1879: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1880: $userhash{$key} = $value;
1881: if ($key eq 'username') {
1882: $uname = $value;
1883: } elsif ($key eq 'domain') {
1884: $udom = $value;
1.911 raeburn 1885: }
1.899 raeburn 1886: }
1887: $results{$uname.':'.$udom} = \%userhash;
1888: }
1889: }
1890: }
1891: }
1892: return %results;
1893: }
1894:
1.912 raeburn 1895: sub get_instuser {
1896: my ($udom,$uname,$id) = @_;
1897: my $homeserver = &domain($udom,'primary');
1898: my ($outcome,%results);
1899: if ($homeserver ne '') {
1900: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1901: &escape($id).':'.&escape($udom),$homeserver);
1902: my $host=&hostname($homeserver);
1903: if ($queryid !~/^\Q$host\E\_/) {
1904: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1905: return;
1906: }
1907: my $response = &get_query_reply($queryid);
1908: my $maxtries = 5;
1909: my $tries = 1;
1910: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1911: $response = &get_query_reply($queryid);
1912: $tries ++;
1913: }
1914: if (!&error($response) && $response ne 'refused') {
1915: if ($response eq 'unavailable') {
1916: $outcome = $response;
1917: } else {
1918: $outcome = 'ok';
1919: my @matches = split(/\n/,$response);
1920: foreach my $match (@matches) {
1921: my ($key,$value) = split(/=/,$match);
1922: $results{&unescape($key)} = &thaw_unescape($value);
1923: }
1924: }
1925: }
1926: }
1927: my %userinfo;
1928: if (ref($results{$uname}) eq 'HASH') {
1929: %userinfo = %{$results{$uname}};
1930: }
1931: return ($outcome,%userinfo);
1932: }
1933:
1934: sub inst_rulecheck {
1.923 raeburn 1935: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1936: my %returnhash;
1937: if ($udom ne '') {
1938: if (ref($rules) eq 'ARRAY') {
1939: @{$rules} = map {&escape($_);} (@{$rules});
1940: my $rulestr = join(':',@{$rules});
1941: my $homeserver=&domain($udom,'primary');
1942: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1943: my $response;
1944: if ($item eq 'username') {
1945: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1946: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1947: $homeserver));
1.923 raeburn 1948: } elsif ($item eq 'id') {
1949: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1950: ':'.&escape($id).':'.$rulestr,
1951: $homeserver));
1.945 raeburn 1952: } elsif ($item eq 'selfcreate') {
1953: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1954: &escape($udom).':'.&escape($uname).
1955: ':'.$rulestr,$homeserver));
1.923 raeburn 1956: }
1.912 raeburn 1957: if ($response ne 'refused') {
1958: my @pairs=split(/\&/,$response);
1959: foreach my $item (@pairs) {
1960: my ($key,$value)=split(/=/,$item,2);
1961: $key = &unescape($key);
1962: next if ($key =~ /^error: 2 /);
1963: $returnhash{$key}=&thaw_unescape($value);
1964: }
1965: }
1966: }
1967: }
1968: }
1969: return %returnhash;
1970: }
1971:
1972: sub inst_userrules {
1.923 raeburn 1973: my ($udom,$check) = @_;
1.912 raeburn 1974: my (%ruleshash,@ruleorder);
1975: if ($udom ne '') {
1976: my $homeserver=&domain($udom,'primary');
1977: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1978: my $response;
1979: if ($check eq 'id') {
1980: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1981: $homeserver);
1.943 raeburn 1982: } elsif ($check eq 'email') {
1983: $response=&reply('instemailrules:'.&escape($udom),
1984: $homeserver);
1.923 raeburn 1985: } else {
1986: $response=&reply('instuserrules:'.&escape($udom),
1987: $homeserver);
1988: }
1.912 raeburn 1989: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1990: ($response ne 'unknown_cmd') &&
1.912 raeburn 1991: ($response ne 'no_such_host')) {
1992: my ($hashitems,$orderitems) = split(/:/,$response);
1993: my @pairs=split(/\&/,$hashitems);
1994: foreach my $item (@pairs) {
1995: my ($key,$value)=split(/=/,$item,2);
1996: $key = &unescape($key);
1997: next if ($key =~ /^error: 2 /);
1998: $ruleshash{$key}=&thaw_unescape($value);
1999: }
2000: my @esc_order = split(/\&/,$orderitems);
2001: foreach my $item (@esc_order) {
2002: push(@ruleorder,&unescape($item));
2003: }
2004: }
2005: }
2006: }
2007: return (\%ruleshash,\@ruleorder);
2008: }
2009:
1.976 raeburn 2010: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2011:
2012: sub get_domain_defaults {
1.1172.2.35 raeburn 2013: my ($domain,$ignore_cache) = @_;
2014: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2015: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2016: unless ($ignore_cache) {
2017: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2018: if (defined($cached)) {
2019: if (ref($result) eq 'HASH') {
2020: return %{$result};
2021: }
1.943 raeburn 2022: }
2023: }
2024: my %domdefaults;
2025: my %domconfig =
1.989 raeburn 2026: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2027: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2028: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2029: 'requestauthor','selfenrollment',
2030: 'coursecategories'],$domain);
1.1172.2.41 raeburn 2031: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2032: if (ref($domconfig{'defaults'}) eq 'HASH') {
2033: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2034: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2035: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2036: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2037: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2038: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2039: } else {
2040: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2041: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2042: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2043: }
1.976 raeburn 2044: if (ref($domconfig{'quotas'}) eq 'HASH') {
2045: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2046: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2047: } else {
2048: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2049: }
1.1172.2.6 raeburn 2050: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2051: foreach my $item (@usertools) {
2052: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2053: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2054: }
2055: }
1.1172.2.29 raeburn 2056: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2057: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2058: }
1.976 raeburn 2059: }
1.985 raeburn 2060: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2061: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2062: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2063: }
2064: }
1.1172.2.9 raeburn 2065: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2066: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2067: }
1.989 raeburn 2068: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2069: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2070: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2071: }
2072: }
1.1047 raeburn 2073: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2074: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2075: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2076: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2077: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2078: }
1.1172.2.41 raeburn 2079: foreach my $type (@coursetypes) {
2080: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2081: unless ($type eq 'community') {
2082: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2083: }
2084: }
2085: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2086: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2087: }
1.1172.2.60 raeburn 2088: if ($domdefaults{'postsubmit'} eq 'on') {
2089: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2090: $domdefaults{$type.'postsubtimeout'} =
2091: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2092: }
2093: }
1.1172.2.30 raeburn 2094: }
1.1047 raeburn 2095: }
1.1073 raeburn 2096: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2097: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2098: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2099: }
2100: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2101: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2102: }
2103: }
1.1172.2.41 raeburn 2104: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2105: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2106: my @settings = ('types','registered','enroll_dates','access_dates','section',
2107: 'approval','limit');
2108: foreach my $type (@coursetypes) {
2109: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2110: my @mgrdc = ();
2111: foreach my $item (@settings) {
2112: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2113: push(@mgrdc,$item);
2114: }
2115: }
2116: if (@mgrdc) {
2117: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2118: }
2119: }
2120: }
2121: }
2122: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2123: foreach my $type (@coursetypes) {
2124: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2125: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2126: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2127: }
2128: }
2129: }
2130: }
2131: }
1.1172.2.46 raeburn 2132: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2133: $domdefaults{'catauth'} = 'std';
2134: $domdefaults{'catunauth'} = 'std';
2135: if ($domconfig{'coursecategories'}{'auth'}) {
2136: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2137: }
2138: if ($domconfig{'coursecategories'}{'unauth'}) {
2139: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2140: }
2141: }
1.1172.2.23 raeburn 2142: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2143: return %domdefaults;
2144: }
2145:
1.344 www 2146: # --------------------------------------------------- Assign a key to a student
2147:
2148: sub assign_access_key {
1.364 www 2149: #
2150: # a valid key looks like uname:udom#comments
2151: # comments are being appended
2152: #
1.498 www 2153: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2154: $kdom=
1.620 albertel 2155: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2156: $knum=
1.620 albertel 2157: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2158: $cdom=
1.620 albertel 2159: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2160: $cnum=
1.620 albertel 2161: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2162: $udom=$env{'user.name'} unless (defined($udom));
2163: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2164: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2165: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2166: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2167: # assigned to this person
2168: # - this should not happen,
1.345 www 2169: # unless something went wrong
2170: # the first time around
2171: # ready to assign
1.364 www 2172: $logentry=$1.'; '.$logentry;
1.496 www 2173: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2174: $kdom,$knum) eq 'ok') {
1.345 www 2175: # key now belongs to user
1.346 www 2176: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2177: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2178: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2179: return 'ok';
2180: } else {
2181: return
2182: 'error: Count not permanently assign key, will need to be re-entered later.';
2183: }
2184: } else {
2185: return 'error: Could not assign key, try again later.';
2186: }
1.364 www 2187: } elsif (!$existing{$ckey}) {
1.345 www 2188: # the key does not exist
2189: return 'error: The key does not exist';
2190: } else {
2191: # the key is somebody else's
2192: return 'error: The key is already in use';
2193: }
1.344 www 2194: }
2195:
1.364 www 2196: # ------------------------------------------ put an additional comment on a key
2197:
2198: sub comment_access_key {
2199: #
2200: # a valid key looks like uname:udom#comments
2201: # comments are being appended
2202: #
2203: my ($ckey,$cdom,$cnum,$logentry)=@_;
2204: $cdom=
1.620 albertel 2205: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2206: $cnum=
1.620 albertel 2207: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2208: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2209: if ($existing{$ckey}) {
2210: $existing{$ckey}.='; '.$logentry;
2211: # ready to assign
1.367 www 2212: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2213: $cdom,$cnum) eq 'ok') {
2214: return 'ok';
2215: } else {
2216: return 'error: Count not store comment.';
2217: }
2218: } else {
2219: # the key does not exist
2220: return 'error: The key does not exist';
2221: }
2222: }
2223:
1.344 www 2224: # ------------------------------------------------------ Generate a set of keys
2225:
2226: sub generate_access_keys {
1.364 www 2227: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2228: $cdom=
1.620 albertel 2229: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2230: $cnum=
1.620 albertel 2231: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2232: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2233: unless (($cdom) && ($cnum)) { return 0; }
2234: if ($number>10000) { return 0; }
2235: sleep(2); # make sure don't get same seed twice
2236: srand(time()^($$+($$<<15))); # from "Programming Perl"
2237: my $total=0;
2238: for (my $i=1;$i<=$number;$i++) {
2239: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2240: sprintf("%lx",int(100000*rand)).'-'.
2241: sprintf("%lx",int(100000*rand));
2242: $newkey=~s/1/g/g; # folks mix up 1 and l
2243: $newkey=~s/0/h/g; # and also 0 and O
2244: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2245: if ($existing{$newkey}) {
2246: $i--;
2247: } else {
1.364 www 2248: if (&put('accesskeys',
2249: { $newkey => '# generated '.localtime().
1.620 albertel 2250: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2251: '; '.$logentry },
2252: $cdom,$cnum) eq 'ok') {
1.344 www 2253: $total++;
2254: }
2255: }
2256: }
1.620 albertel 2257: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2258: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2259: return $total;
2260: }
2261:
2262: # ------------------------------------------------------- Validate an accesskey
2263:
2264: sub validate_access_key {
2265: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2266: $cdom=
1.620 albertel 2267: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2268: $cnum=
1.620 albertel 2269: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2270: $udom=$env{'user.domain'} unless (defined($udom));
2271: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2272: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2273: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2274: }
2275:
2276: # ------------------------------------- Find the section of student in a course
1.652 albertel 2277: sub devalidate_getsection_cache {
2278: my ($udom,$unam,$courseid)=@_;
2279: my $hashid="$udom:$unam:$courseid";
2280: &devalidate_cache_new('getsection',$hashid);
2281: }
1.298 matthew 2282:
1.815 albertel 2283: sub courseid_to_courseurl {
2284: my ($courseid) = @_;
2285: #already url style courseid
2286: return $courseid if ($courseid =~ m{^/});
2287:
2288: if (exists($env{'course.'.$courseid.'.num'})) {
2289: my $cnum = $env{'course.'.$courseid.'.num'};
2290: my $cdom = $env{'course.'.$courseid.'.domain'};
2291: return "/$cdom/$cnum";
2292: }
2293:
2294: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2295: if (exists($courseinfo{'num'})) {
2296: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2297: }
2298:
2299: return undef;
2300: }
2301:
1.298 matthew 2302: sub getsection {
2303: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2304: my $cachetime=1800;
1.551 albertel 2305:
2306: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2307: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2308: if (defined($cached)) { return $result; }
2309:
1.298 matthew 2310: my %Pending;
2311: my %Expired;
2312: #
2313: # Each role can either have not started yet (pending), be active,
2314: # or have expired.
2315: #
2316: # If there is an active role, we are done.
2317: #
2318: # If there is more than one role which has not started yet,
2319: # choose the one which will start sooner
2320: # If there is one role which has not started yet, return it.
2321: #
2322: # If there is more than one expired role, choose the one which ended last.
2323: # If there is a role which has expired, return it.
2324: #
1.815 albertel 2325: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2326: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2327: foreach my $key (keys(%roleshash)) {
1.479 albertel 2328: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2329: my $section=$1;
2330: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2331: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2332: my $now=time;
1.548 albertel 2333: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2334: $Expired{$end}=$section;
2335: next;
2336: }
1.548 albertel 2337: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2338: $Pending{$start}=$section;
2339: next;
2340: }
1.599 albertel 2341: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2342: }
2343: #
2344: # Presumedly there will be few matching roles from the above
2345: # loop and the sorting time will be negligible.
2346: if (scalar(keys(%Pending))) {
2347: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2348: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2349: }
2350: if (scalar(keys(%Expired))) {
2351: my @sorted = sort {$a <=> $b} keys(%Expired);
2352: my $time = pop(@sorted);
1.599 albertel 2353: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2354: }
1.599 albertel 2355: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2356: }
1.70 www 2357:
1.599 albertel 2358: sub save_cache {
2359: &purge_remembered();
1.722 albertel 2360: #&Apache::loncommon::validate_page();
1.620 albertel 2361: undef(%env);
1.780 albertel 2362: undef($env_loaded);
1.599 albertel 2363: }
1.452 albertel 2364:
1.599 albertel 2365: my $to_remember=-1;
2366: my %remembered;
2367: my %accessed;
2368: my $kicks=0;
2369: my $hits=0;
1.849 albertel 2370: sub make_key {
2371: my ($name,$id) = @_;
1.872 albertel 2372: if (length($id) > 65
2373: && length(&escape($id)) > 200) {
2374: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2375: }
1.849 albertel 2376: return &escape($name.':'.$id);
2377: }
2378:
1.599 albertel 2379: sub devalidate_cache_new {
2380: my ($name,$id,$debug) = @_;
2381: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2382: $id=&make_key($name,$id);
1.599 albertel 2383: $memcache->delete($id);
2384: delete($remembered{$id});
2385: delete($accessed{$id});
2386: }
2387:
2388: sub is_cached_new {
2389: my ($name,$id,$debug) = @_;
1.849 albertel 2390: $id=&make_key($name,$id);
1.599 albertel 2391: if (exists($remembered{$id})) {
1.1133 foxr 2392: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2393: $accessed{$id}=[&gettimeofday()];
2394: $hits++;
2395: return ($remembered{$id},1);
2396: }
2397: my $value = $memcache->get($id);
2398: if (!(defined($value))) {
2399: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2400: return (undef,undef);
1.416 albertel 2401: }
1.599 albertel 2402: if ($value eq '__undef__') {
2403: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2404: $value=undef;
2405: }
2406: &make_room($id,$value,$debug);
2407: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2408: return ($value,1);
2409: }
2410:
2411: sub do_cache_new {
2412: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2413: $id=&make_key($name,$id);
1.599 albertel 2414: my $setvalue=$value;
2415: if (!defined($setvalue)) {
2416: $setvalue='__undef__';
2417: }
1.623 albertel 2418: if (!defined($time) ) {
2419: $time=600;
2420: }
1.599 albertel 2421: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2422: my $result = $memcache->set($id,$setvalue,$time);
2423: if (! $result) {
1.872 albertel 2424: &logthis("caching of id -> $id failed");
1.910 albertel 2425: $memcache->disconnect_all();
1.872 albertel 2426: }
1.600 albertel 2427: # need to make a copy of $value
1.919 albertel 2428: &make_room($id,$value,$debug);
1.599 albertel 2429: return $value;
2430: }
2431:
2432: sub make_room {
2433: my ($id,$value,$debug)=@_;
1.919 albertel 2434:
2435: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2436: : $value;
1.599 albertel 2437: if ($to_remember<0) { return; }
2438: $accessed{$id}=[&gettimeofday()];
2439: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2440: my $to_kick;
2441: my $max_time=0;
2442: foreach my $other (keys(%accessed)) {
2443: if (&tv_interval($accessed{$other}) > $max_time) {
2444: $to_kick=$other;
2445: $max_time=&tv_interval($accessed{$other});
2446: }
2447: }
2448: delete($remembered{$to_kick});
2449: delete($accessed{$to_kick});
2450: $kicks++;
2451: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2452: return;
2453: }
2454:
1.599 albertel 2455: sub purge_remembered {
1.604 albertel 2456: #&logthis("Tossing ".scalar(keys(%remembered)));
2457: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2458: undef(%remembered);
2459: undef(%accessed);
1.428 albertel 2460: }
1.70 www 2461: # ------------------------------------- Read an entry from a user's environment
2462:
2463: sub userenvironment {
2464: my ($udom,$unam,@what)=@_;
1.976 raeburn 2465: my $items;
2466: foreach my $item (@what) {
2467: $items.=&escape($item).'&';
2468: }
2469: $items=~s/\&$//;
1.70 www 2470: my %returnhash=();
1.1009 raeburn 2471: my $uhome = &homeserver($unam,$udom);
2472: unless ($uhome eq 'no_host') {
2473: my @answer=split(/\&/,
2474: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2475: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2476: return %returnhash;
2477: }
1.1009 raeburn 2478: my $i;
2479: for ($i=0;$i<=$#what;$i++) {
2480: $returnhash{$what[$i]}=&unescape($answer[$i]);
2481: }
1.70 www 2482: }
2483: return %returnhash;
1.1 albertel 2484: }
2485:
1.617 albertel 2486: # ---------------------------------------------------------- Get a studentphoto
2487: sub studentphoto {
2488: my ($udom,$unam,$ext) = @_;
2489: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2490: if (defined($env{'request.course.id'})) {
1.708 raeburn 2491: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2492: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2493: return(&retrievestudentphoto($udom,$unam,$ext));
2494: } else {
2495: my ($result,$perm_reqd)=
1.707 albertel 2496: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2497: if ($result eq 'ok') {
2498: if (!($perm_reqd eq 'yes')) {
2499: return(&retrievestudentphoto($udom,$unam,$ext));
2500: }
2501: }
2502: }
2503: }
2504: } else {
2505: my ($result,$perm_reqd) =
1.707 albertel 2506: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2507: if ($result eq 'ok') {
2508: if (!($perm_reqd eq 'yes')) {
2509: return(&retrievestudentphoto($udom,$unam,$ext));
2510: }
2511: }
2512: }
2513: return '/adm/lonKaputt/lonlogo_broken.gif';
2514: }
2515:
2516: sub retrievestudentphoto {
2517: my ($udom,$unam,$ext,$type) = @_;
2518: my $home=&Apache::lonnet::homeserver($unam,$udom);
2519: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2520: if ($ret eq 'ok') {
2521: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2522: if ($type eq 'thumbnail') {
2523: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2524: }
2525: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2526: return $tokenurl;
2527: } else {
2528: if ($type eq 'thumbnail') {
2529: return '/adm/lonKaputt/genericstudent_tn.gif';
2530: } else {
2531: return '/adm/lonKaputt/lonlogo_broken.gif';
2532: }
1.617 albertel 2533: }
2534: }
2535:
1.263 www 2536: # -------------------------------------------------------------------- New chat
2537:
2538: sub chatsend {
1.724 raeburn 2539: my ($newentry,$anon,$group)=@_;
1.620 albertel 2540: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2541: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2542: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2543: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2544: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2545: &escape($newentry)).':'.$group,$chome);
1.292 www 2546: }
2547:
2548: # ------------------------------------------ Find current version of a resource
2549:
2550: sub getversion {
2551: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2552: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2553: return ¤tversion(&filelocation('',$fname));
2554: }
2555:
2556: sub currentversion {
2557: my $fname=shift;
2558: my $author=$fname;
2559: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2560: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2561: my $home=&homeserver($uname,$udom);
1.292 www 2562: if ($home eq 'no_host') {
2563: return -1;
2564: }
1.1112 www 2565: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2566: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2567: return -1;
2568: }
1.1112 www 2569: return $answer;
1.263 www 2570: }
2571:
1.1111 www 2572: #
2573: # Return special version number of resource if set by override, empty otherwise
2574: #
2575: sub usedversion {
2576: my $fname=shift;
2577: unless ($fname) { $fname=$env{'request.uri'}; }
2578: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2579: if ($urlversion) { return $urlversion; }
2580: return '';
2581: }
2582:
1.1 albertel 2583: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2584:
1.1 albertel 2585: sub subscribe {
2586: my $fname=shift;
1.761 raeburn 2587: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2588: $fname=~s/[\n\r]//g;
1.1 albertel 2589: my $author=$fname;
2590: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2591: my ($udom,$uname)=split(/\//,$author);
2592: my $home=homeserver($uname,$udom);
1.335 albertel 2593: if ($home eq 'no_host') {
2594: return 'not_found';
1.1 albertel 2595: }
2596: my $answer=reply("sub:$fname",$home);
1.64 www 2597: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2598: $answer.=' by '.$home;
2599: }
1.1 albertel 2600: return $answer;
2601: }
2602:
1.8 www 2603: # -------------------------------------------------------------- Replicate file
2604:
2605: sub repcopy {
2606: my $filename=shift;
1.23 www 2607: $filename=~s/\/+/\//g;
1.1142 raeburn 2608: my $londocroot = $perlvar{'lonDocRoot'};
2609: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2610: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2611: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2612: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2613: return &repcopy_userfile($filename);
2614: }
1.532 albertel 2615: $filename=~s/[\n\r]//g;
1.8 www 2616: my $transname="$filename.in.transfer";
1.828 www 2617: # FIXME: this should flock
1.607 raeburn 2618: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2619: my $remoteurl=subscribe($filename);
1.64 www 2620: if ($remoteurl =~ /^con_lost by/) {
2621: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2622: return 'unavailable';
1.8 www 2623: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2624: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2625: return 'not_found';
1.64 www 2626: } elsif ($remoteurl =~ /^rejected by/) {
2627: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2628: return 'forbidden';
1.20 www 2629: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2630: return 'ok';
1.8 www 2631: } else {
1.290 www 2632: my $author=$filename;
2633: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2634: my ($udom,$uname)=split(/\//,$author);
2635: my $home=homeserver($uname,$udom);
2636: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2637: my @parts=split(/\//,$filename);
2638: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2639: if ($path ne "$londocroot/res") {
1.8 www 2640: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2641: return 'bad_request';
1.8 www 2642: }
2643: my $count;
2644: for ($count=5;$count<$#parts;$count++) {
2645: $path.="/$parts[$count]";
2646: if ((-e $path)!=1) {
2647: mkdir($path,0777);
2648: }
2649: }
2650: my $ua=new LWP::UserAgent;
2651: my $request=new HTTP::Request('GET',"$remoteurl");
2652: my $response=$ua->request($request,$transname);
2653: if ($response->is_error()) {
2654: unlink($transname);
2655: my $message=$response->status_line;
1.672 albertel 2656: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2657: ." LWP get: $message: $filename</font>");
1.607 raeburn 2658: return 'unavailable';
1.8 www 2659: } else {
1.16 www 2660: if ($remoteurl!~/\.meta$/) {
2661: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2662: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2663: if ($mresponse->is_error()) {
2664: unlink($filename.'.meta');
2665: &logthis(
1.672 albertel 2666: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2667: }
2668: }
1.8 www 2669: rename($transname,$filename);
1.607 raeburn 2670: return 'ok';
1.8 www 2671: }
1.290 www 2672: }
1.8 www 2673: }
1.330 www 2674: }
2675:
2676: # ------------------------------------------------ Get server side include body
2677: sub ssi_body {
1.381 albertel 2678: my ($filelink,%form)=@_;
1.606 matthew 2679: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2680: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2681: }
1.953 www 2682: my $output='';
2683: my $response;
1.980 raeburn 2684: if ($filelink=~/^https?\:/) {
1.954 raeburn 2685: ($output,$response)=&externalssi($filelink);
1.953 www 2686: } else {
1.1004 droeschl 2687: $filelink .= $filelink=~/\?/ ? '&' : '?';
2688: $filelink .= 'inhibitmenu=yes';
1.953 www 2689: ($output,$response)=&ssi($filelink,%form);
2690: }
1.778 albertel 2691: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2692: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2693: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2694: if (wantarray) {
2695: return ($output, $response);
2696: } else {
2697: return $output;
2698: }
1.8 www 2699: }
2700:
1.15 www 2701: # --------------------------------------------------------- Server Side Include
2702:
1.782 albertel 2703: sub absolute_url {
2704: my ($host_name) = @_;
2705: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2706: if ($host_name eq '') {
2707: $host_name = $ENV{'SERVER_NAME'};
2708: }
2709: return $protocol.$host_name;
2710: }
2711:
1.942 foxr 2712: #
2713: # Server side include.
2714: # Parameters:
2715: # fn Possibly encrypted resource name/id.
2716: # form Hash that describes how the rendering should be done
2717: # and other things.
1.944 foxr 2718: # Returns:
1.950 raeburn 2719: # Scalar context: The content of the response.
2720: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2721: #
1.15 www 2722: sub ssi {
2723:
1.944 foxr 2724: my ($fn,%form)=@_;
1.15 www 2725: my $ua=new LWP::UserAgent;
1.23 www 2726: my $request;
1.711 albertel 2727:
2728: $form{'no_update_last_known'}=1;
1.895 albertel 2729: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2730: if (%form) {
1.782 albertel 2731: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2732: $request->content(join('&',map {
2733: my $name = escape($_);
2734: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2735: ? join("&$name=", map {escape($_) } @{$form{$_}})
2736: : &escape($form{$_}) );
2737: } keys(%form)));
1.23 www 2738: } else {
1.782 albertel 2739: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2740: }
2741:
1.15 www 2742: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2743: my $response= $ua->request($request);
1.944 foxr 2744: if (wantarray) {
1.1172.2.3 raeburn 2745: return ($response->content, $response);
1.944 foxr 2746: } else {
1.1172.2.3 raeburn 2747: return $response->content;
1.942 foxr 2748: }
1.324 www 2749: }
2750:
2751: sub externalssi {
2752: my ($url)=@_;
2753: my $ua=new LWP::UserAgent;
2754: my $request=new HTTP::Request('GET',$url);
2755: my $response=$ua->request($request);
1.954 raeburn 2756: if (wantarray) {
2757: return ($response->content, $response);
2758: } else {
2759: return $response->content;
2760: }
1.15 www 2761: }
1.254 www 2762:
1.492 albertel 2763: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2764:
2765: sub allowuploaded {
2766: my ($srcurl,$url)=@_;
2767: $url=&clutter(&declutter($url));
2768: my $dir=$url;
2769: $dir=~s/\/[^\/]+$//;
2770: my %httpref=();
2771: my $httpurl=&hreflocation('',$url);
2772: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2773: &Apache::lonnet::appenv(\%httpref);
1.254 www 2774: }
1.477 raeburn 2775:
1.1172.2.13 raeburn 2776: #
2777: # Determine if the current user should be able to edit a particular resource,
2778: # when viewing in course context.
2779: # (a) When viewing resource used to determine if "Edit" item is included in
2780: # Functions.
2781: # (b) When displaying folder contents in course editor, used to determine if
2782: # "Edit" link will be displayed alongside resource.
2783: #
2784: # input: six args -- filename (decluttered), course number, course domain,
2785: # url, symb (if registered) and group (if this is a group
2786: # item -- e.g., bulletin board, group page etc.).
2787: # output: array of five scalars --
2788: # $cfile -- url for file editing if editable on current server
2789: # $home -- homeserver of resource (i.e., for author if published,
2790: # or course if uploaded.).
2791: # $switchserver -- 1 if server switch will be needed.
2792: # $forceedit -- 1 if icon/link should be to go to edit mode
2793: # $forceview -- 1 if icon/link should be to go to view mode
2794: #
2795:
2796: sub can_edit_resource {
2797: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2798: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2799: #
2800: # For aboutme pages user can only edit his/her own.
2801: #
2802: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2803: my ($sdom,$sname) = ($1,$2);
2804: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2805: $home = $env{'user.home'};
2806: $cfile = $resurl;
2807: if ($env{'form.forceedit'}) {
2808: $forceview = 1;
2809: } else {
2810: $forceedit = 1;
2811: }
2812: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2813: } else {
2814: return;
2815: }
2816: }
2817:
2818: if ($env{'request.course.id'}) {
2819: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2820: if ($group ne '') {
2821: # if this is a group homepage or group bulletin board, check group privs
2822: my $allowed = 0;
2823: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2824: if ((&allowed('mdg',$env{'request.course.id'}.
2825: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2826: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2827: $allowed = 1;
2828: }
2829: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2830: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2831: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2832: $allowed = 1;
2833: }
2834: }
2835: if ($allowed) {
2836: $home=&homeserver($cnum,$cdom);
2837: if ($env{'form.forceedit'}) {
2838: $forceview = 1;
2839: } else {
2840: $forceedit = 1;
2841: }
2842: $cfile = $resurl;
2843: } else {
2844: return;
2845: }
2846: } else {
1.1172.2.15 raeburn 2847: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2848: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2849: return;
2850: }
2851: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2852: #
2853: # No edit allowed where CC has switched to student role.
2854: #
2855: return;
2856: }
2857: }
2858: }
2859:
2860: if ($file ne '') {
2861: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2862: if (&is_course_upload($file,$cnum,$cdom)) {
2863: $uploaded = 1;
2864: $incourse = 1;
2865: if ($file =~/\.(htm|html|css|js|txt)$/) {
2866: $cfile = &hreflocation('',$file);
2867: if ($env{'form.forceedit'}) {
2868: $forceview = 1;
2869: } else {
2870: $forceedit = 1;
2871: }
2872: }
2873: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2874: $incourse = 1;
2875: if ($env{'form.forceedit'}) {
2876: $forceview = 1;
2877: } else {
2878: $forceedit = 1;
2879: }
2880: $cfile = $resurl;
2881: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2882: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2883: $incourse = 1;
2884: if ($env{'form.forceedit'}) {
2885: $forceview = 1;
2886: } else {
2887: $forceedit = 1;
2888: }
2889: $cfile = $resurl;
2890: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2891: $incourse = 1;
2892: $cfile = $resurl.'/smpedit';
2893: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2894: $incourse = 1;
2895: if ($env{'form.forceedit'}) {
2896: $forceview = 1;
2897: } else {
2898: $forceedit = 1;
2899: }
2900: $cfile = $resurl;
1.1172.2.15 raeburn 2901: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2902: $incourse = 1;
2903: if ($env{'form.forceedit'}) {
2904: $forceview = 1;
2905: } else {
2906: $forceedit = 1;
2907: }
2908: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2909: }
2910: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2911: my $template = '/res/lib/templates/simpleproblem.problem';
2912: if (&is_on_map($template)) {
2913: $incourse = 1;
2914: $forceview = 1;
2915: $cfile = $template;
2916: }
2917: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2918: $incourse = 1;
2919: if ($env{'form.forceedit'}) {
2920: $forceview = 1;
2921: } else {
2922: $forceedit = 1;
2923: }
2924: $cfile = $resurl;
2925: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2926: $incourse = 1;
2927: $forceview = 1;
2928: if ($symb) {
2929: my ($map,$id,$res)=&decode_symb($symb);
2930: $env{'request.symb'} = $symb;
2931: $cfile = &clutter($res);
2932: } else {
2933: $cfile = $env{'form.suppurl'};
2934: $cfile =~ s{^http://}{};
2935: $cfile = '/adm/wrapper/ext/'.$cfile;
2936: }
1.1172.2.31 raeburn 2937: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2938: if ($env{'form.forceedit'}) {
2939: $forceview = 1;
2940: } else {
2941: $forceedit = 1;
2942: }
2943: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2944: }
2945: }
2946: if ($uploaded || $incourse) {
2947: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2948: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2949: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2950: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2951: # Check that the user has permission to edit this resource
2952: my $setpriv = 1;
2953: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2954: if (defined($cfudom)) {
2955: $home=&homeserver($cfuname,$cfudom);
2956: $cfile=$file;
2957: }
2958: }
2959: if (($cfile ne '') && (!$incourse || $uploaded) &&
2960: (($home ne '') && ($home ne 'no_host'))) {
2961: my @ids=¤t_machine_ids();
2962: unless (grep(/^\Q$home\E$/,@ids)) {
2963: $switchserver=1;
2964: }
2965: }
2966: }
2967: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2968: }
2969:
2970: sub is_course_upload {
2971: my ($file,$cnum,$cdom) = @_;
2972: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2973: $uploadpath =~ s{^\/}{};
2974: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2975: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2976: return 1;
2977: }
2978: return;
2979: }
2980:
2981: sub in_course {
2982: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2983: if ($hideprivileged) {
2984: my $skipuser;
1.1172.2.23 raeburn 2985: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2986: my @possdoms = ($cdom);
2987: if ($coursehash{'checkforpriv'}) {
2988: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2989: }
2990: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2991: $skipuser = 1;
2992: if ($coursehash{'nothideprivileged'}) {
2993: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2994: my $user;
2995: if ($item =~ /:/) {
2996: $user = $item;
2997: } else {
2998: $user = join(':',split(/[\@]/,$item));
2999: }
3000: if ($user eq $uname.':'.$udom) {
3001: undef($skipuser);
3002: last;
3003: }
3004: }
3005: }
3006: if ($skipuser) {
3007: return 0;
3008: }
3009: }
3010: }
3011: $type ||= 'any';
3012: if (!defined($cdom) || !defined($cnum)) {
3013: my $cid = $env{'request.course.id'};
3014: $cdom = $env{'course.'.$cid.'.domain'};
3015: $cnum = $env{'course.'.$cid.'.num'};
3016: }
3017: my $typesref;
3018: if (($type eq 'any') || ($type eq 'all')) {
3019: $typesref = ['active','previous','future'];
3020: } elsif ($type eq 'previous' || $type eq 'future') {
3021: $typesref = [$type];
3022: }
3023: my %roles = &get_my_roles($uname,$udom,'userroles',
3024: $typesref,undef,[$cdom]);
3025: my ($tmp) = keys(%roles);
3026: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3027: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3028: if (@course_roles > 0) {
3029: return 1;
3030: }
3031: return 0;
3032: }
3033:
1.478 albertel 3034: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3035: # input: action, courseID, current domain, intended
1.637 raeburn 3036: # path to file, source of file, instruction to parse file for objects,
3037: # ref to hash for embedded objects,
3038: # ref to hash for codebase of java objects.
1.1095 raeburn 3039: # reference to scalar to accommodate mime type determined
3040: # from File::MMagic if $parser = parse.
1.637 raeburn 3041: #
1.485 raeburn 3042: # output: url to file (if action was uploaddoc),
3043: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3044: #
1.478 albertel 3045: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3046: # course.
1.477 raeburn 3047: #
1.478 albertel 3048: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3049: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3050: # course's home server.
1.477 raeburn 3051: #
1.478 albertel 3052: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3053: # be copied from $source (current location) to
3054: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3055: # and will then be copied to
3056: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3057: # course's home server.
1.485 raeburn 3058: #
1.481 raeburn 3059: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3060: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3061: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3062: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3063: # in course's home server.
1.637 raeburn 3064: #
1.477 raeburn 3065:
3066: sub process_coursefile {
1.1095 raeburn 3067: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3068: $mimetype)=@_;
1.477 raeburn 3069: my $fetchresult;
1.638 albertel 3070: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3071: if ($action eq 'propagate') {
1.638 albertel 3072: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3073: $home);
1.481 raeburn 3074: } else {
1.477 raeburn 3075: my $fpath = '';
3076: my $fname = $file;
1.478 albertel 3077: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3078: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3079: my $filepath = &build_filepath($fpath);
1.481 raeburn 3080: if ($action eq 'copy') {
3081: if ($source eq '') {
3082: $fetchresult = 'no source file';
3083: return $fetchresult;
3084: } else {
3085: my $destination = $filepath.'/'.$fname;
3086: rename($source,$destination);
3087: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3088: $home);
1.481 raeburn 3089: }
3090: } elsif ($action eq 'uploaddoc') {
3091: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3092: print $fh $env{'form.'.$source};
1.481 raeburn 3093: close($fh);
1.637 raeburn 3094: if ($parser eq 'parse') {
1.1024 raeburn 3095: my $mm = new File::MMagic;
1.1095 raeburn 3096: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3097: if ($type eq 'text/html') {
1.1024 raeburn 3098: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3099: unless ($parse_result eq 'ok') {
3100: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3101: }
1.637 raeburn 3102: }
1.1095 raeburn 3103: if (ref($mimetype)) {
3104: $$mimetype = $type;
3105: }
1.637 raeburn 3106: }
1.477 raeburn 3107: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3108: $home);
1.481 raeburn 3109: if ($fetchresult eq 'ok') {
3110: return '/uploaded/'.$fpath.'/'.$fname;
3111: } else {
3112: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3113: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3114: return '/adm/notfound.html';
3115: }
1.477 raeburn 3116: }
3117: }
1.485 raeburn 3118: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3119: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3120: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3121: }
3122: return $fetchresult;
3123: }
3124:
1.637 raeburn 3125: sub build_filepath {
3126: my ($fpath) = @_;
3127: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3128: unless ($fpath eq '') {
3129: my @parts=split('/',$fpath);
3130: foreach my $part (@parts) {
3131: $filepath.= '/'.$part;
3132: if ((-e $filepath)!=1) {
3133: mkdir($filepath,0777);
3134: }
3135: }
3136: }
3137: return $filepath;
3138: }
3139:
3140: sub store_edited_file {
1.638 albertel 3141: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3142: my $file = $primary_url;
3143: $file =~ s#^/uploaded/$docudom/$docuname/##;
3144: my $fpath = '';
3145: my $fname = $file;
3146: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3147: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3148: my $filepath = &build_filepath($fpath);
3149: open(my $fh,'>'.$filepath.'/'.$fname);
3150: print $fh $content;
3151: close($fh);
1.638 albertel 3152: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3153: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3154: $home);
1.637 raeburn 3155: if ($$fetchresult eq 'ok') {
3156: return '/uploaded/'.$fpath.'/'.$fname;
3157: } else {
1.638 albertel 3158: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3159: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3160: return '/adm/notfound.html';
3161: }
3162: }
3163:
1.531 albertel 3164: sub clean_filename {
1.831 albertel 3165: my ($fname,$args)=@_;
1.315 www 3166: # Replace Windows backslashes by forward slashes
1.257 www 3167: $fname=~s/\\/\//g;
1.831 albertel 3168: if (!$args->{'keep_path'}) {
3169: # Get rid of everything but the actual filename
3170: $fname=~s/^.*\/([^\/]+)$/$1/;
3171: }
1.315 www 3172: # Replace spaces by underscores
3173: $fname=~s/\s+/\_/g;
3174: # Replace all other weird characters by nothing
1.831 albertel 3175: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3176: # Replace all .\d. sequences with _\d. so they no longer look like version
3177: # numbers
3178: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3179: return $fname;
3180: }
1.1051 raeburn 3181: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3182: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3183: # image with the same aspect ratio as the original, but with dimensions which do
3184: # not exceed $resizewidth and $resizeheight.
3185:
1.984 neumanie 3186: sub resizeImage {
1.1051 raeburn 3187: my ($img_path,$resizewidth,$resizeheight) = @_;
3188: my $ima = Image::Magick->new;
3189: my $resized;
3190: if (-e $img_path) {
3191: $ima->Read($img_path);
3192: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3193: my $width = $ima->Get('width');
3194: my $height = $ima->Get('height');
3195: if ($width > $resizewidth) {
3196: my $factor = $width/$resizewidth;
3197: my $newheight = $height/$factor;
3198: $ima->Scale(width=>$resizewidth,height=>$newheight);
3199: $resized = 1;
3200: }
3201: }
3202: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3203: my $width = $ima->Get('width');
3204: my $height = $ima->Get('height');
3205: if ($height > $resizeheight) {
3206: my $factor = $height/$resizeheight;
3207: my $newwidth = $width/$factor;
3208: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3209: $resized = 1;
3210: }
3211: }
3212: if ($resized) {
3213: $ima->Write($img_path);
3214: }
3215: }
3216: return;
1.977 amueller 3217: }
3218:
1.608 albertel 3219: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3220: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3221: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3222: # $context - possible values: coursedoc, existingfile, overwrite,
3223: # canceloverwrite, or ''.
3224: # if 'coursedoc': upload to the current course
3225: # if 'existingfile': write file to tmp/overwrites directory
3226: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3227: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3228: # $subdir - directory in userfile to store the file into
1.858 raeburn 3229: # $parser - instruction to parse file for objects ($parser = parse)
3230: # $allfiles - reference to hash for embedded objects
3231: # $codebase - reference to hash for codebase of java objects
3232: # $desuname - username for permanent storage of uploaded file
3233: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3234: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3235: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3236: # $resizewidth - width (pixels) to which to resize uploaded image
3237: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3238: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3239: # from File::MMagic.
1.858 raeburn 3240: #
1.686 albertel 3241: # output: url of file in userspace, or error: <message>
3242: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3243:
1.531 albertel 3244: sub userfileupload {
1.1090 raeburn 3245: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3246: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3247: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3248: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3249: $fname=&clean_filename($fname);
1.1090 raeburn 3250: # See if there is anything left
1.257 www 3251: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3252: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3253: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3254: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3255: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3256: my $now = time;
1.1090 raeburn 3257: my $filepath;
1.1095 raeburn 3258: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3259: $filepath = 'tmp/helprequests/'.$now;
3260: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3261: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3262: '_'.$env{'user.domain'}.'/pending';
3263: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3264: my ($docuname,$docudom);
3265: if ($destudom) {
3266: $docudom = $destudom;
3267: } else {
3268: $docudom = $env{'user.domain'};
3269: }
3270: if ($destuname) {
3271: $docuname = $destuname;
3272: } else {
3273: $docuname = $env{'user.name'};
3274: }
3275: if (exists($env{'form.group'})) {
3276: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3277: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3278: }
3279: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3280: if ($context eq 'canceloverwrite') {
3281: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3282: if (-e $tempfile) {
3283: my @info = stat($tempfile);
3284: if ($info[9] eq $env{'form.timestamp'}) {
3285: unlink($tempfile);
3286: }
3287: }
3288: return;
1.523 raeburn 3289: }
3290: }
1.1090 raeburn 3291: # Create the directory if not present
1.741 raeburn 3292: my @parts=split(/\//,$filepath);
3293: my $fullpath = $perlvar{'lonDaemons'};
3294: for (my $i=0;$i<@parts;$i++) {
3295: $fullpath .= '/'.$parts[$i];
3296: if ((-e $fullpath)!=1) {
3297: mkdir($fullpath,0777);
3298: }
3299: }
3300: open(my $fh,'>'.$fullpath.'/'.$fname);
3301: print $fh $env{'form.'.$formname};
3302: close($fh);
1.1090 raeburn 3303: if ($context eq 'existingfile') {
3304: my @info = stat($fullpath.'/'.$fname);
3305: return ($fullpath.'/'.$fname,$info[9]);
3306: } else {
3307: return $fullpath.'/'.$fname;
3308: }
1.523 raeburn 3309: }
1.995 raeburn 3310: if ($subdir eq 'scantron') {
3311: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3312: } else {
1.995 raeburn 3313: $fname="$subdir/$fname";
3314: }
1.1090 raeburn 3315: if ($context eq 'coursedoc') {
1.638 albertel 3316: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3317: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3318: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3319: return &finishuserfileupload($docuname,$docudom,
3320: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3321: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3322: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3323: } else {
1.1172.2.21 raeburn 3324: if ($env{'form.folder'}) {
3325: $fname=$env{'form.folder'}.'/'.$fname;
3326: }
1.638 albertel 3327: return &process_coursefile('uploaddoc',$docuname,$docudom,
3328: $fname,$formname,$parser,
1.1095 raeburn 3329: $allfiles,$codebase,$mimetype);
1.481 raeburn 3330: }
1.719 banghart 3331: } elsif (defined($destuname)) {
3332: my $docuname=$destuname;
3333: my $docudom=$destudom;
1.860 raeburn 3334: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3335: $parser,$allfiles,$codebase,
1.1051 raeburn 3336: $thumbwidth,$thumbheight,
1.1095 raeburn 3337: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3338: } else {
1.638 albertel 3339: my $docuname=$env{'user.name'};
3340: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3341: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3342: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3343: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3344: }
1.860 raeburn 3345: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3346: $parser,$allfiles,$codebase,
1.1051 raeburn 3347: $thumbwidth,$thumbheight,
1.1095 raeburn 3348: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3349: }
1.271 www 3350: }
3351:
3352: sub finishuserfileupload {
1.860 raeburn 3353: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3354: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3355: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3356: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3357:
1.860 raeburn 3358: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3359: $file=$fname;
3360: if ($fname=~m|/|) {
3361: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3362: $path.=$fnamepath.'/';
3363: }
1.259 www 3364: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3365: my $count;
3366: for ($count=4;$count<=$#parts;$count++) {
3367: $filepath.="/$parts[$count]";
3368: if ((-e $filepath)!=1) {
3369: mkdir($filepath,0777);
3370: }
3371: }
1.984 neumanie 3372:
1.258 www 3373: # Save the file
3374: {
1.701 albertel 3375: if (!open(FH,'>'.$filepath.'/'.$file)) {
3376: &logthis('Failed to create '.$filepath.'/'.$file);
3377: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3378: return '/adm/notfound.html';
3379: }
1.1090 raeburn 3380: if ($context eq 'overwrite') {
1.1117 foxr 3381: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3382: my $target = $filepath.'/'.$file;
3383: if (-e $source) {
3384: my @info = stat($source);
3385: if ($info[9] eq $env{'form.timestamp'}) {
3386: unless (&File::Copy::move($source,$target)) {
3387: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3388: return "Moving from $source failed";
3389: }
3390: } else {
3391: return "Temporary file: $source had unexpected date/time for last modification";
3392: }
3393: } else {
3394: return "Temporary file: $source missing";
3395: }
3396: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3397: &logthis('Failed to write to '.$filepath.'/'.$file);
3398: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3399: return '/adm/notfound.html';
3400: }
1.570 albertel 3401: close(FH);
1.1051 raeburn 3402: if ($resizewidth && $resizeheight) {
3403: my $mm = new File::MMagic;
3404: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3405: if ($mime_type =~ m{^image/}) {
3406: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3407: }
1.977 amueller 3408: }
1.258 www 3409: }
1.1152 raeburn 3410: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3411: if (ref($mimetype)) {
3412: if ($$mimetype eq '') {
3413: my $mm = new File::MMagic;
3414: my $type = $mm->checktype_filename($filepath.'/'.$file);
3415: $$mimetype = $type;
3416: }
3417: }
3418: }
1.637 raeburn 3419: if ($parser eq 'parse') {
1.1152 raeburn 3420: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3421: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3422: $allfiles,$codebase);
3423: unless ($parse_result eq 'ok') {
3424: &logthis('Failed to parse '.$filepath.$file.
3425: ' for embedded media: '.$parse_result);
3426: }
1.637 raeburn 3427: }
3428: }
1.860 raeburn 3429: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3430: my $input = $filepath.'/'.$file;
3431: my $output = $filepath.'/'.'tn-'.$file;
3432: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3433: system("convert -sample $thumbsize $input $output");
3434: if (-e $filepath.'/'.'tn-'.$file) {
3435: $fetchthumb = 1;
3436: }
3437: }
1.858 raeburn 3438:
1.259 www 3439: # Notify homeserver to grep it
3440: #
1.984 neumanie 3441: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3442: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3443: if ($fetchresult eq 'ok') {
1.860 raeburn 3444: if ($fetchthumb) {
3445: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3446: if ($thumbresult ne 'ok') {
3447: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3448: $docuhome.': '.$thumbresult);
3449: }
3450: }
1.259 www 3451: #
1.258 www 3452: # Return the URL to it
1.494 albertel 3453: return '/uploaded/'.$path.$file;
1.263 www 3454: } else {
1.494 albertel 3455: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3456: ': '.$fetchresult);
1.263 www 3457: return '/adm/notfound.html';
1.858 raeburn 3458: }
1.493 albertel 3459: }
3460:
1.637 raeburn 3461: sub extract_embedded_items {
1.961 raeburn 3462: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3463: my @state = ();
1.1164 raeburn 3464: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3465: my %javafiles = (
3466: codebase => '',
3467: code => '',
3468: archive => ''
3469: );
3470: my %mediafiles = (
3471: src => '',
3472: movie => '',
3473: );
1.648 raeburn 3474: my $p;
3475: if ($content) {
3476: $p = HTML::LCParser->new($content);
3477: } else {
1.961 raeburn 3478: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3479: }
1.641 albertel 3480: while (my $t=$p->get_token()) {
1.640 albertel 3481: if ($t->[0] eq 'S') {
3482: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3483: push(@state, $tagname);
1.648 raeburn 3484: if (lc($tagname) eq 'allow') {
3485: &add_filetype($allfiles,$attr->{'src'},'src');
3486: }
1.640 albertel 3487: if (lc($tagname) eq 'img') {
3488: &add_filetype($allfiles,$attr->{'src'},'src');
3489: }
1.886 albertel 3490: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3491: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3492: &add_filetype($allfiles,$attr->{'href'},'href');
3493: }
1.886 albertel 3494: }
1.645 raeburn 3495: if (lc($tagname) eq 'script') {
1.1164 raeburn 3496: my $src;
1.645 raeburn 3497: if ($attr->{'archive'} =~ /\.jar$/i) {
3498: &add_filetype($allfiles,$attr->{'archive'},'archive');
3499: } else {
1.1164 raeburn 3500: if ($attr->{'src'} ne '') {
3501: $src = $attr->{'src'};
3502: &add_filetype($allfiles,$src,'src');
3503: }
3504: }
3505: my $text = $p->get_trimmed_text();
3506: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3507: my @swfargs = split(/,/,$1);
3508: foreach my $item (@swfargs) {
3509: $item =~ s/["']//g;
3510: $item =~ s/^\s+//;
3511: $item =~ s/\s+$//;
3512: }
3513: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3514: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3515: push(@{$related{$swfargs[0]}},$swfargs[2]);
3516: } else {
3517: $related{$swfargs[0]} = [$swfargs[2]];
3518: }
3519: }
1.645 raeburn 3520: }
3521: }
3522: if (lc($tagname) eq 'link') {
3523: if (lc($attr->{'rel'}) eq 'stylesheet') {
3524: &add_filetype($allfiles,$attr->{'href'},'href');
3525: }
3526: }
1.640 albertel 3527: if (lc($tagname) eq 'object' ||
3528: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3529: foreach my $item (keys(%javafiles)) {
3530: $javafiles{$item} = '';
3531: }
1.1164 raeburn 3532: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3533: $lastids{lc($tagname)} = $attr->{'id'};
3534: }
1.640 albertel 3535: }
3536: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3537: my $name = lc($attr->{'name'});
3538: foreach my $item (keys(%javafiles)) {
3539: if ($name eq $item) {
3540: $javafiles{$item} = $attr->{'value'};
3541: last;
3542: }
3543: }
1.1164 raeburn 3544: my $pathfrom;
1.640 albertel 3545: foreach my $item (keys(%mediafiles)) {
3546: if ($name eq $item) {
1.1164 raeburn 3547: $pathfrom = $attr->{'value'};
3548: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3549: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3550: last;
3551: }
3552: }
1.1164 raeburn 3553: if ($name eq 'flashvars') {
3554: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3555: }
3556: if ($pathfrom ne '') {
3557: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3558: $pathfrom);
3559: }
1.640 albertel 3560: }
3561: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3562: foreach my $item (keys(%javafiles)) {
3563: if ($attr->{$item}) {
3564: $javafiles{$item} = $attr->{$item};
3565: last;
3566: }
3567: }
3568: foreach my $item (keys(%mediafiles)) {
3569: if ($attr->{$item}) {
3570: &add_filetype($allfiles,$attr->{$item},$item);
3571: last;
3572: }
3573: }
1.1164 raeburn 3574: if (lc($tagname) eq 'embed') {
3575: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3576: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3577: $attr->{'src'});
3578: }
3579: }
1.640 albertel 3580: }
1.1172.2.35 raeburn 3581: if (lc($tagname) eq 'iframe') {
3582: my $src = $attr->{'src'} ;
3583: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3584: &add_filetype($allfiles,$src,'src');
3585: } elsif ($src =~ m{^/}) {
3586: if ($env{'request.course.id'}) {
3587: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3588: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3589: my $url = &hreflocation('',$fullpath);
3590: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3591: my $relpath = $1;
3592: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3593: &add_filetype($allfiles,$1,'src');
3594: }
3595: }
3596: }
3597: }
3598: }
1.1164 raeburn 3599: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3600: pop(@state);
1.1164 raeburn 3601: }
1.640 albertel 3602: } elsif ($t->[0] eq 'E') {
3603: my ($tagname) = ($t->[1]);
3604: if ($javafiles{'codebase'} ne '') {
3605: $javafiles{'codebase'} .= '/';
3606: }
3607: if (lc($tagname) eq 'applet' ||
3608: lc($tagname) eq 'object' ||
3609: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3610: ) {
3611: foreach my $item (keys(%javafiles)) {
3612: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3613: my $file=$javafiles{'codebase'}.$javafiles{$item};
3614: &add_filetype($allfiles,$file,$item);
3615: }
3616: }
3617: }
3618: pop @state;
3619: }
3620: }
1.1164 raeburn 3621: foreach my $id (sort(keys(%flashvars))) {
3622: if ($shockwave{$id} ne '') {
3623: my @pairs = split(/\&/,$flashvars{$id});
3624: foreach my $pair (@pairs) {
3625: my ($key,$value) = split(/\=/,$pair);
3626: if ($key eq 'thumb') {
3627: &add_filetype($allfiles,$value,$key);
3628: } elsif ($key eq 'content') {
3629: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3630: my ($ext) = ($value =~ /\.([^.]+)$/);
3631: if ($ext ne '') {
3632: &add_filetype($allfiles,$path.$value,$ext);
3633: }
3634: }
3635: }
3636: }
3637: }
1.637 raeburn 3638: return 'ok';
3639: }
3640:
1.639 albertel 3641: sub add_filetype {
3642: my ($allfiles,$file,$type)=@_;
3643: if (exists($allfiles->{$file})) {
3644: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3645: push(@{$allfiles->{$file}}, &escape($type));
3646: }
3647: } else {
3648: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3649: }
3650: }
3651:
1.1164 raeburn 3652: sub embedded_dependency {
3653: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3654: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3655: if (($identifier ne '') &&
3656: (ref($related->{$identifier}) eq 'ARRAY') &&
3657: ($pathfrom ne '')) {
3658: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3659: foreach my $dep (@{$related->{$identifier}}) {
3660: &add_filetype($allfiles,$path.$dep,'object');
3661: }
3662: }
3663: }
3664: return;
3665: }
3666:
1.493 albertel 3667: sub removeuploadedurl {
1.984 neumanie 3668: my ($url)=@_;
3669: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3670: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3671: }
3672:
3673: sub removeuserfile {
3674: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3675: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3676: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3677: if ($result eq 'ok') {
1.798 raeburn 3678: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3679: my $metafile = $fname.'.meta';
3680: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3681: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3682: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3683: my $sqlresult =
1.823 albertel 3684: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3685: 'portfolio_metadata',$group,
3686: 'delete');
1.798 raeburn 3687: }
3688: }
3689: return $result;
1.257 www 3690: }
1.15 www 3691:
1.530 albertel 3692: sub mkdiruserfile {
3693: my ($docuname,$docudom,$dir)=@_;
3694: my $home=&homeserver($docuname,$docudom);
3695: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3696: }
3697:
1.531 albertel 3698: sub renameuserfile {
3699: my ($docuname,$docudom,$old,$new)=@_;
3700: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3701: my $result = &reply("renameuserfile:$docudom:$docuname:".
3702: &escape("$old").':'.&escape("$new"),$home);
3703: if ($result eq 'ok') {
3704: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3705: my $oldmeta = $old.'.meta';
3706: my $newmeta = $new.'.meta';
3707: my $metaresult =
3708: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3709: my $url = "/uploaded/$docudom/$docuname/$old";
3710: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3711: my $sqlresult =
1.823 albertel 3712: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3713: 'portfolio_metadata',$group,
3714: 'delete');
1.798 raeburn 3715: }
3716: }
3717: return $result;
1.531 albertel 3718: }
3719:
1.14 www 3720: # ------------------------------------------------------------------------- Log
3721:
3722: sub log {
3723: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3724: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3725: }
3726:
3727: # ------------------------------------------------------------------ Course Log
1.352 www 3728: #
3729: # This routine flushes several buffers of non-mission-critical nature
3730: #
1.157 www 3731:
3732: sub flushcourselogs {
1.352 www 3733: &logthis('Flushing log buffers');
3734: #
3735: # course logs
3736: # This is a log of all transactions in a course, which can be used
3737: # for data mining purposes
3738: #
3739: # It also collects the courseid database, which lists last transaction
3740: # times and course titles for all courseids
3741: #
3742: my %courseidbuffer=();
1.921 raeburn 3743: foreach my $crsid (keys(%courselogs)) {
1.352 www 3744: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3745: &escape($courselogs{$crsid}),
3746: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3747: delete $courselogs{$crsid};
3748: } else {
3749: &logthis('Failed to flush log buffer for '.$crsid);
3750: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3751: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3752: " exceeded maximum size, deleting.</font>");
3753: delete $courselogs{$crsid};
3754: }
1.352 www 3755: }
1.920 raeburn 3756: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3757: 'description' => $coursedescrbuf{$crsid},
3758: 'inst_code' => $courseinstcodebuf{$crsid},
3759: 'type' => $coursetypebuf{$crsid},
3760: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3761: };
1.191 harris41 3762: }
1.352 www 3763: #
3764: # Write course id database (reverse lookup) to homeserver of courses
3765: # Is used in pickcourse
3766: #
1.840 albertel 3767: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3768: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3769: $courseidbuffer{$crs_home},
3770: $crs_home,'timeonly');
1.352 www 3771: }
3772: #
3773: # File accesses
3774: # Writes to the dynamic metadata of resources to get hit counts, etc.
3775: #
1.449 matthew 3776: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3777: if ($entry =~ /___count$/) {
3778: my ($dom,$name);
1.807 albertel 3779: ($dom,$name,undef)=
1.811 albertel 3780: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3781: if (! defined($dom) || $dom eq '' ||
3782: ! defined($name) || $name eq '') {
1.620 albertel 3783: my $cid = $env{'request.course.id'};
3784: $dom = $env{'request.'.$cid.'.domain'};
3785: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3786: }
1.450 matthew 3787: my $value = $accesshash{$entry};
3788: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3789: my %temphash=($url => $value);
1.449 matthew 3790: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3791: if ($result eq 'ok') {
3792: delete $accesshash{$entry};
3793: }
3794: } else {
1.811 albertel 3795: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3796: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3797: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3798: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3799: delete $accesshash{$entry};
3800: }
1.185 www 3801: }
1.191 harris41 3802: }
1.352 www 3803: #
3804: # Roles
3805: # Reverse lookup of user roles for course faculty/staff and co-authorship
3806: #
1.800 albertel 3807: foreach my $entry (keys(%userrolehash)) {
1.351 www 3808: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3809: split(/\:/,$entry);
3810: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3811: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3812: $rudom,$runame) eq 'ok') {
3813: delete $userrolehash{$entry};
3814: }
3815: }
1.662 raeburn 3816: #
3817: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3818: #
3819: my %domrolebuffer = ();
1.1000 raeburn 3820: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3821: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3822: if ($domrolebuffer{$rudom}) {
3823: $domrolebuffer{$rudom}.='&'.&escape($entry).
3824: '='.&escape($domainrolehash{$entry});
3825: } else {
3826: $domrolebuffer{$rudom}.=&escape($entry).
3827: '='.&escape($domainrolehash{$entry});
3828: }
3829: delete $domainrolehash{$entry};
3830: }
3831: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3832: my %servers = &get_servers($dom,'library');
3833: foreach my $tryserver (keys(%servers)) {
3834: unless (&reply('domroleput:'.$dom.':'.
3835: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3836: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3837: }
1.662 raeburn 3838: }
3839: }
1.186 www 3840: $dumpcount++;
1.157 www 3841: }
3842:
3843: sub courselog {
3844: my $what=shift;
1.158 www 3845: $what=time.':'.$what;
1.620 albertel 3846: unless ($env{'request.course.id'}) { return ''; }
3847: $coursedombuf{$env{'request.course.id'}}=
3848: $env{'course.'.$env{'request.course.id'}.'.domain'};
3849: $coursenumbuf{$env{'request.course.id'}}=
3850: $env{'course.'.$env{'request.course.id'}.'.num'};
3851: $coursehombuf{$env{'request.course.id'}}=
3852: $env{'course.'.$env{'request.course.id'}.'.home'};
3853: $coursedescrbuf{$env{'request.course.id'}}=
3854: $env{'course.'.$env{'request.course.id'}.'.description'};
3855: $courseinstcodebuf{$env{'request.course.id'}}=
3856: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3857: $courseownerbuf{$env{'request.course.id'}}=
3858: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3859: $coursetypebuf{$env{'request.course.id'}}=
3860: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3861: if (defined $courselogs{$env{'request.course.id'}}) {
3862: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3863: } else {
1.620 albertel 3864: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3865: }
1.620 albertel 3866: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3867: &flushcourselogs();
3868: }
1.158 www 3869: }
3870:
3871: sub courseacclog {
3872: my $fnsymb=shift;
1.620 albertel 3873: unless ($env{'request.course.id'}) { return ''; }
3874: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3875: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3876: $what.=':POST';
1.583 matthew 3877: # FIXME: Probably ought to escape things....
1.800 albertel 3878: foreach my $key (keys(%env)) {
3879: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3880: my $formitem = $1;
3881: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3882: $what.=':'.$formitem.'='.$env{$key};
3883: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3884: $what.=':'.$formitem.'='.$env{$key};
3885: }
1.158 www 3886: }
1.191 harris41 3887: }
1.583 matthew 3888: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3889: # FIXME: We should not be depending on a form parameter that someone
3890: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3891: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3892: $what.= ':POST';
3893: # FIXME: Probably ought to escape things....
3894: foreach my $element ('courseexp','crsfulltext','crsrelated',
3895: 'crsdiscuss') {
1.620 albertel 3896: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3897: }
3898: }
1.158 www 3899: }
3900: &courselog($what);
1.149 www 3901: }
3902:
1.185 www 3903: sub countacc {
3904: my $url=&declutter(shift);
1.458 matthew 3905: return if (! defined($url) || $url eq '');
1.620 albertel 3906: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3907: #
3908: # Mark that this url was used in this course
3909: #
1.620 albertel 3910: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3911: #
3912: # Increase the access count for this resource in this child process
3913: #
1.281 www 3914: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3915: $accesshash{$key}++;
1.185 www 3916: }
1.349 www 3917:
1.361 www 3918: sub linklog {
3919: my ($from,$to)=@_;
3920: $from=&declutter($from);
3921: $to=&declutter($to);
3922: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3923: $accesshash{$to.'___'.$from.'___goto'}=1;
3924: }
1.1160 www 3925:
3926: sub statslog {
3927: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3928: if ($users<2) { return; }
3929: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3930: 'course' => $env{'request.course.id'},
3931: 'sections' => '"all"',
3932: 'num_students' => $users,
3933: 'part' => $part,
3934: 'symb' => $symb,
3935: 'mean_tries' => $av_attempts,
3936: 'deg_of_diff' => $degdiff});
3937: foreach my $key (keys(%dynstore)) {
3938: $accesshash{$key}=$dynstore{$key};
3939: }
3940: }
1.361 www 3941:
1.349 www 3942: sub userrolelog {
3943: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3944: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3945: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3946: $userrolehash
3947: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3948: =$tend.':'.$tstart;
1.662 raeburn 3949: }
1.1169 droeschl 3950: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3951: $userrolehash
3952: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3953: =$tend.':'.$tstart;
3954: }
1.1169 droeschl 3955: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3956: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3957: $domainrolehash
3958: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3959: = $tend.':'.$tstart;
3960: }
1.351 www 3961: }
3962:
1.957 raeburn 3963: sub courserolelog {
3964: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3965: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3966: my $cdom = $1;
3967: my $cnum = $2;
3968: my $sec = $3;
3969: my $namespace = 'rolelog';
3970: my %storehash = (
3971: role => $trole,
3972: start => $tstart,
3973: end => $tend,
3974: selfenroll => $selfenroll,
3975: context => $context,
3976: );
3977: if ($trole eq 'gr') {
3978: $namespace = 'groupslog';
3979: $storehash{'group'} = $sec;
3980: } else {
3981: $storehash{'section'} = $sec;
3982: }
3983: &write_log('course',$namespace,\%storehash,$delflag,$username,
3984: $domain,$cnum,$cdom);
3985: if (($trole ne 'st') || ($sec ne '')) {
3986: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3987: }
3988: }
3989: return;
3990: }
3991:
1.1172.2.9 raeburn 3992: sub domainrolelog {
3993: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3994: if ($area =~ m{^/($match_domain)/$}) {
3995: my $cdom = $1;
3996: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3997: my $namespace = 'rolelog';
3998: my %storehash = (
3999: role => $trole,
4000: start => $tstart,
4001: end => $tend,
4002: context => $context,
4003: );
4004: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4005: $domain,$domconfiguser,$cdom);
4006: }
4007: return;
4008:
4009: }
4010:
4011: sub coauthorrolelog {
4012: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4013: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4014: my $audom = $1;
4015: my $auname = $2;
4016: my $namespace = 'rolelog';
4017: my %storehash = (
4018: role => $trole,
4019: start => $tstart,
4020: end => $tend,
4021: context => $context,
4022: );
4023: &write_log('author',$namespace,\%storehash,$delflag,$username,
4024: $domain,$auname,$audom);
4025: }
4026: return;
4027: }
4028:
1.351 www 4029: sub get_course_adv_roles {
1.948 raeburn 4030: my ($cid,$codes) = @_;
1.620 albertel 4031: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4032: my %coursehash=&coursedescription($cid);
1.988 raeburn 4033: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4034: my %nothide=();
1.800 albertel 4035: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4036: if ($user !~ /:/) {
4037: $nothide{join(':',split(/[\@]/,$user))}=1;
4038: } else {
4039: $nothide{$user}=1;
4040: }
1.470 www 4041: }
1.1172.2.23 raeburn 4042: my @possdoms = ($coursehash{'domain'});
4043: if ($coursehash{'checkforpriv'}) {
4044: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4045: }
1.351 www 4046: my %returnhash=();
4047: my %dumphash=
4048: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4049: my $now=time;
1.997 raeburn 4050: my %privileged;
1.1000 raeburn 4051: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4052: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4053: if (($tstart) && ($tstart<0)) { next; }
4054: if (($tend) && ($tend<$now)) { next; }
4055: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4056: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4057: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4058: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4059: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4060: if ($role eq 'cr') { next; }
1.948 raeburn 4061: if ($codes) {
4062: if ($section) { $role .= ':'.$section; }
4063: if ($returnhash{$role}) {
4064: $returnhash{$role}.=','.$username.':'.$domain;
4065: } else {
4066: $returnhash{$role}=$username.':'.$domain;
4067: }
1.351 www 4068: } else {
1.988 raeburn 4069: my $key=&plaintext($role,$crstype);
1.973 bisitz 4070: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4071: if ($returnhash{$key}) {
4072: $returnhash{$key}.=','.$username.':'.$domain;
4073: } else {
4074: $returnhash{$key}=$username.':'.$domain;
4075: }
1.351 www 4076: }
1.948 raeburn 4077: }
1.400 www 4078: return %returnhash;
4079: }
4080:
4081: sub get_my_roles {
1.937 raeburn 4082: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4083: unless (defined($uname)) { $uname=$env{'user.name'}; }
4084: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4085: my (%dumphash,%nothide);
1.1086 raeburn 4086: if ($context eq 'userroles') {
1.1166 raeburn 4087: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4088: } else {
1.1172.2.23 raeburn 4089: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4090: if ($hidepriv) {
4091: my %coursehash=&coursedescription($udom.'_'.$uname);
4092: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4093: if ($user !~ /:/) {
4094: $nothide{join(':',split(/[\@]/,$user))} = 1;
4095: } else {
4096: $nothide{$user} = 1;
4097: }
4098: }
4099: }
1.858 raeburn 4100: }
1.400 www 4101: my %returnhash=();
4102: my $now=time;
1.999 raeburn 4103: my %privileged;
1.800 albertel 4104: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4105: my ($role,$tend,$tstart);
4106: if ($context eq 'userroles') {
1.1149 raeburn 4107: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4108: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4109: } else {
4110: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4111: }
1.400 www 4112: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4113: my $status = 'active';
1.939 raeburn 4114: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4115: $status = 'previous';
4116: }
4117: if (($tstart) && ($now<$tstart)) {
4118: $status = 'future';
4119: }
4120: if (ref($types) eq 'ARRAY') {
4121: if (!grep(/^\Q$status\E$/,@{$types})) {
4122: next;
4123: }
4124: } else {
4125: if ($status ne 'active') {
4126: next;
4127: }
4128: }
1.867 raeburn 4129: my ($rolecode,$username,$domain,$section,$area);
4130: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4131: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4132: (undef,$domain,$username,$section) = split(/\//,$area);
4133: } else {
4134: ($role,$username,$domain,$section) = split(/\:/,$entry);
4135: }
1.832 raeburn 4136: if (ref($roledoms) eq 'ARRAY') {
4137: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4138: next;
4139: }
4140: }
4141: if (ref($roles) eq 'ARRAY') {
4142: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4143: if ($role =~ /^cr\//) {
4144: if (!grep(/^cr$/,@{$roles})) {
4145: next;
4146: }
1.1104 raeburn 4147: } elsif ($role =~ /^gr\//) {
4148: if (!grep(/^gr$/,@{$roles})) {
4149: next;
4150: }
1.922 raeburn 4151: } else {
4152: next;
4153: }
1.832 raeburn 4154: }
1.867 raeburn 4155: }
1.937 raeburn 4156: if ($hidepriv) {
1.1172.2.23 raeburn 4157: my @privroles = ('dc','su');
1.999 raeburn 4158: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4159: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4160: } else {
1.1172.2.23 raeburn 4161: my $possdoms = [$domain];
4162: if (ref($roledoms) eq 'ARRAY') {
4163: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4164: }
1.1172.2.23 raeburn 4165: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4166: if (!$nothide{$username.':'.$domain}) {
4167: next;
4168: }
4169: }
1.937 raeburn 4170: }
4171: }
1.933 raeburn 4172: if ($withsec) {
4173: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4174: $tstart.':'.$tend;
4175: } else {
4176: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4177: }
1.832 raeburn 4178: }
1.373 www 4179: return %returnhash;
1.399 www 4180: }
4181:
4182: # ----------------------------------------------------- Frontpage Announcements
4183: #
4184: #
4185:
4186: sub postannounce {
4187: my ($server,$text)=@_;
1.844 albertel 4188: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4189: unless ($text=~/\w/) { $text=''; }
4190: return &reply('setannounce:'.&escape($text),$server);
4191: }
4192:
4193: sub getannounce {
1.448 albertel 4194:
4195: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4196: my $announcement='';
1.800 albertel 4197: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4198: close($fh);
1.399 www 4199: if ($announcement=~/\w/) {
4200: return
4201: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4202: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4203: } else {
4204: return '';
4205: }
4206: } else {
4207: return '';
4208: }
1.351 www 4209: }
1.353 www 4210:
4211: # ---------------------------------------------------------- Course ID routines
4212: # Deal with domain's nohist_courseid.db files
4213: #
4214:
4215: sub courseidput {
1.921 raeburn 4216: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4217: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4218: my $outcome;
4219: if ($caller eq 'timeonly') {
4220: my $cids = '';
4221: foreach my $item (keys(%$storehash)) {
4222: $cids.=&escape($item).'&';
4223: }
4224: $cids=~s/\&$//;
4225: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4226: $coursehome);
4227: } else {
4228: my $items = '';
4229: foreach my $item (keys(%$storehash)) {
4230: $items.= &escape($item).'='.
4231: &freeze_escape($$storehash{$item}).'&';
4232: }
4233: $items=~s/\&$//;
4234: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4235: $coursehome);
1.918 raeburn 4236: }
4237: if ($outcome eq 'unknown_cmd') {
4238: my $what;
4239: foreach my $cid (keys(%$storehash)) {
4240: $what .= &escape($cid).'=';
1.921 raeburn 4241: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4242: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4243: }
4244: $what =~ s/\:$/&/;
4245: }
4246: $what =~ s/\&$//;
4247: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4248: } else {
4249: return $outcome;
4250: }
1.353 www 4251: }
4252:
4253: sub courseiddump {
1.921 raeburn 4254: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4255: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4256: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4257: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4258: $hasuniquecode)=@_;
1.918 raeburn 4259: my $as_hash = 1;
4260: my %returnhash;
4261: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4262: my %libserv = &all_library();
4263: foreach my $tryserver (keys(%libserv)) {
4264: if ( ( $hostidflag == 1
4265: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4266: || (!defined($hostidflag)) ) {
4267:
1.918 raeburn 4268: if (($domfilter eq '') ||
4269: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4270: my $rep;
4271: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4272: $rep = &LONCAPA::Lond::dump_course_id_handler(
4273: join(":", (&host_domain($tryserver), $sincefilter,
4274: &escape($descfilter), &escape($instcodefilter),
4275: &escape($ownerfilter), &escape($coursefilter),
4276: &escape($typefilter), &escape($regexp_ok),
4277: $as_hash, &escape($selfenrollonly),
4278: &escape($catfilter), $showhidden, $caller,
4279: &escape($cloner), &escape($cc_clone), $cloneonly,
4280: &escape($createdbefore), &escape($createdafter),
1.1172.2.38 raeburn 4281: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22 raeburn 4282: } else {
4283: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4284: $sincefilter.':'.&escape($descfilter).':'.
4285: &escape($instcodefilter).':'.&escape($ownerfilter).
4286: ':'.&escape($coursefilter).':'.&escape($typefilter).
4287: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4288: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4289: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4290: &escape($cc_clone).':'.$cloneonly.':'.
4291: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38 raeburn 4292: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22 raeburn 4293: $tryserver);
4294: }
4295:
1.918 raeburn 4296: my @pairs=split(/\&/,$rep);
4297: foreach my $item (@pairs) {
4298: my ($key,$value)=split(/\=/,$item,2);
4299: $key = &unescape($key);
4300: next if ($key =~ /^error: 2 /);
4301: my $result = &thaw_unescape($value);
4302: if (ref($result) eq 'HASH') {
4303: $returnhash{$key}=$result;
4304: } else {
1.921 raeburn 4305: my @responses = split(/:/,$value);
4306: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4307: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4308: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4309: }
1.1008 raeburn 4310: }
1.353 www 4311: }
4312: }
4313: }
4314: }
4315: return %returnhash;
4316: }
4317:
1.1055 raeburn 4318: sub courselastaccess {
4319: my ($cdom,$cnum,$hostidref) = @_;
4320: my %returnhash;
4321: if ($cdom && $cnum) {
4322: my $chome = &homeserver($cnum,$cdom);
4323: if ($chome ne 'no_host') {
4324: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4325: &extract_lastaccess(\%returnhash,$rep);
4326: }
4327: } else {
4328: if (!$cdom) { $cdom=''; }
4329: my %libserv = &all_library();
4330: foreach my $tryserver (keys(%libserv)) {
4331: if (ref($hostidref) eq 'ARRAY') {
4332: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4333: }
4334: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4335: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4336: &extract_lastaccess(\%returnhash,$rep);
4337: }
4338: }
4339: }
4340: return %returnhash;
4341: }
4342:
4343: sub extract_lastaccess {
4344: my ($returnhash,$rep) = @_;
4345: if (ref($returnhash) eq 'HASH') {
4346: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4347: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4348: $rep eq '') {
4349: my @pairs=split(/\&/,$rep);
4350: foreach my $item (@pairs) {
4351: my ($key,$value)=split(/\=/,$item,2);
4352: $key = &unescape($key);
4353: next if ($key =~ /^error: 2 /);
4354: $returnhash->{$key} = &thaw_unescape($value);
4355: }
4356: }
4357: }
4358: return;
4359: }
4360:
1.658 raeburn 4361: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4362:
4363: sub dcmailput {
1.685 raeburn 4364: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4365: my $status = &Apache::lonnet::critical(
1.740 www 4366: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4367: &escape($message),$server);
1.662 raeburn 4368: return $status;
4369: }
4370:
1.658 raeburn 4371: sub dcmaildump {
4372: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4373: my %returnhash=();
1.846 albertel 4374:
4375: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4376: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4377: &escape($enddate).':';
4378: my @esc_senders=map { &escape($_)} @$senders;
4379: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4380: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4381: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4382: if (($key) && ($value)) {
4383: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4384: }
4385: }
4386: }
4387: return %returnhash;
4388: }
1.662 raeburn 4389: # ---------------------------------------------------------- Domain roles
4390:
4391: sub get_domain_roles {
4392: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4393: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4394: $startdate = '.';
4395: }
1.1018 raeburn 4396: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4397: $enddate = '.';
4398: }
1.922 raeburn 4399: my $rolelist;
4400: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4401: $rolelist = join('&',@{$roles});
1.922 raeburn 4402: }
1.662 raeburn 4403: my %personnel = ();
1.841 albertel 4404:
4405: my %servers = &get_servers($dom,'library');
4406: foreach my $tryserver (keys(%servers)) {
4407: %{$personnel{$tryserver}}=();
4408: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4409: &escape($startdate).':'.
4410: &escape($enddate).':'.
4411: &escape($rolelist), $tryserver))) {
4412: my ($key,$value) = split(/\=/,$line,2);
4413: if (($key) && ($value)) {
4414: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4415: }
4416: }
1.662 raeburn 4417: }
4418: return %personnel;
4419: }
1.658 raeburn 4420:
1.1057 www 4421: # ----------------------------------------------------------- Interval timing
1.149 www 4422:
1.1153 www 4423: {
4424: # Caches needed for speedup of navmaps
4425: # We don't want to cache this for very long at all (5 seconds at most)
4426: #
4427: # The user for whom we cache
4428: my $cachedkey='';
4429: # The cached times for this user
4430: my %cachedtimes=();
4431: # When this was last done
4432: my $cachedtime=();
4433:
4434: sub load_all_first_access {
1.1154 raeburn 4435: my ($uname,$udom)=@_;
1.1156 www 4436: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4437: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4438: return;
4439: }
4440: $cachedtime=time;
4441: $cachedkey=$uname.':'.$udom;
4442: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4443: }
4444:
1.504 albertel 4445: sub get_first_access {
1.1162 raeburn 4446: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4447: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4448: if ($argsymb) { $symb=$argsymb; }
4449: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4450: if ($argmap) { $map = $argmap; }
1.926 albertel 4451: if ($type eq 'course') {
4452: $res='course';
4453: } elsif ($type eq 'map') {
1.588 albertel 4454: $res=&symbread($map);
4455: } else {
4456: $res=$symb;
4457: }
1.1153 www 4458: &load_all_first_access($uname,$udom);
4459: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4460: }
4461:
4462: sub set_first_access {
1.1162 raeburn 4463: my ($type,$interval)=@_;
1.790 albertel 4464: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4465: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4466: if ($type eq 'course') {
4467: $res='course';
4468: } elsif ($type eq 'map') {
1.588 albertel 4469: $res=&symbread($map);
4470: } else {
4471: $res=$symb;
4472: }
1.1153 www 4473: $cachedkey='';
1.1162 raeburn 4474: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4475: if (!$firstaccess) {
1.1162 raeburn 4476: my $start = time;
4477: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4478: $udom,$uname);
4479: if ($putres eq 'ok') {
4480: &put('timerinterval',{"$courseid\0$res"=>$interval},
4481: $udom,$uname);
4482: &appenv(
4483: {
4484: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4485: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4486: }
4487: );
4488: }
4489: return $putres;
1.505 albertel 4490: }
4491: return 'already_set';
1.504 albertel 4492: }
1.1153 www 4493: }
1.1172.2.32 raeburn 4494:
4495: sub checkout {
4496: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4497: my $now=time;
4498: my $lonhost=$perlvar{'lonHostID'};
4499: my $infostr=&escape(
4500: 'CHECKOUTTOKEN&'.
4501: $tuname.'&'.
4502: $tudom.'&'.
4503: $tcrsid.'&'.
4504: $symb.'&'.
4505: $now.'&'.$ENV{'REMOTE_ADDR'});
4506: my $token=&reply('tmpput:'.$infostr,$lonhost);
4507: if ($token=~/^error\:/) {
4508: &logthis("<font color=\"blue\">WARNING: ".
4509: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4510: "</font>");
4511: return '';
4512: }
4513:
4514: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4515: $token=~tr/a-z/A-Z/;
4516:
4517: my %infohash=('resource.0.outtoken' => $token,
4518: 'resource.0.checkouttime' => $now,
4519: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4520:
4521: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4522: return '';
4523: } else {
4524: &logthis("<font color=\"blue\">WARNING: ".
4525: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4526: "</font>");
4527: }
4528:
4529: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4530: &escape('Checkout '.$infostr.' - '.
4531: $token)) ne 'ok') {
4532: return '';
4533: } else {
4534: &logthis("<font color=\"blue\">WARNING: ".
4535: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4536: "</font>");
4537: }
4538: return $token;
4539: }
4540:
4541: # ------------------------------------------------------------ Check in an item
4542:
4543: sub checkin {
4544: my $token=shift;
4545: my $now=time;
4546: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4547: $lonhost=~tr/A-Z/a-z/;
4548: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4549: $dtoken=~s/\W/\_/g;
4550: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4551: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4552:
4553: unless (($tuname) && ($tudom)) {
4554: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4555: return '';
4556: }
4557:
4558: unless (&allowed('mgr',$tcrsid)) {
4559: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4560: $env{'user.name'}.' - '.$env{'user.domain'});
4561: return '';
4562: }
4563:
4564: my %infohash=('resource.0.intoken' => $token,
4565: 'resource.0.checkintime' => $now,
4566: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4567:
4568: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4569: return '';
4570: }
4571:
4572: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4573: &escape('Checkin - '.$token)) ne 'ok') {
4574: return '';
4575: }
4576:
4577: return ($symb,$tuname,$tudom,$tcrsid);
4578: }
4579:
1.110 www 4580: # --------------------------------------------- Set Expire Date for Spreadsheet
4581:
4582: sub expirespread {
4583: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4584: my $cid=$env{'request.course.id'};
1.110 www 4585: if ($cid) {
4586: my $now=time;
4587: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4588: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4589: $env{'course.'.$cid.'.num'}.
1.110 www 4590: ':nohist_expirationdates:'.
4591: &escape($key).'='.$now,
1.620 albertel 4592: $env{'course.'.$cid.'.home'})
1.110 www 4593: }
4594: return 'ok';
1.14 www 4595: }
4596:
1.109 www 4597: # ----------------------------------------------------- Devalidate Spreadsheets
4598:
4599: sub devalidate {
1.325 www 4600: my ($symb,$uname,$udom)=@_;
1.620 albertel 4601: my $cid=$env{'request.course.id'};
1.109 www 4602: if ($cid) {
1.391 matthew 4603: # delete the stored spreadsheets for
4604: # - the student level sheet of this user in course's homespace
4605: # - the assessment level sheet for this resource
4606: # for this user in user's homespace
1.553 albertel 4607: # - current conditional state info
1.325 www 4608: my $key=$uname.':'.$udom.':';
1.109 www 4609: my $status=
1.299 matthew 4610: &del('nohist_calculatedsheets',
1.391 matthew 4611: [$key.'studentcalc:'],
1.620 albertel 4612: $env{'course.'.$cid.'.domain'},
4613: $env{'course.'.$cid.'.num'})
1.133 albertel 4614: .' '.
4615: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4616: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4617: unless ($status eq 'ok ok') {
4618: &logthis('Could not devalidate spreadsheet '.
1.325 www 4619: $uname.' at '.$udom.' for '.
1.109 www 4620: $symb.': '.$status);
1.133 albertel 4621: }
1.553 albertel 4622: &delenv('user.state.'.$cid);
1.109 www 4623: }
4624: }
4625:
1.265 albertel 4626: sub get_scalar {
4627: my ($string,$end) = @_;
4628: my $value;
4629: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4630: $value = $1;
4631: } elsif ($$string =~ s/^([^&]*?)&//) {
4632: $value = $1;
4633: }
4634: return &unescape($value);
4635: }
4636:
4637: sub array2str {
4638: my (@array) = @_;
4639: my $result=&arrayref2str(\@array);
4640: $result=~s/^__ARRAY_REF__//;
4641: $result=~s/__END_ARRAY_REF__$//;
4642: return $result;
4643: }
4644:
1.204 albertel 4645: sub arrayref2str {
4646: my ($arrayref) = @_;
1.265 albertel 4647: my $result='__ARRAY_REF__';
1.204 albertel 4648: foreach my $elem (@$arrayref) {
1.265 albertel 4649: if(ref($elem) eq 'ARRAY') {
4650: $result.=&arrayref2str($elem).'&';
4651: } elsif(ref($elem) eq 'HASH') {
4652: $result.=&hashref2str($elem).'&';
4653: } elsif(ref($elem)) {
4654: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4655: } else {
4656: $result.=&escape($elem).'&';
4657: }
4658: }
4659: $result=~s/\&$//;
1.265 albertel 4660: $result .= '__END_ARRAY_REF__';
1.204 albertel 4661: return $result;
4662: }
4663:
1.168 albertel 4664: sub hash2str {
1.204 albertel 4665: my (%hash) = @_;
4666: my $result=&hashref2str(\%hash);
1.265 albertel 4667: $result=~s/^__HASH_REF__//;
4668: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4669: return $result;
4670: }
4671:
4672: sub hashref2str {
4673: my ($hashref)=@_;
1.265 albertel 4674: my $result='__HASH_REF__';
1.800 albertel 4675: foreach my $key (sort(keys(%$hashref))) {
4676: if (ref($key) eq 'ARRAY') {
4677: $result.=&arrayref2str($key).'=';
4678: } elsif (ref($key) eq 'HASH') {
4679: $result.=&hashref2str($key).'=';
4680: } elsif (ref($key)) {
1.265 albertel 4681: $result.='=';
1.800 albertel 4682: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4683: } else {
1.1132 raeburn 4684: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4685: }
4686:
1.800 albertel 4687: if(ref($hashref->{$key}) eq 'ARRAY') {
4688: $result.=&arrayref2str($hashref->{$key}).'&';
4689: } elsif(ref($hashref->{$key}) eq 'HASH') {
4690: $result.=&hashref2str($hashref->{$key}).'&';
4691: } elsif(ref($hashref->{$key})) {
1.265 albertel 4692: $result.='&';
1.800 albertel 4693: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4694: } else {
1.800 albertel 4695: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4696: }
4697: }
1.168 albertel 4698: $result=~s/\&$//;
1.265 albertel 4699: $result .= '__END_HASH_REF__';
1.168 albertel 4700: return $result;
4701: }
4702:
4703: sub str2hash {
1.265 albertel 4704: my ($string)=@_;
4705: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4706: return %$hash;
4707: }
4708:
4709: sub str2hashref {
1.168 albertel 4710: my ($string) = @_;
1.265 albertel 4711:
4712: my %hash;
4713:
4714: if($string !~ /^__HASH_REF__/) {
4715: if (! ($string eq '' || !defined($string))) {
4716: $hash{'error'}='Not hash reference';
4717: }
4718: return (\%hash, $string);
4719: }
4720:
4721: $string =~ s/^__HASH_REF__//;
4722:
4723: while($string !~ /^__END_HASH_REF__/) {
4724: #key
4725: my $key='';
4726: if($string =~ /^__HASH_REF__/) {
4727: ($key, $string)=&str2hashref($string);
4728: if(defined($key->{'error'})) {
4729: $hash{'error'}='Bad data';
4730: return (\%hash, $string);
4731: }
4732: } elsif($string =~ /^__ARRAY_REF__/) {
4733: ($key, $string)=&str2arrayref($string);
4734: if($key->[0] eq 'Array reference error') {
4735: $hash{'error'}='Bad data';
4736: return (\%hash, $string);
4737: }
4738: } else {
4739: $string =~ s/^(.*?)=//;
1.267 albertel 4740: $key=&unescape($1);
1.265 albertel 4741: }
4742: $string =~ s/^=//;
4743:
4744: #value
4745: my $value='';
4746: if($string =~ /^__HASH_REF__/) {
4747: ($value, $string)=&str2hashref($string);
4748: if(defined($value->{'error'})) {
4749: $hash{'error'}='Bad data';
4750: return (\%hash, $string);
4751: }
4752: } elsif($string =~ /^__ARRAY_REF__/) {
4753: ($value, $string)=&str2arrayref($string);
4754: if($value->[0] eq 'Array reference error') {
4755: $hash{'error'}='Bad data';
4756: return (\%hash, $string);
4757: }
4758: } else {
4759: $value=&get_scalar(\$string,'__END_HASH_REF__');
4760: }
4761: $string =~ s/^&//;
4762:
4763: $hash{$key}=$value;
1.204 albertel 4764: }
1.265 albertel 4765:
4766: $string =~ s/^__END_HASH_REF__//;
4767:
4768: return (\%hash, $string);
1.204 albertel 4769: }
4770:
4771: sub str2array {
1.265 albertel 4772: my ($string)=@_;
4773: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4774: return @$array;
4775: }
4776:
4777: sub str2arrayref {
1.204 albertel 4778: my ($string) = @_;
1.265 albertel 4779: my @array;
4780:
4781: if($string !~ /^__ARRAY_REF__/) {
4782: if (! ($string eq '' || !defined($string))) {
4783: $array[0]='Array reference error';
4784: }
4785: return (\@array, $string);
4786: }
4787:
4788: $string =~ s/^__ARRAY_REF__//;
4789:
4790: while($string !~ /^__END_ARRAY_REF__/) {
4791: my $value='';
4792: if($string =~ /^__HASH_REF__/) {
4793: ($value, $string)=&str2hashref($string);
4794: if(defined($value->{'error'})) {
4795: $array[0] ='Array reference error';
4796: return (\@array, $string);
4797: }
4798: } elsif($string =~ /^__ARRAY_REF__/) {
4799: ($value, $string)=&str2arrayref($string);
4800: if($value->[0] eq 'Array reference error') {
4801: $array[0] ='Array reference error';
4802: return (\@array, $string);
4803: }
4804: } else {
4805: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4806: }
4807: $string =~ s/^&//;
4808:
4809: push(@array, $value);
1.191 harris41 4810: }
1.265 albertel 4811:
4812: $string =~ s/^__END_ARRAY_REF__//;
4813:
4814: return (\@array, $string);
1.168 albertel 4815: }
4816:
1.167 albertel 4817: # -------------------------------------------------------------------Temp Store
4818:
1.168 albertel 4819: sub tmpreset {
4820: my ($symb,$namespace,$domain,$stuname) = @_;
4821: if (!$symb) {
4822: $symb=&symbread();
1.620 albertel 4823: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4824: }
4825: $symb=escape($symb);
4826:
1.620 albertel 4827: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4828: $namespace=~s/\//\_/g;
4829: $namespace=~s/\W//g;
4830:
1.620 albertel 4831: if (!$domain) { $domain=$env{'user.domain'}; }
4832: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4833: if ($domain eq 'public' && $stuname eq 'public') {
4834: $stuname=$ENV{'REMOTE_ADDR'};
4835: }
1.1117 foxr 4836: my $path=LONCAPA::tempdir();
1.168 albertel 4837: my %hash;
4838: if (tie(%hash,'GDBM_File',
4839: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4840: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4841: foreach my $key (keys(%hash)) {
1.180 albertel 4842: if ($key=~ /:$symb/) {
1.168 albertel 4843: delete($hash{$key});
4844: }
4845: }
4846: }
4847: }
4848:
1.167 albertel 4849: sub tmpstore {
1.168 albertel 4850: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4851:
4852: if (!$symb) {
4853: $symb=&symbread();
1.620 albertel 4854: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4855: }
4856: $symb=escape($symb);
4857:
4858: if (!$namespace) {
4859: # I don't think we would ever want to store this for a course.
4860: # it seems this will only be used if we don't have a course.
1.620 albertel 4861: #$namespace=$env{'request.course.id'};
1.168 albertel 4862: #if (!$namespace) {
1.620 albertel 4863: $namespace=$env{'request.state'};
1.168 albertel 4864: #}
4865: }
4866: $namespace=~s/\//\_/g;
4867: $namespace=~s/\W//g;
1.620 albertel 4868: if (!$domain) { $domain=$env{'user.domain'}; }
4869: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4870: if ($domain eq 'public' && $stuname eq 'public') {
4871: $stuname=$ENV{'REMOTE_ADDR'};
4872: }
1.168 albertel 4873: my $now=time;
4874: my %hash;
1.1117 foxr 4875: my $path=LONCAPA::tempdir();
1.168 albertel 4876: if (tie(%hash,'GDBM_File',
4877: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4878: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4879: $hash{"version:$symb"}++;
4880: my $version=$hash{"version:$symb"};
4881: my $allkeys='';
4882: foreach my $key (keys(%$storehash)) {
4883: $allkeys.=$key.':';
1.591 albertel 4884: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4885: }
4886: $hash{"$version:$symb:timestamp"}=$now;
4887: $allkeys.='timestamp';
4888: $hash{"$version:keys:$symb"}=$allkeys;
4889: if (untie(%hash)) {
4890: return 'ok';
4891: } else {
4892: return "error:$!";
4893: }
4894: } else {
4895: return "error:$!";
4896: }
4897: }
1.167 albertel 4898:
1.168 albertel 4899: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4900:
1.168 albertel 4901: sub tmprestore {
4902: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4903:
1.168 albertel 4904: if (!$symb) {
4905: $symb=&symbread();
1.620 albertel 4906: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4907: }
4908: $symb=escape($symb);
4909:
1.620 albertel 4910: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4911:
1.620 albertel 4912: if (!$domain) { $domain=$env{'user.domain'}; }
4913: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4914: if ($domain eq 'public' && $stuname eq 'public') {
4915: $stuname=$ENV{'REMOTE_ADDR'};
4916: }
1.168 albertel 4917: my %returnhash;
4918: $namespace=~s/\//\_/g;
4919: $namespace=~s/\W//g;
4920: my %hash;
1.1117 foxr 4921: my $path=LONCAPA::tempdir();
1.168 albertel 4922: if (tie(%hash,'GDBM_File',
4923: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4924: &GDBM_READER(),0640)) {
1.168 albertel 4925: my $version=$hash{"version:$symb"};
4926: $returnhash{'version'}=$version;
4927: my $scope;
4928: for ($scope=1;$scope<=$version;$scope++) {
4929: my $vkeys=$hash{"$scope:keys:$symb"};
4930: my @keys=split(/:/,$vkeys);
4931: my $key;
4932: $returnhash{"$scope:keys"}=$vkeys;
4933: foreach $key (@keys) {
1.591 albertel 4934: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4935: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4936: }
4937: }
1.168 albertel 4938: if (!(untie(%hash))) {
4939: return "error:$!";
4940: }
4941: } else {
4942: return "error:$!";
4943: }
4944: return %returnhash;
1.167 albertel 4945: }
4946:
1.9 www 4947: # ----------------------------------------------------------------------- Store
4948:
4949: sub store {
1.124 www 4950: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4951: my $home='';
4952:
1.168 albertel 4953: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4954:
1.213 www 4955: $symb=&symbclean($symb);
1.122 albertel 4956: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4957:
1.620 albertel 4958: if (!$domain) { $domain=$env{'user.domain'}; }
4959: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4960:
4961: &devalidate($symb,$stuname,$domain);
1.109 www 4962:
4963: $symb=escape($symb);
1.187 www 4964: if (!$namespace) {
1.620 albertel 4965: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4966: return '';
4967: }
4968: }
1.620 albertel 4969: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4970:
4971: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4972: $$storehash{'host'}=$perlvar{'lonHostID'};
4973:
1.12 www 4974: my $namevalue='';
1.800 albertel 4975: foreach my $key (keys(%$storehash)) {
4976: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4977: }
1.12 www 4978: $namevalue=~s/\&$//;
1.187 www 4979: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4980: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4981: }
4982:
1.47 www 4983: # -------------------------------------------------------------- Critical Store
4984:
4985: sub cstore {
1.124 www 4986: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4987: my $home='';
4988:
1.168 albertel 4989: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4990:
1.213 www 4991: $symb=&symbclean($symb);
1.122 albertel 4992: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4993:
1.620 albertel 4994: if (!$domain) { $domain=$env{'user.domain'}; }
4995: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4996:
4997: &devalidate($symb,$stuname,$domain);
1.109 www 4998:
4999: $symb=escape($symb);
1.187 www 5000: if (!$namespace) {
1.620 albertel 5001: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5002: return '';
5003: }
5004: }
1.620 albertel 5005: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5006:
5007: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5008: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5009:
1.47 www 5010: my $namevalue='';
1.800 albertel 5011: foreach my $key (keys(%$storehash)) {
5012: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5013: }
1.47 www 5014: $namevalue=~s/\&$//;
1.187 www 5015: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5016: return critical
5017: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 5018: }
5019:
1.9 www 5020: # --------------------------------------------------------------------- Restore
5021:
5022: sub restore {
1.124 www 5023: my ($symb,$namespace,$domain,$stuname) = @_;
5024: my $home='';
5025:
1.168 albertel 5026: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5027:
1.122 albertel 5028: if (!$symb) {
1.1172.2.26 raeburn 5029: return if ($namespace eq 'courserequests');
5030: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5031: } else {
1.1172.2.26 raeburn 5032: unless ($namespace eq 'courserequests') {
5033: $symb=&escape(&symbclean($symb));
5034: }
1.122 albertel 5035: }
1.188 www 5036: if (!$namespace) {
1.620 albertel 5037: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5038: return '';
5039: }
5040: }
1.620 albertel 5041: if (!$domain) { $domain=$env{'user.domain'}; }
5042: if (!$stuname) { $stuname=$env{'user.name'}; }
5043: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5044: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5045:
1.12 www 5046: my %returnhash=();
1.800 albertel 5047: foreach my $line (split(/\&/,$answer)) {
5048: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5049: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5050: }
1.75 www 5051: my $version;
5052: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5053: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5054: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5055: }
1.75 www 5056: }
1.13 www 5057: return %returnhash;
1.34 www 5058: }
5059:
5060: # ---------------------------------------------------------- Course Description
1.1118 foxr 5061: #
5062: #
1.34 www 5063:
5064: sub coursedescription {
1.731 albertel 5065: my ($courseid,$args)=@_;
1.34 www 5066: $courseid=~s/^\///;
1.49 www 5067: $courseid=~s/\_/\//g;
1.34 www 5068: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5069: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5070: my $normalid=$cdomain.'_'.$cnum;
5071: # need to always cache even if we get errors otherwise we keep
5072: # trying and trying and trying to get the course description.
5073: my %envhash=();
5074: my %returnhash=();
1.731 albertel 5075:
5076: my $expiretime=600;
5077: if ($env{'request.course.id'} eq $normalid) {
5078: $expiretime=120;
5079: }
5080:
5081: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5082: if (!$args->{'freshen_cache'}
5083: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5084: foreach my $key (keys(%env)) {
5085: next if ($key !~ /^\Q$prefix\E(.*)/);
5086: my ($setting) = $1;
5087: $returnhash{$setting} = $env{$key};
5088: }
5089: return %returnhash;
5090: }
5091:
1.1118 foxr 5092: # get the data again
5093:
1.731 albertel 5094: if (!$args->{'one_time'}) {
5095: $envhash{'course.'.$normalid.'.last_cache'}=time;
5096: }
1.811 albertel 5097:
1.34 www 5098: if ($chome ne 'no_host') {
1.302 albertel 5099: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5100: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5101: my $username = $env{'user.name'}; # Defult username
5102: if(defined $args->{'user'}) {
5103: $username = $args->{'user'};
5104: }
1.129 albertel 5105: $returnhash{'home'}= $chome;
5106: $returnhash{'domain'} = $cdomain;
5107: $returnhash{'num'} = $cnum;
1.741 raeburn 5108: if (!defined($returnhash{'type'})) {
5109: $returnhash{'type'} = 'Course';
5110: }
1.130 albertel 5111: while (my ($name,$value) = each %returnhash) {
1.53 www 5112: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5113: }
1.270 www 5114: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5115: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5116: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5117: $envhash{'course.'.$normalid.'.home'}=$chome;
5118: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5119: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5120: }
5121: }
1.731 albertel 5122: if (!$args->{'one_time'}) {
1.949 raeburn 5123: &appenv(\%envhash);
1.731 albertel 5124: }
1.302 albertel 5125: return %returnhash;
1.461 www 5126: }
5127:
1.1080 raeburn 5128: sub update_released_required {
5129: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5130: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5131: $cid = $env{'request.course.id'};
5132: $cdom = $env{'course.'.$cid.'.domain'};
5133: $cnum = $env{'course.'.$cid.'.num'};
5134: $chome = $env{'course.'.$cid.'.home'};
5135: }
5136: if ($needsrelease) {
5137: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5138: my $needsupdate;
5139: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5140: $needsupdate = 1;
5141: } else {
5142: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5143: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5144: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5145: $needsupdate = 1;
5146: }
5147: }
5148: if ($needsupdate) {
5149: my %needshash = (
5150: 'internal.releaserequired' => $needsrelease,
5151: );
5152: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5153: if ($putresult eq 'ok') {
5154: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5155: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5156: if (ref($crsinfo{$cid}) eq 'HASH') {
5157: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5158: &courseidput($cdom,\%crsinfo,$chome,'notime');
5159: }
5160: }
5161: }
5162: }
5163: return;
5164: }
5165:
1.461 www 5166: # -------------------------------------------------See if a user is privileged
5167:
5168: sub privileged {
1.1172.2.23 raeburn 5169: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5170: my $now = time;
1.1172.2.23 raeburn 5171: my $roles;
5172: if (ref($possroles) eq 'ARRAY') {
5173: $roles = $possroles;
5174: } else {
5175: $roles = ['dc','su'];
5176: }
5177: if (ref($possdomains) eq 'ARRAY') {
5178: my %privileged = &privileged_by_domain($possdomains,$roles);
5179: foreach my $dom (@{$possdomains}) {
5180: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5181: (ref($privileged{$dom}) eq 'HASH')) {
5182: foreach my $role (@{$roles}) {
5183: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5184: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5185: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5186: return 1 unless (($end && $end < $now) ||
5187: ($start && $start > $now));
5188: }
5189: }
5190: }
5191: }
5192: }
5193: } else {
5194: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5195: my $now = time;
1.1170 droeschl 5196:
1.1172.2.58 raeburn 5197: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5198: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5199: if (grep(/^\Q$trole\E$/,@{$roles})) {
5200: return 1 unless ($tend && $tend < $now)
5201: or ($tstart && $tstart > $now);
1.1170 droeschl 5202: }
1.1172.2.23 raeburn 5203: }
5204: }
1.461 www 5205: return 0;
1.9 www 5206: }
1.1 albertel 5207:
1.1172.2.23 raeburn 5208: sub privileged_by_domain {
5209: my ($domains,$roles) = @_;
5210: my %privileged = ();
5211: my $cachetime = 60*60*24;
5212: my $now = time;
5213: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5214: return %privileged;
5215: }
5216: foreach my $dom (@{$domains}) {
5217: next if (ref($privileged{$dom}) eq 'HASH');
5218: my $needroles;
5219: foreach my $role (@{$roles}) {
5220: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5221: if (defined($cached)) {
5222: if (ref($result) eq 'HASH') {
5223: $privileged{$dom}{$role} = $result;
5224: }
5225: } else {
5226: $needroles = 1;
5227: }
5228: }
5229: if ($needroles) {
5230: my %dompersonnel = &get_domain_roles($dom,$roles);
5231: $privileged{$dom} = {};
5232: foreach my $server (keys(%dompersonnel)) {
5233: if (ref($dompersonnel{$server}) eq 'HASH') {
5234: foreach my $item (keys(%{$dompersonnel{$server}})) {
5235: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5236: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5237: next if ($end && $end < $now);
5238: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5239: $dompersonnel{$server}{$item};
5240: }
5241: }
5242: }
5243: if (ref($privileged{$dom}) eq 'HASH') {
5244: foreach my $role (@{$roles}) {
5245: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5246: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5247: } else {
5248: my %hash = ();
5249: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5250: }
5251: }
5252: }
5253: }
5254: }
5255: return %privileged;
5256: }
5257:
1.103 harris41 5258: # -------------------------------------------------------- Get user privileges
1.11 www 5259:
5260: sub rolesinit {
1.1169 droeschl 5261: my ($domain, $username) = @_;
5262: my %userroles = ('user.login.time' => time);
5263: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5264:
5265: # firstaccess and timerinterval are related to timed maps/resources.
5266: # also, blocking can be triggered by an activating timer
5267: # it's saved in the user's %env.
5268: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5269: my %timerinterval = &dump('timerinterval', $domain, $username);
5270: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5271: %timerintchk, %timerintenv);
5272:
1.1162 raeburn 5273: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5274: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5275: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5276: }
1.1169 droeschl 5277:
1.1162 raeburn 5278: foreach my $key (keys(%timerinterval)) {
5279: my ($cid,$rest) = split(/\0/,$key);
5280: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5281: }
1.1169 droeschl 5282:
1.11 www 5283: my %allroles=();
1.1162 raeburn 5284: my %allgroups=();
1.11 www 5285:
1.1172.2.58 raeburn 5286: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5287: my $role = $rolesdump{$area};
5288: $area =~ s/\_\w\w$//;
5289:
5290: my ($trole, $tend, $tstart, $group_privs);
5291:
5292: if ($role =~ /^cr/) {
5293: # Custom role, defined by a user
5294: # e.g., user.role.cr/msu/smith/mynewrole
5295: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5296: $trole = $1;
5297: ($tend, $tstart) = split('_', $2);
5298: } else {
5299: $trole = $role;
5300: }
5301: } elsif ($role =~ m|^gr/|) {
5302: # Role of member in a group, defined within a course/community
5303: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5304: ($trole, $tend, $tstart) = split(/_/, $role);
5305: next if $tstart eq '-1';
5306: ($trole, $group_privs) = split(/\//, $trole);
5307: $group_privs = &unescape($group_privs);
5308: } else {
5309: # Just a normal role, defined in roles.tab
5310: ($trole, $tend, $tstart) = split(/_/,$role);
5311: }
5312:
5313: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5314: $username);
5315: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5316:
5317: # role expired or not available yet?
5318: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5319: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5320:
5321: next if $area eq '' or $trole eq '';
5322:
5323: my $spec = "$trole.$area";
5324: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5325:
5326: if ($trole =~ /^cr\//) {
5327: # Custom role, defined by a user
5328: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5329: } elsif ($trole eq 'gr') {
5330: # Role of a member in a group, defined within a course/community
5331: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5332: next;
5333: } else {
5334: # Normal role, defined in roles.tab
5335: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5336: }
5337:
5338: my $cid = $tdomain.'_'.$trest;
5339: unless ($firstaccchk{$cid}) {
5340: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5341: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5342: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5343: $coursetimerstarts{$cid}{$item};
5344: }
5345: }
5346: $firstaccchk{$cid} = 1;
5347: }
5348: unless ($timerintchk{$cid}) {
5349: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5350: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5351: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5352: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5353: }
1.12 www 5354: }
1.1169 droeschl 5355: $timerintchk{$cid} = 1;
1.191 harris41 5356: }
1.11 www 5357: }
1.1169 droeschl 5358:
5359: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5360: \%allroles, \%allgroups);
5361: $env{'user.adv'} = $userroles{'user.adv'};
5362:
1.1162 raeburn 5363: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5364: }
5365:
1.567 raeburn 5366: sub set_arearole {
1.1172.2.19 raeburn 5367: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5368: unless ($nolog) {
1.567 raeburn 5369: # log the associated role with the area
1.1172.2.19 raeburn 5370: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5371: }
1.743 albertel 5372: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5373: }
5374:
5375: sub custom_roleprivs {
5376: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5377: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5378: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5379: if (&hostname($homsvr) ne '') {
1.567 raeburn 5380: my ($rdummy,$roledef)=
5381: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5382: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5383: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5384: if (defined($syspriv)) {
1.1043 raeburn 5385: if ($trest =~ /^$match_community$/) {
5386: $syspriv =~ s/bre\&S//;
5387: }
1.567 raeburn 5388: $$allroles{'cm./'}.=':'.$syspriv;
5389: $$allroles{$spec.'./'}.=':'.$syspriv;
5390: }
5391: if ($tdomain ne '') {
5392: if (defined($dompriv)) {
5393: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5394: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5395: }
5396: if (($trest ne '') && (defined($coursepriv))) {
5397: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5398: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5399: }
5400: }
5401: }
5402: }
5403: }
5404:
1.678 raeburn 5405: sub group_roleprivs {
5406: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5407: my $access = 1;
5408: my $now = time;
5409: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5410: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5411: if ($access) {
1.811 albertel 5412: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5413: $$allgroups{$course}{$group} .=':'.$group_privs;
5414: }
5415: }
1.567 raeburn 5416:
5417: sub standard_roleprivs {
5418: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5419: if (defined($pr{$trole.':s'})) {
5420: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5421: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5422: }
5423: if ($tdomain ne '') {
5424: if (defined($pr{$trole.':d'})) {
5425: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5426: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5427: }
5428: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5429: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5430: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5431: }
5432: }
5433: }
5434:
5435: sub set_userprivs {
1.1064 raeburn 5436: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5437: my $author=0;
5438: my $adv=0;
1.678 raeburn 5439: my %grouproles = ();
5440: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5441: my @groupkeys;
1.1000 raeburn 5442: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5443: push(@groupkeys,$role);
5444: }
5445: if (ref($groups_roles) eq 'HASH') {
5446: foreach my $key (keys(%{$groups_roles})) {
5447: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5448: push(@groupkeys,$key);
5449: }
5450: }
5451: }
5452: if (@groupkeys > 0) {
5453: foreach my $role (@groupkeys) {
5454: my ($trole,$area,$sec,$extendedarea);
5455: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5456: $trole = $1;
5457: $area = $2;
5458: $sec = $3;
5459: $extendedarea = $area.$sec;
5460: if (exists($$allgroups{$area})) {
5461: foreach my $group (keys(%{$$allgroups{$area}})) {
5462: my $spec = $trole.'.'.$extendedarea;
5463: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5464: $$allgroups{$area}{$group};
1.1064 raeburn 5465: }
1.678 raeburn 5466: }
5467: }
5468: }
5469: }
5470: }
1.800 albertel 5471: foreach my $group (keys(%grouproles)) {
5472: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5473: }
1.800 albertel 5474: foreach my $role (keys(%{$allroles})) {
5475: my %thesepriv;
1.941 raeburn 5476: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5477: foreach my $item (split(/:/,$$allroles{$role})) {
5478: if ($item ne '') {
5479: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5480: if ($restrictions eq '') {
5481: $thesepriv{$privilege}='F';
5482: } elsif ($thesepriv{$privilege} ne 'F') {
5483: $thesepriv{$privilege}.=$restrictions;
5484: }
5485: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5486: }
5487: }
5488: my $thesestr='';
1.1104 raeburn 5489: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5490: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5491: }
5492: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5493: }
5494: return ($author,$adv);
5495: }
5496:
1.994 raeburn 5497: sub role_status {
1.1104 raeburn 5498: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5499: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5500: my ($one,$two) = split(m{\./},$rolekey,2);
5501: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5502: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5503: $$where = '/'.$two;
1.994 raeburn 5504: $$trolecode=$$role.'.'.$$where;
5505: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5506: $$tstatus='is';
1.1104 raeburn 5507: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5508: $$tstatus='future';
1.1034 raeburn 5509: if ($$tstart<$now) {
5510: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5511: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5512: my (%allroles,%allgroups,$group_privs,
5513: %groups_roles,@rolecodes);
1.1002 raeburn 5514: my %userroles = (
5515: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5516: );
1.1064 raeburn 5517: @rolecodes = ('cm');
1.1002 raeburn 5518: my $spec=$$role.'.'.$$where;
5519: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5520: if ($$role =~ /^cr\//) {
5521: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5522: push(@rolecodes,'cr');
1.1002 raeburn 5523: } elsif ($$role eq 'gr') {
1.1064 raeburn 5524: push(@rolecodes,$$role);
1.1002 raeburn 5525: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5526: $env{'user.name'});
1.1064 raeburn 5527: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5528: (undef,my $group_privs) = split(/\//,$trole);
5529: $group_privs = &unescape($group_privs);
5530: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5531: 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 5532: &get_groups_roles($tdomain,$trest,
5533: \%course_roles,\@rolecodes,
5534: \%groups_roles);
1.1002 raeburn 5535: } else {
1.1064 raeburn 5536: push(@rolecodes,$$role);
1.1002 raeburn 5537: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5538: }
1.1064 raeburn 5539: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5540: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5541: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5542: }
5543: }
1.1034 raeburn 5544: $$tstatus = 'is';
1.1002 raeburn 5545: }
1.994 raeburn 5546: }
5547: if ($$tend) {
1.1104 raeburn 5548: if ($$tend<$update) {
1.994 raeburn 5549: $$tstatus='expired';
5550: } elsif ($$tend<$now) {
5551: $$tstatus='will_not';
5552: }
5553: }
5554: }
5555: }
5556: }
5557:
1.1104 raeburn 5558: sub get_groups_roles {
5559: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5560: return unless((ref($cdom_courseroles) eq 'HASH') &&
5561: (ref($rolecodes) eq 'ARRAY') &&
5562: (ref($groups_roles) eq 'HASH'));
5563: if (keys(%{$cdom_courseroles}) > 0) {
5564: my ($cnum) = ($rest =~ /^($match_courseid)/);
5565: if ($cdom ne '' && $cnum ne '') {
5566: foreach my $key (keys(%{$cdom_courseroles})) {
5567: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5568: my $crsrole = $1;
5569: my $crssec = $2;
5570: if ($crsrole =~ /^cr/) {
5571: unless (grep(/^cr$/,@{$rolecodes})) {
5572: push(@{$rolecodes},'cr');
5573: }
5574: } else {
5575: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5576: push(@{$rolecodes},$crsrole);
5577: }
5578: }
5579: my $rolekey = "$crsrole./$cdom/$cnum";
5580: if ($crssec ne '') {
5581: $rolekey .= "/$crssec";
5582: }
5583: $rolekey .= './';
5584: $groups_roles->{$rolekey} = $rolecodes;
5585: }
5586: }
5587: }
5588: }
5589: return;
5590: }
5591:
5592: sub delete_env_groupprivs {
5593: my ($where,$courseroles,$possroles) = @_;
5594: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5595: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5596: unless (ref($courseroles->{$udom}) eq 'HASH') {
5597: %{$courseroles->{$udom}} =
5598: &get_my_roles('','','userroles',['active'],
5599: $possroles,[$udom],1);
5600: }
5601: if (ref($courseroles->{$udom}) eq 'HASH') {
5602: foreach my $item (keys(%{$courseroles->{$udom}})) {
5603: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5604: my $area = '/'.$cdom.'/'.$cnum;
5605: my $privkey = "user.priv.$crsrole.$area";
5606: if ($crssec ne '') {
5607: $privkey .= '/'.$crssec;
5608: }
5609: $privkey .= ".$area/$group";
5610: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5611: }
5612: }
5613: return;
5614: }
5615:
1.994 raeburn 5616: sub check_adhoc_privs {
1.1104 raeburn 5617: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5618: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5619: my $setprivs;
1.994 raeburn 5620: if ($env{$cckey}) {
5621: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5622: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5623: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5624: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5625: $setprivs = 1;
1.994 raeburn 5626: }
5627: } else {
1.1088 raeburn 5628: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5629: $setprivs = 1;
1.994 raeburn 5630: }
1.1172.2.9 raeburn 5631: return $setprivs;
1.994 raeburn 5632: }
5633:
5634: sub set_adhoc_privileges {
5635: # role can be cc or ca
1.1088 raeburn 5636: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5637: my $area = '/'.$dcdom.'/'.$pickedcourse;
5638: my $spec = $role.'.'.$area;
5639: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5640: $env{'user.name'},1);
1.994 raeburn 5641: my %ccrole = ();
5642: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5643: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5644: &appenv(\%userroles,[$role,'cm']);
5645: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5646: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5647: &appenv( {'request.role' => $spec,
5648: 'request.role.domain' => $dcdom,
5649: 'request.course.sec' => ''
5650: }
5651: );
5652: my $tadv=0;
5653: if (&allowed('adv') eq 'F') { $tadv=1; }
5654: &appenv({'request.role.adv' => $tadv});
5655: }
1.994 raeburn 5656: }
5657:
1.12 www 5658: # --------------------------------------------------------------- get interface
5659:
5660: sub get {
1.131 albertel 5661: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5662: my $items='';
1.800 albertel 5663: foreach my $item (@$storearr) {
5664: $items.=&escape($item).'&';
1.191 harris41 5665: }
1.12 www 5666: $items=~s/\&$//;
1.620 albertel 5667: if (!$udomain) { $udomain=$env{'user.domain'}; }
5668: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5669: my $uhome=&homeserver($uname,$udomain);
5670:
1.133 albertel 5671: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5672: my @pairs=split(/\&/,$rep);
1.273 albertel 5673: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5674: return @pairs;
5675: }
1.15 www 5676: my %returnhash=();
1.42 www 5677: my $i=0;
1.800 albertel 5678: foreach my $item (@$storearr) {
5679: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5680: $i++;
1.191 harris41 5681: }
1.15 www 5682: return %returnhash;
1.27 www 5683: }
5684:
5685: # --------------------------------------------------------------- del interface
5686:
5687: sub del {
1.133 albertel 5688: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5689: my $items='';
1.800 albertel 5690: foreach my $item (@$storearr) {
5691: $items.=&escape($item).'&';
1.191 harris41 5692: }
1.984 neumanie 5693:
1.27 www 5694: $items=~s/\&$//;
1.620 albertel 5695: if (!$udomain) { $udomain=$env{'user.domain'}; }
5696: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5697: my $uhome=&homeserver($uname,$udomain);
5698: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5699: }
5700:
5701: # -------------------------------------------------------------- dump interface
5702:
1.1172.2.22 raeburn 5703: sub unserialize {
5704: my ($rep, $escapedkeys) = @_;
5705:
5706: return {} if $rep =~ /^error/;
5707:
5708: my %returnhash=();
5709: foreach my $item (split(/\&/,$rep)) {
5710: my ($key, $value) = split(/=/, $item, 2);
5711: $key = unescape($key) unless $escapedkeys;
5712: next if $key =~ /^error: 2 /;
5713: $returnhash{$key} = &thaw_unescape($value);
5714: }
5715: return \%returnhash;
5716: }
5717:
5718: # see Lond::dump_with_regexp
5719: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5720: sub dump {
1.1172.2.22 raeburn 5721: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5722: if (!$udomain) { $udomain=$env{'user.domain'}; }
5723: if (!$uname) { $uname=$env{'user.name'}; }
5724: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5725:
1.1172.2.55 raeburn 5726: if ($regexp) {
5727: $regexp=&escape($regexp);
5728: } else {
5729: $regexp='.';
5730: }
1.1172.2.22 raeburn 5731: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5732: # user is hosted on this machine
1.1172.2.55 raeburn 5733: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5734: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5735: return %{&unserialize($reply, $escapedkeys)};
5736: }
1.1166 raeburn 5737: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5738: my @pairs=split(/\&/,$rep);
5739: my %returnhash=();
1.1098 foxr 5740: if (!($rep =~ /^error/ )) {
5741: foreach my $item (@pairs) {
5742: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5743: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5744: next if ($key =~ /^error: 2 /);
5745: $returnhash{$key}=&thaw_unescape($value);
5746: }
1.755 albertel 5747: }
5748: return %returnhash;
1.407 www 5749: }
5750:
1.1098 foxr 5751:
1.717 albertel 5752: # --------------------------------------------------------- dumpstore interface
5753:
5754: sub dumpstore {
5755: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5756: # same as dump but keys must be escaped. They may contain colon separated
5757: # lists of values that may themself contain colons (e.g. symbs).
5758: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5759: }
5760:
1.407 www 5761: # -------------------------------------------------------------- keys interface
5762:
5763: sub getkeys {
5764: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5765: if (!$udomain) { $udomain=$env{'user.domain'}; }
5766: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5767: my $uhome=&homeserver($uname,$udomain);
5768: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5769: my @keyarray=();
1.800 albertel 5770: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5771: next if ($key =~ /^error: 2 /);
1.800 albertel 5772: push(@keyarray,&unescape($key));
1.407 www 5773: }
5774: return @keyarray;
1.318 matthew 5775: }
5776:
1.319 matthew 5777: # --------------------------------------------------------------- currentdump
5778: sub currentdump {
1.328 matthew 5779: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5780: $courseid = $env{'request.course.id'} if (! defined($courseid));
5781: $sdom = $env{'user.domain'} if (! defined($sdom));
5782: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5783: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 5784: my $rep;
5785:
5786: if (grep { $_ eq $uhome } current_machine_ids()) {
5787: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5788: $courseid)));
5789: } else {
5790: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5791: }
5792:
1.318 matthew 5793: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5794: #
1.318 matthew 5795: my %returnhash=();
1.319 matthew 5796: #
5797: if ($rep eq "unknown_cmd") {
5798: # an old lond will not know currentdump
5799: # Do a dump and make it look like a currentdump
1.822 albertel 5800: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5801: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5802: my %hash = @tmp;
5803: @tmp=();
1.424 matthew 5804: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5805: } else {
5806: my @pairs=split(/\&/,$rep);
1.800 albertel 5807: foreach my $pair (@pairs) {
5808: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5809: my ($symb,$param) = split(/:/,$key);
5810: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5811: &thaw_unescape($value);
1.319 matthew 5812: }
1.191 harris41 5813: }
1.12 www 5814: return %returnhash;
1.424 matthew 5815: }
5816:
5817: sub convert_dump_to_currentdump{
5818: my %hash = %{shift()};
5819: my %returnhash;
5820: # Code ripped from lond, essentially. The only difference
5821: # here is the unescaping done by lonnet::dump(). Conceivably
5822: # we might run in to problems with parameter names =~ /^v\./
5823: while (my ($key,$value) = each(%hash)) {
5824: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5825: $symb = &unescape($symb);
5826: $param = &unescape($param);
1.424 matthew 5827: next if ($v eq 'version' || $symb eq 'keys');
5828: next if (exists($returnhash{$symb}) &&
5829: exists($returnhash{$symb}->{$param}) &&
5830: $returnhash{$symb}->{'v.'.$param} > $v);
5831: $returnhash{$symb}->{$param}=$value;
5832: $returnhash{$symb}->{'v.'.$param}=$v;
5833: }
5834: #
5835: # Remove all of the keys in the hashes which keep track of
5836: # the version of the parameter.
5837: while (my ($symb,$param_hash) = each(%returnhash)) {
5838: # use a foreach because we are going to delete from the hash.
5839: foreach my $key (keys(%$param_hash)) {
5840: delete($param_hash->{$key}) if ($key =~ /^v\./);
5841: }
5842: }
5843: return \%returnhash;
1.12 www 5844: }
5845:
1.627 albertel 5846: # ------------------------------------------------------ critical inc interface
5847:
5848: sub cinc {
5849: return &inc(@_,'critical');
5850: }
5851:
1.449 matthew 5852: # --------------------------------------------------------------- inc interface
5853:
5854: sub inc {
1.627 albertel 5855: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5856: if (!$udomain) { $udomain=$env{'user.domain'}; }
5857: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5858: my $uhome=&homeserver($uname,$udomain);
5859: my $items='';
5860: if (! ref($store)) {
5861: # got a single value, so use that instead
5862: $items = &escape($store).'=&';
5863: } elsif (ref($store) eq 'SCALAR') {
5864: $items = &escape($$store).'=&';
5865: } elsif (ref($store) eq 'ARRAY') {
5866: $items = join('=&',map {&escape($_);} @{$store});
5867: } elsif (ref($store) eq 'HASH') {
5868: while (my($key,$value) = each(%{$store})) {
5869: $items.= &escape($key).'='.&escape($value).'&';
5870: }
5871: }
5872: $items=~s/\&$//;
1.627 albertel 5873: if ($critical) {
5874: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5875: } else {
5876: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5877: }
1.449 matthew 5878: }
5879:
1.12 www 5880: # --------------------------------------------------------------- put interface
5881:
5882: sub put {
1.134 albertel 5883: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5884: if (!$udomain) { $udomain=$env{'user.domain'}; }
5885: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5886: my $uhome=&homeserver($uname,$udomain);
1.12 www 5887: my $items='';
1.800 albertel 5888: foreach my $item (keys(%$storehash)) {
5889: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5890: }
1.12 www 5891: $items=~s/\&$//;
1.134 albertel 5892: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5893: }
5894:
1.631 albertel 5895: # ------------------------------------------------------------ newput interface
5896:
5897: sub newput {
5898: my ($namespace,$storehash,$udomain,$uname)=@_;
5899: if (!$udomain) { $udomain=$env{'user.domain'}; }
5900: if (!$uname) { $uname=$env{'user.name'}; }
5901: my $uhome=&homeserver($uname,$udomain);
5902: my $items='';
5903: foreach my $key (keys(%$storehash)) {
5904: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5905: }
5906: $items=~s/\&$//;
5907: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5908: }
5909:
5910: # --------------------------------------------------------- putstore interface
5911:
1.524 raeburn 5912: sub putstore {
1.1172.2.59 raeburn 5913: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 5914: if (!$udomain) { $udomain=$env{'user.domain'}; }
5915: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5916: my $uhome=&homeserver($uname,$udomain);
5917: my $items='';
1.715 albertel 5918: foreach my $key (keys(%$storehash)) {
5919: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5920: }
1.715 albertel 5921: $items=~s/\&$//;
1.716 albertel 5922: my $esc_symb=&escape($symb);
5923: my $esc_v=&escape($version);
1.715 albertel 5924: my $reply =
1.716 albertel 5925: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5926: $uhome);
1.1172.2.59 raeburn 5927: if (($tolog) && ($reply eq 'ok')) {
5928: my $namevalue='';
5929: foreach my $key (keys(%{$storehash})) {
5930: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5931: }
5932: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
5933: '&host='.&escape($perlvar{'lonHostID'}).
5934: '&version='.$esc_v.
5935: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
5936: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
5937: }
1.715 albertel 5938: if ($reply eq 'unknown_cmd') {
1.716 albertel 5939: # gfall back to way things use to be done
1.715 albertel 5940: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5941: $uname);
1.524 raeburn 5942: }
1.715 albertel 5943: return $reply;
5944: }
5945:
5946: sub old_putstore {
1.716 albertel 5947: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5948: if (!$udomain) { $udomain=$env{'user.domain'}; }
5949: if (!$uname) { $uname=$env{'user.name'}; }
5950: my $uhome=&homeserver($uname,$udomain);
5951: my %newstorehash;
1.800 albertel 5952: foreach my $item (keys(%$storehash)) {
5953: my $key = $version.':'.&escape($symb).':'.$item;
5954: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5955: }
5956: my $items='';
5957: my %allitems = ();
1.800 albertel 5958: foreach my $item (keys(%newstorehash)) {
5959: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5960: my $key = $1.':keys:'.$2;
5961: $allitems{$key} .= $3.':';
5962: }
1.800 albertel 5963: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5964: }
1.800 albertel 5965: foreach my $item (keys(%allitems)) {
5966: $allitems{$item} =~ s/\:$//;
5967: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5968: }
5969: $items=~s/\&$//;
5970: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5971: }
5972:
1.47 www 5973: # ------------------------------------------------------ critical put interface
5974:
5975: sub cput {
1.134 albertel 5976: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5977: if (!$udomain) { $udomain=$env{'user.domain'}; }
5978: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5979: my $uhome=&homeserver($uname,$udomain);
1.47 www 5980: my $items='';
1.800 albertel 5981: foreach my $item (keys(%$storehash)) {
5982: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5983: }
1.47 www 5984: $items=~s/\&$//;
1.134 albertel 5985: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5986: }
5987:
5988: # -------------------------------------------------------------- eget interface
5989:
5990: sub eget {
1.133 albertel 5991: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5992: my $items='';
1.800 albertel 5993: foreach my $item (@$storearr) {
5994: $items.=&escape($item).'&';
1.191 harris41 5995: }
1.12 www 5996: $items=~s/\&$//;
1.620 albertel 5997: if (!$udomain) { $udomain=$env{'user.domain'}; }
5998: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5999: my $uhome=&homeserver($uname,$udomain);
6000: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6001: my @pairs=split(/\&/,$rep);
6002: my %returnhash=();
1.42 www 6003: my $i=0;
1.800 albertel 6004: foreach my $item (@$storearr) {
6005: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6006: $i++;
1.191 harris41 6007: }
1.12 www 6008: return %returnhash;
6009: }
6010:
1.667 albertel 6011: # ------------------------------------------------------------ tmpput interface
6012: sub tmpput {
1.802 raeburn 6013: my ($storehash,$server,$context)=@_;
1.667 albertel 6014: my $items='';
1.800 albertel 6015: foreach my $item (keys(%$storehash)) {
6016: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6017: }
6018: $items=~s/\&$//;
1.802 raeburn 6019: if (defined($context)) {
6020: $items .= ':'.&escape($context);
6021: }
1.667 albertel 6022: return &reply("tmpput:$items",$server);
6023: }
6024:
6025: # ------------------------------------------------------------ tmpget interface
6026: sub tmpget {
1.688 albertel 6027: my ($token,$server)=@_;
6028: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6029: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6030: my %returnhash;
6031: foreach my $item (split(/\&/,$rep)) {
6032: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6033: next if ($key =~ /^error: 2 /);
1.667 albertel 6034: $returnhash{&unescape($key)}=&thaw_unescape($value);
6035: }
6036: return %returnhash;
6037: }
6038:
1.1113 raeburn 6039: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6040: sub tmpdel {
6041: my ($token,$server)=@_;
6042: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6043: return &reply("tmpdel:$token",$server);
6044: }
6045:
1.1172.2.13 raeburn 6046: # ------------------------------------------------------------ get_timebased_id
6047:
6048: sub get_timebased_id {
6049: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6050: $maxtries) = @_;
6051: my ($newid,$error,$dellock);
6052: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6053: return ('','ok','invalid call to get suffix');
6054: }
6055:
6056: # set defaults for any optional args for which values were not supplied
6057: if ($who eq '') {
6058: $who = $env{'user.name'}.':'.$env{'user.domain'};
6059: }
6060: if (!$locktries) {
6061: $locktries = 3;
6062: }
6063: if (!$maxtries) {
6064: $maxtries = 10;
6065: }
6066:
6067: if (($cdom eq '') || ($cnum eq '')) {
6068: if ($env{'request.course.id'}) {
6069: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6070: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6071: }
6072: if (($cdom eq '') || ($cnum eq '')) {
6073: return ('','ok','call to get suffix not in course context');
6074: }
6075: }
6076:
6077: # construct locking item
6078: my $lockhash = {
6079: $prefix."\0".'locked_'.$keyid => $who,
6080: };
6081: my $tries = 0;
6082:
6083: # attempt to get lock on nohist_$namespace file
6084: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6085: while (($gotlock ne 'ok') && $tries <$locktries) {
6086: $tries ++;
6087: sleep 1;
6088: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6089: }
6090:
6091: # attempt to get unique identifier, based on current timestamp
6092: if ($gotlock eq 'ok') {
6093: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6094: my $id = time;
6095: $newid = $id;
1.1172.2.56 raeburn 6096: if ($idtype eq 'addcode') {
6097: $newid .= &sixnum_code();
6098: }
1.1172.2.13 raeburn 6099: my $idtries = 0;
6100: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6101: if ($idtype eq 'concat') {
6102: $newid = $id.$idtries;
1.1172.2.56 raeburn 6103: } elsif ($idtype eq 'addcode') {
6104: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6105: } else {
6106: $newid ++;
6107: }
6108: $idtries ++;
6109: }
6110: if (!exists($inuse{$prefix."\0".$newid})) {
6111: my %new_item = (
6112: $prefix."\0".$newid => $who,
6113: );
6114: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6115: $cdom,$cnum);
6116: if ($putresult ne 'ok') {
6117: undef($newid);
6118: $error = 'error saving new item: '.$putresult;
6119: }
6120: } else {
1.1172.2.56 raeburn 6121: undef($newid);
1.1172.2.13 raeburn 6122: $error = ('error: no unique suffix available for the new item ');
6123: }
6124: # remove lock
6125: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6126: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6127: } else {
6128: $error = "error: could not obtain lockfile\n";
6129: $dellock = 'ok';
1.1172.2.58 raeburn 6130: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6131: $dellock = 'nolock';
6132: }
1.1172.2.13 raeburn 6133: }
6134: return ($newid,$dellock,$error);
6135: }
6136:
1.1172.2.56 raeburn 6137: sub sixnum_code {
6138: my $code;
6139: for (0..6) {
6140: $code .= int( rand(9) );
6141: }
6142: return $code;
6143: }
6144:
1.765 albertel 6145: # -------------------------------------------------- portfolio access checking
6146:
6147: sub portfolio_access {
1.766 albertel 6148: my ($requrl) = @_;
1.765 albertel 6149: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6150: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6151: if ($result) {
6152: my %setters;
6153: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6154: my ($startblock,$endblock) =
6155: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6156: if ($startblock && $endblock) {
6157: return 'B';
6158: }
6159: } else {
6160: my ($startblock,$endblock) =
6161: &Apache::loncommon::blockcheck(\%setters,'port');
6162: if ($startblock && $endblock) {
6163: return 'B';
6164: }
6165: }
6166: }
1.765 albertel 6167: if ($result eq 'ok') {
1.766 albertel 6168: return 'F';
1.765 albertel 6169: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6170: return 'A';
1.765 albertel 6171: }
1.766 albertel 6172: return '';
1.765 albertel 6173: }
6174:
6175: sub get_portfolio_access {
1.767 albertel 6176: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6177:
6178: if (!ref($access_hash)) {
6179: my $current_perms = &get_portfile_permissions($udom,$unum);
6180: my %access_controls = &get_access_controls($current_perms,$group,
6181: $file_name);
6182: $access_hash = $access_controls{$file_name};
6183: }
6184:
1.765 albertel 6185: my ($public,$guest,@domains,@users,@courses,@groups);
6186: my $now = time;
6187: if (ref($access_hash) eq 'HASH') {
6188: foreach my $key (keys(%{$access_hash})) {
6189: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6190: if ($start > $now) {
6191: next;
6192: }
6193: if ($end && $end<$now) {
6194: next;
6195: }
6196: if ($scope eq 'public') {
6197: $public = $key;
6198: last;
6199: } elsif ($scope eq 'guest') {
6200: $guest = $key;
6201: } elsif ($scope eq 'domains') {
6202: push(@domains,$key);
6203: } elsif ($scope eq 'users') {
6204: push(@users,$key);
6205: } elsif ($scope eq 'course') {
6206: push(@courses,$key);
6207: } elsif ($scope eq 'group') {
6208: push(@groups,$key);
6209: }
6210: }
6211: if ($public) {
6212: return 'ok';
6213: }
6214: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6215: if ($guest) {
6216: return $guest;
6217: }
6218: } else {
6219: if (@domains > 0) {
6220: foreach my $domkey (@domains) {
6221: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6222: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6223: return 'ok';
6224: }
6225: }
6226: }
6227: }
6228: if (@users > 0) {
6229: foreach my $userkey (@users) {
1.865 raeburn 6230: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6231: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6232: if (ref($item) eq 'HASH') {
6233: if (($item->{'uname'} eq $env{'user.name'}) &&
6234: ($item->{'udom'} eq $env{'user.domain'})) {
6235: return 'ok';
6236: }
6237: }
6238: }
6239: }
1.765 albertel 6240: }
6241: }
6242: my %roleshash;
6243: my @courses_and_groups = @courses;
6244: push(@courses_and_groups,@groups);
6245: if (@courses_and_groups > 0) {
6246: my (%allgroups,%allroles);
6247: my ($start,$end,$role,$sec,$group);
6248: foreach my $envkey (%env) {
1.1060 raeburn 6249: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6250: my $cid = $2.'_'.$3;
6251: if ($1 eq 'gr') {
6252: $group = $4;
6253: $allgroups{$cid}{$group} = $env{$envkey};
6254: } else {
6255: if ($4 eq '') {
6256: $sec = 'none';
6257: } else {
6258: $sec = $4;
6259: }
6260: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6261: }
1.811 albertel 6262: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6263: my $cid = $2.'_'.$3;
6264: if ($4 eq '') {
6265: $sec = 'none';
6266: } else {
6267: $sec = $4;
6268: }
6269: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6270: }
6271: }
6272: if (keys(%allroles) == 0) {
6273: return;
6274: }
6275: foreach my $key (@courses_and_groups) {
6276: my %content = %{$$access_hash{$key}};
6277: my $cnum = $content{'number'};
6278: my $cdom = $content{'domain'};
6279: my $cid = $cdom.'_'.$cnum;
6280: if (!exists($allroles{$cid})) {
6281: next;
6282: }
6283: foreach my $role_id (keys(%{$content{'roles'}})) {
6284: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6285: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6286: my @status = @{$content{'roles'}{$role_id}{'access'}};
6287: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6288: foreach my $role (keys(%{$allroles{$cid}})) {
6289: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6290: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6291: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6292: if (grep/^all$/,@sections) {
6293: return 'ok';
6294: } else {
6295: if (grep/^$sec$/,@sections) {
6296: return 'ok';
6297: }
6298: }
6299: }
6300: }
6301: if (keys(%{$allgroups{$cid}}) == 0) {
6302: if (grep/^none$/,@groups) {
6303: return 'ok';
6304: }
6305: } else {
6306: if (grep/^all$/,@groups) {
6307: return 'ok';
6308: }
6309: foreach my $group (keys(%{$allgroups{$cid}})) {
6310: if (grep/^$group$/,@groups) {
6311: return 'ok';
6312: }
6313: }
6314: }
6315: }
6316: }
6317: }
6318: }
6319: }
6320: if ($guest) {
6321: return $guest;
6322: }
6323: }
6324: }
6325: return;
6326: }
6327:
6328: sub course_group_datechecker {
6329: my ($dates,$now,$status) = @_;
6330: my ($start,$end) = split(/\./,$dates);
6331: if (!$start && !$end) {
6332: return 'ok';
6333: }
6334: if (grep/^active$/,@{$status}) {
6335: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6336: return 'ok';
6337: }
6338: }
6339: if (grep/^previous$/,@{$status}) {
6340: if ($end > $now ) {
6341: return 'ok';
6342: }
6343: }
6344: if (grep/^future$/,@{$status}) {
6345: if ($start > $now) {
6346: return 'ok';
6347: }
6348: }
6349: return;
6350: }
6351:
6352: sub parse_portfolio_url {
6353: my ($url) = @_;
6354:
6355: my ($type,$udom,$unum,$group,$file_name);
6356:
1.823 albertel 6357: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6358: $type = 1;
6359: $udom = $1;
6360: $unum = $2;
6361: $file_name = $3;
1.823 albertel 6362: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6363: $type = 2;
6364: $udom = $1;
6365: $unum = $2;
6366: $group = $3;
6367: $file_name = $3.'/'.$4;
6368: }
6369: if (wantarray) {
6370: return ($type,$udom,$unum,$file_name,$group);
6371: }
6372: return $type;
6373: }
6374:
6375: sub is_portfolio_url {
6376: my ($url) = @_;
6377: return scalar(&parse_portfolio_url($url));
6378: }
6379:
1.798 raeburn 6380: sub is_portfolio_file {
6381: my ($file) = @_;
1.820 raeburn 6382: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6383: return 1;
6384: }
6385: return;
6386: }
6387:
1.976 raeburn 6388: sub usertools_access {
1.1084 raeburn 6389: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6390: my ($access,%tools);
6391: if ($context eq '') {
6392: $context = 'tools';
6393: }
6394: if ($context eq 'requestcourses') {
6395: %tools = (
6396: official => 1,
6397: unofficial => 1,
1.1006 raeburn 6398: community => 1,
1.1172.2.37 raeburn 6399: textbook => 1,
1.985 raeburn 6400: );
1.1172.2.9 raeburn 6401: } elsif ($context eq 'requestauthor') {
6402: %tools = (
6403: requestauthor => 1,
6404: );
1.985 raeburn 6405: } else {
6406: %tools = (
6407: aboutme => 1,
6408: blog => 1,
1.1172.2.6 raeburn 6409: webdav => 1,
1.985 raeburn 6410: portfolio => 1,
6411: );
6412: }
1.976 raeburn 6413: return if (!defined($tools{$tool}));
6414:
1.1172.2.35 raeburn 6415: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6416: $udom = $env{'user.domain'};
6417: $uname = $env{'user.name'};
6418: }
6419:
1.978 raeburn 6420: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6421: if ($action ne 'reload') {
1.985 raeburn 6422: if ($context eq 'requestcourses') {
6423: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6424: } elsif ($context eq 'requestauthor') {
6425: return $env{'environment.canrequest.author'};
1.985 raeburn 6426: } else {
6427: return $env{'environment.availabletools.'.$tool};
6428: }
6429: }
1.976 raeburn 6430: }
6431:
1.1172.2.9 raeburn 6432: my ($toolstatus,$inststatus,$envkey);
6433: if ($context eq 'requestauthor') {
6434: $envkey = $context;
6435: } else {
6436: $envkey = $context.'.'.$tool;
6437: }
1.976 raeburn 6438:
1.985 raeburn 6439: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6440: ($action ne 'reload')) {
1.1172.2.9 raeburn 6441: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6442: $inststatus = $env{'environment.inststatus'};
6443: } else {
1.1084 raeburn 6444: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6445: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6446: $inststatus = $userenvref->{'inststatus'};
6447: } else {
1.1172.2.9 raeburn 6448: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6449: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6450: $inststatus = $userenv{'inststatus'};
6451: }
1.976 raeburn 6452: }
6453:
6454: if ($toolstatus ne '') {
6455: if ($toolstatus) {
6456: $access = 1;
6457: } else {
6458: $access = 0;
6459: }
6460: return $access;
6461: }
6462:
1.1084 raeburn 6463: my ($is_adv,%domdef);
6464: if (ref($is_advref) eq 'HASH') {
6465: $is_adv = $is_advref->{'is_adv'};
6466: } else {
6467: $is_adv = &is_advanced_user($udom,$uname);
6468: }
6469: if (ref($domdefref) eq 'HASH') {
6470: %domdef = %{$domdefref};
6471: } else {
6472: %domdef = &get_domain_defaults($udom);
6473: }
1.976 raeburn 6474: if (ref($domdef{$tool}) eq 'HASH') {
6475: if ($is_adv) {
6476: if ($domdef{$tool}{'_LC_adv'} ne '') {
6477: if ($domdef{$tool}{'_LC_adv'}) {
6478: $access = 1;
6479: } else {
6480: $access = 0;
6481: }
6482: return $access;
6483: }
6484: }
6485: if ($inststatus ne '') {
6486: my ($hasaccess,$hasnoaccess);
6487: foreach my $affiliation (split(/:/,$inststatus)) {
6488: if ($domdef{$tool}{$affiliation} ne '') {
6489: if ($domdef{$tool}{$affiliation}) {
6490: $hasaccess = 1;
6491: } else {
6492: $hasnoaccess = 1;
6493: }
6494: }
6495: }
6496: if ($hasaccess || $hasnoaccess) {
6497: if ($hasaccess) {
6498: $access = 1;
6499: } elsif ($hasnoaccess) {
6500: $access = 0;
6501: }
6502: return $access;
6503: }
6504: } else {
6505: if ($domdef{$tool}{'default'} ne '') {
6506: if ($domdef{$tool}{'default'}) {
6507: $access = 1;
6508: } elsif ($domdef{$tool}{'default'} == 0) {
6509: $access = 0;
6510: }
6511: return $access;
6512: }
6513: }
6514: } else {
1.1172.2.6 raeburn 6515: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6516: $access = 1;
6517: } else {
6518: $access = 0;
6519: }
1.976 raeburn 6520: return $access;
6521: }
6522: }
6523:
1.1050 raeburn 6524: sub is_course_owner {
6525: my ($cdom,$cnum,$udom,$uname) = @_;
6526: if (($udom eq '') || ($uname eq '')) {
6527: $udom = $env{'user.domain'};
6528: $uname = $env{'user.name'};
6529: }
6530: unless (($udom eq '') || ($uname eq '')) {
6531: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6532: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6533: return 1;
6534: } else {
6535: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6536: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6537: return 1;
6538: }
6539: }
6540: }
6541: }
6542: return;
6543: }
6544:
1.976 raeburn 6545: sub is_advanced_user {
6546: my ($udom,$uname) = @_;
1.1085 raeburn 6547: if ($udom ne '' && $uname ne '') {
6548: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6549: if (wantarray) {
6550: return ($env{'user.adv'},$env{'user.author'});
6551: } else {
6552: return $env{'user.adv'};
6553: }
1.1085 raeburn 6554: }
6555: }
1.976 raeburn 6556: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6557: my %allroles;
1.1128 raeburn 6558: my ($is_adv,$is_author);
1.976 raeburn 6559: foreach my $role (keys(%roleshash)) {
6560: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6561: my $area = '/'.$tdomain.'/'.$trest;
6562: if ($sec ne '') {
6563: $area .= '/'.$sec;
6564: }
6565: if (($area ne '') && ($trole ne '')) {
6566: my $spec=$trole.'.'.$area;
6567: if ($trole =~ /^cr\//) {
6568: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6569: } elsif ($trole ne 'gr') {
6570: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6571: }
1.1128 raeburn 6572: if ($trole eq 'au') {
6573: $is_author = 1;
6574: }
1.976 raeburn 6575: }
6576: }
6577: foreach my $role (keys(%allroles)) {
6578: last if ($is_adv);
6579: foreach my $item (split(/:/,$allroles{$role})) {
6580: if ($item ne '') {
6581: my ($privilege,$restrictions)=split(/&/,$item);
6582: if ($privilege eq 'adv') {
6583: $is_adv = 1;
6584: last;
6585: }
6586: }
6587: }
6588: }
1.1128 raeburn 6589: if (wantarray) {
6590: return ($is_adv,$is_author);
6591: }
1.976 raeburn 6592: return $is_adv;
6593: }
1.798 raeburn 6594:
1.1035 raeburn 6595: sub check_can_request {
1.1036 raeburn 6596: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6597: my $canreq = 0;
6598: my ($types,$typename) = &Apache::loncommon::course_types();
6599: my @options = ('approval','validate','autolimit');
6600: my $optregex = join('|',@options);
6601: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6602: foreach my $type (@{$types}) {
6603: if (&usertools_access($env{'user.name'},
6604: $env{'user.domain'},
6605: $type,undef,'requestcourses')) {
6606: $canreq ++;
1.1036 raeburn 6607: if (ref($request_domains) eq 'HASH') {
6608: push(@{$request_domains->{$type}},$env{'user.domain'});
6609: }
1.1035 raeburn 6610: if ($dom eq $env{'user.domain'}) {
6611: $can_request->{$type} = 1;
6612: }
6613: }
6614: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6615: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6616: if (@curr > 0) {
1.1036 raeburn 6617: foreach my $item (@curr) {
6618: if (ref($request_domains) eq 'HASH') {
6619: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6620: if ($otherdom ne '') {
6621: if (ref($request_domains->{$type}) eq 'ARRAY') {
6622: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6623: push(@{$request_domains->{$type}},$otherdom);
6624: }
6625: } else {
6626: push(@{$request_domains->{$type}},$otherdom);
6627: }
6628: }
6629: }
6630: }
6631: unless($dom eq $env{'user.domain'}) {
6632: $canreq ++;
1.1035 raeburn 6633: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6634: $can_request->{$type} = 1;
6635: }
6636: }
6637: }
6638: }
6639: }
6640: }
6641: return $canreq;
6642: }
6643:
1.341 www 6644: # ---------------------------------------------- Custom access rule evaluation
6645:
6646: sub customaccess {
6647: my ($priv,$uri)=@_;
1.807 albertel 6648: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6649: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6650: $udom = &LONCAPA::clean_domain($udom);
6651: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6652: my $access=0;
1.800 albertel 6653: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6654: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6655: if ($type eq 'user') {
6656: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6657: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6658: if ($tdom) {
6659: if ($tdom ne $env{'user.domain'}) { next; }
6660: }
1.896 albertel 6661: if ($tuname) {
6662: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6663: }
6664: $access=($effect eq 'allow');
6665: last;
6666: }
6667: } else {
6668: if ($role) {
6669: if ($role ne $urole) { next; }
6670: }
6671: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6672: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6673: if ($tdom) {
6674: if ($tdom ne $udom) { next; }
6675: }
6676: if ($tcrs) {
6677: if ($tcrs ne $ucrs) { next; }
6678: }
6679: if ($tsec) {
6680: if ($tsec ne $usec) { next; }
6681: }
6682: $access=($effect eq 'allow');
6683: last;
6684: }
6685: if ($realm eq '' && $role eq '') {
6686: $access=($effect eq 'allow');
6687: }
1.402 bowersj2 6688: }
1.341 www 6689: }
6690: return $access;
6691: }
6692:
1.103 harris41 6693: # ------------------------------------------------- Check for a user privilege
1.12 www 6694:
6695: sub allowed {
1.810 raeburn 6696: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6697: my $ver_orguri=$uri;
1.439 www 6698: $uri=&deversion($uri);
1.152 www 6699: my $orguri=$uri;
1.52 www 6700: $uri=&declutter($uri);
1.809 raeburn 6701:
1.810 raeburn 6702: if ($priv eq 'evb') {
6703: # Evade communication block restrictions for specified role in a course
6704: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6705: return $1;
6706: } else {
6707: return;
6708: }
6709: }
6710:
1.620 albertel 6711: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6712: # Free bre access to adm and meta resources
1.775 albertel 6713: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6714: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6715: && ($priv eq 'bre')) {
1.14 www 6716: return 'F';
1.159 www 6717: }
6718:
1.545 banghart 6719: # Free bre access to user's own portfolio contents
1.714 raeburn 6720: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6721: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6722: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6723: my %setters;
6724: my ($startblock,$endblock) =
6725: &Apache::loncommon::blockcheck(\%setters,'port');
6726: if ($startblock && $endblock) {
6727: return 'B';
6728: } else {
6729: return 'F';
6730: }
1.545 banghart 6731: }
6732:
1.762 raeburn 6733: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6734: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6735: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6736: if (exists($env{'request.course.id'})) {
6737: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6738: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6739: if (($domain eq $cdom) && ($name eq $cnum)) {
6740: my $courseprivid=$env{'request.course.id'};
6741: $courseprivid=~s/\_/\//;
6742: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6743: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6744: return $1;
1.762 raeburn 6745: } else {
6746: if ($env{'request.course.sec'}) {
6747: $courseprivid.='/'.$env{'request.course.sec'};
6748: }
6749: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6750: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6751: return $2;
6752: }
1.714 raeburn 6753: }
6754: }
6755: }
6756: }
6757:
1.159 www 6758: # Free bre to public access
6759:
6760: if ($priv eq 'bre') {
1.238 www 6761: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6762: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6763: return 'F';
6764: }
1.238 www 6765: if ($copyright eq 'priv') {
6766: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6767: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6768: return '';
6769: }
6770: }
6771: if ($copyright eq 'domain') {
6772: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6773: unless (($env{'user.domain'} eq $1) ||
6774: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6775: return '';
6776: }
1.262 matthew 6777: }
1.620 albertel 6778: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6779: # Library role, so allow browsing of resources in this domain.
6780: return 'F';
1.238 www 6781: }
1.341 www 6782: if ($copyright eq 'custom') {
6783: unless (&customaccess($priv,$uri)) { return ''; }
6784: }
1.14 www 6785: }
1.264 matthew 6786: # Domain coordinator is trying to create a course
1.620 albertel 6787: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6788: # uri is the requested domain in this case.
6789: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6790: # a role of dc for the domain in question.
1.620 albertel 6791: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6792: }
1.29 www 6793:
1.52 www 6794: my $thisallowed='';
6795: my $statecond=0;
6796: my $courseprivid='';
6797:
1.1039 raeburn 6798: my $ownaccess;
1.1043 raeburn 6799: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6800: if (($priv eq 'bro') && ($env{'user.author'})) {
6801: if ($uri eq '') {
6802: $ownaccess = 1;
6803: } else {
6804: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6805: my $udom = $env{'user.domain'};
6806: my $uname = $env{'user.name'};
6807: if ($uri =~ m{^\Q$udom\E/?$}) {
6808: $ownaccess = 1;
1.1040 raeburn 6809: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6810: unless ($uri =~ m{\.\./}) {
6811: $ownaccess = 1;
6812: }
6813: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6814: my $now = time;
6815: if ($uri =~ m{^([^/]+)/?$}) {
6816: my $adom = $1;
6817: foreach my $key (keys(%env)) {
1.1042 raeburn 6818: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6819: my ($start,$end) = split('.',$env{$key});
6820: if (($now >= $start) && (!$end || $end < $now)) {
6821: $ownaccess = 1;
6822: last;
6823: }
6824: }
6825: }
6826: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6827: my $adom = $1;
6828: my $aname = $2;
1.1042 raeburn 6829: foreach my $role ('ca','aa') {
6830: if ($env{"user.role.$role./$adom/$aname"}) {
6831: my ($start,$end) =
6832: split('.',$env{"user.role.$role./$adom/$aname"});
6833: if (($now >= $start) && (!$end || $end < $now)) {
6834: $ownaccess = 1;
6835: last;
6836: }
1.1039 raeburn 6837: }
6838: }
6839: }
6840: }
6841: }
6842: }
6843: }
6844:
1.52 www 6845: # Course
6846:
1.620 albertel 6847: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6848: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6849: $thisallowed.=$1;
6850: }
1.52 www 6851: }
1.29 www 6852:
1.52 www 6853: # Domain
6854:
1.620 albertel 6855: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6856: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6857: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6858: $thisallowed.=$1;
6859: }
1.12 www 6860: }
1.52 www 6861:
1.1141 raeburn 6862: # User who is not author or co-author might still be able to edit
6863: # resource of an author in the domain (e.g., if Domain Coordinator).
6864: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6865: (&allowed('mdc',$env{'request.course.id'}))) {
6866: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6867: $thisallowed.=$1;
6868: }
6869: }
6870:
1.52 www 6871: # Course: uri itself is a course
1.66 www 6872: my $courseuri=$uri;
6873: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6874: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6875:
1.620 albertel 6876: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6877: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6878: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6879: $thisallowed.=$1;
6880: }
1.12 www 6881: }
1.29 www 6882:
1.665 albertel 6883: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6884: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6885: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6886: $thisallowed='';
1.671 raeburn 6887: my ($match)=&is_on_map($uri);
6888: if ($match) {
6889: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6890: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6891: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6892: if (@blockers > 0) {
6893: $thisallowed = 'B';
6894: } else {
6895: $thisallowed.=$1;
6896: }
1.671 raeburn 6897: }
6898: } else {
1.705 albertel 6899: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6900: if ($refuri) {
6901: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6902: $thisallowed='F';
1.671 raeburn 6903: } else {
6904: $refuri=&declutter($refuri);
6905: my ($match) = &is_on_map($refuri);
6906: if ($match) {
1.1162 raeburn 6907: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6908: if (@blockers > 0) {
6909: $thisallowed = 'B';
6910: } else {
6911: $thisallowed='F';
6912: }
1.671 raeburn 6913: }
1.669 raeburn 6914: }
1.671 raeburn 6915: }
6916: }
1.314 www 6917: }
1.492 albertel 6918:
1.766 albertel 6919: if ($priv eq 'bre'
6920: && $thisallowed ne 'F'
6921: && $thisallowed ne '2'
6922: && &is_portfolio_url($uri)) {
6923: $thisallowed = &portfolio_access($uri);
6924: }
6925:
1.52 www 6926: # Full access at system, domain or course-wide level? Exit.
1.29 www 6927: if ($thisallowed=~/F/) {
6928: return 'F';
6929: }
6930:
1.52 www 6931: # If this is generating or modifying users, exit with special codes
1.29 www 6932:
1.643 www 6933: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6934: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6935: my ($audom,$auname)=split('/',$uri);
1.643 www 6936: # no author name given, so this just checks on the general right to make a co-author in this domain
6937: unless ($auname) { return $thisallowed; }
6938: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6939: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6940: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6941: ($audom ne $env{'request.role.domain'}))) { return ''; }
6942: }
1.52 www 6943: return $thisallowed;
6944: }
6945: #
1.103 harris41 6946: # Gathered so far: system, domain and course wide privileges
1.52 www 6947: #
6948: # Course: See if uri or referer is an individual resource that is part of
6949: # the course
6950:
1.620 albertel 6951: if ($env{'request.course.id'}) {
1.232 www 6952:
1.620 albertel 6953: $courseprivid=$env{'request.course.id'};
6954: if ($env{'request.course.sec'}) {
6955: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6956: }
6957: $courseprivid=~s/\_/\//;
6958: my $checkreferer=1;
1.232 www 6959: my ($match,$cond)=&is_on_map($uri);
6960: if ($match) {
6961: $statecond=$cond;
1.620 albertel 6962: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6963: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6964: my $value = $1;
6965: if ($priv eq 'bre') {
6966: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6967: if (@blockers > 0) {
6968: $thisallowed = 'B';
6969: } else {
6970: $thisallowed.=$value;
6971: }
6972: } else {
6973: $thisallowed.=$value;
6974: }
1.52 www 6975: $checkreferer=0;
6976: }
1.29 www 6977: }
1.83 www 6978:
1.148 www 6979: if ($checkreferer) {
1.620 albertel 6980: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6981: unless ($refuri) {
1.800 albertel 6982: foreach my $key (keys(%env)) {
6983: if ($key=~/^httpref\..*\*/) {
6984: my $pattern=$key;
1.156 www 6985: $pattern=~s/^httpref\.\/res\///;
1.148 www 6986: $pattern=~s/\*/\[\^\/\]\+/g;
6987: $pattern=~s/\//\\\//g;
1.152 www 6988: if ($orguri=~/$pattern/) {
1.800 albertel 6989: $refuri=$env{$key};
1.148 www 6990: }
6991: }
1.191 harris41 6992: }
1.148 www 6993: }
1.232 www 6994:
1.148 www 6995: if ($refuri) {
1.152 www 6996: $refuri=&declutter($refuri);
1.232 www 6997: my ($match,$cond)=&is_on_map($refuri);
6998: if ($match) {
6999: my $refstatecond=$cond;
1.620 albertel 7000: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7001: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7002: my $value = $1;
7003: if ($priv eq 'bre') {
7004: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7005: if (@blockers > 0) {
7006: $thisallowed = 'B';
7007: } else {
7008: $thisallowed.=$value;
7009: }
7010: } else {
7011: $thisallowed.=$value;
7012: }
1.53 www 7013: $uri=$refuri;
7014: $statecond=$refstatecond;
1.52 www 7015: }
7016: }
1.148 www 7017: }
1.29 www 7018: }
1.52 www 7019: }
1.29 www 7020:
1.52 www 7021: #
1.103 harris41 7022: # Gathered now: all privileges that could apply, and condition number
1.52 www 7023: #
7024: #
7025: # Full or no access?
7026: #
1.29 www 7027:
1.52 www 7028: if ($thisallowed=~/F/) {
7029: return 'F';
7030: }
1.29 www 7031:
1.52 www 7032: unless ($thisallowed) {
7033: return '';
7034: }
1.29 www 7035:
1.52 www 7036: # Restrictions exist, deal with them
7037: #
7038: # C:according to course preferences
7039: # R:according to resource settings
7040: # L:unless locked
7041: # X:according to user session state
7042: #
7043:
7044: # Possibly locked functionality, check all courses
1.54 www 7045: # Locks might take effect only after 10 minutes cache expiration for other
7046: # courses, and 2 minutes for current course
1.52 www 7047:
7048: my $envkey;
7049: if ($thisallowed=~/L/) {
1.1000 raeburn 7050: foreach $envkey (keys(%env)) {
1.54 www 7051: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7052: my $courseid=$2;
7053: my $roleid=$1.'.'.$2;
1.92 www 7054: $courseid=~s/^\///;
1.54 www 7055: my $expiretime=600;
1.620 albertel 7056: if ($env{'request.role'} eq $roleid) {
1.54 www 7057: $expiretime=120;
7058: }
7059: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7060: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7061: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7062: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7063: }
1.620 albertel 7064: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7065: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7066: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7067: &log($env{'user.domain'},$env{'user.name'},
7068: $env{'user.home'},
1.57 www 7069: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7070: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7071: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7072: return '';
7073: }
7074: }
1.620 albertel 7075: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7076: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7077: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7078: &log($env{'user.domain'},$env{'user.name'},
7079: $env{'user.home'},
1.57 www 7080: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7081: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7082: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7083: return '';
7084: }
7085: }
7086: }
1.29 www 7087: }
1.52 www 7088: }
7089:
7090: #
7091: # Rest of the restrictions depend on selected course
7092: #
7093:
1.620 albertel 7094: unless ($env{'request.course.id'}) {
1.766 albertel 7095: if ($thisallowed eq 'A') {
7096: return 'A';
1.814 raeburn 7097: } elsif ($thisallowed eq 'B') {
7098: return 'B';
1.766 albertel 7099: } else {
7100: return '1';
7101: }
1.52 www 7102: }
1.29 www 7103:
1.52 www 7104: #
7105: # Now user is definitely in a course
7106: #
1.53 www 7107:
7108:
7109: # Course preferences
7110:
7111: if ($thisallowed=~/C/) {
1.620 albertel 7112: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7113: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7114: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7115: =~/\Q$rolecode\E/) {
1.1103 raeburn 7116: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7117: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7118: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7119: $env{'request.course.id'});
7120: }
1.237 www 7121: return '';
7122: }
7123:
1.620 albertel 7124: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7125: =~/\Q$unamedom\E/) {
1.1103 raeburn 7126: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7127: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7128: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7129: $env{'request.course.id'});
7130: }
1.54 www 7131: return '';
7132: }
1.53 www 7133: }
7134:
7135: # Resource preferences
7136:
7137: if ($thisallowed=~/R/) {
1.620 albertel 7138: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7139: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7140: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7141: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7142: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7143: }
7144: return '';
1.54 www 7145: }
1.53 www 7146: }
1.30 www 7147:
1.246 www 7148: # Restricted by state or randomout?
1.30 www 7149:
1.52 www 7150: if ($thisallowed=~/X/) {
1.620 albertel 7151: if ($env{'acc.randomout'}) {
1.579 albertel 7152: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7153: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7154: return '';
7155: }
1.247 www 7156: }
7157: if (&condval($statecond)) {
1.52 www 7158: return '2';
7159: } else {
7160: return '';
7161: }
7162: }
1.30 www 7163:
1.766 albertel 7164: if ($thisallowed eq 'A') {
7165: return 'A';
1.814 raeburn 7166: } elsif ($thisallowed eq 'B') {
7167: return 'B';
1.766 albertel 7168: }
1.52 www 7169: return 'F';
1.232 www 7170: }
1.1162 raeburn 7171:
1.1172.2.13 raeburn 7172: # ------------------------------------------- Check construction space access
7173:
7174: sub constructaccess {
7175: my ($url,$setpriv)=@_;
7176:
7177: # We do not allow editing of previous versions of files
7178: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7179:
7180: # Get username and domain from URL
7181: my ($ownername,$ownerdomain,$ownerhome);
7182:
7183: ($ownerdomain,$ownername) =
7184: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7185:
7186: # The URL does not really point to any authorspace, forget it
7187: unless (($ownername) && ($ownerdomain)) { return ''; }
7188:
7189: # Now we need to see if the user has access to the authorspace of
7190: # $ownername at $ownerdomain
7191:
7192: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7193: # Real author for this?
7194: $ownerhome = $env{'user.home'};
7195: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7196: return ($ownername,$ownerdomain,$ownerhome);
7197: }
7198: } else {
7199: # Co-author for this?
7200: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7201: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7202: $ownerhome = &homeserver($ownername,$ownerdomain);
7203: return ($ownername,$ownerdomain,$ownerhome);
7204: }
7205: }
7206:
7207: # We don't have any access right now. If we are not possibly going to do anything about this,
7208: # we might as well leave
7209: unless ($setpriv) { return ''; }
7210:
7211: # Backdoor access?
7212: my $allowed=&allowed('eco',$ownerdomain);
7213: # Nope
7214: unless ($allowed) { return ''; }
7215: # Looks like we may have access, but could be locked by the owner of the construction space
7216: if ($allowed eq 'U') {
7217: my %blocked=&get('environment',['domcoord.author'],
7218: $ownerdomain,$ownername);
7219: # Is blocked by owner
7220: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7221: }
7222: if (($allowed eq 'F') || ($allowed eq 'U')) {
7223: # Grant temporary access
7224: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7225: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7226: if (!$update) { $update = $then; }
7227: my $refresh=$env{'user.refresh.time'};
7228: if (!$refresh) { $refresh = $update; }
7229: my $now = time;
7230: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7231: $now,'ca','constructaccess');
7232: $ownerhome = &homeserver($ownername,$ownerdomain);
7233: return($ownername,$ownerdomain,$ownerhome);
7234: }
7235: # No business here
7236: return '';
7237: }
7238:
1.1162 raeburn 7239: sub get_comm_blocks {
7240: my ($cdom,$cnum) = @_;
7241: if ($cdom eq '' || $cnum eq '') {
7242: return unless ($env{'request.course.id'});
7243: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7244: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7245: }
7246: my %commblocks;
7247: my $hashid=$cdom.'_'.$cnum;
7248: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7249: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7250: %commblocks = %{$blocksref};
7251: } else {
7252: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7253: my $cachetime = 600;
7254: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7255: }
7256: return %commblocks;
7257: }
7258:
7259: sub has_comm_blocking {
7260: my ($priv,$symb,$uri,$blocks) = @_;
7261: return unless ($env{'request.course.id'});
7262: return unless ($priv eq 'bre');
7263: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7264: my %commblocks;
7265: if (ref($blocks) eq 'HASH') {
7266: %commblocks = %{$blocks};
7267: } else {
7268: %commblocks = &get_comm_blocks();
7269: }
7270: return unless (keys(%commblocks) > 0);
7271: if (!$symb) { $symb=&symbread($uri,1); }
7272: my ($map,$resid,undef)=&decode_symb($symb);
7273: my %tocheck = (
7274: maps => $map,
7275: resources => $symb,
7276: );
7277: my @blockers;
7278: my $now = time;
1.1163 raeburn 7279: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7280: foreach my $block (keys(%commblocks)) {
7281: if ($block =~ /^(\d+)____(\d+)$/) {
7282: my ($start,$end) = ($1,$2);
7283: if ($start <= $now && $end >= $now) {
7284: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7285: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7286: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7287: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7288: unless (grep(/^\Q$block\E$/,@blockers)) {
7289: push(@blockers,$block);
7290: }
7291: }
7292: }
7293: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7294: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7295: unless (grep(/^\Q$block\E$/,@blockers)) {
7296: push(@blockers,$block);
7297: }
7298: }
7299: }
7300: }
7301: }
7302: }
7303: } elsif ($block =~ /^firstaccess____(.+)$/) {
7304: my $item = $1;
1.1163 raeburn 7305: my @to_test;
1.1162 raeburn 7306: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7307: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7308: my $check_interval;
7309: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7310: my @interval;
7311: my $type = 'map';
7312: if ($item eq 'course') {
7313: $type = 'course';
7314: @interval=&EXT("resource.0.interval");
7315: } else {
7316: if ($item =~ /___\d+___/) {
7317: $type = 'resource';
7318: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7319: if (ref($navmap)) {
7320: my $res = $navmap->getBySymb($item);
7321: push(@to_test,$res);
7322: }
1.1162 raeburn 7323: } else {
7324: my $mapsymb = &symbread($item,1);
7325: if ($mapsymb) {
7326: if (ref($navmap)) {
7327: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7328: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7329: foreach my $res (@to_test) {
1.1162 raeburn 7330: my $symb = $res->symb();
7331: next if ($symb eq $mapsymb);
7332: if ($symb ne '') {
7333: @interval=&EXT("resource.0.interval",$symb);
7334: last;
7335: }
7336: }
7337: }
7338: }
7339: }
7340: }
7341: if ($interval[0] =~ /\d+/) {
7342: my $first_access;
7343: if ($type eq 'resource') {
7344: $first_access=&get_first_access($interval[1],$item);
7345: } elsif ($type eq 'map') {
7346: $first_access=&get_first_access($interval[1],undef,$item);
7347: } else {
7348: $first_access=&get_first_access($interval[1]);
7349: }
7350: if ($first_access) {
7351: my $timesup = $first_access+$interval[0];
7352: if ($timesup > $now) {
1.1163 raeburn 7353: foreach my $res (@to_test) {
7354: if ($res->is_problem()) {
7355: if ($res->completable()) {
7356: unless (grep(/^\Q$block\E$/,@blockers)) {
7357: push(@blockers,$block);
7358: }
7359: last;
7360: }
7361: }
1.1162 raeburn 7362: }
7363: }
7364: }
7365: }
7366: }
7367: }
7368: }
7369: }
7370: }
7371: return @blockers;
7372: }
7373:
7374: sub check_docs_block {
7375: my ($docsblock,$tocheck) =@_;
7376: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7377: return;
7378: }
7379: if (ref($docsblock->{'maps'}) eq 'HASH') {
7380: if ($tocheck->{'maps'}) {
7381: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7382: return 1;
7383: }
7384: }
7385: }
7386: if (ref($docsblock->{'resources'}) eq 'HASH') {
7387: if ($tocheck->{'resources'}) {
7388: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7389: return 1;
7390: }
7391: }
7392: }
7393: return;
7394: }
7395:
1.1133 foxr 7396: #
7397: # Removes the versino from a URI and
7398: # splits it in to its filename and path to the filename.
7399: # Seems like File::Basename could have done this more clearly.
7400: # Parameters:
7401: # $uri - input URI
7402: # Returns:
7403: # Two element list consisting of
7404: # $pathname - the URI up to and excluding the trailing /
7405: # $filename - The part of the URI following the last /
7406: # NOTE:
7407: # Another realization of this is simply:
7408: # use File::Basename;
7409: # ...
7410: # $uri = shift;
7411: # $filename = basename($uri);
7412: # $path = dirname($uri);
7413: # return ($filename, $path);
7414: #
7415: # The implementation below is probably faster however.
7416: #
1.710 albertel 7417: sub split_uri_for_cond {
7418: my $uri=&deversion(&declutter(shift));
7419: my @uriparts=split(/\//,$uri);
7420: my $filename=pop(@uriparts);
7421: my $pathname=join('/',@uriparts);
7422: return ($pathname,$filename);
7423: }
1.232 www 7424: # --------------------------------------------------- Is a resource on the map?
7425:
7426: sub is_on_map {
1.710 albertel 7427: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7428: #Trying to find the conditional for the file
1.620 albertel 7429: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7430: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7431: if ($match) {
1.289 bowersj2 7432: return (1,$1);
7433: } else {
1.434 www 7434: return (0,0);
1.289 bowersj2 7435: }
1.12 www 7436: }
7437:
1.427 www 7438: # --------------------------------------------------------- Get symb from alias
7439:
7440: sub get_symb_from_alias {
7441: my $symb=shift;
7442: my ($map,$resid,$url)=&decode_symb($symb);
7443: # Already is a symb
7444: if ($url) { return $symb; }
7445: # Must be an alias
7446: my $aliassymb='';
7447: my %bighash;
1.620 albertel 7448: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7449: &GDBM_READER(),0640)) {
7450: my $rid=$bighash{'mapalias_'.$symb};
7451: if ($rid) {
7452: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7453: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7454: $resid,$bighash{'src_'.$rid});
1.427 www 7455: }
7456: untie %bighash;
7457: }
7458: return $aliassymb;
7459: }
7460:
1.12 www 7461: # ----------------------------------------------------------------- Define Role
7462:
7463: sub definerole {
7464: if (allowed('mcr','/')) {
7465: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7466: foreach my $role (split(':',$sysrole)) {
7467: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7468: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7469: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7470: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7471: return "refused:s:$crole&$cqual";
7472: }
7473: }
1.191 harris41 7474: }
1.800 albertel 7475: foreach my $role (split(':',$domrole)) {
7476: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7477: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7478: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7479: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7480: return "refused:d:$crole&$cqual";
7481: }
7482: }
1.191 harris41 7483: }
1.800 albertel 7484: foreach my $role (split(':',$courole)) {
7485: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7486: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7487: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7488: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7489: return "refused:c:$crole&$cqual";
7490: }
7491: }
1.191 harris41 7492: }
1.620 albertel 7493: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7494: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7495: "rolesdef_$rolename=".
7496: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7497: return reply($command,$env{'user.home'});
1.12 www 7498: } else {
7499: return 'refused';
7500: }
1.105 harris41 7501: }
7502:
7503: # ---------------- Make a metadata query against the network of library servers
7504:
7505: sub metadata_query {
1.1172.2.33 raeburn 7506: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7507: my %rhash;
1.845 albertel 7508: my %libserv = &all_library();
1.244 matthew 7509: my @server_list = (defined($server_array) ? @$server_array
7510: : keys(%libserv) );
7511: for my $server (@server_list) {
1.1172.2.33 raeburn 7512: my $domains = '';
7513: if (ref($domains_hash) eq 'HASH') {
7514: $domains = $domains_hash->{$server};
7515: }
1.118 harris41 7516: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7517: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7518: $rhash{$server}=$reply;
7519: }
7520: else {
7521: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7522: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7523: $server);
7524: $rhash{$server}=$reply;
7525: }
1.112 harris41 7526: }
1.118 harris41 7527: return \%rhash;
1.240 www 7528: }
7529:
7530: # ----------------------------------------- Send log queries and wait for reply
7531:
7532: sub log_query {
7533: my ($uname,$udom,$query,%filters)=@_;
7534: my $uhome=&homeserver($uname,$udom);
7535: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7536: my $uhost=&hostname($uhome);
1.800 albertel 7537: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7538: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7539: $uhome);
1.479 albertel 7540: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7541: return get_query_reply($queryid);
7542: }
7543:
1.818 raeburn 7544: # -------------------------- Update MySQL table for portfolio file
7545:
7546: sub update_portfolio_table {
1.821 raeburn 7547: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7548: if ($group ne '') {
7549: $file_name =~s /^\Q$group\E//;
7550: }
1.818 raeburn 7551: my $homeserver = &homeserver($uname,$udom);
7552: my $queryid=
1.821 raeburn 7553: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7554: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7555: my $reply = &get_query_reply($queryid);
7556: return $reply;
7557: }
7558:
1.899 raeburn 7559: # -------------------------- Update MySQL allusers table
7560:
7561: sub update_allusers_table {
7562: my ($uname,$udom,$names) = @_;
7563: my $homeserver = &homeserver($uname,$udom);
7564: my $queryid=
7565: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7566: 'lastname='.&escape($names->{'lastname'}).'%%'.
7567: 'firstname='.&escape($names->{'firstname'}).'%%'.
7568: 'middlename='.&escape($names->{'middlename'}).'%%'.
7569: 'generation='.&escape($names->{'generation'}).'%%'.
7570: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7571: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7572: return;
1.899 raeburn 7573: }
7574:
1.508 raeburn 7575: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7576:
7577: sub fetch_enrollment_query {
1.511 raeburn 7578: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7579: my $homeserver;
1.547 raeburn 7580: my $maxtries = 1;
1.508 raeburn 7581: if ($context eq 'automated') {
7582: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7583: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7584: } else {
7585: $homeserver = &homeserver($cnum,$dom);
7586: }
1.838 albertel 7587: my $host=&hostname($homeserver);
1.506 raeburn 7588: my $cmd = '';
1.1000 raeburn 7589: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7590: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7591: }
7592: $cmd =~ s/%%$//;
7593: $cmd = &escape($cmd);
7594: my $query = 'fetchenrollment';
1.620 albertel 7595: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7596: unless ($queryid=~/^\Q$host\E\_/) {
7597: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7598: return 'error: '.$queryid;
7599: }
1.506 raeburn 7600: my $reply = &get_query_reply($queryid);
1.547 raeburn 7601: my $tries = 1;
7602: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7603: $reply = &get_query_reply($queryid);
7604: $tries ++;
7605: }
1.526 raeburn 7606: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7607: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7608: } else {
1.901 albertel 7609: my @responses = split(/:/,$reply);
1.515 raeburn 7610: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7611: foreach my $line (@responses) {
7612: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7613: $$replyref{$key} = $value;
7614: }
7615: } else {
1.1117 foxr 7616: my $pathname = LONCAPA::tempdir();
1.800 albertel 7617: foreach my $line (@responses) {
7618: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7619: $$replyref{$key} = $value;
7620: if ($value > 0) {
1.800 albertel 7621: foreach my $item (@{$$affiliatesref{$key}}) {
7622: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7623: my $destname = $pathname.'/'.$filename;
7624: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7625: if ($xml_classlist =~ /^error/) {
7626: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7627: } else {
1.506 raeburn 7628: if ( open(FILE,">$destname") ) {
7629: print FILE &unescape($xml_classlist);
7630: close(FILE);
1.526 raeburn 7631: } else {
7632: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7633: }
7634: }
7635: }
7636: }
7637: }
7638: }
7639: return 'ok';
7640: }
7641: return 'error';
7642: }
7643:
1.242 www 7644: sub get_query_reply {
7645: my $queryid=shift;
1.1117 foxr 7646: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7647: my $reply='';
7648: for (1..100) {
7649: sleep 2;
7650: if (-e $replyfile.'.end') {
1.448 albertel 7651: if (open(my $fh,$replyfile)) {
1.904 albertel 7652: $reply = join('',<$fh>);
7653: close($fh);
1.240 www 7654: } else { return 'error: reply_file_error'; }
1.242 www 7655: return &unescape($reply);
7656: }
1.240 www 7657: }
1.242 www 7658: return 'timeout:'.$queryid;
1.240 www 7659: }
7660:
7661: sub courselog_query {
1.241 www 7662: #
7663: # possible filters:
7664: # url: url or symb
7665: # username
7666: # domain
7667: # action: view, submit, grade
7668: # start: timestamp
7669: # end: timestamp
7670: #
1.240 www 7671: my (%filters)=@_;
1.620 albertel 7672: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7673: if ($filters{'url'}) {
7674: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7675: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7676: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7677: }
1.620 albertel 7678: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7679: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7680: return &log_query($cname,$cdom,'courselog',%filters);
7681: }
7682:
7683: sub userlog_query {
1.858 raeburn 7684: #
7685: # possible filters:
7686: # action: log check role
7687: # start: timestamp
7688: # end: timestamp
7689: #
1.240 www 7690: my ($uname,$udom,%filters)=@_;
7691: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7692: }
7693:
1.506 raeburn 7694: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7695:
7696: sub auto_run {
1.508 raeburn 7697: my ($cnum,$cdom) = @_;
1.876 raeburn 7698: my $response = 0;
7699: my $settings;
7700: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7701: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7702: $settings = $domconfig{'autoenroll'};
7703: if ($settings->{'run'} eq '1') {
7704: $response = 1;
7705: }
7706: } else {
1.934 raeburn 7707: my $homeserver;
7708: if (&is_course($cdom,$cnum)) {
7709: $homeserver = &homeserver($cnum,$cdom);
7710: } else {
7711: $homeserver = &domain($cdom,'primary');
7712: }
7713: if ($homeserver ne 'no_host') {
7714: $response = &reply('autorun:'.$cdom,$homeserver);
7715: }
1.876 raeburn 7716: }
1.506 raeburn 7717: return $response;
7718: }
1.776 albertel 7719:
1.506 raeburn 7720: sub auto_get_sections {
1.508 raeburn 7721: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7722: my $homeserver;
7723: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7724: $homeserver = &homeserver($cnum,$cdom);
7725: }
7726: if (!defined($homeserver)) {
7727: if ($cdom =~ /^$match_domain$/) {
7728: $homeserver = &domain($cdom,'primary');
7729: }
7730: }
7731: my @secs;
7732: if (defined($homeserver)) {
7733: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7734: unless ($response eq 'refused') {
7735: @secs = split(/:/,$response);
7736: }
1.506 raeburn 7737: }
7738: return @secs;
7739: }
1.776 albertel 7740:
1.506 raeburn 7741: sub auto_new_course {
1.1099 raeburn 7742: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7743: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7744: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7745: return $response;
7746: }
1.776 albertel 7747:
1.506 raeburn 7748: sub auto_validate_courseID {
1.508 raeburn 7749: my ($cnum,$cdom,$inst_course_id) = @_;
7750: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7751: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7752: return $response;
7753: }
1.776 albertel 7754:
1.1007 raeburn 7755: sub auto_validate_instcode {
1.1020 raeburn 7756: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7757: my ($homeserver,$response);
7758: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7759: $homeserver = &homeserver($cnum,$cdom);
7760: }
7761: if (!defined($homeserver)) {
7762: if ($cdom =~ /^$match_domain$/) {
7763: $homeserver = &domain($cdom,'primary');
7764: }
7765: }
1.1065 raeburn 7766: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7767: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7768: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7769: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7770: }
7771:
1.506 raeburn 7772: sub auto_create_password {
1.873 raeburn 7773: my ($cnum,$cdom,$authparam,$udom) = @_;
7774: my ($homeserver,$response);
1.506 raeburn 7775: my $create_passwd = 0;
7776: my $authchk = '';
1.873 raeburn 7777: if ($udom =~ /^$match_domain$/) {
7778: $homeserver = &domain($udom,'primary');
7779: }
7780: if ($homeserver eq '') {
7781: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7782: $homeserver = &homeserver($cnum,$cdom);
7783: }
7784: }
7785: if ($homeserver eq '') {
7786: $authchk = 'nodomain';
1.506 raeburn 7787: } else {
1.873 raeburn 7788: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7789: if ($response eq 'refused') {
7790: $authchk = 'refused';
7791: } else {
1.901 albertel 7792: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7793: }
1.506 raeburn 7794: }
7795: return ($authparam,$create_passwd,$authchk);
7796: }
7797:
1.706 raeburn 7798: sub auto_photo_permission {
7799: my ($cnum,$cdom,$students) = @_;
7800: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7801: my ($outcome,$perm_reqd,$conditions) =
7802: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7803: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7804: return (undef,undef);
7805: }
1.706 raeburn 7806: return ($outcome,$perm_reqd,$conditions);
7807: }
7808:
7809: sub auto_checkphotos {
7810: my ($uname,$udom,$pid) = @_;
7811: my $homeserver = &homeserver($uname,$udom);
7812: my ($result,$resulttype);
7813: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7814: &escape($uname).':'.&escape($pid),
7815: $homeserver));
1.709 albertel 7816: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7817: return (undef,undef);
7818: }
1.706 raeburn 7819: if ($outcome) {
7820: ($result,$resulttype) = split(/:/,$outcome);
7821: }
7822: return ($result,$resulttype);
7823: }
7824:
7825: sub auto_photochoice {
7826: my ($cnum,$cdom) = @_;
7827: my $homeserver = &homeserver($cnum,$cdom);
7828: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7829: &escape($cdom),
7830: $homeserver)));
1.709 albertel 7831: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7832: return (undef,undef);
7833: }
1.706 raeburn 7834: return ($update,$comment);
7835: }
7836:
7837: sub auto_photoupdate {
7838: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7839: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7840: my $host=&hostname($homeserver);
1.706 raeburn 7841: my $cmd = '';
7842: my $maxtries = 1;
1.800 albertel 7843: foreach my $affiliate (keys(%{$affiliatesref})) {
7844: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7845: }
7846: $cmd =~ s/%%$//;
7847: $cmd = &escape($cmd);
7848: my $query = 'institutionalphotos';
7849: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7850: unless ($queryid=~/^\Q$host\E\_/) {
7851: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7852: return 'error: '.$queryid;
7853: }
7854: my $reply = &get_query_reply($queryid);
7855: my $tries = 1;
7856: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7857: $reply = &get_query_reply($queryid);
7858: $tries ++;
7859: }
7860: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7861: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7862: } else {
7863: my @responses = split(/:/,$reply);
7864: my $outcome = shift(@responses);
7865: foreach my $item (@responses) {
7866: my ($key,$value) = split(/=/,$item);
7867: $$photo{$key} = $value;
7868: }
7869: return $outcome;
7870: }
7871: return 'error';
7872: }
7873:
1.521 raeburn 7874: sub auto_instcode_format {
1.793 albertel 7875: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7876: $cat_order) = @_;
1.521 raeburn 7877: my $courses = '';
1.772 raeburn 7878: my @homeservers;
1.521 raeburn 7879: if ($caller eq 'global') {
1.841 albertel 7880: my %servers = &get_servers($codedom,'library');
7881: foreach my $tryserver (keys(%servers)) {
7882: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7883: push(@homeservers,$tryserver);
7884: }
1.584 raeburn 7885: }
1.1022 raeburn 7886: } elsif ($caller eq 'requests') {
7887: if ($codedom =~ /^$match_domain$/) {
7888: my $chome = &domain($codedom,'primary');
7889: unless ($chome eq 'no_host') {
7890: push(@homeservers,$chome);
7891: }
7892: }
1.521 raeburn 7893: } else {
1.772 raeburn 7894: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7895: }
1.793 albertel 7896: foreach my $code (keys(%{$instcodes})) {
7897: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7898: }
7899: chop($courses);
1.772 raeburn 7900: my $ok_response = 0;
7901: my $response;
7902: while (@homeservers > 0 && $ok_response == 0) {
7903: my $server = shift(@homeservers);
7904: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7905: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7906: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7907: split(/:/,$response);
1.772 raeburn 7908: %{$codes} = (%{$codes},&str2hash($codes_str));
7909: push(@{$codetitles},&str2array($codetitles_str));
7910: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7911: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7912: $ok_response = 1;
7913: }
7914: }
7915: if ($ok_response) {
1.521 raeburn 7916: return 'ok';
1.772 raeburn 7917: } else {
7918: return $response;
1.521 raeburn 7919: }
7920: }
7921:
1.792 raeburn 7922: sub auto_instcode_defaults {
7923: my ($domain,$returnhash,$code_order) = @_;
7924: my @homeservers;
1.841 albertel 7925:
7926: my %servers = &get_servers($domain,'library');
7927: foreach my $tryserver (keys(%servers)) {
7928: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7929: push(@homeservers,$tryserver);
7930: }
1.792 raeburn 7931: }
1.841 albertel 7932:
1.792 raeburn 7933: my $response;
1.841 albertel 7934: foreach my $server (@homeservers) {
1.792 raeburn 7935: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7936: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7937:
7938: foreach my $pair (split(/\&/,$response)) {
7939: my ($name,$value)=split(/\=/,$pair);
7940: if ($name eq 'code_order') {
7941: @{$code_order} = split(/\&/,&unescape($value));
7942: } else {
7943: $returnhash->{&unescape($name)}=&unescape($value);
7944: }
7945: }
7946: return 'ok';
1.792 raeburn 7947: }
1.841 albertel 7948:
7949: return $response;
1.1003 raeburn 7950: }
7951:
7952: sub auto_possible_instcodes {
1.1007 raeburn 7953: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7954: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7955: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7956: return;
7957: }
1.1003 raeburn 7958: my (@homeservers,$uhome);
7959: if (defined(&domain($domain,'primary'))) {
7960: $uhome=&domain($domain,'primary');
7961: push(@homeservers,&domain($domain,'primary'));
7962: } else {
7963: my %servers = &get_servers($domain,'library');
7964: foreach my $tryserver (keys(%servers)) {
7965: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7966: push(@homeservers,$tryserver);
7967: }
7968: }
7969: }
7970: my $response;
7971: foreach my $server (@homeservers) {
7972: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7973: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7974: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7975: split(':',$response);
7976: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7977: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7978: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7979: my ($name,$value)=split('=',$item);
7980: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7981: }
7982: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7983: my ($name,$value)=split('=',$item);
7984: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7985: }
7986: return 'ok';
7987: }
7988: return $response;
7989: }
1.792 raeburn 7990:
1.1010 raeburn 7991: sub auto_courserequest_checks {
7992: my ($dom) = @_;
1.1020 raeburn 7993: my ($homeserver,%validations);
7994: if ($dom =~ /^$match_domain$/) {
7995: $homeserver = &domain($dom,'primary');
7996: }
7997: unless ($homeserver eq 'no_host') {
7998: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7999: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8000: my @items = split(/&/,$response);
8001: foreach my $item (@items) {
8002: my ($key,$value) = split('=',$item);
8003: $validations{&unescape($key)} = &thaw_unescape($value);
8004: }
8005: }
8006: }
1.1010 raeburn 8007: return %validations;
8008: }
8009:
1.1020 raeburn 8010: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8011: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8012: my ($homeserver,$response);
8013: if ($dom =~ /^$match_domain$/) {
8014: $homeserver = &domain($dom,'primary');
8015: }
1.1172.2.43 raeburn 8016: unless ($homeserver eq 'no_host') {
8017: my $customdata;
8018: if (ref($custominfo) eq 'HASH') {
8019: $customdata = &freeze_escape($custominfo);
8020: }
1.1020 raeburn 8021: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8022: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8023: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8024: $customdata,$homeserver));
1.1020 raeburn 8025: }
8026: return $response;
8027: }
8028:
1.777 albertel 8029: sub auto_validate_class_sec {
1.918 raeburn 8030: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8031: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8032: my $ownerlist;
8033: if (ref($owners) eq 'ARRAY') {
8034: $ownerlist = join(',',@{$owners});
8035: } else {
8036: $ownerlist = $owners;
8037: }
1.773 raeburn 8038: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8039: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8040: return $response;
8041: }
8042:
1.1172.2.38 raeburn 8043: sub auto_crsreq_update {
8044: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8045: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8046: my ($homeserver,%crsreqresponse);
8047: if ($cdom =~ /^$match_domain$/) {
8048: $homeserver = &domain($cdom,'primary');
8049: }
8050: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8051: my $info;
8052: if (ref($inbound) eq 'HASH') {
8053: $info = &freeze_escape($inbound);
8054: }
8055: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8056: ':'.&escape($action).':'.&escape($ownername).':'.
8057: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8058: &escape($title).':'.&escape($code).':'.
8059: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8060: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8061: my @items = split(/&/,$response);
8062: foreach my $item (@items) {
8063: my ($key,$value) = split('=',$item);
8064: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8065: }
8066: }
8067: }
8068: return \%crsreqresponse;
8069: }
8070:
1.679 raeburn 8071: # ------------------------------------------------------- Course Group routines
8072:
8073: sub get_coursegroups {
1.809 raeburn 8074: my ($cdom,$cnum,$group,$namespace) = @_;
8075: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8076: }
8077:
1.679 raeburn 8078: sub modify_coursegroup {
8079: my ($cdom,$cnum,$groupsettings) = @_;
8080: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8081: }
8082:
1.809 raeburn 8083: sub toggle_coursegroup_status {
8084: my ($cdom,$cnum,$group,$action) = @_;
8085: my ($from_namespace,$to_namespace);
8086: if ($action eq 'delete') {
8087: $from_namespace = 'coursegroups';
8088: $to_namespace = 'deleted_groups';
8089: } else {
8090: $from_namespace = 'deleted_groups';
8091: $to_namespace = 'coursegroups';
8092: }
8093: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8094: if (my $tmp = &error(%curr_group)) {
8095: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8096: return ('read error',$tmp);
8097: } else {
8098: my %savedsettings = %curr_group;
1.809 raeburn 8099: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8100: my $deloutcome;
8101: if ($result eq 'ok') {
1.809 raeburn 8102: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8103: } else {
8104: return ('write error',$result);
8105: }
8106: if ($deloutcome eq 'ok') {
8107: return 'ok';
8108: } else {
8109: return ('delete error',$deloutcome);
8110: }
8111: }
8112: }
8113:
1.679 raeburn 8114: sub modify_group_roles {
1.957 raeburn 8115: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8116: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8117: my $role = 'gr/'.&escape($userprivs);
8118: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8119: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8120: if ($result eq 'ok') {
8121: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8122: }
1.679 raeburn 8123: return $result;
8124: }
8125:
8126: sub modify_coursegroup_membership {
8127: my ($cdom,$cnum,$membership) = @_;
8128: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8129: return $result;
8130: }
8131:
1.682 raeburn 8132: sub get_active_groups {
8133: my ($udom,$uname,$cdom,$cnum) = @_;
8134: my $now = time;
8135: my %groups = ();
8136: foreach my $key (keys(%env)) {
1.811 albertel 8137: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8138: my ($start,$end) = split(/\./,$env{$key});
8139: if (($end!=0) && ($end<$now)) { next; }
8140: if (($start!=0) && ($start>$now)) { next; }
8141: if ($1 eq $cdom && $2 eq $cnum) {
8142: $groups{$3} = $env{$key} ;
8143: }
8144: }
8145: }
8146: return %groups;
8147: }
8148:
1.683 raeburn 8149: sub get_group_membership {
8150: my ($cdom,$cnum,$group) = @_;
8151: return(&dump('groupmembership',$cdom,$cnum,$group));
8152: }
8153:
8154: sub get_users_groups {
8155: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8156: my @usersgroups;
1.683 raeburn 8157: my $cachetime=1800;
8158:
8159: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8160: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8161: if (defined($cached)) {
1.734 albertel 8162: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8163: } else {
8164: $grouplist = '';
1.816 raeburn 8165: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8166: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8167: my $access_end = $env{'course.'.$courseid.
8168: '.default_enrollment_end_date'};
8169: my $now = time;
8170: foreach my $key (keys(%roleshash)) {
8171: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8172: my $group = $1;
8173: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8174: my $start = $2;
8175: my $end = $1;
8176: if ($start == -1) { next; } # deleted from group
8177: if (($start!=0) && ($start>$now)) { next; }
8178: if (($end!=0) && ($end<$now)) {
8179: if ($access_end && $access_end < $now) {
8180: if ($access_end - $end < 86400) {
8181: push(@usersgroups,$group);
1.733 raeburn 8182: }
8183: }
1.817 raeburn 8184: next;
1.733 raeburn 8185: }
1.817 raeburn 8186: push(@usersgroups,$group);
1.683 raeburn 8187: }
8188: }
8189: }
1.817 raeburn 8190: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8191: $grouplist = join(':',@usersgroups);
8192: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8193: }
1.733 raeburn 8194: return @usersgroups;
1.683 raeburn 8195: }
8196:
8197: sub devalidate_getgroups_cache {
8198: my ($udom,$uname,$cdom,$cnum)=@_;
8199: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8200:
1.683 raeburn 8201: my $hashid="$udom:$uname:$courseid";
8202: &devalidate_cache_new('getgroups',$hashid);
8203: }
8204:
1.12 www 8205: # ------------------------------------------------------------------ Plain Text
8206:
8207: sub plaintext {
1.988 raeburn 8208: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8209: if ($short =~ m{^cr/}) {
1.758 albertel 8210: return (split('/',$short))[-1];
8211: }
1.742 raeburn 8212: if (!defined($cid)) {
8213: $cid = $env{'request.course.id'};
8214: }
8215: my %rolenames = (
1.1008 raeburn 8216: Course => 'std',
8217: Community => 'alt1',
1.742 raeburn 8218: );
1.1037 raeburn 8219: if ($cid ne '') {
8220: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8221: unless ($forcedefault) {
8222: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8223: &Apache::lonlocal::mt_escape(\$roletext);
8224: return &Apache::lonlocal::mt($roletext);
8225: }
8226: }
8227: }
8228: if ((defined($type)) && (defined($rolenames{$type})) &&
8229: (defined($rolenames{$type})) &&
8230: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8231: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8232: } elsif ($cid ne '') {
8233: my $crstype = $env{'course.'.$cid.'.type'};
8234: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8235: (defined($prp{$short}{$rolenames{$crstype}}))) {
8236: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8237: }
1.742 raeburn 8238: }
1.1037 raeburn 8239: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8240: }
8241:
8242: # ----------------------------------------------------------------- Assign Role
8243:
8244: sub assignrole {
1.957 raeburn 8245: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8246: $context)=@_;
1.21 www 8247: my $mrole;
8248: if ($role =~ /^cr\//) {
1.393 www 8249: my $cwosec=$url;
1.811 albertel 8250: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8251: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8252: my $refused = 1;
8253: if ($context eq 'requestcourses') {
8254: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8255: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8256: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8257: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8258: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8259: if ($crsenv{'internal.courseowner'} eq
8260: $env{'user.name'}.':'.$env{'user.domain'}) {
8261: $refused = '';
8262: }
8263: }
8264: }
8265: }
8266: }
8267: if ($refused) {
8268: &logthis('Refused custom assignrole: '.
8269: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8270: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8271: return 'refused';
8272: }
1.104 www 8273: }
1.21 www 8274: $mrole='cr';
1.678 raeburn 8275: } elsif ($role =~ /^gr\//) {
8276: my $cwogrp=$url;
1.811 albertel 8277: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8278: unless (&allowed('mdg',$cwogrp)) {
8279: &logthis('Refused group assignrole: '.
8280: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8281: $env{'user.name'}.' at '.$env{'user.domain'});
8282: return 'refused';
8283: }
8284: $mrole='gr';
1.21 www 8285: } else {
1.82 www 8286: my $cwosec=$url;
1.811 albertel 8287: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8288: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8289: my $refused;
8290: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8291: if (!(&allowed('c'.$role,$url))) {
8292: $refused = 1;
8293: }
8294: } else {
8295: $refused = 1;
8296: }
1.947 raeburn 8297: if ($refused) {
1.1045 raeburn 8298: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8299: if (!$selfenroll && $context eq 'course') {
8300: my %crsenv;
8301: if ($role eq 'cc' || $role eq 'co') {
8302: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8303: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8304: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8305: if ($crsenv{'internal.courseowner'} eq
8306: $env{'user.name'}.':'.$env{'user.domain'}) {
8307: $refused = '';
8308: }
8309: }
8310: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8311: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8312: if ($crsenv{'internal.courseowner'} eq
8313: $env{'user.name'}.':'.$env{'user.domain'}) {
8314: $refused = '';
8315: }
8316: }
8317: }
8318: }
8319: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8320: $refused = '';
1.1017 raeburn 8321: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8322: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8323: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8324: my $wrongcc;
8325: if ($cnum =~ /^$match_community$/) {
8326: $wrongcc = 1 if ($role eq 'cc');
8327: } else {
8328: $wrongcc = 1 if ($role eq 'co');
8329: }
8330: unless ($wrongcc) {
8331: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8332: if ($crsenv{'internal.courseowner'} eq
8333: $env{'user.name'}.':'.$env{'user.domain'}) {
8334: $refused = '';
8335: }
1.1017 raeburn 8336: }
8337: }
1.1172.2.9 raeburn 8338: } elsif ($context eq 'requestauthor') {
8339: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8340: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8341: if ($env{'environment.requestauthor'} eq 'automatic') {
8342: $refused = '';
8343: } else {
8344: my %domdefaults = &get_domain_defaults($udom);
8345: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8346: my $checkbystatus;
8347: if ($env{'user.adv'}) {
8348: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8349: if ($disposition eq 'automatic') {
8350: $refused = '';
8351: } elsif ($disposition eq '') {
8352: $checkbystatus = 1;
8353: }
8354: } else {
8355: $checkbystatus = 1;
8356: }
8357: if ($checkbystatus) {
8358: if ($env{'environment.inststatus'}) {
8359: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8360: foreach my $type (@inststatuses) {
8361: if (($type ne '') &&
8362: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8363: $refused = '';
8364: }
8365: }
8366: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8367: $refused = '';
8368: }
8369: }
8370: }
8371: }
8372: }
1.1017 raeburn 8373: }
8374: if ($refused) {
1.947 raeburn 8375: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8376: ' '.$role.' '.$end.' '.$start.' by '.
8377: $env{'user.name'}.' at '.$env{'user.domain'});
8378: return 'refused';
8379: }
1.932 raeburn 8380: }
1.1131 raeburn 8381: } elsif ($role eq 'au') {
8382: if ($url ne '/'.$udom.'/') {
8383: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8384: ' to assign author role for '.$uname.':'.$udom.
8385: ' in domain: '.$url.' refused (wrong domain).');
8386: return 'refused';
8387: }
1.104 www 8388: }
1.21 www 8389: $mrole=$role;
8390: }
1.620 albertel 8391: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8392: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8393: if ($end) { $command.='_'.$end; }
1.21 www 8394: if ($start) {
8395: if ($end) {
1.81 www 8396: $command.='_'.$start;
1.21 www 8397: } else {
1.81 www 8398: $command.='_0_'.$start;
1.21 www 8399: }
8400: }
1.739 raeburn 8401: my $origstart = $start;
8402: my $origend = $end;
1.957 raeburn 8403: my $delflag;
1.357 www 8404: # actually delete
8405: if ($deleteflag) {
1.373 www 8406: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8407: # modify command to delete the role
1.620 albertel 8408: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8409: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8410: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8411: # set start and finish to negative values for userrolelog
8412: $start=-1;
8413: $end=-1;
1.957 raeburn 8414: $delflag = 1;
1.357 www 8415: }
8416: }
8417: # send command
1.349 www 8418: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8419: # log new user role if status is ok
1.349 www 8420: if ($answer eq 'ok') {
1.663 raeburn 8421: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8422: if (($role eq 'cc') || ($role eq 'in') ||
8423: ($role eq 'ep') || ($role eq 'ad') ||
8424: ($role eq 'ta') || ($role eq 'st') ||
8425: ($role=~/^cr/) || ($role eq 'gr') ||
8426: ($role eq 'co')) {
1.1172.2.13 raeburn 8427: # for course roles, perform group memberships changes triggered by role change.
8428: unless ($role =~ /^gr/) {
8429: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8430: $origstart,$selfenroll,$context);
8431: }
1.1172.2.9 raeburn 8432: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8433: $selfenroll,$context);
8434: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8435: ($role eq 'au') || ($role eq 'dc')) {
8436: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8437: $context);
8438: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8439: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8440: $context);
8441: }
1.1053 raeburn 8442: if ($role eq 'cc') {
8443: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8444: }
1.349 www 8445: }
8446: return $answer;
1.169 harris41 8447: }
8448:
1.1053 raeburn 8449: sub autoupdate_coowners {
8450: my ($url,$end,$start,$uname,$udom) = @_;
8451: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8452: if (($cdom ne '') && ($cnum ne '')) {
8453: my $now = time;
8454: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8455: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8456: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8457: my $instcode = $coursehash{'internal.coursecode'};
8458: if ($instcode ne '') {
1.1056 raeburn 8459: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8460: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8461: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8462: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8463: if ($result eq 'valid') {
8464: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8465: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8466: push(@newcoowners,$coowner);
8467: }
8468: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8469: push(@newcoowners,$uname.':'.$udom);
8470: }
8471: @newcoowners = sort(@newcoowners);
8472: } else {
8473: push(@newcoowners,$uname.':'.$udom);
8474: }
8475: } else {
8476: if ($coursehash{'internal.co-owners'}) {
8477: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8478: unless ($coowner eq $uname.':'.$udom) {
8479: push(@newcoowners,$coowner);
8480: }
8481: }
8482: unless (@newcoowners > 0) {
8483: $delcoowners = 1;
8484: $coowners = '';
8485: }
8486: }
8487: }
8488: if (@newcoowners || $delcoowners) {
8489: &store_coowners($cdom,$cnum,$coursehash{'home'},
8490: $delcoowners,@newcoowners);
8491: }
8492: }
8493: }
8494: }
8495: }
8496: }
8497: }
8498:
8499: sub store_coowners {
8500: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8501: my $cid = $cdom.'_'.$cnum;
8502: my ($coowners,$delresult,$putresult);
8503: if (@newcoowners) {
8504: $coowners = join(',',@newcoowners);
8505: my %coownershash = (
8506: 'internal.co-owners' => $coowners,
8507: );
8508: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8509: if ($putresult eq 'ok') {
8510: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8511: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8512: }
8513: }
8514: }
8515: if ($delcoowners) {
8516: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8517: if ($delresult eq 'ok') {
8518: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8519: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8520: }
8521: }
8522: }
8523: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8524: my %crsinfo =
8525: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8526: if (ref($crsinfo{$cid}) eq 'HASH') {
8527: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8528: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8529: }
8530: }
8531: }
8532:
1.169 harris41 8533: # -------------------------------------------------- Modify user authentication
1.197 www 8534: # Overrides without validation
8535:
1.169 harris41 8536: sub modifyuserauth {
8537: my ($udom,$uname,$umode,$upass)=@_;
8538: my $uhome=&homeserver($uname,$udom);
1.197 www 8539: unless (&allowed('mau',$udom)) { return 'refused'; }
8540: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8541: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8542: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8543: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8544: &escape($upass),$uhome);
1.620 albertel 8545: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8546: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8547: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8548: &log($udom,,$uname,$uhome,
1.620 albertel 8549: 'Authentication changed by '.$env{'user.domain'}.', '.
8550: $env{'user.name'}.', '.$umode.
1.197 www 8551: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8552: unless ($reply eq 'ok') {
1.197 www 8553: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8554: return 'error: '.$reply;
8555: }
1.170 harris41 8556: return 'ok';
1.80 www 8557: }
8558:
1.81 www 8559: # --------------------------------------------------------------- Modify a user
1.80 www 8560:
1.81 www 8561: sub modifyuser {
1.206 matthew 8562: my ($udom, $uname, $uid,
8563: $umode, $upass, $first,
8564: $middle, $last, $gene,
1.1058 raeburn 8565: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8566: $udom= &LONCAPA::clean_domain($udom);
8567: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8568: my $showcandelete = 'none';
8569: if (ref($candelete) eq 'ARRAY') {
8570: if (@{$candelete} > 0) {
8571: $showcandelete = join(', ',@{$candelete});
8572: }
8573: }
1.81 www 8574: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8575: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8576: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8577: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8578: ' desiredhome not specified').
1.620 albertel 8579: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8580: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8581: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8582: my $newuser;
8583: if ($uhome eq 'no_host') {
8584: $newuser = 1;
8585: }
1.80 www 8586: # ----------------------------------------------------------------- Create User
1.406 albertel 8587: if (($uhome eq 'no_host') &&
8588: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8589: my $unhome='';
1.844 albertel 8590: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8591: $unhome = $desiredhome;
1.620 albertel 8592: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8593: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8594: } else { # load balancing routine for determining $unhome
1.81 www 8595: my $loadm=10000000;
1.841 albertel 8596: my %servers = &get_servers($udom,'library');
8597: foreach my $tryserver (keys(%servers)) {
8598: my $answer=reply('load',$tryserver);
8599: if (($answer=~/\d+/) && ($answer<$loadm)) {
8600: $loadm=$answer;
8601: $unhome=$tryserver;
8602: }
1.80 www 8603: }
8604: }
8605: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8606: return 'error: unable to find a home server for '.$uname.
8607: ' in domain '.$udom;
1.80 www 8608: }
8609: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8610: &escape($upass),$unhome);
8611: unless ($reply eq 'ok') {
8612: return 'error: '.$reply;
8613: }
1.230 stredwic 8614: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8615: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8616: return 'error: unable verify users home machine.';
1.80 www 8617: }
1.209 matthew 8618: } # End of creation of new user
1.80 www 8619: # ---------------------------------------------------------------------- Add ID
8620: if ($uid) {
8621: $uid=~tr/A-Z/a-z/;
8622: my %uidhash=&idrget($udom,$uname);
1.196 www 8623: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8624: && (!$forceid)) {
1.80 www 8625: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8626: return 'error: user id "'.$uid.'" does not match '.
8627: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8628: }
8629: } else {
8630: &idput($udom,($uname => $uid));
8631: }
8632: }
8633: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8634: my @tmp=&get('environment',
1.899 raeburn 8635: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8636: 'permanentemail','inststatus'],
1.134 albertel 8637: $udom,$uname);
1.1075 raeburn 8638: my (%names,%oldnames);
1.313 matthew 8639: if ($tmp[0] =~ m/^error:.*/) {
8640: %names=();
8641: } else {
8642: %names = @tmp;
1.1075 raeburn 8643: %oldnames = %names;
1.313 matthew 8644: }
1.388 www 8645: #
1.1058 raeburn 8646: # If name, email and/or uid are blank (e.g., because an uploaded file
8647: # of users did not contain them), do not overwrite existing values
8648: # unless field is in $candelete array ref.
8649: #
8650:
8651: my @fields = ('firstname','middlename','lastname','generation',
8652: 'permanentemail','id');
8653: my %newvalues;
8654: if (ref($candelete) eq 'ARRAY') {
8655: foreach my $field (@fields) {
8656: if (grep(/^\Q$field\E$/,@{$candelete})) {
8657: if ($field eq 'firstname') {
8658: $names{$field} = $first;
8659: } elsif ($field eq 'middlename') {
8660: $names{$field} = $middle;
8661: } elsif ($field eq 'lastname') {
8662: $names{$field} = $last;
8663: } elsif ($field eq 'generation') {
8664: $names{$field} = $gene;
8665: } elsif ($field eq 'permanentemail') {
8666: $names{$field} = $email;
8667: } elsif ($field eq 'id') {
8668: $names{$field} = $uid;
8669: }
8670: }
8671: }
8672: }
1.388 www 8673: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8674: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8675: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8676: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8677: if ($email) {
8678: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8679: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8680: }
1.899 raeburn 8681: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8682: if (defined($inststatus)) {
8683: $names{'inststatus'} = '';
8684: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8685: if (ref($usertypes) eq 'HASH') {
8686: my @okstatuses;
8687: foreach my $item (split(/:/,$inststatus)) {
8688: if (defined($usertypes->{$item})) {
8689: push(@okstatuses,$item);
8690: }
8691: }
8692: if (@okstatuses) {
8693: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8694: }
8695: }
8696: }
1.1075 raeburn 8697: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8698: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8699: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8700: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8701: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8702: } else {
8703: $logmsg .= ' during self creation';
8704: }
1.1075 raeburn 8705: my $changed;
8706: if ($newuser) {
8707: $changed = 1;
8708: } else {
8709: foreach my $field (@fields) {
8710: if ($names{$field} ne $oldnames{$field}) {
8711: $changed = 1;
8712: last;
8713: }
8714: }
8715: }
8716: unless ($changed) {
8717: $logmsg = 'No changes in user information needed for: '.$logmsg;
8718: &logthis($logmsg);
8719: return 'ok';
8720: }
8721: my $reply = &put('environment', \%names, $udom,$uname);
8722: if ($reply ne 'ok') {
8723: return 'error: '.$reply;
8724: }
1.1087 raeburn 8725: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8726: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8727: }
1.1075 raeburn 8728: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8729: &devalidate_cache_new('namescache',$uname.':'.$udom);
8730: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8731: &logthis($logmsg);
1.134 albertel 8732: return 'ok';
1.80 www 8733: }
8734:
1.81 www 8735: # -------------------------------------------------------------- Modify student
1.80 www 8736:
1.81 www 8737: sub modifystudent {
8738: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8739: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8740: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8741: if (!$cid) {
1.620 albertel 8742: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8743: return 'not_in_class';
8744: }
1.80 www 8745: }
8746: # --------------------------------------------------------------- Make the user
1.81 www 8747: my $reply=&modifyuser
1.209 matthew 8748: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8749: $desiredhome,$email,$inststatus);
1.80 www 8750: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8751: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8752: # student's environment
1.297 matthew 8753: $uid = undef if (!$forceid);
1.455 albertel 8754: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8755: $gene,$usec,$end,$start,$type,$locktype,
8756: $cid,$selfenroll,$context,$credits);
1.297 matthew 8757: return $reply;
8758: }
8759:
8760: sub modify_student_enrollment {
1.1172.2.23 raeburn 8761: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8762: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8763: my ($cdom,$cnum,$chome);
8764: if (!$cid) {
1.620 albertel 8765: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8766: return 'not_in_class';
8767: }
1.620 albertel 8768: $cdom=$env{'course.'.$cid.'.domain'};
8769: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8770: } else {
8771: ($cdom,$cnum)=split(/_/,$cid);
8772: }
1.620 albertel 8773: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8774: if (!$chome) {
1.457 raeburn 8775: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8776: }
1.455 albertel 8777: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8778: # Make sure the user exists
1.81 www 8779: my $uhome=&homeserver($uname,$udom);
8780: if (($uhome eq '') || ($uhome eq 'no_host')) {
8781: return 'error: no such user';
8782: }
1.297 matthew 8783: # Get student data if we were not given enough information
8784: if (!defined($first) || $first eq '' ||
8785: !defined($last) || $last eq '' ||
8786: !defined($uid) || $uid eq '' ||
8787: !defined($middle) || $middle eq '' ||
8788: !defined($gene) || $gene eq '') {
1.294 matthew 8789: # They did not supply us with enough data to enroll the student, so
8790: # we need to pick up more information.
1.297 matthew 8791: my %tmp = &get('environment',
1.294 matthew 8792: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8793: ,$udom,$uname);
8794:
1.800 albertel 8795: #foreach my $key (keys(%tmp)) {
8796: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8797: #}
1.294 matthew 8798: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8799: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8800: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8801: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8802: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8803: }
1.556 albertel 8804: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8805: my $user = "$uname:$udom";
8806: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8807: my $reply=cput('classlist',
1.1148 raeburn 8808: {$user =>
1.1172.2.19 raeburn 8809: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8810: $cdom,$cnum);
1.1148 raeburn 8811: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8812: &devalidate_getsection_cache($udom,$uname,$cid);
8813: } else {
1.81 www 8814: return 'error: '.$reply;
8815: }
1.297 matthew 8816: # Add student role to user
1.83 www 8817: my $uurl='/'.$cid;
1.81 www 8818: $uurl=~s/\_/\//g;
8819: if ($usec) {
8820: $uurl.='/'.$usec;
8821: }
1.1148 raeburn 8822: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8823: $selfenroll,$context);
8824: if ($result ne 'ok') {
8825: if ($old_entry{$user} ne '') {
8826: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8827: } else {
8828: $reply = &del('classlist',[$user],$cdom,$cnum);
8829: }
8830: }
8831: return $result;
1.21 www 8832: }
8833:
1.556 albertel 8834: sub format_name {
8835: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8836: my $name;
8837: if ($first ne 'lastname') {
8838: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8839: } else {
8840: if ($lastname=~/\S/) {
8841: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8842: $name=~s/\s+,/,/;
8843: } else {
8844: $name.= $firstname.' '.$middlename.' '.$generation;
8845: }
8846: }
8847: $name=~s/^\s+//;
8848: $name=~s/\s+$//;
8849: $name=~s/\s+/ /g;
8850: return $name;
8851: }
8852:
1.84 www 8853: # ------------------------------------------------- Write to course preferences
8854:
8855: sub writecoursepref {
8856: my ($courseid,%prefs)=@_;
8857: $courseid=~s/^\///;
8858: $courseid=~s/\_/\//g;
8859: my ($cdomain,$cnum)=split(/\//,$courseid);
8860: my $chome=homeserver($cnum,$cdomain);
8861: if (($chome eq '') || ($chome eq 'no_host')) {
8862: return 'error: no such course';
8863: }
8864: my $cstring='';
1.800 albertel 8865: foreach my $pref (keys(%prefs)) {
8866: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8867: }
1.84 www 8868: $cstring=~s/\&$//;
8869: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8870: }
8871:
8872: # ---------------------------------------------------------- Make/modify course
8873:
8874: sub createcourse {
1.741 raeburn 8875: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8876: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8877: $url=&declutter($url);
8878: my $cid='';
1.1028 raeburn 8879: if ($context eq 'requestcourses') {
8880: my $can_create = 0;
8881: my ($ownername,$ownerdom) = split(':',$course_owner);
8882: if ($udom eq $ownerdom) {
8883: if (&usertools_access($ownername,$ownerdom,$category,undef,
8884: $context)) {
8885: $can_create = 1;
8886: }
8887: } else {
8888: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8889: $category);
8890: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8891: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8892: if (@curr > 0) {
8893: my @options = qw(approval validate autolimit);
8894: my $optregex = join('|',@options);
8895: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8896: $can_create = 1;
8897: }
8898: }
8899: }
8900: }
8901: if ($can_create) {
8902: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8903: unless (&allowed('ccc',$udom)) {
8904: return 'refused';
8905: }
1.1017 raeburn 8906: }
8907: } else {
8908: return 'refused';
8909: }
1.1028 raeburn 8910: } elsif (!&allowed('ccc',$udom)) {
8911: return 'refused';
1.84 www 8912: }
1.1011 raeburn 8913: # --------------------------------------------------------------- Get Unique ID
8914: my $uname;
8915: if ($cnum =~ /^$match_courseid$/) {
8916: my $chome=&homeserver($cnum,$udom,'true');
8917: if (($chome eq '') || ($chome eq 'no_host')) {
8918: $uname = $cnum;
8919: } else {
1.1038 raeburn 8920: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8921: }
8922: } else {
1.1038 raeburn 8923: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8924: }
8925: return $uname if ($uname =~ /^error/);
8926: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8927: if (!defined($course_server)) {
8928: if (defined(&domain($udom,'primary'))) {
8929: $course_server = &domain($udom,'primary');
8930: } else {
8931: $course_server = $env{'user.home'};
8932: }
8933: }
8934: my %host_servers =
8935: &Apache::lonnet::get_servers($udom,'library');
8936: unless ($host_servers{$course_server}) {
8937: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8938: }
1.84 www 8939: # ------------------------------------------------------------- Make the course
8940: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8941: $course_server);
1.84 www 8942: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8943: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8944: if (($uhome eq '') || ($uhome eq 'no_host')) {
8945: return 'error: no such course';
8946: }
1.271 www 8947: # ----------------------------------------------------------------- Course made
1.516 raeburn 8948: # log existence
1.1029 raeburn 8949: my $now = time;
1.918 raeburn 8950: my $newcourse = {
8951: $udom.'_'.$uname => {
1.921 raeburn 8952: description => $description,
8953: inst_code => $inst_code,
8954: owner => $course_owner,
8955: type => $crstype,
1.1029 raeburn 8956: creator => $env{'user.name'}.':'.
8957: $env{'user.domain'},
8958: created => $now,
8959: context => $context,
1.918 raeburn 8960: },
8961: };
1.921 raeburn 8962: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8963: # set toplevel url
1.271 www 8964: my $topurl=$url;
8965: unless ($nonstandard) {
8966: # ------------------------------------------ For standard courses, make top url
8967: my $mapurl=&clutter($url);
1.278 www 8968: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8969: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8970: <map>
8971: <resource id="1" type="start"></resource>
8972: <resource id="2" src="$mapurl"></resource>
8973: <resource id="3" type="finish"></resource>
8974: <link index="1" from="1" to="2"></link>
8975: <link index="2" from="2" to="3"></link>
8976: </map>
8977: ENDINITMAP
8978: $topurl=&declutter(
1.638 albertel 8979: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8980: );
8981: }
8982: # ----------------------------------------------------------- Write preferences
1.84 www 8983: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8984: ('description' => $description,
8985: 'url' => $topurl,
8986: 'internal.creator' => $env{'user.name'}.':'.
8987: $env{'user.domain'},
8988: 'internal.created' => $now,
8989: 'internal.creationcontext' => $context)
8990: );
1.84 www 8991: return '/'.$udom.'/'.$uname;
8992: }
8993:
1.1011 raeburn 8994: # ------------------------------------------------------------------- Create ID
8995: sub generate_coursenum {
1.1038 raeburn 8996: my ($udom,$crstype) = @_;
1.1011 raeburn 8997: my $domdesc = &domain($udom);
8998: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8999: my $first;
9000: if ($crstype eq 'Community') {
9001: $first = '0';
9002: } else {
9003: $first = int(1+rand(9));
9004: }
9005: my $uname=$first.
1.1011 raeburn 9006: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9007: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9008: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9009: # ----------------------------------------------- Make sure that does not exist
9010: my $uhome=&homeserver($uname,$udom,'true');
9011: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9012: if ($crstype eq 'Community') {
9013: $first = '0';
9014: } else {
9015: $first = int(1+rand(9));
9016: }
9017: $uname=$first.
1.1011 raeburn 9018: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9019: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9020: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9021: $uhome=&homeserver($uname,$udom,'true');
9022: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9023: return 'error: unable to generate unique course-ID';
9024: }
9025: }
9026: return $uname;
9027: }
9028:
1.813 albertel 9029: sub is_course {
1.1167 droeschl 9030: my ($cdom, $cnum) = scalar(@_) == 1 ?
9031: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9032:
9033: return unless $cdom and $cnum;
9034:
9035: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9036: '.');
9037:
1.1172.2.23 raeburn 9038: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9039: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9040: }
9041:
1.1015 raeburn 9042: sub store_userdata {
9043: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9044: my $result;
1.1016 raeburn 9045: if ($datakey ne '') {
1.1013 raeburn 9046: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9047: if ($udom eq '' || $uname eq '') {
9048: $udom = $env{'user.domain'};
9049: $uname = $env{'user.name'};
9050: }
9051: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9052: if (($uhome eq '') || ($uhome eq 'no_host')) {
9053: $result = 'error: no_host';
9054: } else {
9055: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9056: $storehash->{'host'} = $perlvar{'lonHostID'};
9057:
9058: my $namevalue='';
9059: foreach my $key (keys(%{$storehash})) {
9060: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9061: }
9062: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9063: unless ($namespace eq 'courserequests') {
9064: $datakey = &escape($datakey);
9065: }
1.1105 raeburn 9066: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9067: $namevalue,$uhome);
1.1013 raeburn 9068: }
9069: } else {
9070: $result = 'error: data to store was not a hash reference';
9071: }
9072: } else {
9073: $result= 'error: invalid requestkey';
9074: }
9075: return $result;
9076: }
9077:
1.21 www 9078: # ---------------------------------------------------------- Assign Custom Role
9079:
9080: sub assigncustomrole {
1.957 raeburn 9081: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9082: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9083: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9084: }
9085:
9086: # ----------------------------------------------------------------- Revoke Role
9087:
9088: sub revokerole {
1.957 raeburn 9089: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9090: my $now=time;
1.965 raeburn 9091: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9092: }
9093:
9094: # ---------------------------------------------------------- Revoke Custom Role
9095:
9096: sub revokecustomrole {
1.957 raeburn 9097: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9098: my $now=time;
1.357 www 9099: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9100: $deleteflag,$selfenroll,$context);
1.17 www 9101: }
9102:
1.533 banghart 9103: # ------------------------------------------------------------ Disk usage
1.535 albertel 9104: sub diskusage {
1.955 raeburn 9105: my ($udom,$uname,$directorypath,$getpropath)=@_;
9106: $directorypath =~ s/\/$//;
9107: my $listing=&reply('du2:'.&escape($directorypath).':'
9108: .&escape($getpropath).':'.&escape($uname).':'
9109: .&escape($udom),homeserver($uname,$udom));
9110: if ($listing eq 'unknown_cmd') {
9111: if ($getpropath) {
9112: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9113: }
9114: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9115: }
1.514 albertel 9116: return $listing;
1.512 banghart 9117: }
9118:
1.566 banghart 9119: sub is_locked {
1.1096 raeburn 9120: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9121: my @check;
9122: my $is_locked;
1.1093 raeburn 9123: push (@check,$file_name);
1.613 albertel 9124: my %locked = &get('file_permissions',\@check,
1.620 albertel 9125: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9126: my ($tmp)=keys(%locked);
9127: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9128:
1.566 banghart 9129: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9130: $is_locked = 'false';
9131: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9132: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9133: $is_locked = 'true';
1.1096 raeburn 9134: if (ref($which) eq 'ARRAY') {
9135: push(@{$which},$entry);
9136: } else {
9137: last;
9138: }
1.745 raeburn 9139: }
9140: }
1.566 banghart 9141: } else {
9142: $is_locked = 'false';
9143: }
1.1093 raeburn 9144: return $is_locked;
1.566 banghart 9145: }
9146:
1.759 albertel 9147: sub declutter_portfile {
9148: my ($file) = @_;
1.833 albertel 9149: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9150: return $file;
9151: }
9152:
1.559 banghart 9153: # ------------------------------------------------------------- Mark as Read Only
9154:
9155: sub mark_as_readonly {
9156: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9157: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9158: my ($tmp)=keys(%current_permissions);
9159: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9160: foreach my $file (@{$files}) {
1.759 albertel 9161: $file = &declutter_portfile($file);
1.561 banghart 9162: push(@{$current_permissions{$file}},$what);
1.559 banghart 9163: }
1.613 albertel 9164: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9165: return;
9166: }
9167:
1.572 banghart 9168: # ------------------------------------------------------------Save Selected Files
9169:
9170: sub save_selected_files {
9171: my ($user, $path, @files) = @_;
9172: my $filename = $user."savedfiles";
1.573 banghart 9173: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9174: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9175: foreach my $file (@files) {
1.620 albertel 9176: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9177: }
9178: foreach my $file (@other_files) {
1.574 banghart 9179: print (OUT $file."\n");
1.572 banghart 9180: }
1.574 banghart 9181: close (OUT);
1.572 banghart 9182: return 'ok';
9183: }
9184:
1.574 banghart 9185: sub clear_selected_files {
9186: my ($user) = @_;
9187: my $filename = $user."savedfiles";
1.1117 foxr 9188: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9189: print (OUT undef);
9190: close (OUT);
9191: return ("ok");
9192: }
9193:
1.572 banghart 9194: sub files_in_path {
9195: my ($user, $path) = @_;
9196: my $filename = $user."savedfiles";
9197: my %return_files;
1.1117 foxr 9198: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9199: while (my $line_in = <IN>) {
1.574 banghart 9200: chomp ($line_in);
9201: my @paths_and_file = split (m!/!, $line_in);
9202: my $file_part = pop (@paths_and_file);
9203: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9204: $path_part.='/';
9205: my $path_and_file = $path_part.$file_part;
9206: if ($path_part eq $path) {
9207: $return_files{$file_part}= 'selected';
9208: }
9209: }
1.574 banghart 9210: close (IN);
9211: return (\%return_files);
1.572 banghart 9212: }
9213:
9214: # called in portfolio select mode, to show files selected NOT in current directory
9215: sub files_not_in_path {
9216: my ($user, $path) = @_;
9217: my $filename = $user."savedfiles";
9218: my @return_files;
9219: my $path_part;
1.1117 foxr 9220: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9221: while (my $line = <IN>) {
1.572 banghart 9222: #ok, I know it's clunky, but I want it to work
1.800 albertel 9223: my @paths_and_file = split(m|/|, $line);
9224: my $file_part = pop(@paths_and_file);
9225: chomp($file_part);
9226: my $path_part = join('/', @paths_and_file);
1.572 banghart 9227: $path_part .= '/';
9228: my $path_and_file = $path_part.$file_part;
9229: if ($path_part ne $path) {
1.800 albertel 9230: push(@return_files, ($path_and_file));
1.572 banghart 9231: }
9232: }
1.800 albertel 9233: close(OUT);
1.574 banghart 9234: return (@return_files);
1.572 banghart 9235: }
9236:
1.745 raeburn 9237: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9238:
1.745 raeburn 9239: sub get_portfile_permissions {
9240: my ($domain,$user) = @_;
1.613 albertel 9241: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9242: my ($tmp)=keys(%current_permissions);
9243: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9244: return \%current_permissions;
9245: }
9246:
9247: #---------------------------------------------Get portfolio file access controls
9248:
1.749 raeburn 9249: sub get_access_controls {
1.745 raeburn 9250: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9251: my %access;
9252: my $real_file = $file;
9253: $file =~ s/\.meta$//;
1.745 raeburn 9254: if (defined($file)) {
1.749 raeburn 9255: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9256: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9257: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9258: }
9259: }
1.745 raeburn 9260: } else {
1.749 raeburn 9261: foreach my $key (keys(%{$current_permissions})) {
9262: if ($key =~ /\0accesscontrol$/) {
9263: if (defined($group)) {
9264: if ($key !~ m-^\Q$group\E/-) {
9265: next;
9266: }
9267: }
9268: my ($fullpath) = split(/\0/,$key);
9269: if (ref($$current_permissions{$key}) eq 'HASH') {
9270: foreach my $control (keys(%{$$current_permissions{$key}})) {
9271: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9272: }
9273: }
9274: }
9275: }
9276: }
9277: return %access;
9278: }
9279:
9280: sub modify_access_controls {
9281: my ($file_name,$changes,$domain,$user)=@_;
9282: my ($outcome,$deloutcome);
9283: my %store_permissions;
9284: my %new_values;
9285: my %new_control;
9286: my %translation;
9287: my @deletions = ();
9288: my $now = time;
9289: if (exists($$changes{'activate'})) {
9290: if (ref($$changes{'activate'}) eq 'HASH') {
9291: my @newitems = sort(keys(%{$$changes{'activate'}}));
9292: my $numnew = scalar(@newitems);
9293: for (my $i=0; $i<$numnew; $i++) {
9294: my $newkey = $newitems[$i];
9295: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9296: if ($newkey =~ /^\d+:/) {
9297: $newkey =~ s/^(\d+)/$newid/;
9298: $translation{$1} = $newid;
9299: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9300: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9301: $translation{$1} = $newid;
9302: }
1.749 raeburn 9303: $new_values{$file_name."\0".$newkey} =
9304: $$changes{'activate'}{$newitems[$i]};
9305: $new_control{$newkey} = $now;
9306: }
9307: }
9308: }
9309: my %todelete;
9310: my %changed_items;
9311: foreach my $action ('delete','update') {
9312: if (exists($$changes{$action})) {
9313: if (ref($$changes{$action}) eq 'HASH') {
9314: foreach my $key (keys(%{$$changes{$action}})) {
9315: my ($itemnum) = ($key =~ /^([^:]+):/);
9316: if ($action eq 'delete') {
9317: $todelete{$itemnum} = 1;
9318: } else {
9319: $changed_items{$itemnum} = $key;
9320: }
9321: }
1.745 raeburn 9322: }
9323: }
1.749 raeburn 9324: }
9325: # get lock on access controls for file.
9326: my $lockhash = {
9327: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9328: ':'.$env{'user.domain'},
9329: };
9330: my $tries = 0;
9331: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9332:
9333: while (($gotlock ne 'ok') && $tries <3) {
9334: $tries ++;
9335: sleep 1;
9336: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9337: }
9338: if ($gotlock eq 'ok') {
9339: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9340: my ($tmp)=keys(%curr_permissions);
9341: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9342: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9343: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9344: if (ref($curr_controls) eq 'HASH') {
9345: foreach my $control_item (keys(%{$curr_controls})) {
9346: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9347: if (defined($todelete{$itemnum})) {
9348: push(@deletions,$file_name."\0".$control_item);
9349: } else {
9350: if (defined($changed_items{$itemnum})) {
9351: $new_control{$changed_items{$itemnum}} = $now;
9352: push(@deletions,$file_name."\0".$control_item);
9353: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9354: } else {
9355: $new_control{$control_item} = $$curr_controls{$control_item};
9356: }
9357: }
1.745 raeburn 9358: }
9359: }
9360: }
1.970 raeburn 9361: my ($group);
9362: if (&is_course($domain,$user)) {
9363: ($group,my $file) = split(/\//,$file_name,2);
9364: }
1.749 raeburn 9365: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9366: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9367: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9368: # remove lock
9369: my @del_lock = ($file_name."\0".'locked_access_records');
9370: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9371: my $sqlresult =
1.970 raeburn 9372: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9373: $group);
1.749 raeburn 9374: } else {
9375: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9376: }
1.749 raeburn 9377: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9378: }
9379:
1.827 raeburn 9380: sub make_public_indefinitely {
9381: my ($requrl) = @_;
9382: my $now = time;
9383: my $action = 'activate';
9384: my $aclnum = 0;
9385: if (&is_portfolio_url($requrl)) {
9386: my (undef,$udom,$unum,$file_name,$group) =
9387: &parse_portfolio_url($requrl);
9388: my $current_perms = &get_portfile_permissions($udom,$unum);
9389: my %access_controls = &get_access_controls($current_perms,
9390: $group,$file_name);
9391: foreach my $key (keys(%{$access_controls{$file_name}})) {
9392: my ($num,$scope,$end,$start) =
9393: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9394: if ($scope eq 'public') {
9395: if ($start <= $now && $end == 0) {
9396: $action = 'none';
9397: } else {
9398: $action = 'update';
9399: $aclnum = $num;
9400: }
9401: last;
9402: }
9403: }
9404: if ($action eq 'none') {
9405: return 'ok';
9406: } else {
9407: my %changes;
9408: my $newend = 0;
9409: my $newstart = $now;
9410: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9411: $changes{$action}{$newkey} = {
9412: type => 'public',
9413: time => {
9414: start => $newstart,
9415: end => $newend,
9416: },
9417: };
9418: my ($outcome,$deloutcome,$new_values,$translation) =
9419: &modify_access_controls($file_name,\%changes,$udom,$unum);
9420: return $outcome;
9421: }
9422: } else {
9423: return 'invalid';
9424: }
9425: }
9426:
1.745 raeburn 9427: #------------------------------------------------------Get Marked as Read Only
9428:
9429: sub get_marked_as_readonly {
9430: my ($domain,$user,$what,$group) = @_;
9431: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9432: my @readonly_files;
1.629 banghart 9433: my $cmp1=$what;
9434: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9435: while (my ($file_name,$value) = each(%{$current_permissions})) {
9436: if (defined($group)) {
9437: if ($file_name !~ m-^\Q$group\E/-) {
9438: next;
9439: }
9440: }
1.561 banghart 9441: if (ref($value) eq "ARRAY"){
9442: foreach my $stored_what (@{$value}) {
1.629 banghart 9443: my $cmp2=$stored_what;
1.759 albertel 9444: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9445: $cmp2=join('',@{$stored_what});
1.745 raeburn 9446: }
1.629 banghart 9447: if ($cmp1 eq $cmp2) {
1.561 banghart 9448: push(@readonly_files, $file_name);
1.745 raeburn 9449: last;
1.563 banghart 9450: } elsif (!defined($what)) {
9451: push(@readonly_files, $file_name);
1.745 raeburn 9452: last;
1.561 banghart 9453: }
9454: }
1.745 raeburn 9455: }
1.561 banghart 9456: }
9457: return @readonly_files;
9458: }
1.577 banghart 9459: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9460:
1.577 banghart 9461: sub get_marked_as_readonly_hash {
1.745 raeburn 9462: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9463: my %readonly_files;
1.745 raeburn 9464: while (my ($file_name,$value) = each(%{$current_permissions})) {
9465: if (defined($group)) {
9466: if ($file_name !~ m-^\Q$group\E/-) {
9467: next;
9468: }
9469: }
1.577 banghart 9470: if (ref($value) eq "ARRAY"){
9471: foreach my $stored_what (@{$value}) {
1.745 raeburn 9472: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9473: foreach my $lock_descriptor(@{$stored_what}) {
9474: if ($lock_descriptor eq 'graded') {
9475: $readonly_files{$file_name} = 'graded';
9476: } elsif ($lock_descriptor eq 'handback') {
9477: $readonly_files{$file_name} = 'handback';
9478: } else {
9479: if (!exists($readonly_files{$file_name})) {
9480: $readonly_files{$file_name} = 'locked';
9481: }
9482: }
1.745 raeburn 9483: }
1.750 banghart 9484: }
1.577 banghart 9485: }
9486: }
9487: }
9488: return %readonly_files;
9489: }
1.559 banghart 9490: # ------------------------------------------------------------ Unmark as Read Only
9491:
9492: sub unmark_as_readonly {
1.629 banghart 9493: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9494: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9495: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9496: $file_name = &declutter_portfile($file_name);
1.634 albertel 9497: my $symb_crs = $what;
9498: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9499: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9500: my ($tmp)=keys(%current_permissions);
9501: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9502: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9503: foreach my $file (@readonly_files) {
1.759 albertel 9504: my $clean_file = &declutter_portfile($file);
9505: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9506: my $current_locks = $current_permissions{$file};
1.563 banghart 9507: my @new_locks;
9508: my @del_keys;
9509: if (ref($current_locks) eq "ARRAY"){
9510: foreach my $locker (@{$current_locks}) {
1.632 albertel 9511: my $compare=$locker;
1.749 raeburn 9512: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9513: $compare=join('',@{$locker});
1.746 raeburn 9514: if ($compare ne $symb_crs) {
9515: push(@new_locks, $locker);
9516: }
1.563 banghart 9517: }
9518: }
1.650 albertel 9519: if (scalar(@new_locks) > 0) {
1.563 banghart 9520: $current_permissions{$file} = \@new_locks;
9521: } else {
9522: push(@del_keys, $file);
1.613 albertel 9523: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9524: delete($current_permissions{$file});
1.563 banghart 9525: }
9526: }
1.561 banghart 9527: }
1.613 albertel 9528: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9529: return;
9530: }
1.512 banghart 9531:
1.17 www 9532: # ------------------------------------------------------------ Directory lister
9533:
9534: sub dirlist {
1.955 raeburn 9535: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9536: $uri=~s/^\///;
9537: $uri=~s/\/$//;
1.253 stredwic 9538: my ($udom, $uname);
1.955 raeburn 9539: if ($getuserdir) {
1.253 stredwic 9540: $udom = $userdomain;
9541: $uname = $username;
1.955 raeburn 9542: } else {
9543: (undef,$udom,$uname)=split(/\//,$uri);
9544: if(defined($userdomain)) {
9545: $udom = $userdomain;
9546: }
9547: if(defined($username)) {
9548: $uname = $username;
9549: }
1.253 stredwic 9550: }
1.955 raeburn 9551: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9552:
1.955 raeburn 9553: $dirRoot = $perlvar{'lonDocRoot'};
9554: if (defined($getpropath)) {
9555: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9556: $dirRoot =~ s/\/$//;
1.955 raeburn 9557: } elsif (defined($getuserdir)) {
9558: my $subdir=$uname.'__';
9559: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9560: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9561: ."/$udom/$subdir/$uname";
9562: } elsif (defined($alternateRoot)) {
9563: $dirRoot = $alternateRoot;
1.751 banghart 9564: }
1.253 stredwic 9565:
9566: if($udom) {
9567: if($uname) {
1.1135 raeburn 9568: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9569: if ($uhome eq 'no_host') {
9570: return ([],'no_host');
9571: }
1.955 raeburn 9572: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9573: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9574: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9575: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9576: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9577: } else {
9578: @listing_results = map { &unescape($_); } split(/:/,$listing);
9579: }
1.605 matthew 9580: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9581: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9582: @listing_results = split(/:/,$listing);
9583: } else {
9584: @listing_results = map { &unescape($_); } split(/:/,$listing);
9585: }
1.1135 raeburn 9586: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9587: ($listing eq 'rejected') || ($listing eq 'refused') ||
9588: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9589: return ([],$listing);
9590: } else {
9591: return (\@listing_results);
1.1135 raeburn 9592: }
1.955 raeburn 9593: } elsif(!$alternateRoot) {
1.1136 raeburn 9594: my (%allusers,%listerror);
1.841 albertel 9595: my %servers = &get_servers($udom,'library');
1.955 raeburn 9596: foreach my $tryserver (keys(%servers)) {
9597: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9598: &escape($udom),$tryserver);
9599: if ($listing eq 'unknown_cmd') {
9600: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9601: $udom, $tryserver);
9602: } else {
9603: @listing_results = map { &unescape($_); } split(/:/,$listing);
9604: }
1.841 albertel 9605: if ($listing eq 'unknown_cmd') {
9606: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9607: $udom, $tryserver);
9608: @listing_results = split(/:/,$listing);
9609: } else {
9610: @listing_results =
9611: map { &unescape($_); } split(/:/,$listing);
9612: }
1.1136 raeburn 9613: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9614: ($listing eq 'rejected') || ($listing eq 'refused') ||
9615: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9616: $listerror{$tryserver} = $listing;
9617: } else {
1.841 albertel 9618: foreach my $line (@listing_results) {
9619: my ($entry) = split(/&/,$line,2);
9620: $allusers{$entry} = 1;
9621: }
9622: }
1.253 stredwic 9623: }
1.1136 raeburn 9624: my @alluserslist=();
1.800 albertel 9625: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9626: push(@alluserslist,$user.'&user');
1.253 stredwic 9627: }
1.1136 raeburn 9628: return (\@alluserslist);
1.253 stredwic 9629: } else {
1.1136 raeburn 9630: return ([],'missing username');
1.253 stredwic 9631: }
1.955 raeburn 9632: } elsif(!defined($getpropath)) {
1.1136 raeburn 9633: my $path = $perlvar{'lonDocRoot'}.'/res/';
9634: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9635: return (\@all_domains);
1.955 raeburn 9636: } else {
1.1136 raeburn 9637: return ([],'missing domain');
1.275 stredwic 9638: }
9639: }
9640:
9641: # --------------------------------------------- GetFileTimestamp
9642: # This function utilizes dirlist and returns the date stamp for
9643: # when it was last modified. It will also return an error of -1
9644: # if an error occurs
9645:
9646: sub GetFileTimestamp {
1.955 raeburn 9647: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9648: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9649: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9650: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9651: undef,$getuserdir);
9652: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9653: return -1;
9654: }
9655: if (ref($fileref) eq 'ARRAY') {
9656: my @stats = split('&',$fileref->[0]);
1.375 matthew 9657: # @stats contains first the filename, then the stat output
9658: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9659: } else {
9660: return -1;
1.253 stredwic 9661: }
1.26 www 9662: }
9663:
1.712 albertel 9664: sub stat_file {
9665: my ($uri) = @_;
1.787 albertel 9666: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9667:
1.955 raeburn 9668: my ($udom,$uname,$file);
1.712 albertel 9669: if ($uri =~ m-^/(uploaded|editupload)/-) {
9670: ($udom,$uname,$file) =
1.811 albertel 9671: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9672: $file = 'userfiles/'.$file;
9673: }
9674: if ($uri =~ m-^/res/-) {
9675: ($udom,$uname) =
1.807 albertel 9676: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9677: $file = $uri;
9678: }
9679:
9680: if (!$udom || !$uname || !$file) {
9681: # unable to handle the uri
9682: return ();
9683: }
1.956 raeburn 9684: my $getpropath;
9685: if ($file =~ /^userfiles\//) {
9686: $getpropath = 1;
9687: }
1.1136 raeburn 9688: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9689: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9690: return ();
9691: } else {
9692: if (ref($listref) eq 'ARRAY') {
9693: my @stats = split('&',$listref->[0]);
9694: shift(@stats); #filename is first
9695: return @stats;
9696: }
1.712 albertel 9697: }
9698: return ();
9699: }
9700:
1.26 www 9701: # -------------------------------------------------------- Value of a Condition
9702:
1.713 albertel 9703: # gets the value of a specific preevaluated condition
9704: # stored in the string $env{user.state.<cid>}
9705: # or looks up a condition reference in the bighash and if if hasn't
9706: # already been evaluated recurses into docondval to get the value of
9707: # the condition, then memoizing it to
9708: # $env{user.state.<cid>.<condition>}
1.40 www 9709: sub directcondval {
9710: my $number=shift;
1.620 albertel 9711: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9712: &Apache::lonuserstate::evalstate();
9713: }
1.713 albertel 9714: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9715: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9716: } elsif ($number =~ /^_/) {
9717: my $sub_condition;
9718: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9719: &GDBM_READER(),0640)) {
9720: $sub_condition=$bighash{'conditions'.$number};
9721: untie(%bighash);
9722: }
9723: my $value = &docondval($sub_condition);
1.949 raeburn 9724: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9725: return $value;
9726: }
1.620 albertel 9727: if ($env{'user.state.'.$env{'request.course.id'}}) {
9728: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9729: } else {
9730: return 2;
9731: }
9732: }
9733:
1.713 albertel 9734: # get the collection of conditions for this resource
1.26 www 9735: sub condval {
9736: my $condidx=shift;
1.54 www 9737: my $allpathcond='';
1.713 albertel 9738: foreach my $cond (split(/\|/,$condidx)) {
9739: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9740: $allpathcond.=
9741: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9742: }
1.191 harris41 9743: }
1.54 www 9744: $allpathcond=~s/\|$//;
1.713 albertel 9745: return &docondval($allpathcond);
9746: }
9747:
9748: #evaluates an expression of conditions
9749: sub docondval {
9750: my ($allpathcond) = @_;
9751: my $result=0;
9752: if ($env{'request.course.id'}
9753: && defined($allpathcond)) {
9754: my $operand='|';
9755: my @stack;
9756: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9757: if ($chunk eq '(') {
9758: push @stack,($operand,$result);
9759: } elsif ($chunk eq ')') {
9760: my $before=pop @stack;
9761: if (pop @stack eq '&') {
9762: $result=$result>$before?$before:$result;
9763: } else {
9764: $result=$result>$before?$result:$before;
9765: }
9766: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9767: $operand=$chunk;
9768: } else {
9769: my $new=directcondval($chunk);
9770: if ($operand eq '&') {
9771: $result=$result>$new?$new:$result;
9772: } else {
9773: $result=$result>$new?$result:$new;
9774: }
9775: }
9776: }
1.26 www 9777: }
9778: return $result;
1.421 albertel 9779: }
9780:
9781: # ---------------------------------------------------- Devalidate courseresdata
9782:
9783: sub devalidatecourseresdata {
9784: my ($coursenum,$coursedomain)=@_;
9785: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9786: &devalidate_cache_new('courseres',$hashid);
1.28 www 9787: }
9788:
1.763 www 9789:
1.200 www 9790: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9791: #
9792: # Parameters:
9793: # $coursenum - Number of the course.
9794: # $coursedomain - Domain at which the course was created.
9795: # Returns:
9796: # A hash of the course parameters along (I think) with timestamps
9797: # and version info.
1.877 foxr 9798:
1.624 albertel 9799: sub get_courseresdata {
9800: my ($coursenum,$coursedomain)=@_;
1.200 www 9801: my $coursehom=&homeserver($coursenum,$coursedomain);
9802: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9803: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9804: my %dumpreply;
1.417 albertel 9805: unless (defined($cached)) {
1.624 albertel 9806: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9807: $result=\%dumpreply;
1.251 albertel 9808: my ($tmp) = keys(%dumpreply);
9809: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9810: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9811: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9812: return $tmp;
1.416 albertel 9813: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9814: $result=undef;
1.599 albertel 9815: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9816: }
9817: }
1.624 albertel 9818: return $result;
9819: }
9820:
1.633 albertel 9821: sub devalidateuserresdata {
9822: my ($uname,$udom)=@_;
9823: my $hashid="$udom:$uname";
9824: &devalidate_cache_new('userres',$hashid);
9825: }
9826:
1.624 albertel 9827: sub get_userresdata {
9828: my ($uname,$udom)=@_;
9829: #most student don\'t have any data set, check if there is some data
9830: if (&EXT_cache_status($udom,$uname)) { return undef; }
9831:
9832: my $hashid="$udom:$uname";
9833: my ($result,$cached)=&is_cached_new('userres',$hashid);
9834: if (!defined($cached)) {
9835: my %resourcedata=&dump('resourcedata',$udom,$uname);
9836: $result=\%resourcedata;
9837: &do_cache_new('userres',$hashid,$result,600);
9838: }
9839: my ($tmp)=keys(%$result);
9840: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9841: return $result;
9842: }
9843: #error 2 occurs when the .db doesn't exist
9844: if ($tmp!~/error: 2 /) {
1.672 albertel 9845: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9846: " Trying to get resource data for ".
9847: $uname." at ".$udom.": ".
9848: $tmp."</font>");
9849: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9850: #&EXT_cache_set($udom,$uname);
9851: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9852: undef($tmp); # not really an error so don't send it back
1.624 albertel 9853: }
9854: return $tmp;
9855: }
1.879 foxr 9856: #----------------------------------------------- resdata - return resource data
9857: # Purpose:
9858: # Return resource data for either users or for a course.
9859: # Parameters:
9860: # $name - Course/user name.
9861: # $domain - Name of the domain the user/course is registered on.
9862: # $type - Type of thing $name is (must be 'course' or 'user'
9863: # @which - Array of names of resources desired.
9864: # Returns:
9865: # The value of the first reasource in @which that is found in the
9866: # resource hash.
9867: # Exceptional Conditions:
9868: # If the $type passed in is not valid (not the string 'course' or
9869: # 'user', an undefined reference is returned.
9870: # If none of the resources are found, an undef is returned
1.624 albertel 9871: sub resdata {
9872: my ($name,$domain,$type,@which)=@_;
9873: my $result;
9874: if ($type eq 'course') {
9875: $result=&get_courseresdata($name,$domain);
9876: } elsif ($type eq 'user') {
9877: $result=&get_userresdata($name,$domain);
9878: }
9879: if (!ref($result)) { return $result; }
1.251 albertel 9880: foreach my $item (@which) {
1.927 albertel 9881: if (defined($result->{$item->[0]})) {
9882: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9883: }
1.250 albertel 9884: }
1.291 albertel 9885: return undef;
1.200 www 9886: }
9887:
1.1172.2.31 raeburn 9888: sub get_numsuppfiles {
9889: my ($cnum,$cdom,$ignorecache)=@_;
9890: my $hashid=$cnum.':'.$cdom;
9891: my ($suppcount,$cached);
9892: unless ($ignorecache) {
9893: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9894: }
9895: unless (defined($cached)) {
9896: my $chome=&homeserver($cnum,$cdom);
9897: unless ($chome eq 'no_host') {
9898: ($suppcount,my $errors) = (0,0);
9899: my $suppmap = 'supplemental.sequence';
9900: ($suppcount,$errors) =
9901: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9902: }
9903: &do_cache_new('suppcount',$hashid,$suppcount,600);
9904: }
9905: return $suppcount;
9906: }
9907:
1.379 matthew 9908: #
9909: # EXT resource caching routines
9910: #
9911:
9912: sub clear_EXT_cache_status {
1.383 albertel 9913: &delenv('cache.EXT.');
1.379 matthew 9914: }
9915:
9916: sub EXT_cache_status {
9917: my ($target_domain,$target_user) = @_;
1.383 albertel 9918: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9919: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9920: # We know already the user has no data
9921: return 1;
9922: } else {
9923: return 0;
9924: }
9925: }
9926:
9927: sub EXT_cache_set {
9928: my ($target_domain,$target_user) = @_;
1.383 albertel 9929: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9930: #&appenv({$cachename => time});
1.379 matthew 9931: }
9932:
1.28 www 9933: # --------------------------------------------------------- Value of a Variable
1.58 www 9934: sub EXT {
1.715 albertel 9935:
1.1172.2.28 raeburn 9936: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9937: unless ($varname) { return ''; }
1.218 albertel 9938: #get real user name/domain, courseid and symb
9939: my $courseid;
1.359 albertel 9940: my $publicuser;
1.427 www 9941: if ($symbparm) {
9942: $symbparm=&get_symb_from_alias($symbparm);
9943: }
1.218 albertel 9944: if (!($uname && $udom)) {
1.790 albertel 9945: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9946: if (!$symbparm) { $symbparm=$cursymb; }
9947: } else {
1.620 albertel 9948: $courseid=$env{'request.course.id'};
1.218 albertel 9949: }
1.48 www 9950: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9951: my $rest;
1.320 albertel 9952: if (defined($therest[0])) {
1.48 www 9953: $rest=join('.',@therest);
9954: } else {
9955: $rest='';
9956: }
1.320 albertel 9957:
1.57 www 9958: my $qualifierrest=$qualifier;
9959: if ($rest) { $qualifierrest.='.'.$rest; }
9960: my $spacequalifierrest=$space;
9961: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9962: if ($realm eq 'user') {
1.48 www 9963: # --------------------------------------------------------------- user.resource
9964: if ($space eq 'resource') {
1.651 albertel 9965: if ( (defined($Apache::lonhomework::parsing_a_problem)
9966: || defined($Apache::lonhomework::parsing_a_task))
9967: &&
1.744 albertel 9968: ($symbparm eq &symbread()) ) {
9969: # if we are in the middle of processing the resource the
9970: # get the value we are planning on committing
9971: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9972: return $Apache::lonhomework::results{$qualifierrest};
9973: } else {
9974: return $Apache::lonhomework::history{$qualifierrest};
9975: }
1.335 albertel 9976: } else {
1.359 albertel 9977: my %restored;
1.620 albertel 9978: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9979: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9980: } else {
9981: %restored=&restore($symbparm,$courseid,$udom,$uname);
9982: }
1.335 albertel 9983: return $restored{$qualifierrest};
9984: }
1.48 www 9985: # ----------------------------------------------------------------- user.access
9986: } elsif ($space eq 'access') {
1.218 albertel 9987: # FIXME - not supporting calls for a specific user
1.48 www 9988: return &allowed($qualifier,$rest);
9989: # ------------------------------------------ user.preferences, user.environment
9990: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9991: if (($uname eq $env{'user.name'}) &&
9992: ($udom eq $env{'user.domain'})) {
9993: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9994: } else {
1.359 albertel 9995: my %returnhash;
9996: if (!$publicuser) {
9997: %returnhash=&userenvironment($udom,$uname,
9998: $qualifierrest);
9999: }
1.218 albertel 10000: return $returnhash{$qualifierrest};
10001: }
1.48 www 10002: # ----------------------------------------------------------------- user.course
10003: } elsif ($space eq 'course') {
1.218 albertel 10004: # FIXME - not supporting calls for a specific user
1.620 albertel 10005: return $env{join('.',('request.course',$qualifier))};
1.48 www 10006: # ------------------------------------------------------------------- user.role
10007: } elsif ($space eq 'role') {
1.218 albertel 10008: # FIXME - not supporting calls for a specific user
1.620 albertel 10009: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10010: if ($qualifier eq 'value') {
10011: return $role;
10012: } elsif ($qualifier eq 'extent') {
10013: return $where;
10014: }
10015: # ----------------------------------------------------------------- user.domain
10016: } elsif ($space eq 'domain') {
1.218 albertel 10017: return $udom;
1.48 www 10018: # ------------------------------------------------------------------- user.name
10019: } elsif ($space eq 'name') {
1.218 albertel 10020: return $uname;
1.48 www 10021: # ---------------------------------------------------- Any other user namespace
1.29 www 10022: } else {
1.359 albertel 10023: my %reply;
10024: if (!$publicuser) {
10025: %reply=&get($space,[$qualifierrest],$udom,$uname);
10026: }
10027: return $reply{$qualifierrest};
1.48 www 10028: }
1.236 www 10029: } elsif ($realm eq 'query') {
10030: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10031: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10032: [$spacequalifierrest]);
1.620 albertel 10033: return $env{'form.'.$spacequalifierrest};
1.236 www 10034: } elsif ($realm eq 'request') {
1.48 www 10035: # ------------------------------------------------------------- request.browser
10036: if ($space eq 'browser') {
1.1145 bisitz 10037: return $env{'browser.'.$qualifier};
1.57 www 10038: # ------------------------------------------------------------ request.filename
10039: } else {
1.620 albertel 10040: return $env{'request.'.$spacequalifierrest};
1.29 www 10041: }
1.28 www 10042: } elsif ($realm eq 'course') {
1.48 www 10043: # ---------------------------------------------------------- course.description
1.620 albertel 10044: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10045: } elsif ($realm eq 'resource') {
1.165 www 10046:
1.620 albertel 10047: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10048: if (!$symbparm) { $symbparm=&symbread(); }
10049: }
1.693 albertel 10050:
1.1172.2.30 raeburn 10051: if ($qualifier eq '') {
10052: if ($space eq 'title') {
10053: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10054: return &gettitle($symbparm);
10055: }
1.693 albertel 10056:
1.1172.2.30 raeburn 10057: if ($space eq 'map') {
10058: my ($map) = &decode_symb($symbparm);
10059: return &symbread($map);
10060: }
10061: if ($space eq 'maptitle') {
10062: my ($map) = &decode_symb($symbparm);
10063: return &gettitle($map);
10064: }
10065: if ($space eq 'filename') {
10066: if ($symbparm) {
10067: return &clutter((&decode_symb($symbparm))[2]);
10068: }
10069: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10070: }
1.1172.2.30 raeburn 10071:
10072: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10073: if ($space eq 'visibleparts') {
10074: my $navmap = Apache::lonnavmaps::navmap->new();
10075: my $item;
10076: if (ref($navmap)) {
10077: my $res = $navmap->getBySymb($symbparm);
10078: my $parts = $res->parts();
10079: if (ref($parts) eq 'ARRAY') {
10080: $item = join(',',@{$parts});
10081: }
10082: undef($navmap);
10083: }
10084: return $item;
10085: }
10086: }
10087: }
1.693 albertel 10088:
10089: my ($section, $group, @groups);
1.593 albertel 10090: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10091: if (($courseid eq '') && ($cid)) {
10092: $courseid = $cid;
10093: }
10094: if (($symbparm && $courseid) &&
10095: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10096:
1.218 albertel 10097: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10098:
1.60 www 10099: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10100: my $symbp=$symbparm;
1.735 albertel 10101: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10102:
10103: my $symbparm=$symbp.'.'.$spacequalifierrest;
10104: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10105:
1.620 albertel 10106: if (($env{'user.name'} eq $uname) &&
10107: ($env{'user.domain'} eq $udom)) {
10108: $section=$env{'request.course.sec'};
1.733 raeburn 10109: @groups = split(/:/,$env{'request.course.groups'});
10110: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10111: } else {
1.539 albertel 10112: if (! defined($usection)) {
1.551 albertel 10113: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10114: } else {
10115: $section = $usection;
10116: }
1.733 raeburn 10117: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10118: }
10119:
10120: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10121: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10122: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10123:
1.593 albertel 10124: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10125: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10126: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10127:
1.60 www 10128: # ----------------------------------------------------------- first, check user
1.624 albertel 10129:
10130: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10131: ([$courselevelr,'resource'],
10132: [$courselevelm,'map' ],
10133: [$courselevel, 'course' ]));
1.931 albertel 10134: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10135:
1.594 albertel 10136: # ------------------------------------------------ second, check some of course
1.684 raeburn 10137: my $coursereply;
1.691 raeburn 10138: if (@groups > 0) {
10139: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10140: $mapparm,$spacequalifierrest);
1.927 albertel 10141: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10142: }
1.96 www 10143:
1.684 raeburn 10144: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10145: $env{'course.'.$courseid.'.domain'},
10146: 'course',
10147: ([$seclevelr, 'resource'],
10148: [$seclevelm, 'map' ],
10149: [$seclevel, 'course' ],
10150: [$courselevelr,'resource']));
10151: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10152:
1.60 www 10153: # ------------------------------------------------------ third, check map parms
1.218 albertel 10154: my %parmhash=();
10155: my $thisparm='';
10156: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10157: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10158: &GDBM_READER(),0640)) {
1.218 albertel 10159: $thisparm=$parmhash{$symbparm};
10160: untie(%parmhash);
10161: }
1.927 albertel 10162: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10163: }
1.594 albertel 10164: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10165:
1.218 albertel 10166: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10167: my $filename;
10168: if (!$symbparm) { $symbparm=&symbread(); }
10169: if ($symbparm) {
1.409 www 10170: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10171: } else {
1.620 albertel 10172: $filename=$env{'request.filename'};
1.282 albertel 10173: }
10174: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10175: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10176: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10177: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10178:
1.927 albertel 10179: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10180: if ($symbparm && defined($courseid) &&
1.620 albertel 10181: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10182: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10183: $env{'course.'.$courseid.'.domain'},
10184: 'course',
1.927 albertel 10185: ([$courselevelm,'map' ],
10186: [$courselevel, 'course']));
10187: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10188: }
1.145 www 10189: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10190: unless ($space eq '0') {
1.336 albertel 10191: my @parts=split(/_/,$space);
10192: my $id=pop(@parts);
10193: my $part=join('_',@parts);
10194: if ($part eq '') { $part='0'; }
1.927 albertel 10195: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10196: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10197: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10198: }
1.395 albertel 10199: if ($recurse) { return undef; }
10200: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10201: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10202: # ---------------------------------------------------- Any other user namespace
10203: } elsif ($realm eq 'environment') {
10204: # ----------------------------------------------------------------- environment
1.620 albertel 10205: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10206: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10207: } else {
1.770 albertel 10208: if ($uname eq 'anonymous' && $udom eq '') {
10209: return '';
10210: }
1.219 albertel 10211: my %returnhash=&userenvironment($udom,$uname,
10212: $spacequalifierrest);
10213: return $returnhash{$spacequalifierrest};
10214: }
1.28 www 10215: } elsif ($realm eq 'system') {
1.48 www 10216: # ----------------------------------------------------------------- system.time
10217: if ($space eq 'time') {
10218: return time;
10219: }
1.696 albertel 10220: } elsif ($realm eq 'server') {
10221: # ----------------------------------------------------------------- system.time
10222: if ($space eq 'name') {
10223: return $ENV{'SERVER_NAME'};
10224: }
1.28 www 10225: }
1.48 www 10226: return '';
1.61 www 10227: }
10228:
1.927 albertel 10229: sub get_reply {
10230: my ($reply_value) = @_;
1.940 raeburn 10231: if (ref($reply_value) eq 'ARRAY') {
10232: if (wantarray) {
10233: return @$reply_value;
10234: }
10235: return $reply_value->[0];
10236: } else {
10237: return $reply_value;
1.927 albertel 10238: }
10239: }
10240:
1.691 raeburn 10241: sub check_group_parms {
10242: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10243: my @groupitems = ();
10244: my $resultitem;
1.927 albertel 10245: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10246: foreach my $group (@{$groups}) {
10247: foreach my $level (@levels) {
1.927 albertel 10248: my $item = $courseid.'.['.$group.'].'.$level->[0];
10249: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10250: }
10251: }
10252: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10253: $env{'course.'.$courseid.'.domain'},
10254: 'course',@groupitems);
10255: return $coursereply;
10256: }
10257:
10258: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10259: my ($courseid,@groups) = @_;
10260: @groups = sort(@groups);
1.691 raeburn 10261: return @groups;
10262: }
10263:
1.395 albertel 10264: sub packages_tab_default {
10265: my ($uri,$varname)=@_;
10266: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10267:
10268: my (@extension,@specifics,$do_default);
10269: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10270: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10271: if ($pack_type eq 'default') {
10272: $do_default=1;
10273: } elsif ($pack_type eq 'extension') {
10274: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10275: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10276: # only look at packages defaults for packages that this id is
1.738 albertel 10277: push(@specifics,[$package,$pack_type,$pack_part]);
10278: }
10279: }
10280: # first look for a package that matches the requested part id
10281: foreach my $package (@specifics) {
10282: my (undef,$pack_type,$pack_part)=@{$package};
10283: next if ($pack_part ne $part);
10284: if (defined($packagetab{"$pack_type&$name&default"})) {
10285: return $packagetab{"$pack_type&$name&default"};
10286: }
10287: }
10288: # look for any possible matching non extension_ package
10289: foreach my $package (@specifics) {
10290: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10291: if (defined($packagetab{"$pack_type&$name&default"})) {
10292: return $packagetab{"$pack_type&$name&default"};
10293: }
1.585 albertel 10294: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10295: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10296: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10297: }
10298: }
1.738 albertel 10299: # look for any posible extension_ match
10300: foreach my $package (@extension) {
10301: my ($package,$pack_type)=@{$package};
10302: if (defined($packagetab{"$pack_type&$name&default"})) {
10303: return $packagetab{"$pack_type&$name&default"};
10304: }
10305: if (defined($packagetab{$package."&$name&default"})) {
10306: return $packagetab{$package."&$name&default"};
10307: }
10308: }
10309: # look for a global default setting
10310: if ($do_default && defined($packagetab{"default&$name&default"})) {
10311: return $packagetab{"default&$name&default"};
10312: }
1.395 albertel 10313: return undef;
10314: }
10315:
1.334 albertel 10316: sub add_prefix_and_part {
10317: my ($prefix,$part)=@_;
10318: my $keyroot;
10319: if (defined($prefix) && $prefix !~ /^__/) {
10320: # prefix that has a part already
10321: $keyroot=$prefix;
10322: } elsif (defined($prefix)) {
10323: # prefix that is missing a part
10324: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10325: } else {
10326: # no prefix at all
10327: if (defined($part)) { $keyroot='_'.$part; }
10328: }
10329: return $keyroot;
10330: }
10331:
1.71 www 10332: # ---------------------------------------------------------------- Get metadata
10333:
1.599 albertel 10334: my %metaentry;
1.1070 www 10335: my %importedpartids;
1.71 www 10336: sub metadata {
1.176 www 10337: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10338: $uri=&declutter($uri);
1.288 albertel 10339: # if it is a non metadata possible uri return quickly
1.529 albertel 10340: if (($uri eq '') ||
10341: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10342: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10343: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10344: return undef;
10345: }
1.1172.2.49 raeburn 10346: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10347: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10348: return undef;
1.288 albertel 10349: }
1.73 www 10350: my $filename=$uri;
10351: $uri=~s/\.meta$//;
1.172 www 10352: #
10353: # Is the metadata already cached?
1.177 www 10354: # Look at timestamp of caching
1.172 www 10355: # Everything is cached by the main uri, libraries are never directly cached
10356: #
1.428 albertel 10357: if (!defined($liburi)) {
1.599 albertel 10358: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10359: if (defined($cached)) { return $result->{':'.$what}; }
10360: }
10361: {
1.1069 www 10362: # Imported parts would go here
1.1070 www 10363: my %importedids=();
10364: my @origfileimportpartids=();
1.1069 www 10365: my $importedparts=0;
1.172 www 10366: #
10367: # Is this a recursive call for a library?
10368: #
1.599 albertel 10369: # if (! exists($metacache{$uri})) {
10370: # $metacache{$uri}={};
10371: # }
1.924 albertel 10372: my $cachetime = 60*60;
1.171 www 10373: if ($liburi) {
10374: $liburi=&declutter($liburi);
10375: $filename=$liburi;
1.401 bowersj2 10376: } else {
1.599 albertel 10377: &devalidate_cache_new('meta',$uri);
10378: undef(%metaentry);
1.401 bowersj2 10379: }
1.140 www 10380: my %metathesekeys=();
1.73 www 10381: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10382: my $metastring;
1.1140 www 10383: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10384: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10385: $metastring =
1.929 albertel 10386: &Apache::lonnet::ssi_body($which,
1.924 albertel 10387: ('grade_target' => 'meta'));
10388: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10389: } elsif (($uri !~ m -^(editupload)/-) &&
10390: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10391: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10392: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10393: $metastring=&getfile($file);
1.489 albertel 10394: }
1.208 albertel 10395: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10396: my $token;
1.140 www 10397: undef %metathesekeys;
1.71 www 10398: while ($token=$parser->get_token) {
1.339 albertel 10399: if ($token->[0] eq 'S') {
10400: if (defined($token->[2]->{'package'})) {
1.172 www 10401: #
10402: # This is a package - get package info
10403: #
1.339 albertel 10404: my $package=$token->[2]->{'package'};
10405: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10406: if (defined($token->[2]->{'id'})) {
10407: $keyroot.='_'.$token->[2]->{'id'};
10408: }
1.599 albertel 10409: if ($metaentry{':packages'}) {
10410: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10411: } else {
1.599 albertel 10412: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10413: }
1.736 albertel 10414: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10415: my $part=$keyroot;
10416: $part=~s/^\_//;
1.736 albertel 10417: if ($pack_entry=~/^\Q$package\E\&/ ||
10418: $pack_entry=~/^\Q$package\E_0\&/) {
10419: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10420: # ignore package.tab specified default values
10421: # here &package_tab_default() will fetch those
10422: if ($subp eq 'default') { next; }
1.736 albertel 10423: my $value=$packagetab{$pack_entry};
1.432 albertel 10424: my $unikey;
10425: if ($pack =~ /_0$/) {
10426: $unikey='parameter_0_'.$name;
10427: $part=0;
10428: } else {
10429: $unikey='parameter'.$keyroot.'_'.$name;
10430: }
1.339 albertel 10431: if ($subp eq 'display') {
10432: $value.=' [Part: '.$part.']';
10433: }
1.599 albertel 10434: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10435: $metathesekeys{$unikey}=1;
1.599 albertel 10436: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10437: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10438: }
1.599 albertel 10439: if (defined($metaentry{':'.$unikey.'.default'})) {
10440: $metaentry{':'.$unikey}=
10441: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10442: }
1.339 albertel 10443: }
10444: }
10445: } else {
1.172 www 10446: #
10447: # This is not a package - some other kind of start tag
1.339 albertel 10448: #
10449: my $entry=$token->[1];
1.1068 www 10450: my $unikey='';
1.175 www 10451:
1.339 albertel 10452: if ($entry eq 'import') {
1.175 www 10453: #
10454: # Importing a library here
1.339 albertel 10455: #
1.1067 www 10456: my $location=$parser->get_text('/import');
10457: my $dir=$filename;
10458: $dir=~s|[^/]*$||;
10459: $location=&filelocation($dir,$location);
1.1069 www 10460:
1.1068 www 10461: my $importmode=$token->[2]->{'importmode'};
10462: if ($importmode eq 'problem') {
1.1069 www 10463: # Import as problem/response
1.1068 www 10464: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10465: } elsif ($importmode eq 'part') {
10466: # Import as part(s)
1.1069 www 10467: $importedparts=1;
10468: # We need to get the original file and the imported file to get the part order correct
10469: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10470: # Load and inspect original file
1.1070 www 10471: if ($#origfileimportpartids<0) {
10472: undef(%importedpartids);
10473: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10474: my $origfile=&getfile($origfilelocation);
10475: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10476: }
10477:
1.1069 www 10478: # Load and inspect imported file
10479: my $impfile=&getfile($location);
10480: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10481: if ($#impfilepartids>=0) {
10482: # This problem had parts
1.1070 www 10483: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10484: } else {
10485: # Importing by turning a single problem into a problem part
10486: # It gets the import-tags ID as part-ID
10487: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10488: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10489: }
1.1068 www 10490: } else {
10491: # Normal import
10492: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10493: if (defined($token->[2]->{'id'})) {
10494: $unikey.='_'.$token->[2]->{'id'};
10495: }
1.1067 www 10496: }
10497:
1.339 albertel 10498: if ($depthcount<20) {
1.736 albertel 10499: my $metadata =
10500: &metadata($uri,'keys', $location,$unikey,
10501: $depthcount+1);
10502: foreach my $meta (split(',',$metadata)) {
10503: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10504: $metathesekeys{$meta}=1;
1.339 albertel 10505: }
1.1068 www 10506:
10507: }
1.1067 www 10508: } else {
10509: #
10510: # Not importing, some other kind of non-package, non-library start tag
10511: #
10512: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10513: if (defined($token->[2]->{'id'})) {
10514: $unikey.='_'.$token->[2]->{'id'};
10515: }
1.339 albertel 10516: if (defined($token->[2]->{'name'})) {
10517: $unikey.='_'.$token->[2]->{'name'};
10518: }
10519: $metathesekeys{$unikey}=1;
1.736 albertel 10520: foreach my $param (@{$token->[3]}) {
10521: $metaentry{':'.$unikey.'.'.$param} =
10522: $token->[2]->{$param};
1.339 albertel 10523: }
10524: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10525: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10526: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10527: # only ws inside the tag, and not in default, so use default
10528: # as value
1.599 albertel 10529: $metaentry{':'.$unikey}=$default;
1.908 albertel 10530: } elsif ( $internaltext =~ /\S/ ) {
10531: # something interesting inside the tag
10532: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10533: } else {
1.908 albertel 10534: # no interesting values, don't set a default
1.339 albertel 10535: }
1.172 www 10536: # end of not-a-package not-a-library import
1.339 albertel 10537: }
1.172 www 10538: # end of not-a-package start tag
1.339 albertel 10539: }
1.172 www 10540: # the next is the end of "start tag"
1.339 albertel 10541: }
10542: }
1.483 albertel 10543: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10544: $extension = lc($extension);
10545: if ($extension eq 'htm') { $extension='html'; }
10546:
1.737 albertel 10547: foreach my $key (keys(%packagetab)) {
1.483 albertel 10548: #no specific packages #how's our extension
10549: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10550: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10551: \%metathesekeys);
10552: }
1.883 albertel 10553:
10554: if (!exists($metaentry{':packages'})
10555: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10556: foreach my $key (keys(%packagetab)) {
1.483 albertel 10557: #no specific packages well let's get default then
10558: if ($key!~/^default&/) { next; }
1.488 albertel 10559: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10560: \%metathesekeys);
10561: }
10562: }
1.338 www 10563: # are there custom rights to evaluate
1.599 albertel 10564: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10565:
1.338 www 10566: #
10567: # Importing a rights file here
1.339 albertel 10568: #
10569: unless ($depthcount) {
1.599 albertel 10570: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10571: my $dir=$filename;
10572: $dir=~s|[^/]*$||;
10573: $location=&filelocation($dir,$location);
1.736 albertel 10574: my $rights_metadata =
10575: &metadata($uri,'keys',$location,'_rights',
10576: $depthcount+1);
10577: foreach my $rights (split(',',$rights_metadata)) {
10578: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10579: $metathesekeys{$rights}=1;
1.339 albertel 10580: }
10581: }
10582: }
1.737 albertel 10583: # uniqifiy package listing
10584: my %seen;
10585: my @uniq_packages =
10586: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10587: $metaentry{':packages'} = join(',',@uniq_packages);
10588:
1.1070 www 10589: if ($importedparts) {
10590: # We had imported parts and need to rebuild partorder
10591: $metaentry{':partorder'}='';
10592: $metathesekeys{'partorder'}=1;
10593: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10594: if ($origfileimportpartids[$index] eq 'part') {
10595: # original part, part of the problem
10596: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10597: } else {
10598: # we have imported parts at this position
10599: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10600: }
10601: }
10602: $metaentry{':partorder'}=~s/^\,//;
10603: }
10604:
1.737 albertel 10605: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10606: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 10607: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10608: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10609: # this is the end of "was not already recently cached
1.71 www 10610: }
1.599 albertel 10611: return $metaentry{':'.$what};
1.261 albertel 10612: }
10613:
1.488 albertel 10614: sub metadata_create_package_def {
1.483 albertel 10615: my ($uri,$key,$package,$metathesekeys)=@_;
10616: my ($pack,$name,$subp)=split(/\&/,$key);
10617: if ($subp eq 'default') { next; }
10618:
1.599 albertel 10619: if (defined($metaentry{':packages'})) {
10620: $metaentry{':packages'}.=','.$package;
1.483 albertel 10621: } else {
1.599 albertel 10622: $metaentry{':packages'}=$package;
1.483 albertel 10623: }
10624: my $value=$packagetab{$key};
10625: my $unikey;
10626: $unikey='parameter_0_'.$name;
1.599 albertel 10627: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10628: $$metathesekeys{$unikey}=1;
1.599 albertel 10629: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10630: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10631: }
1.599 albertel 10632: if (defined($metaentry{':'.$unikey.'.default'})) {
10633: $metaentry{':'.$unikey}=
10634: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10635: }
10636: }
10637:
1.261 albertel 10638: sub metadata_generate_part0 {
10639: my ($metadata,$metacache,$uri) = @_;
10640: my %allnames;
1.737 albertel 10641: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10642: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10643: my $part=$$metacache{':'.$metakey.'.part'};
10644: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10645: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10646: $allnames{$name}=$part;
10647: }
10648: }
10649: }
10650: foreach my $name (keys(%allnames)) {
10651: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10652: my $key=":parameter_0_$name";
1.261 albertel 10653: $$metacache{"$key.part"}='0';
10654: $$metacache{"$key.name"}=$name;
1.428 albertel 10655: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10656: $allnames{$name}.'_'.$name.
10657: '.type'};
1.428 albertel 10658: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10659: '.display'};
1.644 www 10660: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10661: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10662: $$metacache{"$key.display"}=$olddis;
10663: }
1.71 www 10664: }
10665:
1.764 albertel 10666: # ------------------------------------------------------ Devalidate title cache
10667:
10668: sub devalidate_title_cache {
10669: my ($url)=@_;
10670: if (!$env{'request.course.id'}) { return; }
10671: my $symb=&symbread($url);
10672: if (!$symb) { return; }
10673: my $key=$env{'request.course.id'}."\0".$symb;
10674: &devalidate_cache_new('title',$key);
10675: }
10676:
1.1014 droeschl 10677: # ------------------------------------------------- Get the title of a course
10678:
10679: sub current_course_title {
10680: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10681: }
1.301 www 10682: # ------------------------------------------------- Get the title of a resource
10683:
10684: sub gettitle {
10685: my $urlsymb=shift;
10686: my $symb=&symbread($urlsymb);
1.534 albertel 10687: if ($symb) {
1.620 albertel 10688: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10689: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10690: if (defined($cached)) {
10691: return $result;
10692: }
1.534 albertel 10693: my ($map,$resid,$url)=&decode_symb($symb);
10694: my $title='';
1.907 albertel 10695: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10696: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10697: } else {
10698: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10699: &GDBM_READER(),0640)) {
10700: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10701: $title=$bighash{'title_'.$mapid.'.'.$resid};
10702: untie(%bighash);
10703: }
1.534 albertel 10704: }
10705: $title=~s/\&colon\;/\:/gs;
10706: if ($title) {
1.1159 www 10707: # Remember both $symb and $title for dynamic metadata
10708: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10709: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10710: # Cache this title and then return it
1.599 albertel 10711: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10712: }
10713: $urlsymb=$url;
10714: }
10715: my $title=&metadata($urlsymb,'title');
10716: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10717: return $title;
1.301 www 10718: }
1.613 albertel 10719:
1.614 albertel 10720: sub get_slot {
10721: my ($which,$cnum,$cdom)=@_;
10722: if (!$cnum || !$cdom) {
1.790 albertel 10723: (undef,my $courseid)=&whichuser();
1.620 albertel 10724: $cdom=$env{'course.'.$courseid.'.domain'};
10725: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10726: }
1.703 albertel 10727: my $key=join("\0",'slots',$cdom,$cnum,$which);
10728: my %slotinfo;
10729: if (exists($remembered{$key})) {
10730: $slotinfo{$which} = $remembered{$key};
10731: } else {
10732: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10733: &Apache::lonhomework::showhash(%slotinfo);
10734: my ($tmp)=keys(%slotinfo);
10735: if ($tmp=~/^error:/) { return (); }
10736: $remembered{$key} = $slotinfo{$which};
10737: }
1.616 albertel 10738: if (ref($slotinfo{$which}) eq 'HASH') {
10739: return %{$slotinfo{$which}};
10740: }
10741: return $slotinfo{$which};
1.614 albertel 10742: }
1.1150 raeburn 10743:
10744: sub get_reservable_slots {
10745: my ($cnum,$cdom,$uname,$udom) = @_;
10746: my $now = time;
10747: my $reservable_info;
10748: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10749: if (exists($remembered{$key})) {
10750: $reservable_info = $remembered{$key};
10751: } else {
10752: my %resv;
10753: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10754: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10755: $reservable_info = \%resv;
10756: $remembered{$key} = $reservable_info;
10757: }
10758: return $reservable_info;
10759: }
10760:
10761: sub get_course_slots {
10762: my ($cnum,$cdom) = @_;
10763: my $hashid=$cnum.':'.$cdom;
10764: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10765: if (defined($cached)) {
10766: if (ref($result) eq 'HASH') {
10767: return %{$result};
10768: }
10769: } else {
10770: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10771: my ($tmp) = keys(%slots);
10772: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10773: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10774: return %slots;
10775: }
10776: }
10777: return;
10778: }
10779:
10780: sub devalidate_slots_cache {
10781: my ($cnum,$cdom)=@_;
10782: my $hashid=$cnum.':'.$cdom;
10783: &devalidate_cache_new('allslots',$hashid);
10784: }
10785:
1.1172.2.8 raeburn 10786: sub get_coursechange {
10787: my ($cdom,$cnum) = @_;
10788: if ($cdom eq '' || $cnum eq '') {
10789: return unless ($env{'request.course.id'});
10790: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10791: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10792: }
10793: my $hashid=$cdom.'_'.$cnum;
10794: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10795: if ((defined($cached)) && ($change ne '')) {
10796: return $change;
10797: } else {
10798: my %crshash;
10799: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10800: if ($crshash{'internal.contentchange'} eq '') {
10801: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10802: if ($change eq '') {
10803: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10804: $change = $crshash{'internal.created'};
10805: }
10806: } else {
10807: $change = $crshash{'internal.contentchange'};
10808: }
10809: my $cachetime = 600;
10810: &do_cache_new('crschange',$hashid,$change,$cachetime);
10811: }
10812: return $change;
10813: }
10814:
10815: sub devalidate_coursechange_cache {
10816: my ($cnum,$cdom)=@_;
10817: my $hashid=$cnum.':'.$cdom;
10818: &devalidate_cache_new('crschange',$hashid);
10819: }
10820:
1.31 www 10821: # ------------------------------------------------- Update symbolic store links
10822:
10823: sub symblist {
10824: my ($mapname,%newhash)=@_;
1.438 www 10825: $mapname=&deversion(&declutter($mapname));
1.31 www 10826: my %hash;
1.620 albertel 10827: if (($env{'request.course.fn'}) && (%newhash)) {
10828: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10829: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10830: foreach my $url (keys(%newhash)) {
1.711 albertel 10831: next if ($url eq 'last_known'
10832: && $env{'form.no_update_last_known'});
10833: $hash{declutter($url)}=&encode_symb($mapname,
10834: $newhash{$url}->[1],
10835: $newhash{$url}->[0]);
1.191 harris41 10836: }
1.31 www 10837: if (untie(%hash)) {
10838: return 'ok';
10839: }
10840: }
10841: }
10842: return 'error';
1.212 www 10843: }
10844:
10845: # --------------------------------------------------------------- Verify a symb
10846:
10847: sub symbverify {
1.1172.2.11 raeburn 10848: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10849: my $thisfn=$thisurl;
1.439 www 10850: $thisfn=&declutter($thisfn);
1.215 www 10851: # direct jump to resource in page or to a sequence - will construct own symbs
10852: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10853: # check URL part
1.409 www 10854: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10855:
1.431 www 10856: unless ($url eq $thisfn) { return 0; }
1.213 www 10857:
1.216 www 10858: $symb=&symbclean($symb);
1.510 www 10859: $thisurl=&deversion($thisurl);
1.439 www 10860: $thisfn=&deversion($thisfn);
1.213 www 10861:
10862: my %bighash;
10863: my $okay=0;
1.431 www 10864:
1.620 albertel 10865: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10866: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10867: my $noclutter;
1.1032 raeburn 10868: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10869: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10870: if ($map =~ m{^uploaded/.+\.page$}) {
10871: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10872: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10873: $noclutter = 1;
10874: }
10875: }
10876: my $ids;
10877: if ($noclutter) {
10878: $ids=$bighash{'ids_'.$thisurl};
10879: } else {
10880: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10881: }
1.1102 raeburn 10882: unless ($ids) {
1.1172.2.13 raeburn 10883: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10884: $ids=$bighash{$idkey};
1.216 www 10885: }
10886: if ($ids) {
10887: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10888: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10889: $symb =~ s/\?.+$//;
10890: }
1.800 albertel 10891: foreach my $id (split(/\,/,$ids)) {
10892: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10893: if (
10894: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10895: eq $symb) {
1.1172.2.11 raeburn 10896: if (ref($encstate)) {
10897: $$encstate = $bighash{'encrypted_'.$id};
10898: }
1.1172.2.13 raeburn 10899: if (($env{'request.role.adv'}) ||
10900: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10901: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10902: $okay=1;
10903: last;
10904: }
10905: }
10906: }
1.216 www 10907: }
1.213 www 10908: untie(%bighash);
10909: }
10910: return $okay;
1.31 www 10911: }
10912:
1.210 www 10913: # --------------------------------------------------------------- Clean-up symb
10914:
10915: sub symbclean {
10916: my $symb=shift;
1.568 albertel 10917: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10918: # remove version from map
10919: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10920:
1.210 www 10921: # remove version from URL
10922: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10923:
1.507 www 10924: # remove wrapper
10925:
1.510 www 10926: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10927: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10928: return $symb;
1.409 www 10929: }
10930:
10931: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10932:
10933: sub encode_symb {
10934: my ($map,$resid,$url)=@_;
10935: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10936: }
1.409 www 10937:
10938: sub decode_symb {
1.568 albertel 10939: my $symb=shift;
10940: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10941: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10942: return (&fixversion($map),$resid,&fixversion($url));
10943: }
10944:
10945: sub fixversion {
10946: my $fn=shift;
1.609 banghart 10947: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10948: my %bighash;
10949: my $uri=&clutter($fn);
1.620 albertel 10950: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10951: # is this cached?
1.599 albertel 10952: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10953: if (defined($cached)) { return $result; }
10954: # unfortunately not cached, or expired
1.620 albertel 10955: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10956: &GDBM_READER(),0640)) {
10957: if ($bighash{'version_'.$uri}) {
10958: my $version=$bighash{'version_'.$uri};
1.444 www 10959: unless (($version eq 'mostrecent') ||
10960: ($version==&getversion($uri))) {
1.440 www 10961: $uri=~s/\.(\w+)$/\.$version\.$1/;
10962: }
10963: }
10964: untie %bighash;
1.413 www 10965: }
1.599 albertel 10966: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10967: }
10968:
10969: sub deversion {
10970: my $url=shift;
10971: $url=~s/\.\d+\.(\w+)$/\.$1/;
10972: return $url;
1.210 www 10973: }
10974:
1.31 www 10975: # ------------------------------------------------------ Return symb list entry
10976:
10977: sub symbread {
1.249 www 10978: my ($thisfn,$donotrecurse)=@_;
1.1172.2.54 raeburn 10979: my $cache_str='request.symbread.cached.'.$thisfn;
10980: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 10981: # no filename provided? try from environment
1.1172.2.54 raeburn 10982: unless ($thisfn) {
1.620 albertel 10983: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10984: return $env{$cache_str}=&symbclean($env{'request.symb'});
10985: }
10986: $thisfn=$env{'request.filename'};
1.44 www 10987: }
1.569 albertel 10988: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10989: # is that filename actually a symb? Verify, clean, and return
10990: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10991: if (&symbverify($thisfn,$1)) {
1.620 albertel 10992: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10993: }
1.242 www 10994: }
1.44 www 10995: $thisfn=declutter($thisfn);
1.31 www 10996: my %hash;
1.37 www 10997: my %bighash;
10998: my $syval='';
1.620 albertel 10999: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11000: my $targetfn = $thisfn;
1.609 banghart 11001: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11002: $targetfn = 'adm/wrapper/'.$thisfn;
11003: }
1.687 albertel 11004: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11005: $targetfn=$1;
11006: }
1.620 albertel 11007: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11008: &GDBM_READER(),0640)) {
1.481 raeburn 11009: $syval=$hash{$targetfn};
1.37 www 11010: untie(%hash);
11011: }
11012: # ---------------------------------------------------------- There was an entry
11013: if ($syval) {
1.601 albertel 11014: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11015: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11016: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11017: #return $env{$cache_str}='';
1.601 albertel 11018: #}
11019: #$syval.=$1;
11020: #}
1.37 www 11021: } else {
11022: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11023: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11024: &GDBM_READER(),0640)) {
1.37 www 11025: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11026: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11027: unless ($ids) {
11028: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11029: }
11030: unless ($ids) {
11031: # alias?
11032: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11033: }
1.37 www 11034: if ($ids) {
11035: # ------------------------------------------------------------------- Has ID(s)
11036: my @possibilities=split(/\,/,$ids);
1.39 www 11037: if ($#possibilities==0) {
11038: # ----------------------------------------------- There is only one possibility
1.37 www 11039: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11040: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11041: $resid,$thisfn);
1.249 www 11042: } elsif (!$donotrecurse) {
1.39 www 11043: # ------------------------------------------ There is more than one possibility
11044: my $realpossible=0;
1.800 albertel 11045: foreach my $id (@possibilities) {
11046: my $file=$bighash{'src_'.$id};
1.39 www 11047: if (&allowed('bre',$file)) {
1.800 albertel 11048: my ($mapid,$resid)=split(/\./,$id);
1.39 www 11049: if ($bighash{'map_type_'.$mapid} ne 'page') {
11050: $realpossible++;
1.626 albertel 11051: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11052: $resid,$thisfn);
1.39 www 11053: }
11054: }
1.191 harris41 11055: }
1.39 www 11056: if ($realpossible!=1) { $syval=''; }
1.249 www 11057: } else {
11058: $syval='';
1.37 www 11059: }
11060: }
11061: untie(%bighash)
1.481 raeburn 11062: }
1.31 www 11063: }
1.62 www 11064: if ($syval) {
1.620 albertel 11065: return $env{$cache_str}=$syval;
1.62 www 11066: }
1.31 www 11067: }
1.949 raeburn 11068: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11069: return $env{$cache_str}='';
1.31 www 11070: }
11071:
11072: # ---------------------------------------------------------- Return random seed
11073:
1.32 www 11074: sub numval {
11075: my $txt=shift;
11076: $txt=~tr/A-J/0-9/;
11077: $txt=~tr/a-j/0-9/;
11078: $txt=~tr/K-T/0-9/;
11079: $txt=~tr/k-t/0-9/;
11080: $txt=~tr/U-Z/0-5/;
11081: $txt=~tr/u-z/0-5/;
11082: $txt=~s/\D//g;
1.564 albertel 11083: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11084: return int($txt);
1.368 albertel 11085: }
11086:
1.484 albertel 11087: sub numval2 {
11088: my $txt=shift;
11089: $txt=~tr/A-J/0-9/;
11090: $txt=~tr/a-j/0-9/;
11091: $txt=~tr/K-T/0-9/;
11092: $txt=~tr/k-t/0-9/;
11093: $txt=~tr/U-Z/0-5/;
11094: $txt=~tr/u-z/0-5/;
11095: $txt=~s/\D//g;
11096: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11097: my $total;
11098: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11099: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11100: return int($total);
11101: }
11102:
1.575 albertel 11103: sub numval3 {
11104: use integer;
11105: my $txt=shift;
11106: $txt=~tr/A-J/0-9/;
11107: $txt=~tr/a-j/0-9/;
11108: $txt=~tr/K-T/0-9/;
11109: $txt=~tr/k-t/0-9/;
11110: $txt=~tr/U-Z/0-5/;
11111: $txt=~tr/u-z/0-5/;
11112: $txt=~s/\D//g;
11113: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11114: my $total;
11115: foreach my $val (@txts) { $total+=$val; }
11116: if ($_64bit) { $total=(($total<<32)>>32); }
11117: return $total;
11118: }
11119:
1.675 albertel 11120: sub digest {
11121: my ($data)=@_;
11122: my $digest=&Digest::MD5::md5($data);
11123: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11124: my ($e,$f);
11125: {
11126: use integer;
11127: $e=($a+$b);
11128: $f=($c+$d);
11129: if ($_64bit) {
11130: $e=(($e<<32)>>32);
11131: $f=(($f<<32)>>32);
11132: }
11133: }
11134: if (wantarray) {
11135: return ($e,$f);
11136: } else {
11137: my $g;
11138: {
11139: use integer;
11140: $g=($e+$f);
11141: if ($_64bit) {
11142: $g=(($g<<32)>>32);
11143: }
11144: }
11145: return $g;
11146: }
11147: }
11148:
1.368 albertel 11149: sub latest_rnd_algorithm_id {
1.675 albertel 11150: return '64bit5';
1.366 albertel 11151: }
1.32 www 11152:
1.503 albertel 11153: sub get_rand_alg {
11154: my ($courseid)=@_;
1.790 albertel 11155: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11156: if ($courseid) {
1.620 albertel 11157: return $env{"course.$courseid.rndseed"};
1.503 albertel 11158: }
11159: return &latest_rnd_algorithm_id();
11160: }
11161:
1.562 albertel 11162: sub validCODE {
11163: my ($CODE)=@_;
11164: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11165: return 0;
11166: }
11167:
1.491 albertel 11168: sub getCODE {
1.620 albertel 11169: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11170: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11171: defined($Apache::lonhomework::parsing_a_task) ) &&
11172: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11173: return $Apache::lonhomework::history{'resource.CODE'};
11174: }
11175: return undef;
11176: }
1.1133 foxr 11177: #
11178: # Determines the random seed for a specific context:
11179: #
11180: # parameters:
11181: # symb - in course context the symb for the seed.
11182: # course_id - The course id of the form domain_coursenum.
11183: # domain - Domain for the user.
11184: # course - Course for the user.
11185: # cenv - environment of the course.
11186: #
11187: # NOTE:
11188: # All parameters are picked out of the environment if missing
11189: # or not defined.
11190: # If a symb cannot be determined the current time is used instead.
11191: #
11192: # For a given well defined symb, courside, domain, username,
11193: # and course environment, the seed is reproducible.
11194: #
1.31 www 11195: sub rndseed {
1.1133 foxr 11196: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11197: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11198: if (!defined($symb)) {
1.366 albertel 11199: unless ($symb=$wsymb) { return time; }
11200: }
1.1146 foxr 11201: if (!defined $courseid) {
11202: $courseid=$wcourseid;
11203: }
11204: if (!defined $domain) { $domain=$wdomain; }
11205: if (!defined $username) { $username=$wusername }
1.1133 foxr 11206:
11207: my $which;
11208: if (defined($cenv->{'rndseed'})) {
11209: $which = $cenv->{'rndseed'};
11210: } else {
11211: $which =&get_rand_alg($courseid);
11212: }
1.491 albertel 11213: if (defined(&getCODE())) {
1.675 albertel 11214: if ($which eq '64bit5') {
11215: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11216: } elsif ($which eq '64bit4') {
1.575 albertel 11217: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11218: } else {
11219: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11220: }
1.675 albertel 11221: } elsif ($which eq '64bit5') {
11222: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11223: } elsif ($which eq '64bit4') {
11224: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11225: } elsif ($which eq '64bit3') {
11226: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11227: } elsif ($which eq '64bit2') {
11228: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11229: } elsif ($which eq '64bit') {
11230: return &rndseed_64bit($symb,$courseid,$domain,$username);
11231: }
11232: return &rndseed_32bit($symb,$courseid,$domain,$username);
11233: }
11234:
11235: sub rndseed_32bit {
11236: my ($symb,$courseid,$domain,$username)=@_;
11237: {
11238: use integer;
11239: my $symbchck=unpack("%32C*",$symb) << 27;
11240: my $symbseed=numval($symb) << 22;
11241: my $namechck=unpack("%32C*",$username) << 17;
11242: my $nameseed=numval($username) << 12;
11243: my $domainseed=unpack("%32C*",$domain) << 7;
11244: my $courseseed=unpack("%32C*",$courseid);
11245: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11246: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11247: #&logthis("rndseed :$num:$symb");
1.564 albertel 11248: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11249: return $num;
11250: }
11251: }
11252:
11253: sub rndseed_64bit {
11254: my ($symb,$courseid,$domain,$username)=@_;
11255: {
11256: use integer;
11257: my $symbchck=unpack("%32S*",$symb) << 21;
11258: my $symbseed=numval($symb) << 10;
11259: my $namechck=unpack("%32S*",$username);
11260:
11261: my $nameseed=numval($username) << 21;
11262: my $domainseed=unpack("%32S*",$domain) << 10;
11263: my $courseseed=unpack("%32S*",$courseid);
11264:
11265: my $num1=$symbchck+$symbseed+$namechck;
11266: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11267: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11268: #&logthis("rndseed :$num:$symb");
1.564 albertel 11269: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11270: return "$num1,$num2";
1.155 albertel 11271: }
1.366 albertel 11272: }
11273:
1.443 albertel 11274: sub rndseed_64bit2 {
11275: my ($symb,$courseid,$domain,$username)=@_;
11276: {
11277: use integer;
11278: # strings need to be an even # of cahracters long, it it is odd the
11279: # last characters gets thrown away
11280: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11281: my $symbseed=numval($symb) << 10;
11282: my $namechck=unpack("%32S*",$username.' ');
11283:
11284: my $nameseed=numval($username) << 21;
1.501 albertel 11285: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11286: my $courseseed=unpack("%32S*",$courseid.' ');
11287:
11288: my $num1=$symbchck+$symbseed+$namechck;
11289: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11290: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11291: #&logthis("rndseed :$num:$symb");
1.803 albertel 11292: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11293: return "$num1,$num2";
11294: }
11295: }
11296:
11297: sub rndseed_64bit3 {
11298: my ($symb,$courseid,$domain,$username)=@_;
11299: {
11300: use integer;
11301: # strings need to be an even # of cahracters long, it it is odd the
11302: # last characters gets thrown away
11303: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11304: my $symbseed=numval2($symb) << 10;
11305: my $namechck=unpack("%32S*",$username.' ');
11306:
11307: my $nameseed=numval2($username) << 21;
1.443 albertel 11308: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11309: my $courseseed=unpack("%32S*",$courseid.' ');
11310:
11311: my $num1=$symbchck+$symbseed+$namechck;
11312: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11313: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11314: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11315: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11316:
1.503 albertel 11317: return "$num1:$num2";
1.443 albertel 11318: }
11319: }
11320:
1.575 albertel 11321: sub rndseed_64bit4 {
11322: my ($symb,$courseid,$domain,$username)=@_;
11323: {
11324: use integer;
11325: # strings need to be an even # of cahracters long, it it is odd the
11326: # last characters gets thrown away
11327: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11328: my $symbseed=numval3($symb) << 10;
11329: my $namechck=unpack("%32S*",$username.' ');
11330:
11331: my $nameseed=numval3($username) << 21;
11332: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11333: my $courseseed=unpack("%32S*",$courseid.' ');
11334:
11335: my $num1=$symbchck+$symbseed+$namechck;
11336: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11337: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11338: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11339: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11340:
1.575 albertel 11341: return "$num1:$num2";
11342: }
11343: }
11344:
1.675 albertel 11345: sub rndseed_64bit5 {
11346: my ($symb,$courseid,$domain,$username)=@_;
11347: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11348: return "$num1:$num2";
11349: }
11350:
1.366 albertel 11351: sub rndseed_CODE_64bit {
11352: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11353: {
1.366 albertel 11354: use integer;
1.443 albertel 11355: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11356: my $symbseed=numval2($symb);
1.491 albertel 11357: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11358: my $CODEseed=numval(&getCODE());
1.443 albertel 11359: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11360: my $num1=$symbseed+$CODEchck;
11361: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11362: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11363: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11364: if ($_64bit) { $num1=(($num1<<32)>>32); }
11365: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11366: return "$num1:$num2";
1.366 albertel 11367: }
11368: }
11369:
1.575 albertel 11370: sub rndseed_CODE_64bit4 {
11371: my ($symb,$courseid,$domain,$username)=@_;
11372: {
11373: use integer;
11374: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11375: my $symbseed=numval3($symb);
11376: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11377: my $CODEseed=numval3(&getCODE());
11378: my $courseseed=unpack("%32S*",$courseid.' ');
11379: my $num1=$symbseed+$CODEchck;
11380: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11381: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11382: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11383: if ($_64bit) { $num1=(($num1<<32)>>32); }
11384: if ($_64bit) { $num2=(($num2<<32)>>32); }
11385: return "$num1:$num2";
11386: }
11387: }
11388:
1.675 albertel 11389: sub rndseed_CODE_64bit5 {
11390: my ($symb,$courseid,$domain,$username)=@_;
11391: my $code = &getCODE();
11392: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11393: return "$num1:$num2";
11394: }
11395:
1.366 albertel 11396: sub setup_random_from_rndseed {
11397: my ($rndseed)=@_;
1.503 albertel 11398: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11399: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11400: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11401: &Math::Random::random_set_seed_from_phrase($rndseed);
11402: } else {
11403: &Math::Random::random_set_seed($num1,$num2);
11404: }
1.366 albertel 11405: } else {
11406: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11407: }
1.36 albertel 11408: }
11409:
1.474 albertel 11410: sub latest_receipt_algorithm_id {
1.835 albertel 11411: return 'receipt3';
1.474 albertel 11412: }
11413:
1.480 www 11414: sub recunique {
11415: my $fucourseid=shift;
11416: my $unique;
1.835 albertel 11417: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11418: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11419: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11420: } else {
11421: $unique=$perlvar{'lonReceipt'};
11422: }
11423: return unpack("%32C*",$unique);
11424: }
11425:
11426: sub recprefix {
11427: my $fucourseid=shift;
11428: my $prefix;
1.835 albertel 11429: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11430: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11431: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11432: } else {
11433: $prefix=$perlvar{'lonHostID'};
11434: }
11435: return unpack("%32C*",$prefix);
11436: }
11437:
1.76 www 11438: sub ireceipt {
1.474 albertel 11439: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11440:
11441: my $return =&recprefix($fucourseid).'-';
11442:
11443: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11444: $env{'request.state'} eq 'construct') {
11445: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11446: return $return;
11447: }
11448:
1.76 www 11449: my $cuname=unpack("%32C*",$funame);
11450: my $cudom=unpack("%32C*",$fudom);
11451: my $cucourseid=unpack("%32C*",$fucourseid);
11452: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11453: my $cunique=&recunique($fucourseid);
1.474 albertel 11454: my $cpart=unpack("%32S*",$part);
1.835 albertel 11455: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11456:
1.790 albertel 11457: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11458:
11459: $return.= ($cunique%$cuname+
11460: $cunique%$cudom+
11461: $cusymb%$cuname+
11462: $cusymb%$cudom+
11463: $cucourseid%$cuname+
11464: $cucourseid%$cudom+
11465: $cpart%$cuname+
11466: $cpart%$cudom);
11467: } else {
11468: $return.= ($cunique%$cuname+
11469: $cunique%$cudom+
11470: $cusymb%$cuname+
11471: $cusymb%$cudom+
11472: $cucourseid%$cuname+
11473: $cucourseid%$cudom);
11474: }
11475: return $return;
1.76 www 11476: }
11477:
11478: sub receipt {
1.474 albertel 11479: my ($part)=@_;
1.790 albertel 11480: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11481: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11482: }
1.260 ng 11483:
1.790 albertel 11484: sub whichuser {
11485: my ($passedsymb)=@_;
11486: my ($symb,$courseid,$domain,$name,$publicuser);
11487: if (defined($env{'form.grade_symb'})) {
11488: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11489: my $allowed=&allowed('vgr',$tmp_courseid);
11490: if (!$allowed &&
11491: exists($env{'request.course.sec'}) &&
11492: $env{'request.course.sec'} !~ /^\s*$/) {
11493: $allowed=&allowed('vgr',$tmp_courseid.
11494: '/'.$env{'request.course.sec'});
11495: }
11496: if ($allowed) {
11497: ($symb)=&get_env_multiple('form.grade_symb');
11498: $courseid=$tmp_courseid;
11499: ($domain)=&get_env_multiple('form.grade_domain');
11500: ($name)=&get_env_multiple('form.grade_username');
11501: return ($symb,$courseid,$domain,$name,$publicuser);
11502: }
11503: }
11504: if (!$passedsymb) {
11505: $symb=&symbread();
11506: } else {
11507: $symb=$passedsymb;
11508: }
11509: $courseid=$env{'request.course.id'};
11510: $domain=$env{'user.domain'};
11511: $name=$env{'user.name'};
11512: if ($name eq 'public' && $domain eq 'public') {
11513: if (!defined($env{'form.username'})) {
11514: $env{'form.username'}.=time.rand(10000000);
11515: }
11516: $name.=$env{'form.username'};
11517: }
11518: return ($symb,$courseid,$domain,$name,$publicuser);
11519:
11520: }
11521:
1.36 albertel 11522: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11523: # returns either the contents of the file or
11524: # -1 if the file doesn't exist
1.481 raeburn 11525: #
11526: # if the target is a file that was uploaded via DOCS,
11527: # a check will be made to see if a current copy exists on the local server,
11528: # if it does this will be served, otherwise a copy will be retrieved from
11529: # the home server for the course and stored in /home/httpd/html/userfiles on
11530: # the local server.
1.472 albertel 11531:
1.36 albertel 11532: sub getfile {
1.538 albertel 11533: my ($file) = @_;
1.609 banghart 11534: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11535: &repcopy($file);
11536: return &readfile($file);
11537: }
11538:
11539: sub repcopy_userfile {
11540: my ($file)=@_;
1.1142 raeburn 11541: my $londocroot = $perlvar{'lonDocRoot'};
11542: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11543: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11544: my ($cdom,$cnum,$filename) =
1.811 albertel 11545: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11546: my $uri="/uploaded/$cdom/$cnum/$filename";
11547: if (-e "$file") {
1.828 www 11548: # we already have a local copy, check it out
1.538 albertel 11549: my @fileinfo = stat($file);
1.828 www 11550: my $rtncode;
11551: my $info;
1.538 albertel 11552: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11553: if ($lwpresp ne 'ok') {
1.828 www 11554: # there is no such file anymore, even though we had a local copy
1.482 albertel 11555: if ($rtncode eq '404') {
1.538 albertel 11556: unlink($file);
1.482 albertel 11557: }
11558: return -1;
11559: }
11560: if ($info < $fileinfo[9]) {
1.828 www 11561: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11562: return 'ok';
1.828 www 11563: } else {
11564: # the file is outdated, get rid of it
11565: unlink($file);
1.482 albertel 11566: }
1.828 www 11567: }
11568: # one way or the other, at this point, we don't have the file
11569: # construct the correct path for the file
11570: my @parts = ($cdom,$cnum);
11571: if ($filename =~ m|^(.+)/[^/]+$|) {
11572: push @parts, split(/\//,$1);
11573: }
11574: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11575: foreach my $part (@parts) {
11576: $path .= '/'.$part;
11577: if (!-e $path) {
11578: mkdir($path,0770);
1.482 albertel 11579: }
11580: }
1.828 www 11581: # now the path exists for sure
11582: # get a user agent
11583: my $ua=new LWP::UserAgent;
11584: my $transferfile=$file.'.in.transfer';
11585: # FIXME: this should flock
11586: if (-e $transferfile) { return 'ok'; }
11587: my $request;
11588: $uri=~s/^\///;
1.980 raeburn 11589: my $homeserver = &homeserver($cnum,$cdom);
11590: my $protocol = $protocol{$homeserver};
11591: $protocol = 'http' if ($protocol ne 'https');
11592: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11593: my $response=$ua->request($request,$transferfile);
11594: # did it work?
11595: if ($response->is_error()) {
11596: unlink($transferfile);
11597: &logthis("Userfile repcopy failed for $uri");
11598: return -1;
11599: }
11600: # worked, rename the transfer file
11601: rename($transferfile,$file);
1.607 raeburn 11602: return 'ok';
1.481 raeburn 11603: }
11604:
1.517 albertel 11605: sub tokenwrapper {
11606: my $uri=shift;
1.980 raeburn 11607: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11608: $uri=~s|^/||;
1.620 albertel 11609: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11610: my $token=$1;
1.552 albertel 11611: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11612: if ($udom && $uname && $file) {
11613: $file=~s|(\?\.*)*$||;
1.949 raeburn 11614: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11615: my $homeserver = &homeserver($uname,$udom);
11616: my $protocol = $protocol{$homeserver};
11617: $protocol = 'http' if ($protocol ne 'https');
11618: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11619: (($uri=~/\?/)?'&':'?').'token='.$token.
11620: '&tokenissued='.$perlvar{'lonHostID'};
11621: } else {
11622: return '/adm/notfound.html';
11623: }
11624: }
11625:
1.828 www 11626: # call with reqtype HEAD: get last modification time
11627: # call with reqtype GET: get the file contents
11628: # Do not call this with reqtype GET for large files! It loads everything into memory
11629: #
1.481 raeburn 11630: sub getuploaded {
11631: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11632: $uri=~s/^\///;
1.980 raeburn 11633: my $homeserver = &homeserver($cnum,$cdom);
11634: my $protocol = $protocol{$homeserver};
11635: $protocol = 'http' if ($protocol ne 'https');
11636: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11637: my $ua=new LWP::UserAgent;
11638: my $request=new HTTP::Request($reqtype,$uri);
11639: my $response=$ua->request($request);
11640: $$rtncode = $response->code;
1.482 albertel 11641: if (! $response->is_success()) {
11642: return 'failed';
11643: }
11644: if ($reqtype eq 'HEAD') {
1.486 www 11645: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11646: } elsif ($reqtype eq 'GET') {
11647: $$info = $response->content;
1.472 albertel 11648: }
1.482 albertel 11649: return 'ok';
1.36 albertel 11650: }
11651:
1.481 raeburn 11652: sub readfile {
11653: my $file = shift;
11654: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11655: my $fh;
11656: open($fh,"<$file");
11657: my $a='';
1.800 albertel 11658: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11659: return $a;
11660: }
11661:
1.36 albertel 11662: sub filelocation {
1.590 banghart 11663: my ($dir,$file) = @_;
11664: my $location;
11665: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11666:
11667: if ($file =~ m-^/adm/-) {
11668: $file=~s-^/adm/wrapper/-/-;
11669: $file=~s-^/adm/coursedocs/showdoc/-/-;
11670: }
1.882 albertel 11671:
1.1139 www 11672: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11673: $location = $file;
1.609 banghart 11674: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11675: my ($udom,$uname,$filename)=
1.811 albertel 11676: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11677: my $home=&homeserver($uname,$udom);
11678: my $is_me=0;
11679: my @ids=¤t_machine_ids();
11680: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11681: if ($is_me) {
1.1117 foxr 11682: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11683: } else {
11684: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11685: $udom.'/'.$uname.'/'.$filename;
11686: }
1.882 albertel 11687: } elsif ($file =~ m-^/adm/-) {
11688: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11689: } else {
11690: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11691: $file=~s:^/(res|priv)/:/:;
11692: my $space=$1;
1.590 banghart 11693: if ( !( $file =~ m:^/:) ) {
11694: $location = $dir. '/'.$file;
11695: } else {
1.1142 raeburn 11696: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11697: }
1.59 albertel 11698: }
1.590 banghart 11699: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11700: while ($location=~m{/\.\./}) {
11701: if ($location =~ m{/[^/]+/\.\./}) {
11702: $location=~ s{/[^/]+/\.\./}{/}g;
11703: } else {
11704: $location=~ s{/\.\./}{/}g;
11705: }
11706: } #remove dir/..
1.590 banghart 11707: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11708: return $location;
1.46 www 11709: }
1.36 albertel 11710:
1.46 www 11711: sub hreflocation {
11712: my ($dir,$file)=@_;
1.980 raeburn 11713: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11714: $file=filelocation($dir,$file);
1.700 albertel 11715: } elsif ($file=~m-^/adm/-) {
11716: $file=~s-^/adm/wrapper/-/-;
11717: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11718: }
11719: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11720: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11721: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11722: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11723: {/uploaded/$1/$2/}x;
1.46 www 11724: }
1.913 albertel 11725: if ($file=~ m{^/userfiles/}) {
11726: $file =~ s{^/userfiles/}{/uploaded/};
11727: }
1.462 albertel 11728: return $file;
1.465 albertel 11729: }
11730:
1.1139 www 11731:
11732:
11733:
11734:
1.465 albertel 11735: sub current_machine_domains {
1.853 albertel 11736: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11737: }
11738:
11739: sub machine_domains {
11740: my ($hostname) = @_;
1.465 albertel 11741: my @domains;
1.838 albertel 11742: my %hostname = &all_hostnames();
1.465 albertel 11743: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11744: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11745: if ($hostname eq $name) {
1.844 albertel 11746: push(@domains,&host_domain($id));
1.465 albertel 11747: }
11748: }
11749: return @domains;
11750: }
11751:
11752: sub current_machine_ids {
1.853 albertel 11753: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11754: }
11755:
11756: sub machine_ids {
11757: my ($hostname) = @_;
11758: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11759: my @ids;
1.888 albertel 11760: my %name_to_host = &all_names();
1.889 albertel 11761: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11762: return @{ $name_to_host{$hostname} };
11763: }
11764: return;
1.31 www 11765: }
11766:
1.824 raeburn 11767: sub additional_machine_domains {
11768: my @domains;
11769: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11770: while( my $line = <$fh>) {
11771: $line =~ s/\s//g;
11772: push(@domains,$line);
11773: }
11774: return @domains;
11775: }
11776:
11777: sub default_login_domain {
11778: my $domain = $perlvar{'lonDefDomain'};
11779: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11780: foreach my $posdom (¤t_machine_domains(),
11781: &additional_machine_domains()) {
11782: if (lc($posdom) eq lc($testdomain)) {
11783: $domain=$posdom;
11784: last;
11785: }
11786: }
11787: return $domain;
11788: }
11789:
1.31 www 11790: # ------------------------------------------------------------- Declutters URLs
11791:
11792: sub declutter {
11793: my $thisfn=shift;
1.569 albertel 11794: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 11795: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11796: $thisfn=~s{^/home/httpd/html}{};
11797: }
1.31 www 11798: $thisfn=~s/^\///;
1.697 albertel 11799: $thisfn=~s|^adm/wrapper/||;
11800: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11801: $thisfn=~s/^res\///;
1.1172 bisitz 11802: $thisfn=~s/^priv\///;
1.1032 raeburn 11803: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11804: $thisfn=~s/\?.+$//;
11805: }
1.268 www 11806: return $thisfn;
11807: }
11808:
11809: # ------------------------------------------------------------- Clutter up URLs
11810:
11811: sub clutter {
11812: my $thisfn='/'.&declutter(shift);
1.887 albertel 11813: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11814: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11815: $thisfn='/res'.$thisfn;
11816: }
1.1031 raeburn 11817: if ($thisfn !~m|^/adm|) {
11818: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11819: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11820: } else {
11821: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11822: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11823: if ($embstyle eq 'ssi'
11824: || ($embstyle eq 'hdn')
11825: || ($embstyle eq 'rat')
11826: || ($embstyle eq 'prv')
11827: || ($embstyle eq 'ign')) {
11828: #do nothing with these
11829: } elsif (($embstyle eq 'img')
1.695 albertel 11830: || ($embstyle eq 'emb')
11831: || ($embstyle eq 'wrp')) {
11832: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11833: } elsif ($embstyle eq 'unk'
11834: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11835: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11836: } else {
1.718 www 11837: # &logthis("Got a blank emb style");
1.695 albertel 11838: }
1.694 albertel 11839: }
11840: }
1.31 www 11841: return $thisfn;
1.12 www 11842: }
11843:
1.787 albertel 11844: sub clutter_with_no_wrapper {
11845: my $uri = &clutter(shift);
11846: if ($uri =~ m-^/adm/-) {
11847: $uri =~ s-^/adm/wrapper/-/-;
11848: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11849: }
11850: return $uri;
11851: }
11852:
1.557 albertel 11853: sub freeze_escape {
11854: my ($value)=@_;
11855: if (ref($value)) {
11856: $value=&nfreeze($value);
11857: return '__FROZEN__'.&escape($value);
11858: }
11859: return &escape($value);
11860: }
11861:
1.11 www 11862:
1.557 albertel 11863: sub thaw_unescape {
11864: my ($value)=@_;
11865: if ($value =~ /^__FROZEN__/) {
11866: substr($value,0,10,undef);
11867: $value=&unescape($value);
11868: return &thaw($value);
11869: }
11870: return &unescape($value);
11871: }
11872:
1.436 albertel 11873: sub correct_line_ends {
11874: my ($result)=@_;
11875: $$result =~s/\r\n/\n/mg;
11876: $$result =~s/\r/\n/mg;
1.415 albertel 11877: }
1.1 albertel 11878: # ================================================================ Main Program
11879:
1.184 www 11880: sub goodbye {
1.204 albertel 11881: &logthis("Starting Shut down");
1.443 albertel 11882: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11883: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11884: #converted
1.599 albertel 11885: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11886: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11887: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11888: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11889: #1.1 only
1.870 albertel 11890: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11891: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11892: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11893: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11894: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11895: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11896: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11897: &flushcourselogs();
11898: &logthis("Shutting down");
11899: }
11900:
1.852 albertel 11901: sub get_dns {
1.1172.2.17 raeburn 11902: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11903: if (!$ignore_cache) {
11904: my ($content,$cached)=
11905: &Apache::lonnet::is_cached_new('dns',$url);
11906: if ($cached) {
1.1172.2.17 raeburn 11907: &$func($content,$hashref);
1.869 albertel 11908: return;
11909: }
11910: }
11911:
11912: my %alldns;
1.852 albertel 11913: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11914: foreach my $dns (<$config>) {
11915: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11916: my $line = $1;
11917: my ($host,$protocol) = split(/:/,$line);
11918: if ($protocol ne 'https') {
11919: $protocol = 'http';
11920: }
11921: $alldns{$host} = $protocol;
1.869 albertel 11922: }
11923: while (%alldns) {
1.1172.2.52 raeburn 11924: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 11925: my $ua=new LWP::UserAgent;
1.1134 raeburn 11926: $ua->timeout(30);
1.979 raeburn 11927: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11928: my $response=$ua->request($request);
1.979 raeburn 11929: delete($alldns{$dns});
1.852 albertel 11930: next if ($response->is_error());
11931: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11932: unless ($nocache) {
1.1172.2.23 raeburn 11933: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11934: }
11935: &$func(\@content,$hashref);
1.869 albertel 11936: return;
1.852 albertel 11937: }
11938: close($config);
1.871 albertel 11939: my $which = (split('/',$url))[3];
11940: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11941: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11942: my @content = <$config>;
1.1172.2.17 raeburn 11943: &$func(\@content,$hashref);
11944: return;
11945: }
11946:
11947: # ------------------------------------------------------Get DNS checksums file
11948: sub parse_dns_checksums_tab {
11949: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 11950: my $lonhost = $perlvar{'lonHostID'};
11951: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 11952: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 11953: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
11954: my $webconfdir = '/etc/httpd/conf';
11955: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
11956: $webconfdir = '/etc/apache2';
11957: } elsif ($distro =~ /^sles(\d+)$/) {
11958: if ($1 >= 10) {
11959: $webconfdir = '/etc/apache2';
11960: }
11961: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
11962: if ($1 >= 10.0) {
11963: $webconfdir = '/etc/apache2';
11964: }
11965: }
1.1172.2.17 raeburn 11966: my ($release,$timestamp) = split(/\-/,$loncaparev);
11967: my (%chksum,%revnum);
11968: if (ref($lines) eq 'ARRAY') {
11969: chomp(@{$lines});
1.1172.2.34 raeburn 11970: my $version = shift(@{$lines});
11971: if ($version eq $release) {
1.1172.2.17 raeburn 11972: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 11973: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 11974: if ($file =~ m{^/etc/httpd/conf}) {
11975: if ($webconfdir eq '/etc/apache2') {
11976: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
11977: }
11978: }
1.1172.2.34 raeburn 11979: $chksum{$file} = $shasum;
11980: $revnum{$file} = $version;
1.1172.2.17 raeburn 11981: }
11982: if (ref($hashref) eq 'HASH') {
11983: %{$hashref} = (
11984: sums => \%chksum,
11985: versions => \%revnum,
11986: );
11987: }
11988: }
11989: }
1.869 albertel 11990: return;
1.852 albertel 11991: }
1.1172.2.17 raeburn 11992:
11993: sub fetch_dns_checksums {
11994: my %checksums;
1.1172.2.34 raeburn 11995: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 11996: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 11997: my ($release,$timestamp) = split(/\-/,$loncaparev);
11998: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 11999: \%checksums);
12000: return \%checksums;
12001: }
12002:
1.327 albertel 12003: # ------------------------------------------------------------ Read domain file
12004: {
1.852 albertel 12005: my $loaded;
1.846 albertel 12006: my %domain;
12007:
1.852 albertel 12008: sub parse_domain_tab {
12009: my ($lines) = @_;
12010: foreach my $line (@$lines) {
12011: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12012:
1.846 albertel 12013: chomp($line);
1.852 albertel 12014: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12015: my %this_domain;
12016: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12017: 'lang_def', 'city', 'longi', 'lati',
12018: 'primary') {
12019: $this_domain{$field} = shift(@elements);
12020: }
12021: $domain{$name} = \%this_domain;
1.852 albertel 12022: }
12023: }
1.864 albertel 12024:
12025: sub reset_domain_info {
12026: undef($loaded);
12027: undef(%domain);
12028: }
12029:
1.852 albertel 12030: sub load_domain_tab {
1.869 albertel 12031: my ($ignore_cache) = @_;
12032: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 12033: my $fh;
12034: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12035: my @lines = <$fh>;
12036: &parse_domain_tab(\@lines);
1.448 albertel 12037: }
1.852 albertel 12038: close($fh);
12039: $loaded = 1;
1.327 albertel 12040: }
1.846 albertel 12041:
12042: sub domain {
1.852 albertel 12043: &load_domain_tab() if (!$loaded);
12044:
1.846 albertel 12045: my ($name,$what) = @_;
12046: return if ( !exists($domain{$name}) );
12047:
12048: if (!$what) {
12049: return $domain{$name}{'description'};
12050: }
12051: return $domain{$name}{$what};
12052: }
1.974 raeburn 12053:
12054: sub domain_info {
12055: &load_domain_tab() if (!$loaded);
12056: return %domain;
12057: }
12058:
1.327 albertel 12059: }
12060:
12061:
1.1 albertel 12062: # ------------------------------------------------------------- Read hosts file
12063: {
1.838 albertel 12064: my %hostname;
1.844 albertel 12065: my %hostdom;
1.845 albertel 12066: my %libserv;
1.852 albertel 12067: my $loaded;
1.888 albertel 12068: my %name_to_host;
1.1074 raeburn 12069: my %internetdom;
1.1107 raeburn 12070: my %LC_dns_serv;
1.852 albertel 12071:
12072: sub parse_hosts_tab {
12073: my ($file) = @_;
12074: foreach my $configline (@$file) {
12075: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12076: chomp($configline);
12077: if ($configline =~ /^\^/) {
12078: if ($configline =~ /^\^([\w.\-]+)/) {
12079: $LC_dns_serv{$1} = 1;
12080: }
12081: next;
12082: }
1.1074 raeburn 12083: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12084: $name=~s/\s//g;
12085: if ($id && $domain && $role && $name) {
12086: $hostname{$id}=$name;
1.888 albertel 12087: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12088: $hostdom{$id}=$domain;
12089: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12090: if (defined($protocol)) {
12091: if ($protocol eq 'https') {
12092: $protocol{$id} = $protocol;
12093: } else {
12094: $protocol{$id} = 'http';
12095: }
1.968 raeburn 12096: } else {
1.969 raeburn 12097: $protocol{$id} = 'http';
1.968 raeburn 12098: }
1.1074 raeburn 12099: if (defined($intdom)) {
12100: $internetdom{$id} = $intdom;
12101: }
1.852 albertel 12102: }
12103: }
12104: }
1.864 albertel 12105:
12106: sub reset_hosts_info {
1.897 albertel 12107: &purge_remembered();
1.864 albertel 12108: &reset_domain_info();
12109: &reset_hosts_ip_info();
1.892 albertel 12110: undef(%name_to_host);
1.864 albertel 12111: undef(%hostname);
12112: undef(%hostdom);
12113: undef(%libserv);
12114: undef($loaded);
12115: }
1.1 albertel 12116:
1.852 albertel 12117: sub load_hosts_tab {
1.869 albertel 12118: my ($ignore_cache) = @_;
12119: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12120: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12121: my @config = <$config>;
12122: &parse_hosts_tab(\@config);
12123: close($config);
12124: $loaded=1;
1.1 albertel 12125: }
1.852 albertel 12126:
1.838 albertel 12127: sub hostname {
1.852 albertel 12128: &load_hosts_tab() if (!$loaded);
12129:
1.838 albertel 12130: my ($lonid) = @_;
12131: return $hostname{$lonid};
12132: }
1.845 albertel 12133:
1.838 albertel 12134: sub all_hostnames {
1.852 albertel 12135: &load_hosts_tab() if (!$loaded);
12136:
1.838 albertel 12137: return %hostname;
12138: }
1.845 albertel 12139:
1.888 albertel 12140: sub all_names {
12141: &load_hosts_tab() if (!$loaded);
12142:
12143: return %name_to_host;
12144: }
12145:
1.974 raeburn 12146: sub all_host_domain {
12147: &load_hosts_tab() if (!$loaded);
12148: return %hostdom;
12149: }
12150:
1.845 albertel 12151: sub is_library {
1.852 albertel 12152: &load_hosts_tab() if (!$loaded);
12153:
1.845 albertel 12154: return exists($libserv{$_[0]});
12155: }
12156:
12157: sub all_library {
1.852 albertel 12158: &load_hosts_tab() if (!$loaded);
12159:
1.845 albertel 12160: return %libserv;
12161: }
12162:
1.1062 droeschl 12163: sub unique_library {
12164: #2x reverse removes all hostnames that appear more than once
12165: my %unique = reverse &all_library();
12166: return reverse %unique;
12167: }
12168:
1.841 albertel 12169: sub get_servers {
1.852 albertel 12170: &load_hosts_tab() if (!$loaded);
12171:
1.841 albertel 12172: my ($domain,$type) = @_;
12173: my %possible_hosts = ($type eq 'library') ? %libserv
12174: : %hostname;
12175: my %result;
1.842 albertel 12176: if (ref($domain) eq 'ARRAY') {
12177: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12178: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12179: $result{$host} = $hostname;
12180: }
12181: }
12182: } else {
12183: while ( my ($host,$hostname) = each(%possible_hosts)) {
12184: if ($hostdom{$host} eq $domain) {
12185: $result{$host} = $hostname;
12186: }
1.841 albertel 12187: }
12188: }
12189: return %result;
12190: }
1.845 albertel 12191:
1.1062 droeschl 12192: sub get_unique_servers {
12193: my %unique = reverse &get_servers(@_);
12194: return reverse %unique;
12195: }
12196:
1.844 albertel 12197: sub host_domain {
1.852 albertel 12198: &load_hosts_tab() if (!$loaded);
12199:
1.844 albertel 12200: my ($lonid) = @_;
12201: return $hostdom{$lonid};
12202: }
12203:
1.841 albertel 12204: sub all_domains {
1.852 albertel 12205: &load_hosts_tab() if (!$loaded);
12206:
1.841 albertel 12207: my %seen;
12208: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12209: return @uniq;
12210: }
1.1074 raeburn 12211:
12212: sub internet_dom {
12213: &load_hosts_tab() if (!$loaded);
12214:
12215: my ($lonid) = @_;
12216: return $internetdom{$lonid};
12217: }
1.1107 raeburn 12218:
12219: sub is_LC_dns {
12220: &load_hosts_tab() if (!$loaded);
12221:
12222: my ($hostname) = @_;
12223: return exists($LC_dns_serv{$hostname});
12224: }
12225:
1.1 albertel 12226: }
12227:
1.847 albertel 12228: {
12229: my %iphost;
1.856 albertel 12230: my %name_to_ip;
12231: my %lonid_to_ip;
1.869 albertel 12232:
1.847 albertel 12233: sub get_hosts_from_ip {
12234: my ($ip) = @_;
12235: my %iphosts = &get_iphost();
12236: if (ref($iphosts{$ip})) {
12237: return @{$iphosts{$ip}};
12238: }
12239: return;
1.839 albertel 12240: }
1.864 albertel 12241:
12242: sub reset_hosts_ip_info {
12243: undef(%iphost);
12244: undef(%name_to_ip);
12245: undef(%lonid_to_ip);
12246: }
1.856 albertel 12247:
12248: sub get_host_ip {
12249: my ($lonid) = @_;
12250: if (exists($lonid_to_ip{$lonid})) {
12251: return $lonid_to_ip{$lonid};
12252: }
12253: my $name=&hostname($lonid);
12254: my $ip = gethostbyname($name);
12255: return if (!$ip || length($ip) ne 4);
12256: $ip=inet_ntoa($ip);
12257: $name_to_ip{$name} = $ip;
12258: $lonid_to_ip{$lonid} = $ip;
12259: return $ip;
12260: }
1.847 albertel 12261:
12262: sub get_iphost {
1.869 albertel 12263: my ($ignore_cache) = @_;
1.894 albertel 12264:
1.869 albertel 12265: if (!$ignore_cache) {
12266: if (%iphost) {
12267: return %iphost;
12268: }
12269: my ($ip_info,$cached)=
12270: &Apache::lonnet::is_cached_new('iphost','iphost');
12271: if ($cached) {
12272: %iphost = %{$ip_info->[0]};
12273: %name_to_ip = %{$ip_info->[1]};
12274: %lonid_to_ip = %{$ip_info->[2]};
12275: return %iphost;
12276: }
12277: }
1.894 albertel 12278:
12279: # get yesterday's info for fallback
12280: my %old_name_to_ip;
12281: my ($ip_info,$cached)=
12282: &Apache::lonnet::is_cached_new('iphost','iphost');
12283: if ($cached) {
12284: %old_name_to_ip = %{$ip_info->[1]};
12285: }
12286:
1.888 albertel 12287: my %name_to_host = &all_names();
12288: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12289: my $ip;
12290: if (!exists($name_to_ip{$name})) {
12291: $ip = gethostbyname($name);
12292: if (!$ip || length($ip) ne 4) {
1.894 albertel 12293: if (defined($old_name_to_ip{$name})) {
12294: $ip = $old_name_to_ip{$name};
12295: &logthis("Can't find $name defaulting to old $ip");
12296: } else {
12297: &logthis("Name $name no IP found");
12298: next;
12299: }
12300: } else {
12301: $ip=inet_ntoa($ip);
1.847 albertel 12302: }
12303: $name_to_ip{$name} = $ip;
12304: } else {
12305: $ip = $name_to_ip{$name};
1.653 albertel 12306: }
1.888 albertel 12307: foreach my $id (@{ $name_to_host{$name} }) {
12308: $lonid_to_ip{$id} = $ip;
12309: }
12310: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12311: }
1.1172.2.23 raeburn 12312: &do_cache_new('iphost','iphost',
12313: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12314: 48*60*60);
1.869 albertel 12315:
1.847 albertel 12316: return %iphost;
1.598 albertel 12317: }
12318:
1.992 raeburn 12319: #
12320: # Given a DNS returns the loncapa host name for that DNS
12321: #
12322: sub host_from_dns {
12323: my ($dns) = @_;
12324: my @hosts;
12325: my $ip;
12326:
1.993 raeburn 12327: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12328: $ip = $name_to_ip{$dns};
12329: }
12330: if (!$ip) {
12331: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12332: if (length($ip) == 4) {
12333: $ip = &IO::Socket::inet_ntoa($ip);
12334: }
12335: }
12336: if ($ip) {
12337: @hosts = get_hosts_from_ip($ip);
12338: return $hosts[0];
12339: }
12340: return undef;
1.986 foxr 12341: }
1.992 raeburn 12342:
1.1074 raeburn 12343: sub get_internet_names {
12344: my ($lonid) = @_;
12345: return if ($lonid eq '');
12346: my ($idnref,$cached)=
12347: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12348: if ($cached) {
12349: return $idnref;
12350: }
12351: my $ip = &get_host_ip($lonid);
12352: my @hosts = &get_hosts_from_ip($ip);
12353: my %iphost = &get_iphost();
12354: my (@idns,%seen);
12355: foreach my $id (@hosts) {
12356: my $dom = &host_domain($id);
12357: my $prim_id = &domain($dom,'primary');
12358: my $prim_ip = &get_host_ip($prim_id);
12359: next if ($seen{$prim_ip});
12360: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12361: foreach my $id (@{$iphost{$prim_ip}}) {
12362: my $intdom = &internet_dom($id);
12363: unless (grep(/^\Q$intdom\E$/,@idns)) {
12364: push(@idns,$intdom);
12365: }
12366: }
12367: }
12368: $seen{$prim_ip} = 1;
12369: }
1.1172.2.23 raeburn 12370: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12371: }
12372:
1.986 foxr 12373: }
12374:
1.1079 raeburn 12375: sub all_loncaparevs {
1.1172.2.39 raeburn 12376: 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 12377: }
12378:
1.1172.2.27 raeburn 12379: # ------------------------------------------------------- Read loncaparev table
12380: {
12381: sub load_loncaparevs {
12382: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12383: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12384: while (my $configline=<$config>) {
12385: chomp($configline);
12386: my ($hostid,$loncaparev)=split(/:/,$configline);
12387: $loncaparevs{$hostid}=$loncaparev;
12388: }
12389: close($config);
12390: }
12391: }
12392: }
12393: }
12394:
12395: # ----------------------------------------------------- Read serverhostID table
12396: {
12397: sub load_serverhomeIDs {
12398: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12399: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12400: while (my $configline=<$config>) {
12401: chomp($configline);
12402: my ($name,$id)=split(/:/,$configline);
12403: $serverhomeIDs{$name}=$id;
12404: }
12405: close($config);
12406: }
12407: }
12408: }
12409: }
12410:
12411:
1.862 albertel 12412: BEGIN {
12413:
12414: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12415: unless ($readit) {
12416: {
12417: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12418: %perlvar = (%perlvar,%{$configvars});
12419: }
12420:
12421:
1.1 albertel 12422: # ------------------------------------------------------ Read spare server file
12423: {
1.448 albertel 12424: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12425:
12426: while (my $configline=<$config>) {
12427: chomp($configline);
1.284 matthew 12428: if ($configline) {
1.784 albertel 12429: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12430: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12431: push(@{ $spareid{$type} }, $host);
1.1 albertel 12432: }
12433: }
1.448 albertel 12434: close($config);
1.1 albertel 12435: }
1.11 www 12436: # ------------------------------------------------------------ Read permissions
12437: {
1.448 albertel 12438: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12439:
12440: while (my $configline=<$config>) {
1.448 albertel 12441: chomp($configline);
12442: if ($configline) {
12443: my ($role,$perm)=split(/ /,$configline);
12444: if ($perm ne '') { $pr{$role}=$perm; }
12445: }
1.11 www 12446: }
1.448 albertel 12447: close($config);
1.11 www 12448: }
12449:
12450: # -------------------------------------------- Read plain texts for permissions
12451: {
1.448 albertel 12452: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12453:
12454: while (my $configline=<$config>) {
1.448 albertel 12455: chomp($configline);
12456: if ($configline) {
1.742 raeburn 12457: my ($short,@plain)=split(/:/,$configline);
12458: %{$prp{$short}} = ();
12459: if (@plain > 0) {
12460: $prp{$short}{'std'} = $plain[0];
12461: for (my $i=1; $i<@plain; $i++) {
12462: $prp{$short}{'alt'.$i} = $plain[$i];
12463: }
12464: }
1.448 albertel 12465: }
1.135 www 12466: }
1.448 albertel 12467: close($config);
1.135 www 12468: }
12469:
12470: # ---------------------------------------------------------- Read package table
12471: {
1.448 albertel 12472: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12473:
12474: while (my $configline=<$config>) {
1.483 albertel 12475: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12476: chomp($configline);
12477: my ($short,$plain)=split(/:/,$configline);
12478: my ($pack,$name)=split(/\&/,$short);
12479: if ($plain ne '') {
12480: $packagetab{$pack.'&'.$name.'&name'}=$name;
12481: $packagetab{$short}=$plain;
12482: }
1.11 www 12483: }
1.448 albertel 12484: close($config);
1.329 matthew 12485: }
12486:
1.1172.2.27 raeburn 12487: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12488:
1.1172.2.27 raeburn 12489: &load_loncaparevs();
12490:
12491: # ------------------------------------------------------- Read serverhostID table
12492:
12493: &load_serverhomeIDs();
1.1074 raeburn 12494:
1.1172.2.27 raeburn 12495: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12496: {
12497: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12498: if (-e $file) {
12499: my $parser = HTML::LCParser->new($file);
12500: while (my $token = $parser->get_token()) {
12501: if ($token->[0] eq 'S') {
12502: my $item = $token->[1];
12503: my $name = $token->[2]{'name'};
12504: my $value = $token->[2]{'value'};
12505: if ($item ne '' && $name ne '' && $value ne '') {
12506: my $release = $parser->get_text();
12507: $release =~ s/(^\s*|\s*$ )//gx;
12508: $needsrelease{$item.':'.$name.':'.$value} = $release;
12509: }
12510: }
12511: }
12512: }
1.1073 raeburn 12513: }
12514:
1.1138 raeburn 12515: # ---------------------------------------------------------- Read managers table
12516: {
12517: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12518: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12519: while (my $configline=<$config>) {
12520: chomp($configline);
12521: next if ($configline =~ /^\#/);
12522: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12523: $managerstab{$configline} = 1;
12524: }
12525: }
12526: close($config);
12527: }
12528: }
12529: }
12530:
1.329 matthew 12531: # ------------- set up temporary directory
12532: {
1.1117 foxr 12533: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12534:
1.11 www 12535: }
12536:
1.794 albertel 12537: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12538: 'compress_threshold'=> 20_000,
12539: });
1.185 www 12540:
1.281 www 12541: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12542: $dumpcount=0;
1.958 www 12543: $locknum=0;
1.22 www 12544:
1.163 harris41 12545: &logtouch();
1.672 albertel 12546: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12547: $readit=1;
1.564 albertel 12548: {
12549: use integer;
12550: my $test=(2**32)+1;
1.568 albertel 12551: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12552: &logthis(" Detected 64bit platform ($_64bit)");
12553: }
1.195 www 12554: }
1.1 albertel 12555: }
1.179 www 12556:
1.1 albertel 12557: 1;
1.191 harris41 12558: __END__
12559:
1.243 albertel 12560: =pod
12561:
1.191 harris41 12562: =head1 NAME
12563:
1.243 albertel 12564: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12565:
12566: =head1 SYNOPSIS
12567:
1.243 albertel 12568: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12569:
12570: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12571:
1.243 albertel 12572: Common parameters:
12573:
12574: =over 4
12575:
12576: =item *
12577:
12578: $uname : an internal username (if $cname expecting a course Id specifically)
12579:
12580: =item *
12581:
12582: $udom : a domain (if $cdom expecting a course's domain specifically)
12583:
12584: =item *
12585:
12586: $symb : a resource instance identifier
12587:
12588: =item *
12589:
12590: $namespace : the name of a .db file that contains the data needed or
12591: being set.
12592:
12593: =back
12594:
1.394 bowersj2 12595: =head1 OVERVIEW
1.191 harris41 12596:
1.394 bowersj2 12597: lonnet provides subroutines which interact with the
12598: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12599: about classes, users, and resources.
1.243 albertel 12600:
12601: For many of these objects you can also use this to store data about
12602: them or modify them in various ways.
1.191 harris41 12603:
1.394 bowersj2 12604: =head2 Symbs
1.191 harris41 12605:
1.394 bowersj2 12606: To identify a specific instance of a resource, LON-CAPA uses symbols
12607: or "symbs"X<symb>. These identifiers are built from the URL of the
12608: map, the resource number of the resource in the map, and the URL of
12609: the resource itself. The latter is somewhat redundant, but might help
12610: if maps change.
12611:
12612: An example is
12613:
12614: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12615:
12616: The respective map entry is
12617:
12618: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12619: title="Problem 2">
12620: </resource>
12621:
12622: Symbs are used by the random number generator, as well as to store and
12623: restore data specific to a certain instance of for example a problem.
12624:
12625: =head2 Storing And Retrieving Data
12626:
12627: X<store()>X<cstore()>X<restore()>Three of the most important functions
12628: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12629: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12630: is is the non-critical message twin of cstore. These functions are for
12631: handlers to store a perl hash to a user's permanent data space in an
12632: easy manner, and to retrieve it again on another call. It is expected
12633: that a handler would use this once at the beginning to retrieve data,
12634: and then again once at the end to send only the new data back.
12635:
12636: The data is stored in the user's data directory on the user's
12637: homeserver under the ID of the course.
12638:
12639: The hash that is returned by restore will have all of the previous
12640: value for all of the elements of the hash.
12641:
12642: Example:
12643:
12644: #creating a hash
12645: my %hash;
12646: $hash{'foo'}='bar';
12647:
12648: #storing it
12649: &Apache::lonnet::cstore(\%hash);
12650:
12651: #changing a value
12652: $hash{'foo'}='notbar';
12653:
12654: #adding a new value
12655: $hash{'bar'}='foo';
12656: &Apache::lonnet::cstore(\%hash);
12657:
12658: #retrieving the hash
12659: my %history=&Apache::lonnet::restore();
12660:
12661: #print the hash
12662: foreach my $key (sort(keys(%history))) {
12663: print("\%history{$key} = $history{$key}");
12664: }
12665:
12666: Will print out:
1.191 harris41 12667:
1.394 bowersj2 12668: %history{1:foo} = bar
12669: %history{1:keys} = foo:timestamp
12670: %history{1:timestamp} = 990455579
12671: %history{2:bar} = foo
12672: %history{2:foo} = notbar
12673: %history{2:keys} = foo:bar:timestamp
12674: %history{2:timestamp} = 990455580
12675: %history{bar} = foo
12676: %history{foo} = notbar
12677: %history{timestamp} = 990455580
12678: %history{version} = 2
12679:
12680: Note that the special hash entries C<keys>, C<version> and
12681: C<timestamp> were added to the hash. C<version> will be equal to the
12682: total number of versions of the data that have been stored. The
12683: C<timestamp> attribute will be the UNIX time the hash was
12684: stored. C<keys> is available in every historical section to list which
12685: keys were added or changed at a specific historical revision of a
12686: hash.
12687:
12688: B<Warning>: do not store the hash that restore returns directly. This
12689: will cause a mess since it will restore the historical keys as if the
12690: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12691:
1.394 bowersj2 12692: Calling convention:
1.191 harris41 12693:
1.1172.2.27 raeburn 12694: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12695: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12696:
1.394 bowersj2 12697: For more detailed information, see lonnet specific documentation.
1.191 harris41 12698:
1.394 bowersj2 12699: =head1 RETURN MESSAGES
1.191 harris41 12700:
1.394 bowersj2 12701: =over 4
1.191 harris41 12702:
1.394 bowersj2 12703: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12704:
1.394 bowersj2 12705: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12706: when the connection is brought back up
1.191 harris41 12707:
1.394 bowersj2 12708: =item * B<con_failed>: unable to contact remote host and unable to save message
12709: for later delivery
1.191 harris41 12710:
1.967 bisitz 12711: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12712:
1.394 bowersj2 12713: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12714: that was requested
1.191 harris41 12715:
1.243 albertel 12716: =back
1.191 harris41 12717:
1.243 albertel 12718: =head1 PUBLIC SUBROUTINES
1.191 harris41 12719:
1.243 albertel 12720: =head2 Session Environment Functions
1.191 harris41 12721:
1.243 albertel 12722: =over 4
1.191 harris41 12723:
1.394 bowersj2 12724: =item *
12725: X<appenv()>
1.949 raeburn 12726: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12727: the user envirnoment file, and will be restored for each access this
1.620 albertel 12728: user makes during this session, also modifies the %env for the current
1.949 raeburn 12729: process. Optional rolesarrayref - if defined contains a reference to an array
12730: of roles which are exempt from the restriction on modifying user.role entries
12731: in the user's environment.db and in %env.
1.191 harris41 12732:
12733: =item *
1.394 bowersj2 12734: X<delenv()>
1.987 raeburn 12735: B<delenv($delthis,$regexp)>: removes all items from the session
12736: environment file that begin with $delthis. If the
12737: optional second arg - $regexp - is true, $delthis is treated as a
12738: regular expression, otherwise \Q$delthis\E is used.
12739: The values are also deleted from the current processes %env.
1.191 harris41 12740:
1.795 albertel 12741: =item * get_env_multiple($name)
12742:
12743: gets $name from the %env hash, it seemlessly handles the cases where multiple
12744: values may be defined and end up as an array ref.
12745:
12746: returns an array of values
12747:
1.243 albertel 12748: =back
12749:
12750: =head2 User Information
1.191 harris41 12751:
1.243 albertel 12752: =over 4
1.191 harris41 12753:
12754: =item *
1.394 bowersj2 12755: X<queryauthenticate()>
12756: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12757: authentication scheme
12758:
12759: =item *
1.394 bowersj2 12760: X<authenticate()>
1.1073 raeburn 12761: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12762: authenticate user from domain's lib servers (first use the current
12763: one). C<$upass> should be the users password.
1.1073 raeburn 12764: $checkdefauth is optional (value is 1 if a check should be made to
12765: authenticate user using default authentication method, and allow
12766: account creation if username does not have account in the domain).
12767: $clientcancheckhost is optional (value is 1 if checking whether the
12768: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12769:
12770: =item *
1.394 bowersj2 12771: X<homeserver()>
12772: B<homeserver($uname,$udom)>: find the server which has
12773: the user's directory and files (there must be only one), this caches
12774: the answer, and also caches if there is a borken connection.
1.191 harris41 12775:
12776: =item *
1.394 bowersj2 12777: X<idget()>
12778: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12779: (IDs are a unique resource in a domain, there must be only 1 ID per
12780: username, and only 1 username per ID in a specific domain) (returns
12781: hash: id=>name,id=>name)
1.191 harris41 12782:
12783: =item *
1.394 bowersj2 12784: X<idrget()>
12785: B<idrget($udom,@unames)>: find the IDs behind a list of
12786: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12787:
12788: =item *
1.394 bowersj2 12789: X<idput()>
12790: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12791:
12792: =item *
1.394 bowersj2 12793: X<rolesinit()>
1.1169 droeschl 12794: B<rolesinit($udom,$username)>: get user privileges.
12795: returns user role, first access and timer interval hashes
1.243 albertel 12796:
12797: =item *
1.1171 droeschl 12798: X<privileged()>
12799: B<privileged($username,$domain)>: returns a true if user has a
12800: privileged and active role (i.e. su or dc), false otherwise.
12801:
12802: =item *
1.551 albertel 12803: X<getsection()>
12804: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12805: course $cname, return section name/number or '' for "not in course"
12806: and '-1' for "no section"
12807:
12808: =item *
1.394 bowersj2 12809: X<userenvironment()>
12810: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12811: passed in @what from the requested user's environment, returns a hash
12812:
1.858 raeburn 12813: =item *
12814: X<userlog_query()>
1.859 albertel 12815: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12816: activity.log file. %filters defines filters applied when parsing the
12817: log file. These can be start or end timestamps, or the type of action
12818: - log to look for Login or Logout events, check for Checkin or
12819: Checkout, role for role selection. The response is in the form
12820: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12821: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12822:
1.243 albertel 12823: =back
12824:
12825: =head2 User Roles
12826:
12827: =over 4
12828:
12829: =item *
12830:
1.810 raeburn 12831: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12832: F: full access
12833: U,I,K: authentication modes (cxx only)
12834: '': forbidden
12835: 1: user needs to choose course
12836: 2: browse allowed
1.766 albertel 12837: A: passphrase authentication needed
1.243 albertel 12838:
12839: =item *
12840:
1.1172.2.13 raeburn 12841: constructaccess($url,$setpriv) : check for access to construction space URL
12842:
12843: See if the owner domain and name in the URL match those in the
12844: expected environment. If so, return three element list
12845: ($ownername,$ownerdomain,$ownerhome).
12846:
12847: Otherwise return the null string.
12848:
12849: If second argument 'setpriv' is true, it assigns the privileges,
12850: and returns the same three element list, unless the owner has
12851: blocked "ad hoc" Domain Coordinator access to the Author Space,
12852: in which case the null string is returned.
12853:
12854: =item *
12855:
1.243 albertel 12856: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12857: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12858: and course level
12859:
12860: =item *
12861:
1.988 raeburn 12862: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12863: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12864: $type is Course (default) or Community.
1.988 raeburn 12865: If $forcedefault evaluates to true, text returned will be default
12866: text for $type. Otherwise, if this is a course, the text returned
12867: will be a custom name for the role (if defined in the course's
12868: environment). If no custom name is defined the default is returned.
12869:
1.832 raeburn 12870: =item *
12871:
1.1172.2.23 raeburn 12872: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12873: All arguments are optional. Returns a hash of a roles, either for
12874: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12875: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12876: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12877: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12878: For each key, value is set to colon-separated start and end times for
12879: the role. If no username and domain are specified, will default to
1.934 raeburn 12880: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12881: of role statuses (active, future or previous), roles
12882: (e.g., cc,in, st etc.) and domains of the roles which can be used
12883: to restrict the list of roles reported. If no array ref is
12884: provided for types, will default to return only active roles.
1.834 albertel 12885:
1.1172.2.13 raeburn 12886: =item *
12887:
12888: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12889: user: $uname:$udom has a role in the course: $cdom_$cnum.
12890:
12891: Additional optional arguments are: $type (if role checking is to be restricted
12892: to certain user status types -- previous (expired roles), active (currently
12893: available roles) or future (roles available in the future), and
12894: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12895: have active Domain Coordinator role in course's domain or in additional
12896: domains (specified in 'Domains to check for privileged users' in course
12897: environment -- set via: Course Settings -> Classlists and staff listing).
12898:
12899: =item *
12900:
12901: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12902: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12903: $possdomains and $possroles are optional array refs -- to domains to check and
12904: roles to check. If $possdomains is not specified, a dump will be done of the
12905: users' roles.db to check for a dc or su role in any domain. This can be
12906: time consuming if &privileged is called repeatedly (e.g., when displaying a
12907: classlist), so in such cases, supplying a $possdomains array is preferred, as
12908: this then allows &privileged_by_domain() to be used, which caches the identity
12909: of privileged users, eliminating the need for repeated calls to &dump().
12910:
12911: =item *
12912:
12913: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12914: where the outer hash keys are domains specified in the $possdomains array ref,
12915: next inner hash keys are privileged roles specified in the $roles array ref,
12916: and the innermost hash contains key = value pairs for username:domain = end:start
12917: for active or future "privileged" users with that role in that domain. To avoid
12918: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12919: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12920:
1.243 albertel 12921: =back
12922:
12923: =head2 User Modification
12924:
12925: =over 4
12926:
12927: =item *
12928:
1.957 raeburn 12929: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12930: user for the level given by URL. Optional start and end dates (leave empty
12931: string or zero for "no date")
1.191 harris41 12932:
12933: =item *
12934:
1.243 albertel 12935: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12936: change a users, password, possible return values are: ok,
12937: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12938: refused
1.191 harris41 12939:
12940: =item *
12941:
1.243 albertel 12942: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12943:
12944: =item *
12945:
1.1058 raeburn 12946: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12947: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12948:
12949: will update user information (firstname,middlename,lastname,generation,
12950: permanentemail), and if forceid is true, student/employee ID also.
12951: A user's institutional affiliation(s) can also be updated.
12952: User information fields will not be overwritten with empty entries
12953: unless the field is included in the $candelete array reference.
12954: This array is included when a single user is modified via "Manage Users",
12955: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12956:
12957: =item *
12958:
1.286 matthew 12959: modifystudent
12960:
1.957 raeburn 12961: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 12962: The course id is resolved based on the current user's environment.
12963: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12964: associated with a course.
12965:
1.297 matthew 12966: This call is essentially a wrapper for lonnet::modifyuser and
12967: lonnet::modify_student_enrollment
1.286 matthew 12968:
12969: Inputs:
12970:
12971: =over 4
12972:
1.957 raeburn 12973: =item B<$udom> Student's loncapa domain
1.286 matthew 12974:
1.957 raeburn 12975: =item B<$uname> Student's loncapa login name
1.286 matthew 12976:
1.964 bisitz 12977: =item B<$uid> Student/Employee ID
1.286 matthew 12978:
1.957 raeburn 12979: =item B<$umode> Student's authentication mode
1.286 matthew 12980:
1.957 raeburn 12981: =item B<$upass> Student's password
1.286 matthew 12982:
1.957 raeburn 12983: =item B<$first> Student's first name
1.286 matthew 12984:
1.957 raeburn 12985: =item B<$middle> Student's middle name
1.286 matthew 12986:
1.957 raeburn 12987: =item B<$last> Student's last name
1.286 matthew 12988:
1.957 raeburn 12989: =item B<$gene> Student's generation
1.286 matthew 12990:
1.957 raeburn 12991: =item B<$usec> Student's section in course
1.286 matthew 12992:
12993: =item B<$end> Unix time of the roles expiration
12994:
12995: =item B<$start> Unix time of the roles start date
12996:
12997: =item B<$forceid> If defined, allow $uid to be changed
12998:
12999: =item B<$desiredhome> server to use as home server for student
13000:
1.957 raeburn 13001: =item B<$email> Student's permanent e-mail address
13002:
13003: =item B<$type> Type of enrollment (auto or manual)
13004:
1.963 raeburn 13005: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13006:
13007: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13008:
1.963 raeburn 13009: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13010:
1.963 raeburn 13011: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13012:
1.1172.2.19 raeburn 13013: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13014:
13015: =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 13016:
1.286 matthew 13017: =back
1.297 matthew 13018:
13019: =item *
13020:
13021: modify_student_enrollment
13022:
1.1172.2.31 raeburn 13023: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13024: 'role.request.course' must be defined for this function to proceed.
13025:
13026: Inputs:
13027:
13028: =over 4
13029:
1.1172.2.31 raeburn 13030: =item $udom, student's domain
1.297 matthew 13031:
1.1172.2.31 raeburn 13032: =item $uname, student's name
1.297 matthew 13033:
1.1172.2.31 raeburn 13034: =item $uid, student's user id
1.297 matthew 13035:
1.1172.2.31 raeburn 13036: =item $first, student's first name
1.297 matthew 13037:
13038: =item $middle
13039:
13040: =item $last
13041:
13042: =item $gene
13043:
13044: =item $usec
13045:
13046: =item $end
13047:
13048: =item $start
13049:
1.957 raeburn 13050: =item $type
13051:
13052: =item $locktype
13053:
13054: =item $cid
13055:
13056: =item $selfenroll
13057:
13058: =item $context
13059:
1.1172.2.19 raeburn 13060: =item $credits, number of credits student will earn from this class
13061:
1.297 matthew 13062: =back
13063:
1.191 harris41 13064:
13065: =item *
13066:
1.243 albertel 13067: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13068: custom role; give a custom role to a user for the level given by URL. Specify
13069: name and domain of role author, and role name
1.191 harris41 13070:
13071: =item *
13072:
1.243 albertel 13073: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13074:
13075: =item *
13076:
1.243 albertel 13077: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13078:
13079: =back
13080:
13081: =head2 Course Infomation
13082:
13083: =over 4
1.191 harris41 13084:
13085: =item *
13086:
1.1118 foxr 13087: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13088: specified course id, including all environment settings for the
13089: course, the description of the course will be in the hash under the
13090: key 'description'
1.191 harris41 13091:
1.1118 foxr 13092: $options is an optional parameter that if supplied is a hash reference that controls
13093: what how this function works. It has the following key/values:
13094:
13095: =over 4
13096:
13097: =item freshen_cache
13098:
13099: If defined, and the environment cache for the course is valid, it is
13100: returned in the returned hash.
13101:
13102: =item one_time
13103:
13104: If defined, the last cache time is set to _now_
13105:
13106: =item user
13107:
13108: If defined, the supplied username is used instead of the current user.
13109:
13110:
13111: =back
13112:
1.191 harris41 13113: =item *
13114:
1.624 albertel 13115: resdata($name,$domain,$type,@which) : request for current parameter
13116: setting for a specific $type, where $type is either 'course' or 'user',
13117: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13118: answers for 10 minutes.
1.243 albertel 13119:
1.877 foxr 13120: =item *
13121:
13122: get_courseresdata($courseid, $domain) : dump the entire course resource
13123: data base, returning a hash that is keyed by the resource name and has
13124: values that are the resource value. I believe that the timestamps and
13125: versions are also returned.
13126:
1.1172.2.31 raeburn 13127: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13128: supplemental content area. This routine caches the number of files for
13129: 10 minutes.
13130:
1.243 albertel 13131: =back
13132:
13133: =head2 Course Modification
13134:
13135: =over 4
1.191 harris41 13136:
13137: =item *
13138:
1.243 albertel 13139: writecoursepref($courseid,%prefs) : write preferences (environment
13140: database) for a course
1.191 harris41 13141:
13142: =item *
13143:
1.1011 raeburn 13144: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13145:
13146: =item *
13147:
1.1038 raeburn 13148: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13149:
1.1167 droeschl 13150: =item *
13151:
13152: is_course($courseid), is_course($cdom, $cnum)
13153:
13154: Accepts either a combined $courseid (in the form of domain_courseid) or the
13155: two component version $cdom, $cnum. It checks if the specified course exists.
13156:
13157: Returns:
13158: undef if the course doesn't exist, otherwise
13159: in scalar context the combined courseid.
13160: in list context the two components of the course identifier, domain and
13161: courseid.
13162:
1.243 albertel 13163: =back
13164:
13165: =head2 Resource Subroutines
13166:
13167: =over 4
1.191 harris41 13168:
13169: =item *
13170:
1.243 albertel 13171: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13172:
13173: =item *
13174:
1.243 albertel 13175: repcopy($filename) : subscribes to the requested file, and attempts to
13176: replicate from the owning library server, Might return
1.607 raeburn 13177: 'unavailable', 'not_found', 'forbidden', 'ok', or
13178: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13179: resource. Expects the local filesystem pathname
13180: (/home/httpd/html/res/....)
13181:
13182: =back
13183:
13184: =head2 Resource Information
13185:
13186: =over 4
1.191 harris41 13187:
13188: =item *
13189:
1.1172.2.28 raeburn 13190: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13191: and returns the value of a variety of different possible values,
13192: $varname should be a request string, and the other parameters can be
13193: used to specify who and what one is asking about. Ordinarily, $cid
13194: does not need to be specified, as it is retrived from
13195: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13196: within lonuserstate::loadmap() when initializing a course, before
13197: $env{'request.course.id'} has been set, so it needs to be provided
13198: in that one case.
1.243 albertel 13199:
13200: Possible values for $varname are environment.lastname (or other item
13201: from the envirnment hash), user.name (or someother aspect about the
13202: user), resource.0.maxtries (or some other part and parameter of a
13203: resource)
1.204 albertel 13204:
13205: =item *
13206:
1.243 albertel 13207: directcondval($number) : get current value of a condition; reads from a state
13208: string
1.204 albertel 13209:
13210: =item *
13211:
1.243 albertel 13212: condval($condidx) : value of condition index based on state
1.204 albertel 13213:
13214: =item *
13215:
1.243 albertel 13216: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13217: resource's metadata, $what should be either a specific key, or either
13218: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13219: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13220:
13221: this function automatically caches all requests
1.191 harris41 13222:
13223: =item *
13224:
1.243 albertel 13225: metadata_query($query,$custom,$customshow) : make a metadata query against the
13226: network of library servers; returns file handle of where SQL and regex results
13227: will be stored for query
1.191 harris41 13228:
13229: =item *
13230:
1.243 albertel 13231: symbread($filename) : return symbolic list entry (filename argument optional);
13232: returns the data handle
1.191 harris41 13233:
13234: =item *
13235:
1.1172.2.17 raeburn 13236: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13237: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13238: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13239: on failure, user must be in a course, as it assumes the existence of
13240: the course initial hash, and uses $env('request.course.id'}. The third
13241: arg is an optional reference to a scalar. If this arg is passed in the
13242: call to symbverify, it will be set to 1 if the symb has been set to be
13243: encrypted; otherwise it will be null.
1.243 albertel 13244:
1.191 harris41 13245: =item *
13246:
1.243 albertel 13247: symbclean($symb) : removes versions numbers from a symb, returns the
13248: cleaned symb
1.191 harris41 13249:
13250: =item *
13251:
1.243 albertel 13252: is_on_map($uri) : checks if the $uri is somewhere on the current
13253: course map, user must be in a course for it to work.
1.191 harris41 13254:
13255: =item *
13256:
1.243 albertel 13257: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13258:
13259: =item *
13260:
1.243 albertel 13261: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13262: a random seed, all arguments are optional, if they aren't sent it uses the
13263: environment to derive them. Note: if symb isn't sent and it can't get one
13264: from &symbread it will use the current time as its return value
1.191 harris41 13265:
13266: =item *
13267:
1.243 albertel 13268: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13269: unfakeable, receipt
1.191 harris41 13270:
13271: =item *
13272:
1.620 albertel 13273: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13274:
13275: =item *
13276:
1.243 albertel 13277: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13278:
13279: =item *
13280:
1.243 albertel 13281: 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 13282:
13283: =item *
13284:
1.243 albertel 13285: 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 13286:
13287: =item *
13288:
1.243 albertel 13289: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13290:
13291: =item *
13292:
1.243 albertel 13293: devalidate($symb) : devalidate temporary spreadsheet calculations,
13294: forcing spreadsheet to reevaluate the resource scores next time.
13295:
1.1172.2.13 raeburn 13296: =item *
13297:
13298: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13299: when viewing in course context.
13300:
13301: input: six args -- filename (decluttered), course number, course domain,
13302: url, symb (if registered) and group (if this is a
13303: group item -- e.g., bulletin board, group page etc.).
13304:
13305: output: array of five scalars --
13306: $cfile -- url for file editing if editable on current server
13307: $home -- homeserver of resource (i.e., for author if published,
13308: or course if uploaded.).
13309: $switchserver -- 1 if server switch will be needed.
13310: $forceedit -- 1 if icon/link should be to go to edit mode
13311: $forceview -- 1 if icon/link should be to go to view mode
13312:
13313: =item *
13314:
13315: is_course_upload($file,$cnum,$cdom)
13316:
13317: Used in course context to determine if current file was uploaded to
13318: the course (i.e., would be found in /userfiles/docs on the course's
13319: homeserver.
13320:
13321: input: 3 args -- filename (decluttered), course number and course domain.
13322: output: boolean -- 1 if file was uploaded.
13323:
1.243 albertel 13324: =back
13325:
13326: =head2 Storing/Retreiving Data
13327:
13328: =over 4
1.191 harris41 13329:
13330: =item *
13331:
1.243 albertel 13332: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13333: for this url; hashref needs to be given and should be a \%hashname; the
13334: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13335: be derived from the env
1.191 harris41 13336:
13337: =item *
13338:
1.243 albertel 13339: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13340: uses critical subroutine
1.191 harris41 13341:
13342: =item *
13343:
1.243 albertel 13344: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13345: all args are optional
1.191 harris41 13346:
13347: =item *
13348:
1.717 albertel 13349: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13350: dumps the complete (or key matching regexp) namespace into a hash
13351: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13352: normally &store()ed into
13353:
13354: $range should be either an integer '100' (give me the first 100
13355: matching records)
13356: or be two integers sperated by a - with no spaces
13357: '30-50' (give me the 30th through the 50th matching
13358: records)
13359:
13360:
13361: =item *
13362:
1.1172.2.59 raeburn 13363: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13364: replaces a &store() version of data with a replacement set of data
13365: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 13366: reference. If $tolog is true, the transaction is logged in the courselog
13367: with an action=PUTSTORE.
1.717 albertel 13368:
13369: =item *
13370:
1.243 albertel 13371: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13372: works very similar to store/cstore, but all data is stored in a
13373: temporary location and can be reset using tmpreset, $storehash should
13374: be a hash reference, returns nothing on success
1.191 harris41 13375:
13376: =item *
13377:
1.243 albertel 13378: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13379: similar to restore, but all data is stored in a temporary location and
13380: can be reset using tmpreset. Returns a hash of values on success,
13381: error string otherwise.
1.191 harris41 13382:
13383: =item *
13384:
1.243 albertel 13385: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13386: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13387:
13388: =item *
13389:
1.243 albertel 13390: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13391: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13392:
13393: =item *
13394:
1.243 albertel 13395: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13396: namesp ($udom and $uname are optional)
1.191 harris41 13397:
13398: =item *
13399:
1.702 albertel 13400: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13401: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13402: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13403:
1.702 albertel 13404: $range should be either an integer '100' (give me the first 100
13405: matching records)
13406: or be two integers sperated by a - with no spaces
13407: '30-50' (give me the 30th through the 50th matching
13408: records)
1.449 matthew 13409: =item *
13410:
13411: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13412: $store can be a scalar, an array reference, or if the amount to be
13413: incremented is > 1, a hash reference.
13414:
13415: ($udom and $uname are optional)
1.191 harris41 13416:
13417: =item *
13418:
1.243 albertel 13419: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13420: ($udom and $uname are optional)
1.191 harris41 13421:
13422: =item *
13423:
1.243 albertel 13424: cput($namespace,$storehash,$udom,$uname) : critical put
13425: ($udom and $uname are optional)
1.191 harris41 13426:
13427: =item *
13428:
1.748 albertel 13429: newput($namespace,$storehash,$udom,$uname) :
13430:
13431: Attempts to store the items in the $storehash, but only if they don't
13432: currently exist, if this succeeds you can be certain that you have
13433: successfully created a new key value pair in the $namespace db.
13434:
13435:
13436: Args:
13437: $namespace: name of database to store values to
13438: $storehash: hashref to store to the db
13439: $udom: (optional) domain of user containing the db
13440: $uname: (optional) name of user caontaining the db
13441:
13442: Returns:
13443: 'ok' -> succeeded in storing all keys of $storehash
13444: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13445: least <key> already existed in the db (other
13446: requested keys may also already exist)
1.967 bisitz 13447: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13448: 'con_lost' -> unable to contact request server
13449: 'refused' -> action was not allowed by remote machine
13450:
13451:
13452: =item *
13453:
1.243 albertel 13454: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13455: reference filled in from namesp (encrypts the return communication)
13456: ($udom and $uname are optional)
1.191 harris41 13457:
13458: =item *
13459:
1.243 albertel 13460: log($udom,$name,$home,$message) : write to permanent log for user; use
13461: critical subroutine
13462:
1.806 raeburn 13463: =item *
13464:
1.860 raeburn 13465: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13466: array reference filled in from namespace found in domain level on either
13467: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13468:
13469: =item *
13470:
1.860 raeburn 13471: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13472: domain level either on specified domain server ($uhome) or primary domain
13473: server ($udom and $uhome are optional)
1.806 raeburn 13474:
1.943 raeburn 13475: =item *
13476:
1.1172.2.35 raeburn 13477: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13478: for: authentication, language, quotas, timezone, date locale, and portal URL in
13479: the target domain.
13480:
13481: May also include additional key => value pairs for the following groups:
13482:
13483: =over
13484:
13485: =item
13486: disk quotas (MB allocated by default to portfolios and authoring spaces).
13487:
13488: =over
13489:
13490: =item defaultquota, authorquota
13491:
13492: =back
13493:
13494: =item
13495: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13496: portfolio for users).
13497:
13498: =over
13499:
13500: =item
13501: aboutme, blog, webdav, portfolio
13502:
13503: =back
13504:
13505: =item
13506: requestcourses: ability to request courses, and how requests are processed.
13507:
13508: =over
13509:
13510: =item
1.1172.2.37 raeburn 13511: official, unofficial, community, textbook
1.1172.2.35 raeburn 13512:
13513: =back
13514:
13515: =item
13516: inststatus: types of institutional affiliation, and order in which they are displayed.
13517:
13518: =over
13519:
13520: =item
1.1172.2.44 raeburn 13521: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13522:
13523: =back
13524:
13525: =item
13526: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13527: for course's uploaded content.
13528:
13529: =over
13530:
13531: =item
1.1172.2.37 raeburn 13532: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35 raeburn 13533:
13534: =back
13535:
13536: =item
13537: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13538: on your servers.
13539:
13540: =over
13541:
13542: =item
13543: remotesessions, hostedsessions
13544:
13545: =back
13546:
13547: =back
13548:
13549: In cases where a domain coordinator has never used the "Set Domain Configuration"
13550: utility to create a configuration.db file on a domain's primary library server
13551: only the following domain defaults: auth_def, auth_arg_def, lang_def
13552: -- corresponding values are authentication type (internal, krb4, krb5,
13553: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13554: will be available. Values are retrieved from cache (if current), unless the
13555: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13556: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13557:
13558: Typical usage:
1.943 raeburn 13559:
1.1172.2.35 raeburn 13560: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13561:
1.243 albertel 13562: =back
13563:
13564: =head2 Network Status Functions
13565:
13566: =over 4
1.191 harris41 13567:
13568: =item *
13569:
1.1137 raeburn 13570: dirlist() : return directory list based on URI (first arg).
13571:
13572: Inputs: 1 required, 5 optional.
13573:
13574: =over
13575:
13576: =item
13577: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13578:
13579: =item
13580: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13581:
13582: =item
13583: $username - username of user/course to be listed. Extracted from $uri if absent.
13584:
13585: =item
13586: $getpropath - boolean: 1 if prepend path using &propath().
13587:
13588: =item
13589: $getuserdir - boolean: 1 if prepend path for "userfiles".
13590:
13591: =item
13592: $alternateRoot - path to prepend in place of path from $uri.
13593:
13594: =back
13595:
13596: Returns: Array of up to two items.
13597:
13598: =over
13599:
13600: a reference to an array of files/subdirectories
13601:
13602: =over
13603:
13604: Each element in the array of files/subdirectories is a & separated list of
13605: item name and the result of running stat on the item. If dirlist was requested
13606: for a file instead of a directory, the item name will be ''. For a directory
13607: listing, if the item is a metadata file, the element will end &N&M
13608: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13609: default copyright set (1).
13610:
13611: =back
13612:
13613: a scalar containing error condition (if encountered).
13614:
13615: =over
13616:
13617: =item
13618: no_host (no homeserver identified for $username:$domain).
13619:
13620: =item
13621: no_such_host (server contacted for listing not identified as valid host).
13622:
13623: =item
13624: con_lost (connection to remote server failed).
13625:
13626: =item
13627: refused (invalid $username:$domain received on lond side).
13628:
13629: =item
13630: no_such_dir (directory at specified path on lond side does not exist).
13631:
13632: =item
13633: empty (directory at specified path on lond side is empty).
13634:
13635: =over
13636:
13637: This is currently not encountered because the &ls3, &ls2,
13638: &ls (_handler) routines on the lond side do not filter out
13639: . and .. from a directory listing.
13640:
13641: =back
13642:
13643: =back
13644:
13645: =back
1.191 harris41 13646:
13647: =item *
13648:
1.243 albertel 13649: spareserver() : find server with least workload from spare.tab
13650:
1.986 foxr 13651:
13652: =item *
13653:
13654: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13655: if there is no corresponding loncapa host.
13656:
1.243 albertel 13657: =back
13658:
1.986 foxr 13659:
1.243 albertel 13660: =head2 Apache Request
13661:
13662: =over 4
1.191 harris41 13663:
13664: =item *
13665:
1.243 albertel 13666: ssi($url,%hash) : server side include, does a complete request cycle on url to
13667: localhost, posts hash
13668:
13669: =back
13670:
13671: =head2 Data to String to Data
13672:
13673: =over 4
1.191 harris41 13674:
13675: =item *
13676:
1.243 albertel 13677: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13678: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13679:
13680: =item *
13681:
1.243 albertel 13682: hashref2str($hashref) : convert a hashref into a string complete with
13683: escaping and '=' and '&' separators, supports elements that are
13684: arrayrefs and hashrefs
1.191 harris41 13685:
13686: =item *
13687:
1.243 albertel 13688: arrayref2str($arrayref) : convert an arrayref into a string complete
13689: with escaping and '&' separators, supports elements that are arrayrefs
13690: and hashrefs
1.191 harris41 13691:
13692: =item *
13693:
1.243 albertel 13694: str2hash($string) : convert string to hash using unescaping and
13695: splitting on '=' and '&', supports elements that are arrayrefs and
13696: hashrefs
1.191 harris41 13697:
13698: =item *
13699:
1.243 albertel 13700: str2array($string) : convert string to hash using unescaping and
13701: splitting on '&', supports elements that are arrayrefs and hashrefs
13702:
13703: =back
13704:
13705: =head2 Logging Routines
13706:
13707:
13708: These routines allow one to make log messages in the lonnet.log and
13709: lonnet.perm logfiles.
1.191 harris41 13710:
1.1119 foxr 13711: =over 4
13712:
1.191 harris41 13713: =item *
13714:
1.243 albertel 13715: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13716:
13717: =item *
13718:
1.243 albertel 13719: logthis() : append message to the normal lonnet.log file, it gets
13720: preiodically rolled over and deleted.
1.191 harris41 13721:
13722: =item *
13723:
1.243 albertel 13724: logperm() : append a permanent message to lonnet.perm.log, this log
13725: file never gets deleted by any automated portion of the system, only
13726: messages of critical importance should go in here.
13727:
1.1119 foxr 13728:
1.243 albertel 13729: =back
13730:
13731: =head2 General File Helper Routines
13732:
13733: =over 4
1.191 harris41 13734:
13735: =item *
13736:
1.481 raeburn 13737: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13738: (a) files in /uploaded
13739: (i) If a local copy of the file exists -
13740: compares modification date of local copy with last-modified date for
13741: definitive version stored on home server for course. If local copy is
13742: stale, requests a new version from the home server and stores it.
13743: If the original has been removed from the home server, then local copy
13744: is unlinked.
13745: (ii) If local copy does not exist -
13746: requests the file from the home server and stores it.
13747:
13748: If $caller is 'uploadrep':
13749: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13750: for request for files originally uploaded via DOCS.
13751: - returns 'ok' if fresh local copy now available, -1 otherwise.
13752:
13753: Otherwise:
13754: This indicates a call from the content generation phase of the request.
13755: - returns the entire contents of the file or -1.
13756:
13757: (b) files in /res
13758: - returns the entire contents of a file or -1;
13759: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13760:
1.712 albertel 13761:
13762: =item *
13763:
13764: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13765: reference
13766:
13767: returns either a stat() list of data about the file or an empty list
13768: if the file doesn't exist or couldn't find out about it (connection
13769: problems or user unknown)
13770:
1.191 harris41 13771: =item *
13772:
1.243 albertel 13773: filelocation($dir,$file) : returns file system location of a file
13774: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13775: directory that relative $file lookups are to looked in ($dir of /a/dir
13776: and a file of ../bob will become /a/bob)
1.191 harris41 13777:
13778: =item *
13779:
13780: hreflocation($dir,$file) : returns file system location or a URL; same as
13781: filelocation except for hrefs
13782:
13783: =item *
13784:
1.1172.2.49 raeburn 13785: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13786: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 13787:
1.243 albertel 13788: =back
13789:
1.608 albertel 13790: =head2 Usererfile file routines (/uploaded*)
13791:
13792: =over 4
13793:
13794: =item *
13795:
13796: userfileupload(): main rotine for putting a file in a user or course's
13797: filespace, arguments are,
13798:
1.620 albertel 13799: formname - required - this is the name of the element in $env where the
1.608 albertel 13800: filename, and the contents of the file to create/modifed exist
1.620 albertel 13801: the filename is in $env{'form.'.$formname.'.filename'} and the
13802: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13803: context - if coursedoc, store the file in the course of the active role
13804: of the current user;
13805: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13806: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13807: subdir - required - subdirectory to put the file in under ../userfiles/
13808: if undefined, it will be placed in "unknown"
13809:
13810: (This routine calls clean_filename() to remove any dangerous
13811: characters from the filename, and then calls finuserfileupload() to
13812: complete the transaction)
13813:
13814: returns either the url of the uploaded file (/uploaded/....) if successful
13815: and /adm/notfound.html if unsuccessful
13816:
13817: =item *
13818:
13819: clean_filename(): routine for cleaing a filename up for storage in
13820: userfile space, argument is:
13821:
13822: filename - proposed filename
13823:
13824: returns: the new clean filename
13825:
13826: =item *
13827:
1.1090 raeburn 13828: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13829: userspace, probably shouldn't be called directly
13830:
13831: docuname: username or courseid of destination for the file
13832: docudom: domain of user/course of destination for the file
13833: formname: same as for userfileupload()
1.1090 raeburn 13834: fname: filename (including subdirectories) for the file
13835: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13836: allfiles: reference to hash used to store objects found by parser
13837: codebase: reference to hash used for codebases of java objects found by parser
13838: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13839: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13840: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13841: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13842: context: if 'overwrite', will move the uploaded file from its temporary location to
13843: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13844: mimetype: reference to scalar to accommodate mime type determined
13845: from File::MMagic if $parser = parse.
1.608 albertel 13846:
13847: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13848: and /adm/notfound.html if unsuccessful (or an error message if context
13849: was 'overwrite').
13850:
1.608 albertel 13851:
13852: =item *
13853:
13854: renameuserfile(): renames an existing userfile to a new name
13855:
13856: Args:
13857: docuname: username or courseid of destination for the file
13858: docudom: domain of user/course of destination for the file
13859: old: current file name (including any subdirs under userfiles)
13860: new: desired file name (including any subdirs under userfiles)
13861:
13862: =item *
13863:
13864: mkdiruserfile(): creates a directory is a userfiles dir
13865:
13866: Args:
13867: docuname: username or courseid of destination for the file
13868: docudom: domain of user/course of destination for the file
13869: dir: dir to create (including any subdirs under userfiles)
13870:
13871: =item *
13872:
13873: removeuserfile(): removes a file that exists in userfiles
13874:
13875: Args:
13876: docuname: username or courseid of destination for the file
13877: docudom: domain of user/course of destination for the file
13878: fname: filname to delete (including any subdirs under userfiles)
13879:
13880: =item *
13881:
13882: removeuploadedurl(): convience function for removeuserfile()
13883:
13884: Args:
13885: url: a full /uploaded/... url to delete
13886:
1.747 albertel 13887: =item *
13888:
13889: get_portfile_permissions():
13890: Args:
13891: domain: domain of user or course contain the portfolio files
13892: user: name of user or num of course contain the portfolio files
13893: Returns:
13894: hashref of a dump of the proper file_permissions.db
13895:
13896:
13897: =item *
13898:
13899: get_access_controls():
13900:
13901: Args:
13902: current_permissions: the hash ref returned from get_portfile_permissions()
13903: group: (optional) the group you want the files associated with
13904: file: (optional) the file you want access info on
13905:
13906: Returns:
1.749 raeburn 13907: a hash (keys are file names) of hashes containing
13908: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13909: values are XML containing access control settings (see below)
1.747 albertel 13910:
13911: Internal notes:
13912:
1.749 raeburn 13913: access controls are stored in file_permissions.db as key=value pairs.
13914: key -> path to file/file_name\0uniqueID:scope_end_start
13915: where scope -> public,guest,course,group,domains or users.
13916: end -> UNIX time for end of access (0 -> no end date)
13917: start -> UNIX time for start of access
13918:
13919: value -> XML description of access control
13920: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13921: <start></start>
13922: <end></end>
13923:
13924: <password></password> for scope type = guest
13925:
13926: <domain></domain> for scope type = course or group
13927: <number></number>
13928: <roles id="">
13929: <role></role>
13930: <access></access>
13931: <section></section>
13932: <group></group>
13933: </roles>
13934:
13935: <dom></dom> for scope type = domains
13936:
13937: <users> for scope type = users
13938: <user>
13939: <uname></uname>
13940: <udom></udom>
13941: </user>
13942: </users>
13943: </scope>
13944:
13945: Access data is also aggregated for each file in an additional key=value pair:
13946: key -> path to file/file_name\0accesscontrol
13947: value -> reference to hash
13948: hash contains key = value pairs
13949: where key = uniqueID:scope_end_start
13950: value = UNIX time record was last updated
13951:
13952: Used to improve speed of look-ups of access controls for each file.
13953:
13954: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13955:
1.1172.2.13 raeburn 13956: =item *
13957:
1.749 raeburn 13958: modify_access_controls():
13959:
13960: Modifies access controls for a portfolio file
13961: Args
13962: 1. file name
13963: 2. reference to hash of required changes,
13964: 3. domain
13965: 4. username
13966: where domain,username are the domain of the portfolio owner
13967: (either a user or a course)
13968:
13969: Returns:
13970: 1. result of additions or updates ('ok' or 'error', with error message).
13971: 2. result of deletions ('ok' or 'error', with error message).
13972: 3. reference to hash of any new or updated access controls.
13973: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13974: key = integer (inbound ID)
1.1172.2.13 raeburn 13975: value = uniqueID
13976:
13977: =item *
13978:
13979: get_timebased_id():
13980:
13981: Attempts to get a unique timestamp-based suffix for use with items added to a
13982: course via the Course Editor (e.g., folders, composite pages,
13983: group bulletin boards).
13984:
13985: Args: (first three required; six others optional)
13986:
13987: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13988: docssequence, or name of group
13989:
13990: 2. keyid (alphanumeric): name of temporary locking key in hash,
13991: e.g., num, boardids
13992:
13993: 3. namespace: name of gdbm file used to store suffixes already assigned;
13994: file will be named nohist_namespace.db
13995:
13996: 4. cdom: domain of course; default is current course domain from %env
13997:
13998: 5. cnum: course number; default is current course number from %env
13999:
14000: 6. idtype: set to concat if an additional digit is to be appended to the
14001: unix timestamp to form the suffix, if the plain timestamp is already
14002: in use. Default is to not do this, but simply increment the unix
14003: timestamp by 1 until a unique key is obtained.
14004:
14005: 7. who: holder of locking key; defaults to user:domain for user.
14006:
14007: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14008: retrying); default is 3.
14009:
14010: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14011:
14012: Returns:
14013:
14014: 1. suffix obtained (numeric)
14015:
14016: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14017:
14018: 3. error: contains (localized) error message if an error occurred.
14019:
1.747 albertel 14020:
1.608 albertel 14021: =back
14022:
1.243 albertel 14023: =head2 HTTP Helper Routines
14024:
14025: =over 4
14026:
1.191 harris41 14027: =item *
14028:
14029: escape() : unpack non-word characters into CGI-compatible hex codes
14030:
14031: =item *
14032:
14033: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14034:
1.243 albertel 14035: =back
14036:
14037: =head1 PRIVATE SUBROUTINES
14038:
14039: =head2 Underlying communication routines (Shouldn't call)
14040:
14041: =over 4
14042:
14043: =item *
14044:
14045: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14046:
14047: =item *
14048:
14049: reply() : uses subreply to send a message to remote machine, logs all failures
14050:
14051: =item *
14052:
14053: critical() : passes a critical message to another server; if cannot
14054: get through then place message in connection buffer directory and
14055: returns con_delayed, if incapable of saving message, returns
14056: con_failed
14057:
14058: =item *
14059:
14060: reconlonc() : tries to reconnect lonc client processes.
14061:
14062: =back
14063:
14064: =head2 Resource Access Logging
14065:
14066: =over 4
14067:
14068: =item *
14069:
14070: flushcourselogs() : flush (save) buffer logs and access logs
14071:
14072: =item *
14073:
14074: courselog($what) : save message for course in hash
14075:
14076: =item *
14077:
14078: courseacclog($what) : save message for course using &courselog(). Perform
14079: special processing for specific resource types (problems, exams, quizzes, etc).
14080:
1.191 harris41 14081: =item *
14082:
14083: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14084: as a PerlChildExitHandler
1.243 albertel 14085:
14086: =back
14087:
14088: =head2 Other
14089:
14090: =over 4
14091:
14092: =item *
14093:
14094: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14095:
14096: =back
14097:
14098: =cut
1.877 foxr 14099:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>